问:
Grab class from each element and move to next element in line - like a round robin
I have a circle with icons placed around it using CSS. On mouseenter or click, the html content is stored as a variable belonging to the icon and output inside the center of the circle. Each icon has a class that determines its position. (e.g. first, second, third, etc).

I would like to move whichever icon is active to the top (first) and position all the other in line respectively. So, if I click/mouseenter on the icon with a class of "third", I would like to:
a) remove the 'active' class from the active element (done)
b) add the 'active' class to this element (done)
c) change this element's class to 'first', which would make the fourth element's class be 'second', the fifth's 'third' and so on down the line.

I started by doing 'each' to store the current class in a variable, but I and then going to the parent() to change the class attr(), but couldn't figure out how to target this in a round robin style to move the class down the line. You can see below the code to move the 'active' class as well as the html content. I also have a codepen mocked up here: https://codepen.io/jphogan/pen/KqdNYZ

```<code>// on circle click add/remove class and replace html
$('.icon_circle_container .icon_circle').on('mouseenter click', function() {
    // if it's already active, do nothing, but return false
    if ( $(this).hasClass('active')) {
        return false;
    } else {
        // otherwise...
        $('.icon_circle_container .icon_circle.active').removeClass('active'); // remove active class from element that has it
        $(this).addClass('active'); // add active class to this element
        newData = $(this).find('.icon_circle_content').html(); //store html as attribute
        $('.icon_circle_container .center .icon_circle_content').fadeOut(function() { // fade out old content
            $(this).html(newData).fadeIn(); // fade in new html content
        }); // replace with stored data
        return false;
    }
})
</code>```

答:
Codepen example

```<code>(function($) {

$(document).ready(function() {
    // on circle click add/remove class and replace html
    $(".icon_circle_container .icon_circle").on("click", function() {
      // if it's already active, do nothing, but return false
      if ($(this).hasClass("active")) {
        return false;
      } else {
        // otherwise...

    // What is the new active index
    var new_item = $(this).attr('data-item-index');

    // How many items total
    var items_count = $('.icon_circle').length;

    // Rotate
    $('.icon_circle').each(function( index ) {
      var adjusted_index = index + 1; // Since js indexes from 0
      var difference = adjusted_index - new_item;
      if(difference == 0){
        console.log('activate '+ adjusted_index);
      }else{
        console.log('not active '+adjusted_index);
        if(difference > items_count){
          difference = difference - items_count;
        }else if(difference < 1){
          difference = difference + items_count;
        }
      }
      var position = difference + 1;
      // This is where you can active things and set the proper position class on the item
      $(this).removeClass('position-1 position-2 position-3 position-4 position-5').addClass('position-' + position);
    });

    $(".icon_circle_container .icon_circle.active").removeClass("active"); // remove active class from element that has it
    $(this).addClass("active"); // add active class to this element
    newData = $(this).find(".icon_circle_content").html(); //store html as attribute
    $(
      ".icon_circle_container .center .icon_circle_content"
    ).fadeOut(function() {
      // fade out old content
      $(this).html(newData).fadeIn(); // fade in new html content
    }); // replace with stored data
    return false;
  }
});
// end document ready
  });
  // end jquery wrap
})(jQuery);
</code>```

Key things:

I changed the classes for the positions to be numeric (position-1, position-2, etc).

I didn't look at your animation or fading stuff.

Essentially the stuff from line 38 down(your old stuff) may still need to apply differently around line 35 where I set the position class.

It loops through each item and figures out what position class to assign to that particular element based on where they clicked and the original data-item-index number.
We are going to assume that the order of the elements in the dom schematically is the same as the data-item-index.
In theory, we could probably drop the data-item-index and use some jquery to figure out where the clicked item fits into that order of the 5 icons in its parent but I didn't bother.

Body:
I have a circle with icons placed around it using CSS. On mouseenter or click, the html content is stored as a variable belonging to the icon and output inside the center of the circle. Each icon has a class that determines its position. (e.g. first, second, third, etc).

I would like to move whichever icon is active to the top (first) and position all the other in line respectively. So, if I click/mouseenter on the icon with a class of "third", I would like to:
a) remove the 'active' class from the active element (done)
b) add the 'active' class to this element (done)
c) change this element's class to 'first', which would make the fourth element's class be 'second', the fifth's 'third' and so on down the line.

I started by doing 'each' to store the current class in a variable, but I and then going to the parent() to change the class attr(), but couldn't figure out how to target this in a round robin style to move the class down the line. You can see below the code to move the 'active' class as well as the html content. I also have a codepen mocked up here: https://codepen.io/jphogan/pen/KqdNYZ

// on circle click add/remove class and replace html
$('.icon_circle_container .icon_circle').on('mouseenter click', function() {
    // if it's already active, do nothing, but return false
    if ( $(this).hasClass('active')) {
        return false;
    } else {
        // otherwise...
        $('.icon_circle_container .icon_circle.active').removeClass('active'); // remove active class from element that has it
        $(this).addClass('active'); // add active class to this element
        newData = $(this).find('.icon_circle_content').html(); //store html as attribute
        $('.icon_circle_container .center .icon_circle_content').fadeOut(function() { // fade out old content
            $(this).html(newData).fadeIn(); // fade in new html content
        }); // replace with stored data
        return false;
    }
})

Body:
Codepen example

(function($) {

$(document).ready(function() {
    // on circle click add/remove class and replace html
    $(".icon_circle_container .icon_circle").on("click", function() {
      // if it's already active, do nothing, but return false
      if ($(this).hasClass("active")) {
        return false;
      } else {
        // otherwise...

    // What is the new active index
    var new_item = $(this).attr('data-item-index');

    // How many items total
    var items_count = $('.icon_circle').length;

    // Rotate
    $('.icon_circle').each(function( index ) {
      var adjusted_index = index + 1; // Since js indexes from 0
      var difference = adjusted_index - new_item;
      if(difference == 0){
        console.log('activate '+ adjusted_index);
      }else{
        console.log('not active '+adjusted_index);
        if(difference > items_count){
          difference = difference - items_count;
        }else if(difference < 1){
          difference = difference + items_count;
        }
      }
      var position = difference + 1;
      // This is where you can active things and set the proper position class on the item
      $(this).removeClass('position-1 position-2 position-3 position-4 position-5').addClass('position-' + position);
    });

    $(".icon_circle_container .icon_circle.active").removeClass("active"); // remove active class from element that has it
    $(this).addClass("active"); // add active class to this element
    newData = $(this).find(".icon_circle_content").html(); //store html as attribute
    $(
      ".icon_circle_container .center .icon_circle_content"
    ).fadeOut(function() {
      // fade out old content
      $(this).html(newData).fadeIn(); // fade in new html content
    }); // replace with stored data
    return false;
  }
});
// end document ready
  });
  // end jquery wrap
})(jQuery);

Key things:

I changed the classes for the positions to be numeric (position-1, position-2, etc).

I didn't look at your animation or fading stuff.

Essentially the stuff from line 38 down(your old stuff) may still need to apply differently around line 35 where I set the position class.

It loops through each item and figures out what position class to assign to that particular element based on where they clicked and the original data-item-index number.
We are going to assume that the order of the elements in the dom schematically is the same as the data-item-index.
In theory, we could probably drop the data-item-index and use some jquery to figure out where the clicked item fits into that order of the 5 icons in its parent but I didn't bother.


来源: stackexchange

问:
How do I cast decimal values to string from my database?
The below code snippet pulls a pack size column from my table but am using getString which I get an error then now see is an issue because the column am pulling is of decimal type. How would I cast my snippet to accept the decimal values?</p>

```<code>try
        {
            string connectionString = "Data Source=CMDLAP121\\SQLEXPRESS;Initial Catalog=TESTBAR;Integrated Security=True";

            string query = "SELECT * FROM BCODEREF WHERE BAR_CODE = '" + comboBox1.Text + "';";
            string mystring = query;
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                string spo = dr.GetString(dr.GetOrdinal("PACKSIZE"));
                ponum.Text = spo;
            }
        }

        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }
</code>```

答:
Parse to decimal first and convert to a string with the format you need:

```<code>decimal packSize= 0;
decimal.TryParse(dr["PACKSIZE"].ToString(), out packSize);

ponum.Text = packSize.ToString("0.00");  //specify format you need
</code>```

See this post for details of how to set up appropriate string format

ContentLicense: CC BY-SA 3.0

Body:
The below code snippet pulls a pack size column from my table but am using getString which I get an error then now see is an issue because the column am pulling is of decimal type. How would I cast my snippet to accept the decimal values?

try
        {
            string connectionString = "Data Source=CMDLAP121\\SQLEXPRESS;Initial Catalog=TESTBAR;Integrated Security=True";

            string query = "SELECT * FROM BCODEREF WHERE BAR_CODE = '" + comboBox1.Text + "';";
            string mystring = query;
            SqlConnection con = new SqlConnection(connectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand(query, con);
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                string spo = dr.GetString(dr.GetOrdinal("PACKSIZE"));
                ponum.Text = spo;
            }
        }

        catch (Exception ex)
        {

            MessageBox.Show(ex.ToString());
        }

Body:
Parse to decimal first and convert to a string with the format you need:

decimal packSize= 0;
decimal.TryParse(dr["PACKSIZE"].ToString(), out packSize);

ponum.Text = packSize.ToString("0.00");  //specify format you need

See this post for details of how to set up appropriate string format


问:
Swift3 not playing nicely with my JSON file
I have the following code:

```<code>let urlString = "https://str8red.com/jsonoverallleaderboard/"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    if error != nil {
        print("there was an error")
        print(error)
    }
    do {
        let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
    } catch let error as NSError {
        print(error)
    }
}
}.resume()
</code>```

which is returning the following error on the "let parsedData" line:

```<code>Could not cast value of type '__NSArrayI'
</code>```

The JSON iIam using is from the website https://str8red.com/jsonoverallleaderboard/ and is in the following format:

```<code>[["shanu", "1056"], ["snookro", "828"], ["tingeypa", "709"], ["shaun", "620"], ["chrakers", "506"]]
</code>```

If it helps the end game is to use the JSON and map it as follows:

```<code>players = jsonPlayers.map { Player(name: $0[0], score: $0[1]) }
</code>```

Appreciate any help.

答:
Well your JSON data isn't of type [String:Any]. Rather it's [[String]].

So following will do the job:

```<code>let parsedData = try JSONSerialization.jsonObject(with: data!) as! [[String]]
</code>```

But here is a handy way to do parsing JSON data.

```<code>enum JSONError: String, Error {
    case NoData = "ERROR: no data"
    case ConversionFailed = "ERROR: conversion from JSON failed"
}

typealias myJSONObjectType = [[String]]  // change this according to your data type that is in your JSON

func parseJSON(fromPath jsonURLString:String) {
    guard let jsonURL = URL(string: jsonURLString) else {
        print("Error creating an URL from \(jsonURLString)")
        return
    }
    URLSession.shared.dataTask(with: jsonURL) { (data, response, error) in
        do {
            guard let data = data else {
                throw JSONError.NoData
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? myJSONObjectType else {
                throw JSONError.ConversionFailed
            }
            print(json)
        } catch let error as JSONError {
            print(error.rawValue)
        } catch let error as NSError {
            print(error.debugDescription)
        }
        }.resume()
}
</code>```

And use it like:

```<code>object.parseJSON(fromPath: "https://str8red.com/jsonoverallleaderboard/")
</code>```

Body:
I have the following code:

let urlString = "https://str8red.com/jsonoverallleaderboard/"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
    if error != nil {
        print("there was an error")
        print(error)
    }
    do {
        let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
    } catch let error as NSError {
        print(error)
    }
}
}.resume()

which is returning the following error on the "let parsedData" line:

Could not cast value of type '__NSArrayI'

The JSON iIam using is from the website https://str8red.com/jsonoverallleaderboard/ and is in the following format:

[["shanu", "1056"], ["snookro", "828"], ["tingeypa", "709"], ["shaun", "620"], ["chrakers", "506"]]

If it helps the end game is to use the JSON and map it as follows:

players = jsonPlayers.map { Player(name: $0[0], score: $0[1]) }

Appreciate any help.

Body:
Well your JSON data isn't of type [String:Any]. Rather it's [[String]].

So following will do the job:

let parsedData = try JSONSerialization.jsonObject(with: data!) as! [[String]]

But here is a handy way to do parsing JSON data.

enum JSONError: String, Error {
    case NoData = "ERROR: no data"
    case ConversionFailed = "ERROR: conversion from JSON failed"
}

typealias myJSONObjectType = [[String]]  // change this according to your data type that is in your JSON

func parseJSON(fromPath jsonURLString:String) {
    guard let jsonURL = URL(string: jsonURLString) else {
        print("Error creating an URL from \(jsonURLString)")
        return
    }
    URLSession.shared.dataTask(with: jsonURL) { (data, response, error) in
        do {
            guard let data = data else {
                throw JSONError.NoData
            }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? myJSONObjectType else {
                throw JSONError.ConversionFailed
            }
            print(json)
        } catch let error as JSONError {
            print(error.rawValue)
        } catch let error as NSError {
            print(error.debugDescription)
        }
        }.resume()
}

And use it like:

object.parseJSON(fromPath: "https://str8red.com/jsonoverallleaderboard/")


问:
Cloud Datastore and Node.js: Cannot get entity
I am using App Engine flexible environment with Node.js and am trying to store and retrieve entities in Cloud Datastore.

The following code successfully creates a new Event Entity:

```<code>/* Create event */
router.post('/', function(req, res, next) {
  const eventKey = datastore.key('Event');
  datastore.save({
    key: eventKey,
    data: req.body
  })
  .then(() => {
    console.log('New event created');
    res.json({id: eventKey.id});
  })
  .catch((err) => { next(err); });
});
</code>```

However, the following returns an empty array when I provide the previously returned id:

```<code>/* Get an event */
router.get('/:id', function(req, res, next) {
  console.log(req.params.id);
  var eventKey = datastore.key(['Event', req.params.id]);
  datastore.get(eventKey)
  .then((event) => {
    console.log(event);
    res.json(event);
  })
  .catch((err) => { console.log(err); next(err); });
});
</code>```

I seem to be using datastore.get correctly and to do what the docs is telling me to do.

Any idea why I cannot get the entity I previously created?

答:
It's worth noting that Cloud Datastore keys ([Ancestor path +] kind + id/name) treat integers (id) and strings (name) differently. That is to say that the following 2 keys refer to different entities:

Key(Event, 1234)

Key(Event, "1234")

I'm not a node expert, but is it possible it is writing and reading these different keys?

parseInt can solve this:

```<code>/* Get an event */
router.get('/:id', function(req, res, next) {
  console.log(req.params.id);
  var eventId = parseInt(req.params.id, 10)
  var eventKey = datastore.key(['Event', eventId]);
  datastore.get(eventKey)
  .then((event) => {
    console.log(event);
    res.json(event);
  })
  .catch((err) => { console.log(err); next(err); });
});
</code>```

Body:
I am using App Engine flexible environment with Node.js and am trying to store and retrieve entities in Cloud Datastore.

The following code successfully creates a new Event Entity:

/* Create event */
router.post('/', function(req, res, next) {
  const eventKey = datastore.key('Event');
  datastore.save({
    key: eventKey,
    data: req.body
  })
  .then(() => {
    console.log('New event created');
    res.json({id: eventKey.id});
  })
  .catch((err) => { next(err); });
});

However, the following returns an empty array when I provide the previously returned id:

/* Get an event */
router.get('/:id', function(req, res, next) {
  console.log(req.params.id);
  var eventKey = datastore.key(['Event', req.params.id]);
  datastore.get(eventKey)
  .then((event) => {
    console.log(event);
    res.json(event);
  })
  .catch((err) => { console.log(err); next(err); });
});

I seem to be using datastore.get correctly and to do what the docs is telling me to do.

Any idea why I cannot get the entity I previously created?

Body:
It's worth noting that Cloud Datastore keys ([Ancestor path +] kind + id/name) treat integers (id) and strings (name) differently. That is to say that the following 2 keys refer to different entities:

Key(Event, 1234)

Key(Event, "1234")

I'm not a node expert, but is it possible it is writing and reading these different keys?

parseInt can solve this:

/* Get an event */
router.get('/:id', function(req, res, next) {
  console.log(req.params.id);
  var eventId = parseInt(req.params.id, 10)
  var eventKey = datastore.key(['Event', eventId]);
  datastore.get(eventKey)
  .then((event) => {
    console.log(event);
    res.json(event);
  })
  .catch((err) => { console.log(err); next(err); });
});


问:
Is it possible to create NSFetchedResultsController to fetch all entities with distinct values for specific property?
Suppose I have Person entity with properties: id, name, age:

And I have following records:

```
101, Katherine, 23
102, Madelaine, 23
103, Katherine, 27
104, Vicky, 18
105, Kirsten, 45
106, Vicky, 12
```

And I need all records sorted by age, without duplicating name.

The output should be:

```
105, Kirsten, 45
103, Katherine, 27
102, Madelaine, 23
104, Vicky, 18
```

This is how I create NSFRC:

```<code>    let context = NSManagedObjectContext.mr_default()
    let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
    let ageDescriptor = NSSortDescriptor(key: "age", ascending: false)

    fetchRequest.sortDescriptors = [ageDescriptor]

    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    fetchedResultsController.delegate = self
</code>```

How to apply rule to fetch all persons and only one (oldest) person with the same name?

答:
You can use the property returnsDistinctResults and propertiesToFetchin NSFetchrequest to return only distinct results of a fetch request. In your case the propertiesToFetch will be the name of the entity.

You can find more info here:
https://developer.apple.com/documentation/coredata/nsfetchrequest

Just as example code. (I am doing it off top of my head so may not be 100% accurate with exact syntax):

```<code>let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)

let entityProperties = entity.propertiesByName
let namePropertyDescription = entityProperties["name"]

fetchrequest.propertiesToFetch = [namePropertyDescription]
fetchrequest.returnsDistinctResults = true
</code>```

Body:
Suppose I have Person entity with properties: id, name, age:

And I have following records:

101, Katherine, 23
102, Madelaine, 23
103, Katherine, 27
104, Vicky, 18
105, Kirsten, 45
106, Vicky, 12

And I need all records sorted by age, without duplicating name.

The output should be:

105, Kirsten, 45
103, Katherine, 27
102, Madelaine, 23
104, Vicky, 18

This is how I create NSFRC:

    let context = NSManagedObjectContext.mr_default()
    let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
    let ageDescriptor = NSSortDescriptor(key: "age", ascending: false)

    fetchRequest.sortDescriptors = [ageDescriptor]

    fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    fetchedResultsController.delegate = self

How to apply rule to fetch all persons and only one (oldest) person with the same name?

Body:
You can use the property returnsDistinctResults and propertiesToFetchin NSFetchrequest to return only distinct results of a fetch request. In your case the propertiesToFetch will be the name of the entity.

You can find more info here:
https://developer.apple.com/documentation/coredata/nsfetchrequest

Just as example code. (I am doing it off top of my head so may not be 100% accurate with exact syntax):

let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)

let entityProperties = entity.propertiesByName
let namePropertyDescription = entityProperties["name"]

fetchrequest.propertiesToFetch = [namePropertyDescription]
fetchrequest.returnsDistinctResults = true


问:
How to efficiently merge sort with vectors using C++
I have implemented a merge sort in c++ by using vectors as function
arguments instead of indices (start, end). However, I would love to
know if there is any trade off by doing this, in terms of speed
and space complexity

The code:

```<code>void mergeSort(std::vector<int> &array) {
    if(array.size() == 1) return;
    else {
      const unsigned int len = array.size();
      const int lo = floor((double)len/2);
      const int hi = ceil((double)len/2);

      std::vector<int> L(&array[0], &array[lo]);
      std::vector<int> R(&array[lo], &array[len]);

      mergeSort(L);
      mergeSort(R);
      merge(array, L, R);
    }
    return;
}
</code>```

Creating new lists every call to merge sort might not be the way to go,
but this is how the merge sort function works. Also, how fast/slow is the:

```<code>std::vector<int> L(&array[0], &array[lo]);
</code>```

The merge function then looks like:

```<code>void merge(
           std::vector<int> &array,
           std::vector<int> &L,
           std::vector<int> &R
          ) {
    std::vector<int>::iterator a = array.begin();
    std::vector<int>::iterator l = L.begin();
    std::vector<int>::iterator r = R.begin();

    while(l != L.end() && r != R.end()) {
      if (*l <= *r) {
      *a = *l;
      l++;
      }
      else {
        *a = *r;
        r++;
      }
      a++;
   }
   while (l != L.end()) {
     *a = *l;
     a++;
     l++;
   }
   while (r != R.end()) {
     *a = *r;
     a++;
     r++;
   }
   return;
</code>```

}

答:
The only additional memory you need for merge sort is array of size n for merging any of two sorted vectors produced on any step of the algorithm. Obviously, your solution uses more. On first merge it allocates two vectors of n/2 length , then it will be four vectors of n/4 and so all, giving n * log(n) in total. That's slightly more than n.

The cost for allocating vector is generally linear from its length (if copying vector's elements can be done in O(1)), but you should remember that allocating memory on the heap is expensive operation if you did not use custom allocator. Allocating memory may issue a system call, which may use complex algorithms to find the continuous piece of memory to satisfy your requirements. It may even need to move already allocated pieces of memory somewhere else. So there's really no point in allocating memory many times if you can stick with just a single allocation.

Body:
I have implemented a merge sort in c++ by using vectors as function
arguments instead of indices (start, end). However, I would love to
know if there is any trade off by doing this, in terms of speed
and space complexity

The code:

void mergeSort(std::vector<int> &array) {
    if(array.size() == 1) return;
    else {
      const unsigned int len = array.size();
      const int lo = floor((double)len/2);
      const int hi = ceil((double)len/2);

      std::vector<int> L(&array[0], &array[lo]);
      std::vector<int> R(&array[lo], &array[len]);

      mergeSort(L);
      mergeSort(R);
      merge(array, L, R);
    }
    return;
}

Creating new lists every call to merge sort might not be the way to go,
but this is how the merge sort function works. Also, how fast/slow is the:

std::vector<int> L(&array[0], &array[lo]);

The merge function then looks like:

void merge(
           std::vector<int> &array,
           std::vector<int> &L,
           std::vector<int> &R
          ) {
    std::vector<int>::iterator a = array.begin();
    std::vector<int>::iterator l = L.begin();
    std::vector<int>::iterator r = R.begin();

    while(l != L.end() && r != R.end()) {
      if (*l <= *r) {
      *a = *l;
      l++;
      }
      else {
        *a = *r;
        r++;
      }
      a++;
   }
   while (l != L.end()) {
     *a = *l;
     a++;
     l++;
   }
   while (r != R.end()) {
     *a = *r;
     a++;
     r++;
   }
   return;

}


问:
url or content as a variable in the header of the page
I am designing a site where external links form various are being shown on my page. I am using

```<code>$url=$_GET['url'];
$website_data = file_get_contents($url);
echo $website_data;
</code>```

so essentially a user would click on a hyperlink which is something like www.test.com/display_page.php?url=http://www.xyz.com/article/2.jpg

My page, list_of_images.php, typically has a list of images with href for each image as above on the page and when any image is clicked it would go to display_page.php, which would show our banner on the top of this page, some text and then this image beneath that. This image could be from any website.

I am currently sending the url directly and grabbing it using GET. I understand that users/hackers can actually do some coding and send commands for the url variable and could break the server or do something harmful and so i would like to avoid this method or sending the url directly in the header. what is the alternate approach for this problem?

答:
Try POST....

Try doing this using POST method

ContentLicense: CC BY-SA 2.5

Body:
I am designing a site where external links form various are being shown on my page. I am using

$url=$_GET['url'];
$website_data = file_get_contents($url);
echo $website_data;

so essentially a user would click on a hyperlink which is something like www.test.com/display_page.php?url=http://www.xyz.com/article/2.jpg

My page, list_of_images.php, typically has a list of images with href for each image as above on the page and when any image is clicked it would go to display_page.php, which would show our banner on the top of this page, some text and then this image beneath that. This image could be from any website.

I am currently sending the url directly and grabbing it using GET. I understand that users/hackers can actually do some coding and send commands for the url variable and could break the server or do something harmful and so i would like to avoid this method or sending the url directly in the header. what is the alternate approach for this problem?


问:
Swift 3 button.addTarget not working on all table cells
I have created an app to allow users to store various voice recordings against reviews. When I display this a table and the data is populated with the following code:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let row = (indexPath as NSIndexPath).item
    let cell = tableView.dequeueReusableCell(withIdentifier: "voiceRecordingCell", for: indexPath) as! VoiceRecordingTableViewCell
    let voiceRecording = self.voiceRecordings[row] as! NSDictionary

    let isoFormatter = DateFormatter()
    isoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.000Z'"
    let createdAt = isoFormatter.date(from: voiceRecording["created_at"] as! String)
    self.recordingIndexPaths.insert(indexPath, at: row)

    cell.recording = voiceRecording
    cell.date.text = getDateFormatter("dd-MM-y").string(from: createdAt!)
    cell.time.text = getDateFormatter("HH:mm").string(from: createdAt!)
    cell.length.text = voiceRecording["length"] as? String
    cell.location.text = voiceRecording["location"] as? String

    let audioPlayerController = self.storyboard?.instantiateViewController(withIdentifier: "AudioPlayerController") as! AudioPlayerController

    audioPlayerController.voiceRecording = voiceRecording

    cell.audioPlayer.addSubview(audioPlayerController.view)
    self.addChildViewController(audioPlayerController)
    audioPlayerController.didMove(toParentViewController: self)

    cell.deleteRecordingButton.tag = row
    cell.deleteRecordingButton.addTarget(self, action: #selector(deleteRecordingPressed(_:)), for: .touchUpInside)

    return cell
}
</code>```

The cells all appear to be rendering correctly however for the cells that are not initially rendered with the page, the ones I have to scroll down to view, when I click on the buttons either on the audio player controls or the deleteRecordingButton nothing happens, its as though the addTarget is not being set. The code to set the buttons is being called and doesn't create an error, its just not applying to those button.

The buttons that are initially displayed on the screen have the correct actions and all work perfectly so I know that works.

I'm really at a loss as to what is causing this. I did try searching google and stackoverflow but I've not found anything. Any assistance with this would be greatly received.

--------------- UPDATE -----------

I just tried putting some breakpoints in

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}
</code>```

That also only works get called on the top 2 cells or the top one if in landscape!

答:
Finally I have figured this out...

This was happening because I was using a scrollview with to scroll up and down the table without using the tables native scroll functionality.

When using the tables scroll functionality the buttons are applied the actions as they are brought into the view. This is handled by the func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { method. However when you do it the way I was it initially renders all the cells and the ones that are off the screen don't work!

Its a little bit annoying working in this way but at least I now know about it.

Body:
I have created an app to allow users to store various voice recordings against reviews. When I display this a table and the data is populated with the following code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let row = (indexPath as NSIndexPath).item
    let cell = tableView.dequeueReusableCell(withIdentifier: "voiceRecordingCell", for: indexPath) as! VoiceRecordingTableViewCell
    let voiceRecording = self.voiceRecordings[row] as! NSDictionary

    let isoFormatter = DateFormatter()
    isoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.000Z'"
    let createdAt = isoFormatter.date(from: voiceRecording["created_at"] as! String)
    self.recordingIndexPaths.insert(indexPath, at: row)

    cell.recording = voiceRecording
    cell.date.text = getDateFormatter("dd-MM-y").string(from: createdAt!)
    cell.time.text = getDateFormatter("HH:mm").string(from: createdAt!)
    cell.length.text = voiceRecording["length"] as? String
    cell.location.text = voiceRecording["location"] as? String

    let audioPlayerController = self.storyboard?.instantiateViewController(withIdentifier: "AudioPlayerController") as! AudioPlayerController

    audioPlayerController.voiceRecording = voiceRecording

    cell.audioPlayer.addSubview(audioPlayerController.view)
    self.addChildViewController(audioPlayerController)
    audioPlayerController.didMove(toParentViewController: self)

    cell.deleteRecordingButton.tag = row
    cell.deleteRecordingButton.addTarget(self, action: #selector(deleteRecordingPressed(_:)), for: .touchUpInside)

    return cell
}

The cells all appear to be rendering correctly however for the cells that are not initially rendered with the page, the ones I have to scroll down to view, when I click on the buttons either on the audio player controls or the deleteRecordingButton nothing happens, its as though the addTarget is not being set. The code to set the buttons is being called and doesn't create an error, its just not applying to those button.

The buttons that are initially displayed on the screen have the correct actions and all work perfectly so I know that works.

I'm really at a loss as to what is causing this. I did try searching google and stackoverflow but I've not found anything. Any assistance with this would be greatly received.

--------------- UPDATE -----------

I just tried putting some breakpoints in

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

That also only works get called on the top 2 cells or the top one if in landscape!


问:
Any thoughts on DevExpress XPO ORM Package?
XPO is the object relational mapper of choice at my company. Any thoughts on the pros and cons?

I was just looking for general feeling and anecdotes about the product. We are not switching to XPO. We are just getting rid of hard coded sql strings living in the app and moving completely to ORM for all data access.

答:
XPO ver 10.2 now supports for both StoredProcedures and SqlQueries. See infomation
here...</p>

OwnerDisplayName: kazakdogofspace


问:
Conversion of char to int in C?
To convert String to integer, I know there is a function atoi()
but i found this one helps too!
Please explain this
int h1 = (int)str[1] - '0';
I founded this here
http://www.geeksforgeeks.org/cpp-program-convert-time-12-hour-24-hour-format/

答:
It is basically taking the second character in str (remember arrays are zero based) and assuming it will be in the range '0'..'9'. For this reason, it is later subtracting the ascii code of '0'

This will only work for a single character and it is not a replacement for atoi

ContentLicense: CC BY-SA 4.0

Title: Conversion of char to int in C?


问:
Trouble with Slick/Postgres database testing in Play2/Specs2
I have been having a lot of trouble building an application test and was hoping someone with some more Scala experience could point me in the right direction.

I have a number of data models that reside in a Postgres database, mapped to case classes using Slick.  My Play app then provides JSON based REST endpoints to said data models.
Since most of the actual code is similar between each endpoint, most of the code is implemented as a trait which is mixed in to the actual controllers which over-ride the necessary bits.

This works fine, but when I try to run unit tests on each of them most controllers work then I end up with the error:

```<code>[error] Can't find a constructor for class helpers.DatabaseHelper
[warn] c.z.h.HikariConfig - The jdbcConnectionTest property is now deprecated, see the documentation for connectionTestQuery
[error]
[error] cannot create an instance for class FileControllerSpec
[error]   caused by java.sql.SQLTransientConnectionException: db - Connection is not available, request timed out after 1005ms.
[error]   caused by org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
[error]
[error] STACKTRACE
[error]   sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[error]   sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[error]   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[error]   java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[error]   org.specs2.reflect.Classes$$anonfun$org$specs2$reflect$Classes$$createInstanceForConstructor$1.apply(Classes.scala:104)
[error]   org.specs2.control.ActionT$$anonfun$safe$1.apply(ActionT.scala:88)
[error]   org.specs2.control.ActionT$$anonfun$reader$1$$anonfun$apply$6.apply(ActionT.scala:79)
[error]   org.specs2.control.Status$.safe(Status.scala:100)
[error]   org.specs2.control.StatusT$$anonfun$safe$1.apply(StatusT.scala:62)
[error]   org.specs2.control.StatusT$$anonfun$safe$1.apply(StatusT.scala:62)
[error]   scalaz.syntax.ToApplicativeOps$$anon$1.self$lzycompute(ApplicativeSyntax.scala:29)
[error]   scalaz.syntax.ToApplicativeOps$$anon$1.self(ApplicativeSyntax.scala:29)
[error]   scalaz.syntax.ToApplicativeOps$ApplicativeIdV$$anonfun$point$1.apply(ApplicativeSyntax.scala:33)
[error]   scalaz.WriterTApplicative$$anonfun$point$1.apply(WriterT.scala:282)
[error]   scalaz.WriterTApplicative$$anonfun$point$1.apply(WriterT.scala:282)
[error]   scalaz.effect.IO$$anonfun$apply$19$$anonfun$apply$20.apply(IO.scala:136)
[error]   scalaz.effect.IO$$anonfun$apply$19$$anonfun$apply$20.apply(IO.scala:136)
[error]   scalaz.FreeFunctions$$anonfun$return_$1.apply(Free.scala:326)
[error]   scalaz.FreeFunctions$$anonfun$return_$1.apply(Free.scala:326)
[error]   scalaz.std.FunctionInstances$$anon$1$$anonfun$map$1.apply(Function.scala:56)
[error]   scalaz.Free$$anonfun$run$1.apply(Free.scala:172)
[error]   scalaz.Free$$anonfun$run$1.apply(Free.scala:172)
[error]   scalaz.Free.go2$1(Free.scala:119)
[error]   scalaz.Free.go(Free.scala:122)
[error]   scalaz.Free.run(Free.scala:172)
[error]   scalaz.effect.IO$class.unsafePerformIO(IO.scala:22)
[error]   scalaz.effect.IOFunctions$$anon$6.unsafePerformIO(IO.scala:227)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1$$anonfun$3.apply(Classes.scala:37)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1$$anonfun$3.apply(Classes.scala:36)
[error]   scala.collection.immutable.List.map(List.scala:273)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1.apply(Classes.scala:36)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1.apply(Classes.scala:29)
[error]   scala.Function1$$anonfun$andThen$1.apply(Function1.scala:52)
[error]   org.specs2.control.Status$class.fold(Status.scala:30)
[error]   org.specs2.control.Ok.fold(Status.scala:95)
[error]   org.specs2.control.Status$class.flatMap(Status.scala:48)
[error]   org.specs2.control.Ok.flatMap(Status.scala:95)
[error]   org.specs2.control.Status$class.map(Status.scala:45)
[error]   org.specs2.control.Ok.map(Status.scala:95)
[error]   org.specs2.control.StatusT$$anonfun$map$1.apply(StatusT.scala:16)
[error]   org.specs2.control.StatusT$$anonfun$map$1.apply(StatusT.scala:16)
[error]   scalaz.WriterT$$anonfun$map$1.apply(WriterT.scala:46)
[error]   scalaz.WriterT$$anonfun$map$1.apply(WriterT.scala:46)
[error]   scalaz.effect.IO$$anonfun$map$1$$anonfun$apply$8.apply(IO.scala:56)
[error]   scalaz.effect.IO$$anonfun$map$1$$anonfun$apply$8.apply(IO.scala:55)
[error]   scalaz.Free$$anonfun$map$1.apply(Free.scala:52)
[error]   scalaz.Free$$anonfun$map$1.apply(Free.scala:52)
[error]   scalaz.Free$$anonfun$flatMap$1$$anonfun$apply$1.apply(Free.scala:60)
[error]   scalaz.Free$$anonfun$flatMap$1$$anonfun$apply$1.apply(Free.scala:60)
[error]   scalaz.Free.resume(Free.scala:72)
[error]   scalaz.Free.go2$1(Free.scala:118)
[error]   scalaz.Free.go(Free.scala:122)
[error]   scalaz.Free.run(Free.scala:172)
[error]   scalaz.effect.IO$class.unsafePerformIO(IO.scala:22)
[error]   scalaz.effect.IOFunctions$$anon$6.unsafePerformIO(IO.scala:227)
[error]   org.specs2.runner.SbtRunner$$anonfun$newTask$1$$anon$4.execute(SbtRunner.scala:37)
[error]   sbt.ForkMain$Run$2.call(ForkMain.java:294)
[error]   sbt.ForkMain$Run$2.call(ForkMain.java:284)
[error]   java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[error]   java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[error]   java.lang.Thread.run(Thread.java:745)
</code>```

DatabaseHelper is an object that sets up my test data.

Reducing the number of specs makes the error go away, so I know that the issue is not with that particular test spec.

I am using runtime DI as recommended by the Play documentation and over-riding the database binding for testing to avoid blanking my development database.

I am using Play evolutions to manage the database schema, but intentionally blanking the database and re-setting it up during setup/teardown in order to ensure that it is pristine before each test spec.

I think that what is going on is that all of my test specs are being initialised at the same time, which means that they all try to connect to the database at the same time and it therefore runs out of connections.

I have tried using the parallelExecution and concurrentRestrictions settings in sbt to set only one process going at a time but this is to no avail.  I've tried setting each spec to run sequentially as well but this seems not to work.  I have also tried catching the exception and retrying the setup but this seems not to work either.

I am now at a loss as to what to try to make my tests work!  Please help.

Thanks a lot.

Test case:

```<code>@RunWith(classOf[JUnitRunner])
class FileControllerSpec extends GenericControllerSpec {
  sequential

  override val componentName: String = "FileController"
  override val uriRoot: String = "/file"

  override def testParsedJsonObject(checkdata: JsLookupResult, parsed_test_json: JsValue) = {
    val object_keys = Seq("filepath","user","ctime","mtime","atime")
    val object_keys_int = Seq("storage","version")

    object_keys.map(key=>
      (checkdata \ key).as[String] must equalTo((parsed_test_json \ key).as[String])
    ) ++ object_keys_int.map(key=>
      (checkdata \ key).as[Int] must equalTo((parsed_test_json \ key).as[Int])
    )
  }

  override val testGetId: Int = 3
  override val testGetDocument: String = """{"filepath":"/path/to/a/video.mxf","storage":1,"user":"me","version":1,"ctime":"1970-01-01T04:25:45.678+0100","mtime":"1970-01-01T04:25:45.678+0100","atime":"1970-01-01T04:25:45.678+0100"}"""
  override val testCreateDocument: String =  """{"filepath":"/path/to/some/other.project","storage":1,"user":"test","version":3,"ctime":"2017-03-17T13:51:00.123+0000","mtime":"2017-03-17T13:51:00.123+0000","atime":"2017-03-17T13:51:00.123+0000"}"""
  override val minimumNewRecordId = 3
  override val testDeleteId: Int = 2
  override val testConflictId: Int = -1
}
</code>```

GenericControllerSpec:

```<code>@RunWith(classOf[JUnitRunner])
trait GenericControllerSpec extends Specification with BeforeAfterAll {
  //can over-ride bindings here. see https://www.playframework.com/documentation/2.5.x/ScalaTestingWithGuice
  val application:Application = new GuiceApplicationBuilder()
    .overrides(bind[DatabaseConfigProvider].to[TestDatabase.testDbProvider])
    .build

  val injector:Injector = new GuiceApplicationBuilder()
      .overrides(bind[DatabaseConfigProvider].to[TestDatabase.testDbProvider])
      .injector()

  def inject[T : ClassTag]: T = injector.instanceOf[T]

  //needed for body.consumeData
  implicit val system = ActorSystem("storage-controller-spec")
  implicit val materializer = ActorMaterializer()

  protected val databaseHelper:DatabaseHelper = inject[DatabaseHelper]

  val logger: Logger = Logger(this.getClass)

  override def beforeAll(): Unit ={
    logger.warn(">>>> before all <<<<")
    val theFuture = databaseHelper.setUpDB().map({
      case Success(result)=>logger.info("DB setup successful")
      case Failure(error)=>logger.error(s"DB setup failed: $error")
    })

    Await.result(theFuture, 10.seconds)
  }

  override def afterAll(): Unit ={
    logger.warn("<<<< after all >>>>")
    Await.result(databaseHelper.teardownDB(), 10.seconds)
  }

  val componentName:String
  val uriRoot:String

  def testParsedJsonObject(checkdata:JsLookupResult,test_parsed_json:JsValue):Seq[MatchResult[Any]]

  val testGetId:Int
  val testGetDocument:String
  val testCreateDocument:String
  val testDeleteId:Int
  val testConflictId:Int
  val minimumNewRecordId:Int

  def bodyAsJsonFuture(response:Future[play.api.mvc.Result]) = response.flatMap(result=>
    result.body.consumeData.map(contentBytes=> {
      logger.debug(contentBytes.decodeString("UTF-8"))
      Json.parse(contentBytes.decodeString("UTF-8"))
    }
    )
  )

  componentName should {

    "return 400 on a bad request" in {
      logger.debug(s"$uriRoot/boum")
      val response = route(application,FakeRequest(GET, s"$uriRoot/boum")).get
      status(response) must equalTo(BAD_REQUEST)
    }

    "return valid data for a valid record" in  {
      logger.warn(s"Test URL is $uriRoot/1")
      val response:Future[play.api.mvc.Result] = route(application, FakeRequest(GET, s"$uriRoot/1")).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("ok")
      (jsondata \ "result" \ "id").as[Int] must equalTo(1)
      testParsedJsonObject(jsondata \ "result", Json.parse(testGetDocument))
    }

    "accept new data to create a new record" in {
      val response = route(application, FakeRequest(
        method="PUT",
        uri=uriRoot,
        headers=FakeHeaders(Seq(("Content-Type", "application/json"))),
        body=testCreateDocument)
      ).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("ok")
      (jsondata \ "detail").as[String] must equalTo("added")
      (jsondata \ "id").as[Int] must greaterThanOrEqualTo(minimumNewRecordId) //if we re-run the tests without blanking the database explicitly this goes up

      val newRecordId = (jsondata \ "id").as[Int]
      val checkResponse = route(application, FakeRequest(GET, s"$uriRoot/$newRecordId")).get
      val checkdata = Await.result(bodyAsJsonFuture(checkResponse), 5.seconds)

      (checkdata \ "status").as[String] must equalTo("ok")
      (checkdata \ "result" \ "id").as[Int] must equalTo(newRecordId)
      testParsedJsonObject(checkdata \ "result", Json.parse(testCreateDocument))
    }

    "delete a record" in {
      val response = route(application, FakeRequest(
        method="DELETE",
        uri=s"$uriRoot/$testDeleteId",
        headers=FakeHeaders(),
        body="")
      ).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("ok")
      (jsondata \ "detail").as[String] must equalTo("deleted")
      (jsondata \ "id").as[Int] must equalTo(testDeleteId)
    }

    "return conflict (409) if attempting to delete something with sub-objects" in {
      val response = route(application, FakeRequest(
        method = "DELETE",
        uri = s"$uriRoot/$testConflictId",
        headers = FakeHeaders(),
        body = "")
      ).get

      status(response) must equalTo(CONFLICT)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("error")
      (jsondata \ "detail").as[String] must equalTo("This is still referenced by sub-objects")
    }
  }
}
</code>```

DatabaseHelper:

```<code>class DatabaseHelper @Inject()(configuration: Configuration, dbConfigProvider: DatabaseConfigProvider) {

  private val dbConfig = dbConfigProvider.get[JdbcProfile]
  private val logger: Logger = Logger(this.getClass)

  def setUpDB():Future[Try[Unit]] = {
    logger.warn("In setUpDB")
    dbConfig.db.run(
      DBIO.seq(
        (TableQuery[FileAssociationRow].schema ++
          TableQuery[FileEntryRow].schema ++
          TableQuery[ProjectEntryRow].schema ++
          TableQuery[ProjectTemplateRow].schema ++
          TableQuery[ProjectTypeRow].schema ++
          TableQuery[StorageEntryRow].schema
        ).create,
        TableQuery[StorageEntryRow] += StorageEntry(None,None,"filesystem",Some("me"),None,None,None),
        TableQuery[StorageEntryRow] += StorageEntry(None,None,"omms",Some("you"),None,None,None),
        TableQuery[FileEntryRow] += FileEntry(None,"/path/to/a/video.mxf",1,"me",1,new Timestamp(12345678),new Timestamp(12345678),new Timestamp(12345678)),
        TableQuery[FileEntryRow] += FileEntry(None,"/path/to/secondtestfile",1,"tstuser",1,new Timestamp(123456789),new Timestamp(123456789),new Timestamp(123456789)),
        //"""{"name": "Premiere test template 1","projectTypeId": 1,"filepath", "storageId": 1}"""
        //"{"name":,"opensWith":"AdobePremierePro.app","targetVersion":"14.0"}"
        TableQuery[ProjectTypeRow] += ProjectType(None,"Premiere 2014 test","AdobePremierePro.app","14.0"),
        TableQuery[ProjectTypeRow] += ProjectType(None,"Cubase 7.0 test","Cubase.app","7.0"),
        TableQuery[ProjectTemplateRow] += ProjectTemplate(Some(1),"Premiere test template 1",1,"/srv/projectfiles/ProjectTemplatesDev/Premiere/premiere_template_2014.prproj",1)

      ).asTry
    )
  }

  def teardownDB():Future[Try[Unit]] = {
    logger.warn("In teardownDB")
    dbConfig.db.run(
      DBIO.seq(
        (
          TableQuery[FileAssociationRow].schema ++
            TableQuery[FileEntryRow].schema ++
            TableQuery[ProjectEntryRow].schema ++
            TableQuery[ProjectTemplateRow].schema ++
            TableQuery[ProjectTypeRow].schema ++
            TableQuery[StorageEntryRow].schema
        ).drop
      ).asTry
    )
  }
}
</code>```

build.sbt settings:

```<code>concurrentRestrictions in Global := Seq(
  Tags.limit(Tags.Test, 1),
  Tags.limitAll(1)
)

parallelExecution in Test := false
</code>```

答:
the exception tells you that your connection pool is out of connections.

I see two issues here:

You are not closing the db connection in your teardown.

You may open to many connections per connection pool and since each of your specs is creating a new connection pool you are running out of the connection maximum configured on your postgres server. You can reduce the number of connections per connection pool by reducing the "numThreads" parameter of your slick config

Due to performance reasons I recommend you anyways to use H2DB drivers with postgres settings for unit testing as long you are not using postgres specific features that H2DB is not able to emulate.

Body:
I have been having a lot of trouble building an application test and was hoping someone with some more Scala experience could point me in the right direction.

I have a number of data models that reside in a Postgres database, mapped to case classes using Slick.  My Play app then provides JSON based REST endpoints to said data models.
Since most of the actual code is similar between each endpoint, most of the code is implemented as a trait which is mixed in to the actual controllers which over-ride the necessary bits.

This works fine, but when I try to run unit tests on each of them most controllers work then I end up with the error:

[error] Can't find a constructor for class helpers.DatabaseHelper
[warn] c.z.h.HikariConfig - The jdbcConnectionTest property is now deprecated, see the documentation for connectionTestQuery
[error]
[error] cannot create an instance for class FileControllerSpec
[error]   caused by java.sql.SQLTransientConnectionException: db - Connection is not available, request timed out after 1005ms.
[error]   caused by org.postgresql.util.PSQLException: FATAL: remaining connection slots are reserved for non-replication superuser connections
[error]
[error] STACKTRACE
[error]   sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[error]   sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
[error]   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
[error]   java.lang.reflect.Constructor.newInstance(Constructor.java:423)
[error]   org.specs2.reflect.Classes$$anonfun$org$specs2$reflect$Classes$$createInstanceForConstructor$1.apply(Classes.scala:104)
[error]   org.specs2.control.ActionT$$anonfun$safe$1.apply(ActionT.scala:88)
[error]   org.specs2.control.ActionT$$anonfun$reader$1$$anonfun$apply$6.apply(ActionT.scala:79)
[error]   org.specs2.control.Status$.safe(Status.scala:100)
[error]   org.specs2.control.StatusT$$anonfun$safe$1.apply(StatusT.scala:62)
[error]   org.specs2.control.StatusT$$anonfun$safe$1.apply(StatusT.scala:62)
[error]   scalaz.syntax.ToApplicativeOps$$anon$1.self$lzycompute(ApplicativeSyntax.scala:29)
[error]   scalaz.syntax.ToApplicativeOps$$anon$1.self(ApplicativeSyntax.scala:29)
[error]   scalaz.syntax.ToApplicativeOps$ApplicativeIdV$$anonfun$point$1.apply(ApplicativeSyntax.scala:33)
[error]   scalaz.WriterTApplicative$$anonfun$point$1.apply(WriterT.scala:282)
[error]   scalaz.WriterTApplicative$$anonfun$point$1.apply(WriterT.scala:282)
[error]   scalaz.effect.IO$$anonfun$apply$19$$anonfun$apply$20.apply(IO.scala:136)
[error]   scalaz.effect.IO$$anonfun$apply$19$$anonfun$apply$20.apply(IO.scala:136)
[error]   scalaz.FreeFunctions$$anonfun$return_$1.apply(Free.scala:326)
[error]   scalaz.FreeFunctions$$anonfun$return_$1.apply(Free.scala:326)
[error]   scalaz.std.FunctionInstances$$anon$1$$anonfun$map$1.apply(Function.scala:56)
[error]   scalaz.Free$$anonfun$run$1.apply(Free.scala:172)
[error]   scalaz.Free$$anonfun$run$1.apply(Free.scala:172)
[error]   scalaz.Free.go2$1(Free.scala:119)
[error]   scalaz.Free.go(Free.scala:122)
[error]   scalaz.Free.run(Free.scala:172)
[error]   scalaz.effect.IO$class.unsafePerformIO(IO.scala:22)
[error]   scalaz.effect.IOFunctions$$anon$6.unsafePerformIO(IO.scala:227)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1$$anonfun$3.apply(Classes.scala:37)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1$$anonfun$3.apply(Classes.scala:36)
[error]   scala.collection.immutable.List.map(List.scala:273)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1.apply(Classes.scala:36)
[error]   org.specs2.reflect.Classes$$anonfun$createInstance$1$$anonfun$apply$1.apply(Classes.scala:29)
[error]   scala.Function1$$anonfun$andThen$1.apply(Function1.scala:52)
[error]   org.specs2.control.Status$class.fold(Status.scala:30)
[error]   org.specs2.control.Ok.fold(Status.scala:95)
[error]   org.specs2.control.Status$class.flatMap(Status.scala:48)
[error]   org.specs2.control.Ok.flatMap(Status.scala:95)
[error]   org.specs2.control.Status$class.map(Status.scala:45)
[error]   org.specs2.control.Ok.map(Status.scala:95)
[error]   org.specs2.control.StatusT$$anonfun$map$1.apply(StatusT.scala:16)
[error]   org.specs2.control.StatusT$$anonfun$map$1.apply(StatusT.scala:16)
[error]   scalaz.WriterT$$anonfun$map$1.apply(WriterT.scala:46)
[error]   scalaz.WriterT$$anonfun$map$1.apply(WriterT.scala:46)
[error]   scalaz.effect.IO$$anonfun$map$1$$anonfun$apply$8.apply(IO.scala:56)
[error]   scalaz.effect.IO$$anonfun$map$1$$anonfun$apply$8.apply(IO.scala:55)
[error]   scalaz.Free$$anonfun$map$1.apply(Free.scala:52)
[error]   scalaz.Free$$anonfun$map$1.apply(Free.scala:52)
[error]   scalaz.Free$$anonfun$flatMap$1$$anonfun$apply$1.apply(Free.scala:60)
[error]   scalaz.Free$$anonfun$flatMap$1$$anonfun$apply$1.apply(Free.scala:60)
[error]   scalaz.Free.resume(Free.scala:72)
[error]   scalaz.Free.go2$1(Free.scala:118)
[error]   scalaz.Free.go(Free.scala:122)
[error]   scalaz.Free.run(Free.scala:172)
[error]   scalaz.effect.IO$class.unsafePerformIO(IO.scala:22)
[error]   scalaz.effect.IOFunctions$$anon$6.unsafePerformIO(IO.scala:227)
[error]   org.specs2.runner.SbtRunner$$anonfun$newTask$1$$anon$4.execute(SbtRunner.scala:37)
[error]   sbt.ForkMain$Run$2.call(ForkMain.java:294)
[error]   sbt.ForkMain$Run$2.call(ForkMain.java:284)
[error]   java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[error]   java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[error]   java.lang.Thread.run(Thread.java:745)

DatabaseHelper is an object that sets up my test data.

Reducing the number of specs makes the error go away, so I know that the issue is not with that particular test spec.

I am using runtime DI as recommended by the Play documentation and over-riding the database binding for testing to avoid blanking my development database.

I am using Play evolutions to manage the database schema, but intentionally blanking the database and re-setting it up during setup/teardown in order to ensure that it is pristine before each test spec.

I think that what is going on is that all of my test specs are being initialised at the same time, which means that they all try to connect to the database at the same time and it therefore runs out of connections.

I have tried using the parallelExecution and concurrentRestrictions settings in sbt to set only one process going at a time but this is to no avail.  I've tried setting each spec to run sequentially as well but this seems not to work.  I have also tried catching the exception and retrying the setup but this seems not to work either.

I am now at a loss as to what to try to make my tests work!  Please help.

Thanks a lot.

Test case:

@RunWith(classOf[JUnitRunner])
class FileControllerSpec extends GenericControllerSpec {
  sequential

  override val componentName: String = "FileController"
  override val uriRoot: String = "/file"

  override def testParsedJsonObject(checkdata: JsLookupResult, parsed_test_json: JsValue) = {
    val object_keys = Seq("filepath","user","ctime","mtime","atime")
    val object_keys_int = Seq("storage","version")

    object_keys.map(key=>
      (checkdata \ key).as[String] must equalTo((parsed_test_json \ key).as[String])
    ) ++ object_keys_int.map(key=>
      (checkdata \ key).as[Int] must equalTo((parsed_test_json \ key).as[Int])
    )
  }

  override val testGetId: Int = 3
  override val testGetDocument: String = """{"filepath":"/path/to/a/video.mxf","storage":1,"user":"me","version":1,"ctime":"1970-01-01T04:25:45.678+0100","mtime":"1970-01-01T04:25:45.678+0100","atime":"1970-01-01T04:25:45.678+0100"}"""
  override val testCreateDocument: String =  """{"filepath":"/path/to/some/other.project","storage":1,"user":"test","version":3,"ctime":"2017-03-17T13:51:00.123+0000","mtime":"2017-03-17T13:51:00.123+0000","atime":"2017-03-17T13:51:00.123+0000"}"""
  override val minimumNewRecordId = 3
  override val testDeleteId: Int = 2
  override val testConflictId: Int = -1
}

GenericControllerSpec:

@RunWith(classOf[JUnitRunner])
trait GenericControllerSpec extends Specification with BeforeAfterAll {
  //can over-ride bindings here. see https://www.playframework.com/documentation/2.5.x/ScalaTestingWithGuice
  val application:Application = new GuiceApplicationBuilder()
    .overrides(bind[DatabaseConfigProvider].to[TestDatabase.testDbProvider])
    .build

  val injector:Injector = new GuiceApplicationBuilder()
      .overrides(bind[DatabaseConfigProvider].to[TestDatabase.testDbProvider])
      .injector()

  def inject[T : ClassTag]: T = injector.instanceOf[T]

  //needed for body.consumeData
  implicit val system = ActorSystem("storage-controller-spec")
  implicit val materializer = ActorMaterializer()

  protected val databaseHelper:DatabaseHelper = inject[DatabaseHelper]

  val logger: Logger = Logger(this.getClass)

  override def beforeAll(): Unit ={
    logger.warn(">>>> before all <<<<")
    val theFuture = databaseHelper.setUpDB().map({
      case Success(result)=>logger.info("DB setup successful")
      case Failure(error)=>logger.error(s"DB setup failed: $error")
    })

    Await.result(theFuture, 10.seconds)
  }

  override def afterAll(): Unit ={
    logger.warn("<<<< after all >>>>")
    Await.result(databaseHelper.teardownDB(), 10.seconds)
  }

  val componentName:String
  val uriRoot:String

  def testParsedJsonObject(checkdata:JsLookupResult,test_parsed_json:JsValue):Seq[MatchResult[Any]]

  val testGetId:Int
  val testGetDocument:String
  val testCreateDocument:String
  val testDeleteId:Int
  val testConflictId:Int
  val minimumNewRecordId:Int

  def bodyAsJsonFuture(response:Future[play.api.mvc.Result]) = response.flatMap(result=>
    result.body.consumeData.map(contentBytes=> {
      logger.debug(contentBytes.decodeString("UTF-8"))
      Json.parse(contentBytes.decodeString("UTF-8"))
    }
    )
  )

  componentName should {

    "return 400 on a bad request" in {
      logger.debug(s"$uriRoot/boum")
      val response = route(application,FakeRequest(GET, s"$uriRoot/boum")).get
      status(response) must equalTo(BAD_REQUEST)
    }

    "return valid data for a valid record" in  {
      logger.warn(s"Test URL is $uriRoot/1")
      val response:Future[play.api.mvc.Result] = route(application, FakeRequest(GET, s"$uriRoot/1")).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("ok")
      (jsondata \ "result" \ "id").as[Int] must equalTo(1)
      testParsedJsonObject(jsondata \ "result", Json.parse(testGetDocument))
    }

    "accept new data to create a new record" in {
      val response = route(application, FakeRequest(
        method="PUT",
        uri=uriRoot,
        headers=FakeHeaders(Seq(("Content-Type", "application/json"))),
        body=testCreateDocument)
      ).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("ok")
      (jsondata \ "detail").as[String] must equalTo("added")
      (jsondata \ "id").as[Int] must greaterThanOrEqualTo(minimumNewRecordId) //if we re-run the tests without blanking the database explicitly this goes up

      val newRecordId = (jsondata \ "id").as[Int]
      val checkResponse = route(application, FakeRequest(GET, s"$uriRoot/$newRecordId")).get
      val checkdata = Await.result(bodyAsJsonFuture(checkResponse), 5.seconds)

      (checkdata \ "status").as[String] must equalTo("ok")
      (checkdata \ "result" \ "id").as[Int] must equalTo(newRecordId)
      testParsedJsonObject(checkdata \ "result", Json.parse(testCreateDocument))
    }

    "delete a record" in {
      val response = route(application, FakeRequest(
        method="DELETE",
        uri=s"$uriRoot/$testDeleteId",
        headers=FakeHeaders(),
        body="")
      ).get

      status(response) must equalTo(OK)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("ok")
      (jsondata \ "detail").as[String] must equalTo("deleted")
      (jsondata \ "id").as[Int] must equalTo(testDeleteId)
    }

    "return conflict (409) if attempting to delete something with sub-objects" in {
      val response = route(application, FakeRequest(
        method = "DELETE",
        uri = s"$uriRoot/$testConflictId",
        headers = FakeHeaders(),
        body = "")
      ).get

      status(response) must equalTo(CONFLICT)
      val jsondata = Await.result(bodyAsJsonFuture(response), 5.seconds).as[JsValue]
      (jsondata \ "status").as[String] must equalTo("error")
      (jsondata \ "detail").as[String] must equalTo("This is still referenced by sub-objects")
    }
  }
}

DatabaseHelper:

class DatabaseHelper @Inject()(configuration: Configuration, dbConfigProvider: DatabaseConfigProvider) {

  private val dbConfig = dbConfigProvider.get[JdbcProfile]
  private val logger: Logger = Logger(this.getClass)

  def setUpDB():Future[Try[Unit]] = {
    logger.warn("In setUpDB")
    dbConfig.db.run(
      DBIO.seq(
        (TableQuery[FileAssociationRow].schema ++
          TableQuery[FileEntryRow].schema ++
          TableQuery[ProjectEntryRow].schema ++
          TableQuery[ProjectTemplateRow].schema ++
          TableQuery[ProjectTypeRow].schema ++
          TableQuery[StorageEntryRow].schema
        ).create,
        TableQuery[StorageEntryRow] += StorageEntry(None,None,"filesystem",Some("me"),None,None,None),
        TableQuery[StorageEntryRow] += StorageEntry(None,None,"omms",Some("you"),None,None,None),
        TableQuery[FileEntryRow] += FileEntry(None,"/path/to/a/video.mxf",1,"me",1,new Timestamp(12345678),new Timestamp(12345678),new Timestamp(12345678)),
        TableQuery[FileEntryRow] += FileEntry(None,"/path/to/secondtestfile",1,"tstuser",1,new Timestamp(123456789),new Timestamp(123456789),new Timestamp(123456789)),
        //"""{"name": "Premiere test template 1","projectTypeId": 1,"filepath", "storageId": 1}"""
        //"{"name":,"opensWith":"AdobePremierePro.app","targetVersion":"14.0"}"
        TableQuery[ProjectTypeRow] += ProjectType(None,"Premiere 2014 test","AdobePremierePro.app","14.0"),
        TableQuery[ProjectTypeRow] += ProjectType(None,"Cubase 7.0 test","Cubase.app","7.0"),
        TableQuery[ProjectTemplateRow] += ProjectTemplate(Some(1),"Premiere test template 1",1,"/srv/projectfiles/ProjectTemplatesDev/Premiere/premiere_template_2014.prproj",1)

      ).asTry
    )
  }

  def teardownDB():Future[Try[Unit]] = {
    logger.warn("In teardownDB")
    dbConfig.db.run(
      DBIO.seq(
        (
          TableQuery[FileAssociationRow].schema ++
            TableQuery[FileEntryRow].schema ++
            TableQuery[ProjectEntryRow].schema ++
            TableQuery[ProjectTemplateRow].schema ++
            TableQuery[ProjectTypeRow].schema ++
            TableQuery[StorageEntryRow].schema
        ).drop
      ).asTry
    )
  }
}

build.sbt settings:

concurrentRestrictions in Global := Seq(
  Tags.limit(Tags.Test, 1),
  Tags.limitAll(1)
)

parallelExecution in Test := false


问:
PHP Combine arrays in a loop
Currently I want to output a data from a database. I have two separate arrays. May I know is there a way to combine those arrays. The code is as below,</p>

```<code>$array_1 = [
  'memo' => 'title string',
  'break_down' => 'title string',
  'images' => 'title string',
  'email_content' => 'title string'
];

// content from db
$array_2 = [$memo, $break_down, $images, $email_content];

// I want it to display like this
<?php foreach ($array_1 as $key=> $name) : ?>

<p>
<?= $name; ?> = <?php  //content on $array_2 ?>
<?php //eg: title string = $memo and so on.. ?>
</p>

<?php endforeach ?>
</code>```

答:
With array_combine and array_keys:

```<code>$keys = array_keys($array_1);
$array_2 = array_combine($keys, $array_2);

foreach ($array_1 as $key => $name): ?>
<p>
<?= $name; ?> = <?php echo $array_2[$key]; ...
</code>```

Note that you can also have the keys you want directly from your SQL query using the as SQL keyword:

```<code>select field1 as memo, field2 as break_down ...
</code>```

and using mysqli_fetch_assoc or PDO::FETCH_ASSOC

Title: PHP Combine arrays in a loop

Body:
Currently I want to output a data from a database. I have two separate arrays. May I know is there a way to combine those arrays. The code is as below,

$array_1 = [
  'memo' => 'title string',
  'break_down' => 'title string',
  'images' => 'title string',
  'email_content' => 'title string'
];

// content from db
$array_2 = [$memo, $break_down, $images, $email_content];

// I want it to display like this
<?php foreach ($array_1 as $key=> $name) : ?>

<?= $name; ?> = <?php  //content on $array_2 ?>
<?php //eg: title string = $memo and so on.. ?>

<?php endforeach ?>

Body:
With array_combine and array_keys:

$keys = array_keys($array_1);
$array_2 = array_combine($keys, $array_2);

foreach ($array_1 as $key => $name): ?>
<p>
<?= $name; ?> = <?php echo $array_2[$key]; ...

Note that you can also have the keys you want directly from your SQL query using the as SQL keyword:

select field1 as memo, field2 as break_down ...

and using mysqli_fetch_assoc or PDO::FETCH_ASSOC


问:
Store objects in an array and print it out JAVA
I've created different types of objects like object1 object2 etc. Now, how can I store these objects into an array and print that array out? The idea below does not work.

```<code>Buch buch = new Buch("Blablabla", "Baba Isi", "DE 1234567890", 50, 1234f);
    System.out.println(buch.toString());
    //5 Objekte erstellen
    /*2*/Buch buch2 = new Buch("Blabla2", "blubb", "DE 5461563259", 50, 1234f);
    System.out.println(buch2.toString());
    /*3*/Buch buch3 = new Buch("Check this out", "oke", "DE 67892011789", 50, 1234f);
    System.out.println(buch3.toString());
    /*4*/Buch buch4 = new Buch("Got ya", "catch ya", "DE 678198771890", 50, 1234f);
    System.out.println(buch4.toString());
    /*5*/Buch buch5 = new Buch("IDK", "IDK2", "DE 47740710974691", 50, 1234f);
    System.out.println(buch5.toString());

    Buch[] arr = new Buch[5];
    for(int i = 0; i<5; i++){
        arr[i] = new Buch();
    }
    for(int i = 0; i < arr.length; i++){      //toString method exists an it works
        System.out.println(arr[i].toString());
    }
</code>```

The output:

Titel: Ein Mann ein Wort   Autor: Baba Isi   ISBN: DE 1234567890   Seitenzahl: 50   Preis:    1234.0

Titel: Wanna smash   Autor: smash it   ISBN: DE 5461563259   Seitenzahl: 50   Preis:    1234.0

Titel: Smash Me   Autor: oke   ISBN: DE 67892011789   Seitenzahl: 50   Preis:    1234.0

Titel: Got ya   Autor: catch ya   ISBN: DE 678198771890   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

答:
You have gave data to objects in constructor. Indeed, when you are creating new array, you are generating new objects which do not contain your strings.

To resolve that, you can give the arguments of objects in another function and call that function for each one of array item after generation such as following:

```<code>        Buch[] arr = new Buch[5];
        for(int i = 0; i<5; i++){
            arr[i] = new Buch();
        }

        arr[0].fill("Blablabla", "Baba Isi", "DE 1234567890", 50, 1234f);
        arr[1].fill("Blabla2", "blubb", "DE 5461563259", 50, 1234f);
        arr[2].fill("Check this out", "oke", "DE 67892011789", 50, 1234f);
        arr[3].fill("Got ya", "catch ya", "DE 678198771890", 50, 1234f);
        arr[4].fill("IDK", "IDK2", "DE 47740710974691", 50, 1234f);

        for(int i = 0; i < arr.length; i++){      //toString method exists an it works
            System.out.println(arr[i].toString());
        }
</code>```

Body:
I've created different types of objects like object1 object2 etc. Now, how can I store these objects into an array and print that array out? The idea below does not work.

Buch buch = new Buch("Blablabla", "Baba Isi", "DE 1234567890", 50, 1234f);
    System.out.println(buch.toString());
    //5 Objekte erstellen
    /*2*/Buch buch2 = new Buch("Blabla2", "blubb", "DE 5461563259", 50, 1234f);
    System.out.println(buch2.toString());
    /*3*/Buch buch3 = new Buch("Check this out", "oke", "DE 67892011789", 50, 1234f);
    System.out.println(buch3.toString());
    /*4*/Buch buch4 = new Buch("Got ya", "catch ya", "DE 678198771890", 50, 1234f);
    System.out.println(buch4.toString());
    /*5*/Buch buch5 = new Buch("IDK", "IDK2", "DE 47740710974691", 50, 1234f);
    System.out.println(buch5.toString());

    Buch[] arr = new Buch[5];
    for(int i = 0; i<5; i++){
        arr[i] = new Buch();
    }
    for(int i = 0; i < arr.length; i++){      //toString method exists an it works
        System.out.println(arr[i].toString());
    }

The output:

Titel: Ein Mann ein Wort   Autor: Baba Isi   ISBN: DE 1234567890   Seitenzahl: 50   Preis:    1234.0

Titel: Wanna smash   Autor: smash it   ISBN: DE 5461563259   Seitenzahl: 50   Preis:    1234.0

Titel: Smash Me   Autor: oke   ISBN: DE 67892011789   Seitenzahl: 50   Preis:    1234.0

Titel: Got ya   Autor: catch ya   ISBN: DE 678198771890   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Titel: IDK   Autor: IDK2   ISBN: DE 47740710974691   Seitenzahl: 50   Preis:    1234.0

Body:
You have gave data to objects in constructor. Indeed, when you are creating new array, you are generating new objects which do not contain your strings.

To resolve that, you can give the arguments of objects in another function and call that function for each one of array item after generation such as following:

        Buch[] arr = new Buch[5];
        for(int i = 0; i<5; i++){
            arr[i] = new Buch();
        }

        arr[0].fill("Blablabla", "Baba Isi", "DE 1234567890", 50, 1234f);
        arr[1].fill("Blabla2", "blubb", "DE 5461563259", 50, 1234f);
        arr[2].fill("Check this out", "oke", "DE 67892011789", 50, 1234f);
        arr[3].fill("Got ya", "catch ya", "DE 678198771890", 50, 1234f);
        arr[4].fill("IDK", "IDK2", "DE 47740710974691", 50, 1234f);

        for(int i = 0; i < arr.length; i++){      //toString method exists an it works
            System.out.println(arr[i].toString());
        }


问:
How convert string with underscore to unicode?
I try to create array with string elements in python.

```<code> a = array('u',["sub_id","datetime"])
</code>```

Python show TypeError: array item must be unicode character

Reason of create array is to send it with request. I use rest API with JSON of some product and send request, but It says this param is must be a array.(tuple and list don't suit)

I use python 3.4.4,How can I fix this?

答:
The problem has nothing to do with the underscore.

You don't need the square brackets for arrays of typecode 'u'; unicode objects are iterable:

```<code>>>> a = array('u', u'sub_id')
>>> a.append(u'g')
>>> a
array('u', u'sub_idg')
</code>```

```<code>>>> a = array('u', u'sub_id datetime')
>>> a.extend(u' time')
>>> a
array('u', u'sub_id datetime time')
</code>```

This is different for numeric types since they are not iterable, and you need to pass the iterable of numbers via a list.

With Python 3.4 version included, I'm starting to think your API actually wants a list of strings.

Body:
I try to create array with string elements in python.

 a = array('u',["sub_id","datetime"])

Python show TypeError: array item must be unicode character

Reason of create array is to send it with request. I use rest API with JSON of some product and send request, but It says this param is must be a array.(tuple and list don't suit)

I use python 3.4.4,How can I fix this?

Body:
The problem has nothing to do with the underscore.

You don't need the square brackets for arrays of typecode 'u'; unicode objects are iterable:

>>> a = array('u', u'sub_id')
>>> a.append(u'g')
>>> a
array('u', u'sub_idg')

>>> a = array('u', u'sub_id datetime')
>>> a.extend(u' time')
>>> a
array('u', u'sub_id datetime time')

This is different for numeric types since they are not iterable, and you need to pass the iterable of numbers via a list.

With Python 3.4 version included, I'm starting to think your API actually wants a list of strings.


问:
How do you manage your gists on GitHub?
I love GitHub and their gist service, and that's why I'm keeping a lot of code snippets and even development notes as a gist on my GitHub account. It also makes it easy to share them with my colleagues.

The problem is that it doesn't scale!! The GitHub features for gist are primitive, and I have lots of gists there which make it really difficult to find some of my old gists. There's no search, no tagging, or anything.

Do you know any application that can handle this mess? I would like an application that could

Search my gists

List my gists by source type and date

Let me edit or copy them

Let me tag or at least edit description

I would love to see something like this, and I'm willing to pay even some bucks for it.

So how do you manage you gists on GitHub? Do you know any software?

There's one called drift written in MacRuby, but I couldn't compile it, and it hasn't been updated for a while.

答:
You can also try Snipit: https://snipit.xyz - it helps you easily save and organize your code snippets. It's still in beta, but it allows you to:

snip code blocks directly from the pages you visit, with a handy browser extensions;

organize your snippets in lists;

search snippets by list, title, syntax and tags.

Features from upcoming version:

collections: group multiple lists in packages or libraries (e.g. "Bootstrap code examples", or "PHP functions");

sharing and collaboration: share snippets with everybody, or only with specific people; collaborate with team members;

companion desktop app and IDE extensions: quickly find snippets while you're working, without breaking your development flow;

last but not least: integration with Gist.

Give it a try and hope it solves all your needs.

Title: How do you manage your gists on GitHub?


问:
IQueryable WhereLike extension with unknown property type
I'm trying to create a WhereLike extension to IQueryable but I can't know the type of the property at runtime.

Here is my code:

```<code>    public static IQueryable WhereLike(this IQueryable source, string propertyName, string pattern)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (propertyName == null) throw new ArgumentNullException("propertyName");

        var a = Expression.Parameter(typeof(object), "a");
        var prop = Expression.Property(a, propertyName);

        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(SqlMethods), "Like",
                null,
                prop, Expression.Constant(pattern)));
    }
</code>```

I get the exception: Instance property 'foo' is not defined for type 'System.Object'

Do you know a way to handle property setting without knowing target type at compile time ?

答:
If you are able to use the generic IQueryable<T> variant, this becomes a much easier problem since you no longer need CreateQuery and you can execute directly against the IQueryable<T> source.

```<code>public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, string propertyName,
    string pattern)
{
    if (source == null) throw new ArgumentNullException("source");
    if (propertyName == null) throw new ArgumentNullException("propertyName");

    var a = Expression.Parameter(typeof(T), "a");
    var prop = Expression.PropertyOrField(a, propertyName);

    var expr = Expression.Call(
            typeof(SqlMethods), "Like",
            null,
            prop, Expression.Constant(pattern));

    var lambda = Expression.Lambda<Func<T, bool>>(expr, a);
    return source.Where(lambda);
}
</code>```

Note two key points:

Instead of only grabbing properties, if we use PropertyOrField we can properly support code generated for Linq-2-SQL that may be exposing fields.

In addition, since we are executing against the IQueryable<T> source, we need to create a lambda expression from the results of our "Like" MethodCallExpression.

If you need the non-generic variant, you can still accomplish the same thing, although you'll need to wrap your Like MethodCallExpression in a Where MethodCallExpression in order for it to be properly structured:

```<code>public static IQueryable WhereLike(this IQueryable source, string propertyName,
    string pattern)
{
    if (source == null) throw new ArgumentNullException("source");
    if (propertyName == null) throw new ArgumentNullException("propertyName");

    var a = Expression.Parameter(source.GetType().GetGenericArguments().First(), "a");
    var prop = Expression.PropertyOrField(a, propertyName);

    var expr = Expression.Call(
            typeof(SqlMethods), "Like",
            null,
            prop, Expression.Constant(pattern));

    MethodCallExpression whereCallExpression = Expression.Call(
            typeof(Queryable),
            "Where",
            new Type[] { source.ElementType },
            source.Expression,
            Expression.Lambda(expr, a));

    return source.Provider.CreateQuery(whereCallExpression);
}
</code>```

You can invoke either variant with wildcards:

```<code>var data = source.WhereLike("ColumnName", "%o%");
</code>```

Body:
I'm trying to create a WhereLike extension to IQueryable but I can't know the type of the property at runtime.

Here is my code:

    public static IQueryable WhereLike(this IQueryable source, string propertyName, string pattern)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (propertyName == null) throw new ArgumentNullException("propertyName");

        var a = Expression.Parameter(typeof(object), "a");
        var prop = Expression.Property(a, propertyName);

        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(SqlMethods), "Like",
                null,
                prop, Expression.Constant(pattern)));
    }

I get the exception: Instance property 'foo' is not defined for type 'System.Object'

Do you know a way to handle property setting without knowing target type at compile time ?

Body:
If you are able to use the generic IQueryable<T> variant, this becomes a much easier problem since you no longer need CreateQuery and you can execute directly against the IQueryable<T> source.

public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, string propertyName,
    string pattern)
{
    if (source == null) throw new ArgumentNullException("source");
    if (propertyName == null) throw new ArgumentNullException("propertyName");

    var a = Expression.Parameter(typeof(T), "a");
    var prop = Expression.PropertyOrField(a, propertyName);

    var expr = Expression.Call(
            typeof(SqlMethods), "Like",
            null,
            prop, Expression.Constant(pattern));

    var lambda = Expression.Lambda<Func<T, bool>>(expr, a);
    return source.Where(lambda);
}

Note two key points:

Instead of only grabbing properties, if we use PropertyOrField we can properly support code generated for Linq-2-SQL that may be exposing fields.

In addition, since we are executing against the IQueryable<T> source, we need to create a lambda expression from the results of our "Like" MethodCallExpression.

If you need the non-generic variant, you can still accomplish the same thing, although you'll need to wrap your Like MethodCallExpression in a Where MethodCallExpression in order for it to be properly structured:

public static IQueryable WhereLike(this IQueryable source, string propertyName,
    string pattern)
{
    if (source == null) throw new ArgumentNullException("source");
    if (propertyName == null) throw new ArgumentNullException("propertyName");

    var a = Expression.Parameter(source.GetType().GetGenericArguments().First(), "a");
    var prop = Expression.PropertyOrField(a, propertyName);

    var expr = Expression.Call(
            typeof(SqlMethods), "Like",
            null,
            prop, Expression.Constant(pattern));

    MethodCallExpression whereCallExpression = Expression.Call(
            typeof(Queryable),
            "Where",
            new Type[] { source.ElementType },
            source.Expression,
            Expression.Lambda(expr, a));

    return source.Provider.CreateQuery(whereCallExpression);
}

You can invoke either variant with wildcards:

var data = source.WhereLike("ColumnName", "%o%");


问:
Exclude specific Sub Folders
I got a package that runs through a folder and it's sub folders to get client data. The agreement has changed and now the client will post his data in different folder name every time. I was wondering if I can do a foreach loop on the main folder and exclude specific folders like archive .

I don't have knowledge in writing scripts so I was wondering if SSIS can do that without the script.

答:
Using Execute Script Task

Get List of - filtered - files using an Execute Script Task before entering Loop and loop over then using ForEach Loop container (Ado enumerator)

You have to a a SSIS variable (ex: User::FilesList) with type System.Object (Scope: Package)

Add an Execute Script Task before the for each Loop container and add User::FilesList as a ReadWrite Variable

In the Script Write The following Code:

```<code>Imports System.Linq
Imports System.IO
Imports System.Collections.Generic

Public Sub Main()
    Dim Directory as String = "C\Temp"
    Dim strSubDirectory as String = Directory & "\New Folder"
    Dim lstFiles As New List(Of String)
    lstFiles.AddRange(Directory.GetFiles(Directory, "*.*", SearchOption.TopDirectoryOnly).Where(Function(x) Not x.Contains(strSubDirectory)).ToList)

    Dts.Variables.Item("FilesList").Value = lstFiles

    Dts.TaskResult = ScriptResults.Success
End Sub
</code>```

In the For each Loop Container Choose the Enumertaion Type as From variable Enumerator and choose FilesList variable as a source

ScreenShots

Using Expression Task

For more details you can refer to my answer in the following link (it is a similar case) WildCards in SSIS Collection {not include} name xlsx

Title: Exclude specific Sub Folders

Body:
Using Execute Script Task

Get List of - filtered - files using an Execute Script Task before entering Loop and loop over then using ForEach Loop container (Ado enumerator)

You have to a a SSIS variable (ex: User::FilesList) with type System.Object (Scope: Package)

Add an Execute Script Task before the for each Loop container and add User::FilesList as a ReadWrite Variable

In the Script Write The following Code:

Imports System.Linq
Imports System.IO
Imports System.Collections.Generic

Public Sub Main()
    Dim Directory as String = "C\Temp"
    Dim strSubDirectory as String = Directory & "\New Folder"
    Dim lstFiles As New List(Of String)
    lstFiles.AddRange(Directory.GetFiles(Directory, "*.*", SearchOption.TopDirectoryOnly).Where(Function(x) Not x.Contains(strSubDirectory)).ToList)

    Dts.Variables.Item("FilesList").Value = lstFiles

    Dts.TaskResult = ScriptResults.Success
End Sub

In the For each Loop Container Choose the Enumertaion Type as From variable Enumerator and choose FilesList variable as a source

ScreenShots

Using Expression Task

For more details you can refer to my answer in the following link (it is a similar case) WildCards in SSIS Collection {not include} name xlsx


问:
TableView resizing parent view iOS
This is a problem that has been bugging me for quite some time.

Assume a view that holds a tableView with X items. The goal is to make that view resize so that it is as high as the contents of the tableView.

An approach

Calculate the contents of the tableView in total ( e.g if there are 5 rows and each is 50 units high, its just a multiplication matter ). Then set the tableView constrained at a  0 0 0 0 into the view and set the view height to 250.

This works well for fixed height cell sizes. However!

a) How would the problem be approached for dynamic height cells though with complex constraints in a scenario where resizing happens automatically and the tableHeightForRow is set to UITableViewAutomaticDimension?

b) An idea could be using tableView.contentSize. However when would we retrieve that value safely in order to set the parent view frame accordingly? Is that even possible?

Thanks everyone

答:
If you have a UITableView subclass, you can set up a property observer on the contentSize like this:

```<code>override var contentSize: CGSize {
        didSet {
            // make delegate call or use some other mechanism to communicate size change to parent
        }
    }
</code>```

The most straightforward approach to this in my opinion is to use Autolayout. If you take this approach, you can use the contentSize to automatically invalidate the intrinsicContentSize which is what autolayout uses to dynamically size elements (as long as they don't have higher priority placement constraints restricting or explicitly setting their size).

Something like this:

```<code>override var contentSize: CGSize {
        didSet {
            self.invalidateIntrinsicContentSize()
        }
    }

override var intrinsicContentSize: CGSize {
        return contentSize
    }
</code>```

Then, just add your table view to your parent view hierarchy with valid placement constraints and a content hugging/compression resistance of required.

Title: TableView resizing parent view iOS

Body:
If you have a UITableView subclass, you can set up a property observer on the contentSize like this:

override var contentSize: CGSize {
        didSet {
            // make delegate call or use some other mechanism to communicate size change to parent
        }
    }

The most straightforward approach to this in my opinion is to use Autolayout. If you take this approach, you can use the contentSize to automatically invalidate the intrinsicContentSize which is what autolayout uses to dynamically size elements (as long as they don't have higher priority placement constraints restricting or explicitly setting their size).

Something like this:

override var contentSize: CGSize {
        didSet {
            self.invalidateIntrinsicContentSize()
        }
    }

override var intrinsicContentSize: CGSize {
        return contentSize
    }

Then, just add your table view to your parent view hierarchy with valid placement constraints and a content hugging/compression resistance of required.


问:
How to secure passwords in the Software Development?
how do you secure your passwords in propertie Files?
Encryption / Encoding?

Or do you use a different approach to handle Database User / Passwords for connection Strings?

Thanks for you help!

Update: Thanks for your responses! In this special case we talk about two tier architecture. We have many clients with direct connections to the databases. Propertie Files are on a network share.

答:
I think for your usual three-tier web application, the secrecy of your database username and password is not something that you care about too much, because you can control network security. Look at MongoDB for example, where passwords are optional and not supported by all configurations. You need to set your database server to only accept connections from your own application servers anyway.

You have multiple accounts (with associated permissions) mostly to protect yourself from accidents, not to really keep separate people apart from each other.

There is no way end users can connect to the database directly.

So keeping the connection credential in an unencrypted property file on the server is fine. If someone gets to the server, you are already in trouble anyway.

Better keep this file outside of the source repository, though.