text:
Q: Alter div content using jQuery and save result to variable I have content on a page that contains ads. I need to be able to pull the content of this page using jQuery and strip the ads from the content. I have gotten this to work, but it also alters the elements on the page. I need to get a variable that contains a clean version of the html inside the div, but strip all of the ads.
I had hoped that something like this would work, but it doesnt. is there anything i can do to make it save the html of "postbody" with the changes from the "find/remove" method applied, without altering the live content on the page.
var content = jQuery('#postbody').find('.adsbygoogle').remove().html();

When i run the above command, it does what i want it to do, but it removes the content from the actual post on the page.
There also appears to be some code in the adsense library that prevents me from getting the page content, saving it to a placeholder. Altering the page, get the content without ads then replacing it all with the content from the placeholder variable.

A: You can try something like this:
$postbody = $("#postbody").clone();
$postbody.find('.adsbygoogle').remove();
return $postbody.html();


text:
Q: Angular js ellipsis Is there any way where we can use angular js to substring the string and add the ellipsis at the end while ignoring the anchor tag if it is coming inside the substring?
For example, my text is:

Lorem Ipsum has been the industry's standard
  dummy text ever since the 1500s when an unknown printer took a
  galley of type and scrambled it to make a type specimen book.

I can only show the text up to 70 characters after that ellipsis.
In this case, from "55 - 100 approx" is anchor link, substring chips the string from 0,70 and create a bad string with broken anchor link.
On HTML, I am using:
> data-ng-bind-html

to parse the Substring.
How can we ignore   Tags inside the string and substring other content?
Don't want to use CSS as content can be of any length.
Filter used:
filter('customEllipsis', function() {
        return function(input, number) {
            if (input) {
                return input.length > number ? input.substring(0, number) + '...' : input;
            }
        };
    });

A: Use Angular sanitizer to parse html. See this jsbin for an example of usage.
app.filter('customEllipsis', function($sce) {
  return function(input, number) {
    if (input) {
      input = input.length > number ? input.substring(0, number) + '...' : input;
      input = $sce.trustAsHtml(input);
      return input;
    }
  };
});

A: You can use Angular's  built-in filter  limitTo

A: Here is a solution that:

*

*Converts the HTML content to a DOM document

*Performs a depth-first traversal of the document

*Evaluates all text nodes, cuts off after the maximum length has been reached, and adds the ellipsis

*Discards remaining nodes

*Serializes the result back to HTML

The snippet below contains the complete implementation. It ends with an example in which the example string
Click this absolutely ah-mah-zing link to access Stackoverflow.
gets limited to 20, 25, 30, 35, 40, 45 and 50 characters respectively.
Run the code snippet to see the results.

function limit(string, maxLength) {
  let visit = function(node) {
    if (count < maxLength) {
      if (node.nodeType === Node.TEXT_NODE) {
        let left = maxLength - count;
        let length = node.nodeValue.length;

        if (length > left) {
          node.nodeValue = node.nodeValue.substring(0, left) + '...';
          count += left;
        } else {
          count += length;
        }
      } else {
        for (let childNode of Array.from(node.childNodes)) {
          visit(childNode);
        }
      }
    } else {
      node.remove();
    }

    return node;
  };
  let dom = new DOMParser().parseFromString(string, "text/html");
  let tree = dom.body;
  let count = 0;

  return visit(tree).innerHTML;
}

let string = 'Click this absolutely ah-mah-zing link to access Stackoverflow.';

document.getElementById('container').innerHTML = [20, 25, 30, 35, 40, 45, 50]
        .map(maxLength => limit(string, maxLength))
        .join('
');

Advantages

*

*It preserves all relevant tags, even nested tags

*It's precise because the HTML tags and attributes are not taken into account to determine how many characters to display.

Disadvantages

*

*Performance might not be stellar, although there's still room for optimization (e.g. the serializing back to HTML can be skipped, the DOMParser instance can be shared, etc.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling a function in from main() I've just started to learn C, and right now I find it a bit confusing how to call one function from another. Here's my little project, I thought that writhing the line "int result = timeToWork;" would be enough to call that function, but the warning "initialization of 'int' from 'int(*)(int)' makes integer from pointer without a cast" appears. The project compiles, but the result is some weird numbers instead of printing the line. What am I doing wrong?
#include<stdio.h>
int timeToWork(int input);
int main()
{
    printf("Please, enter the number  \n");
    int key = 0;
    fflush(stdout);
    scanf("%d", &key);
    int result = timeToWork;
    printf("Time = %d  \n",timeToWork);

    return 0;
}
int timeToWork(int input)
{
    if(input == 1)printf("It will take you 25 minutes to get to your destination by car  \n");
    else if(input == 2)printf("It will take you 20 minutes to get to your destination by bike  \n");
    else if(input == 3)printf("It will take you 35 minutes to get to your destination by bus  \n");
    else if(input == 4)printf("It will take you 30 minutes to get to your destination by train  \n");
    else printf("ERROR: please, enter a number from 1 to 4  \n");

    return 0;
}

A: The function has one parameter.
int timeToWork(int input);

So how are you going to call it without passing an argument to the function?
int result = timeToWork;

Even if a function does not accept an argument you have to specify parentheses after the function deisgnator.
In the declaration above the function designator is just converted to pointer to the function
it looks like
int( *fp )( int ) = timeToWork;
int result = fp;

To call the function you should write
int result = timeToWork( key );

And instead of
printf("Time = %d  \n",timeToWork);

it is evident you mean
printf("Time = %d  \n", result);

Though the function is defined incorrectly because it always returns 0.
I think the function should be declared and defined the following way
int timeToWork( int input )
{
    int time = 0;

    if(input == 1)
    {
        printf("It will take you 25 minutes to get to your destination by car  \n");
        time = 25;
    }
    else if(input == 2)
    {
        printf("It will take you 20 minutes to get to your destination by bike\n");
        time = 20;
    }
    else if(input == 3)
    {
        printf("It will take you 35 minutes to get to your destination by bus  \n");
        time = 35;
    }
    else if(input == 4)
    {
        printf("It will take you 30 minutes to get to your destination by train  \n");
        time = 30;
    }
    else
    {
         printf("ERROR: please, enter a number from 1 to 4  \n");
    }

    return time;
}

A: Your function timeToWork expects an input.
It should be int result = timeTowork(key);
Also, what are trying to print here?:
printf("Time = %d  \n",timeToWork);

A: You need to be sending in a parameter of type int as the function is expecting it.
int result = timetowork(#your input goes here);


text:
Q: An inner product inequality In this article: http://rgmia.org/papers/v7e/RBKIIPS.pdf, the author claims that the inequality (after (2.4))
$$\frac{|\langle a,x\rangle \langle x,b\rangle|}{\|x\|^2} \leq \frac{1}{|\beta|}\left[|\langle a, b\rangle|+\frac{\|b\|}{\|x\|}\right]\left[|\beta-1|^2|\langle x,a\rangle|^2+\|x\|^2\|a\|^2-|\langle x,a\rangle|^2\right]^{\frac{1}{2}} $$
holds for arbitrary complex vectors $a,x,b$ and complex scalar $\beta \neq 0$ (The author uses $\alpha$ istead of $\beta$, which becomes a little difficult to read, so I wrote $\beta$ here.).
Well, let us set $a,x,b$ to be unit vectors that are all equal to each other, and suppose that $\beta$ is real and $\geq 1$. We get the inequality
$$1 \leq \frac{2(\beta-1)}{\beta},$$ which fails for $1 \leq \beta < 2$. What am I missing here?

A: The inequality is indeed wrong. If you follow the derivation it should be
$$\frac{|\langle a,x\rangle \langle x,b\rangle|}{\|x\|^2} \leq \frac{|\langle a, b\rangle|}{|\beta|}+\frac{\|b\|}{|\beta|\|x\|}\left[|\beta-1|^2|\langle x,a\rangle|^2+\|x\|^2\|a\|^2-|\langle x,a\rangle|^2\right]^{\frac{1}{2}} $$
They misplaced one of the square brackets. Pay close attention to the square brackets in the first inequality in (2.5) - they are correct.


text:
Q: PHP: Understanding string type juggling If I set $var to a string in PHP, that variable will evaluate to true in any conditions:
$var = "foo";
if ( $var ) {
    echo 'I will be printed';
} else {
    echo 'I will not be printed';
}

I understand that my condition above automatically does type juggling so that $var is converted in a bool.
Now, if I cast $var to an integer, I get 0:
var_dump( (int)$var ); // int(0)

0 is a falsy value which becomes false when converted to a bool:
$zero = 0;
var_dump( (bool)$zero ); // bool(false)

Considering the above, why doesn't my condition print "I will not be printed"?

A: Type juggling isn't lossless. It comes with potential loss of data.
For instance...
var_dump( strval(intval("foo"))); // string(1) "0"

But if you were to write...
if( "foo" == "0") // non-strict comparison intended

You would surely not expect it to run! And indeed it doesn't.
So because type changes come with data loss, you can't expect conversions to be equivalent. In other words, boolval(intval($var)) and boolval($var) need not be the same.
If you want to be strict in your comparisons, use something like this:
if( is_string($var) && $var !== "") // is not the empty string

(Arguably !== is redundant and != works fine, but arguably this whole condition is overkill)

A: Here is a simple test of truth:
$s = array( // bool  (int)cast
    '',     // FALSE int=0
    'Test', // TRUE  int=0
    '0.0',  // TRUE  int=0
    '124',  // TRUE  int=124
    '000',  // TRUE  int=0
    '0',    // FALSE int=0
    NULL    // FALSE int=0
);

foreach( $s as $var )
    echo $var . ' // '
        . ( $var ? 'TRUE' : 'FALSE' ) . ' '
        . 'int=' . (int)$var . PHP_EOL;

In case of a string casting to bool, FALSE is an empty string, NULL and the value '0'. Everything else is TRUE. See the manual on false.
In your case, $var is a string "foo", which is not being converted to FALSE since it is neither NULL, "0" or "", therefore you will not get 'I will not be printed'.
If you cast it to an INT, everything is 0 except a pure numerical value.

A: You will not get the else echo done, as a string that is not empty evaluates to true when used in an if, i.e.:
$foo = "Hello";
if ($foo)
    print "True"; //This will print as a string is true if not empty
else
    print "False"; //Doesn't print as string is not empty

Try this:
$foo = "Hello";
if ((int)$foo)
    print "True";
else
    print "False"; //Will print as the string evaluates to 0 (false) as it is not an integer


text:
Q: Efficient way to use max_by with multiple conditions I've been trying to figure out how to use max_by and max methods, with multiple conditions. While I thought I did, after extensive testing it turned out not to be the case.
For example, I have a hash whose values are hashes:
chapters = { "686050": {
        "volume": '1',
        "chapter": '1',
        "title": 'Chapter Title',
        "lang_code": 'gb',
        "timestamp": 1_565_434_815
      },
      "686049": {
        "volume": '2',
        "chapter": '1',
        "title": 'Chapter Title',
        "lang_code": 'gb',
        "timestamp": 1_565_300_815
      },
      "686048": {
        "volume": '2',
        "chapter": '2',
        "title": 'Chapter Title',
        "lang_code": 'gb',
        "timestamp": 1_565_300_815
      }
    }

I want to find one hash, that has the maximum volume AND chapter. So in this case, I am expecting to get the one with volume 2 and chapter 2.
My first implementation was using max:
chapters.max do |a, b|
  a[1][:volume].to_d <=> b[1][:volume].to_d &&
    a[1][:chapter].to_d <=> b[1][:chapter].to_d
end

When looking at this, my thinking was that it would first compare by volume and then by chapter. This code have worked... until I changed the hash to be:
  "686050": {
    "volume": '1',
    "chapter": '1',
    "title": 'Chapter Title',
    "lang_code": 'gb',
    "timestamp": 1_565_434_815
  },
  "686049": {
    "volume": '2',
    "chapter": '1',
    "title": 'Chapter Title',
    "lang_code": 'gb',
    "timestamp": 1_565_300_815
  }

Which suddenly started to return the one with volume 1 and chapter 2! I am still unsure why this was happening...
So I decided to try max_by, using this chapters.max_by { |_, v| v[:volume].to_d && v[:chapter].to_d }, with the same assumption. Which also ended up failing for when there is a single chapter per volume.
My solution ended up being:
chapters
  .group_by { |_, v| v[:volume].to_d }.max.last.to_h
  .max_by { |_, v| v[:chapter].to_d }

Which works for obvious reasons, but feels quite inefficient. There must be a way to use a single max or max_by. Would love to hear some ideas on this

A: You may do the following.
def max_val(h,key)
  h.map { |_,g| g[key] }.max
end

max_volume = max_val(h, :volume)    #=> "2"
max_chapter = max_val(h, :chapter)  #=> "2"

chapters.find { |_,g| g[:volume] == max_volume && g[:chapter] == max_chapter }
  #=> [:"686048", {:volume=>"2", :chapter=>"2", :title=>"Chapter Title",
  #                :lang_code=>"gb", :timestamp=>1565300815}]

nil is returned if no value contains the maximum values of both keys. Replace find with select if all key-value pairs having the desired property are to be returned (i.e., if there are ties). That array would be empty if no value contains the maximum values of both keys.
This requires three passes through the hash. It could be done in a single pass but it's messy and I expect it would be more time-consuming, largely because Enumerable#map and Array#max are both implemented in C.
The desired result could be obtained in a single pass as follows.
max_volume  = 0.chr
max_chapter = 0.chr
candidate = [nil, {}]
chapters.each do |k,g|
  old_max_volume = max_volume
  max_volume = [max_volume, g[:volume]].max
  old_max_chapter = max_chapter
  max_chapter = [max_chapter, g[:chapter]].max
  if max_volume > old_max_volume || max_chapter > old_max_chapter
    candidate = (max_volume == g[:volume] && max_chapter == g[:chapter]) ?
     [k,g] : [nil, {}]
  end
end
candidate
  #=> [:"686048", {:volume=>"2", :chapter=>"2", :title=>"Chapter Title",
  #    :lang_code=>"gb", :timestamp=>1565300815}]

Now set:
chapters[:"686048"][:volume] = '1'

The first method above now returns nil, the second (one-pass), returns [nil, {}]

A: Enumerable#max_by
# example 1
a = %w[albatross dog horse]
a.max_by(2) {|x| x.length } #=> ["albatross", "horse"]

# example 2 - Arrays are compared in an "element-wise" manner
arrays = [['1', '1'], ['2', '1'], ['2', '2']]
arrays.max_by(2) { |arr| arr } #=> ["2","2"], ["2", "1"]

So
chapters.max_by { |_, elem| [elem[:volume], elem[:chapter]] }

Let's test
book1 = {
  "686050": {
    "volume": '1',
    "chapter": '1',
    "title": 'Chapter Title',
    "lang_code": 'gb',
    "timestamp": 1_565_434_815
  },
  "686049": {
    "volume": '2',
    "chapter": '1',
    "title": 'Chapter Title',
    "lang_code": 'gb',
    "timestamp": 1_565_300_815
  },
  "686048": {
    "volume": '2',
    "chapter": '2',
    "title": 'Chapter Title',
    "lang_code": 'gb',
    "timestamp": 1_565_300_815
  }
}

book2 = {
  "686050": {
    "volume": '1',
    "chapter": '1',
    "title": 'Chapter Title',
    "lang_code": 'gb',
    "timestamp": 1_565_434_815
  },
  "686049": {
    "volume": '2',
    "chapter": '1',
    "title": 'Chapter Title',
    "lang_code": 'gb',
    "timestamp": 1_565_300_815
  }
}

pp book1.max_by(2) { |_, elem| [elem[:volume], elem[:chapter]] }
pp book2.max_by { |_, elem| [elem[:volume], elem[:chapter]] }

outputs
# 1st test
[[:"686048",
  {:volume=>"2",
   :chapter=>"2",
   :title=>"Chapter Title",
   :lang_code=>"gb",
   :timestamp=>1565300815}],
 [:"686049",
  {:volume=>"2",
   :chapter=>"1",
   :title=>"Chapter Title",
   :lang_code=>"gb",
   :timestamp=>1565300815}]]

# 2nd test
[:"686049",
 {:volume=>"2",
  :chapter=>"1",
  :title=>"Chapter Title",
  :lang_code=>"gb",
  :timestamp=>1565300815}]


text:
Q: autocomplete freezes with up and down keys I have used primeng autocomplete and it is working fine. but with arrow up and down keys, after 3-4 hits it gets freezes and not able to move down or up. with mouse scroll, it is working smoothly. I have only 100 of records in the autocomplete.
I tried with 10 elements in the filter and call the next 10 with scroll event. In this case, also I am facing the same problem.
Any help will be much appreciated.


text:
Q: Get the value of return within class Goodday. The question is, how can I get the return value and pass to my other php file?
myclass.php file
class myClass{
function banner(){
    $sql = "Select * From tblBanner";
    $query = mysql_query($sql) or die (mysql_error());
    $row = mysql_fetch_assoc($query);
    $banner = $row;
return $banner;
}

}

my index.php file

include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner;
echo $ban;

This is what im trying to do. Im a newbie so spare with me. Thank you.

A: Like I already wrote in the comments, $banner->banner would be a property of the class "myClass". But you want to get a method, so you have to use $banner->banner().
myclass.php file
class myClass{
    function banner(){
        $sql = "Select * From tblBanner";
        $query = mysql_query($sql) or die (mysql_error());
        $row = mysql_fetch_assoc($query);
        $banner = $row;
        return $banner;
    }
}

my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner();

// example for array:

foreach($ban as $banner) {
    echo $banner;
}
// example for string:
echo $ban;

An example for $banner->banner:
myclass.php file
class myClass{

    public $banner = 'Banner Property';

    function banner(){
        $sql = "Select * From tblBanner";
        $query = mysql_query($sql) or die (mysql_error());
        $row = mysql_fetch_assoc($query);
        $banner = $row;
        return $banner;
    }
}

my index.php file
include 'myclass.php';
$banner = new myclass;
$ban = $banner->banner;
echo $ban;


text:
Q: cannot find C# netcore controller I have added a netcore controller in my existing IdentityServer4 project. Here is my code
namespace IdentityServer4.Quickstart.UI
{
  public class VersionController : Controller
  {
    IVersionService _repository;
    public VersionController(IVersionService repository)
    {
        _repository = repository;
    }
    [HttpGet(nameof(GetBackgroundId))]
    public IActionResult GetBackgroundId()
    {
        return new OkObjectResult(_repository.GetBackgroundId());
    }
    [HttpPut(nameof(SetBackgroundId))]
    public IActionResult SetBackgroundId([FromQuery]int id)
    {
        _repository.SetBackgroundId(id);
        return new NoContentResult();
    }
 }
}

I also have the following line of code in startup.cs
app.UseMvcWithDefaultRoute();

I can access the account controller by the following url
http://localhost:5001/account/login

However, I cannot access the version controller by the following url:
http://localhost:5001/version/GetBackgroundId

The error code is 404.
What is wrong?

A: You are missing a route prefix for controller. You are using attribute routing so you need to include the entire desired route.
The current GetBackgroundId controller action would map to
http://localhost:5001/GetBackgroundId

Add a route to the controller
[Route("[controller]")]
public class VersionController : Controller {
    IVersionService _repository;
    public VersionController(IVersionService repository) {
        _repository = repository;
    }

    //Match GET version/GetBackgroundId
    [HttpGet("[action]")]
    public IActionResult GetBackgroundId() {
        return Ok(_repository.GetBackgroundId());
    }

    //Match PUT version/SetBackgroundId?id=5
    [HttpPut("[action]")]
    public IActionResult SetBackgroundId([FromQuery]int id) {
        _repository.SetBackgroundId(id);
        return NoContent();
    }
 }

Also note the use of route tokens and that instead of newing up the responses, Controller already has helper methods that provide those results.
Reference Routing to controller actions in ASP.NET Core


text:
Q: SWRevealViewController with Google maps IOS Swift I am using SWRevealViewController with Google Maps.My rear view controller loads google map. Problem is that first time it loads google map with my current location correctly but when i redirect to different screen from menu and comes back to google map screen from menu again instead of going to my current location it goes to some where in UK.
My Code: For Google Map view controller
    override func viewDidLoad()
     {
   super.viewDidLoad()
   locationManager.delegate = self
   locationManager.requestWhenInUseAuthorization()

   searchResultController = SearchResultsController()
   searchResultController.delegate = self

   dispatch_async(dispatch_get_main_queue(), { () -> Void in
       self.mapView.myLocationEnabled = true
   })

   if revealViewController() != nil {
       menuButton.target = self.revealViewController()
       menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
       self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
   }
 }

  func locateWithLongitude(lon: Double, andLatitude lat: Double, andTitle title: String) {

   dispatch_async(dispatch_get_main_queue()) { () -> Void in

       let position = CLLocationCoordinate2DMake(lat, lon)
       let marker = GMSMarker(position: position)

       let camera = GMSCameraPosition.cameraWithLatitude(lat, longitude: lon, zoom: :sunglasses:
       self.mapView.camera = camera

       marker.title = "Address : \(title)"
       marker.map  = self.mapView
   }
}

  func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
 {
   if status == CLAuthorizationStatus.AuthorizedWhenInUse
   {
       locationManager.startUpdatingLocation()
       mapView.myLocationEnabled = true
       mapView.settings.myLocationButton = true
   }
 }

  func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

   if let location = locations.last {
       mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 8, bearing: 0, viewingAngle: 0)
       locationManager.stopUpdatingLocation()
   }
  }

  func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {

   let placeClient = GMSPlacesClient()
   placeClient.autocompleteQuery(searchText, bounds: nil, filter: nil) { (results,error: NSError?) -> Void in

       self.resultsArray.removeAll()
       if results == nil{
           return
       }

       for result in results! {
           //if let result  = result as? GMSAutocompletePrediction {
           self.resultsArray.append(result.attributedFullText.string)
       }
       self.searchResultController.reloadDataWithArray(self.resultsArray)
   }

storyboard


text:
Q: Converting issue in java - xlsx to csv problem I am currently working on a small program to automatically convert xlsx files to csv, but it does not really work.
It has an input file and an output file, the details are in the codesnippet.
You need the followings:
import java.io.*;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Can you please help me fix it? Thanks
static void convertToXlsx(File inputFile, File outputFile) {
    // For storing data into CSV files
    StringBuffer cellValue = new StringBuffer();
    try {
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook instance for XLSX file
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));

        // Get first sheet from the workbook
        XSSFSheet sheet = wb.getSheetAt(0);

        Row row;
        Cell cell;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();

        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {

                    case Cell.CELL_TYPE_BOOLEAN:
                        cellValue.append(cell.getBooleanCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_NUMERIC:
                        cellValue.append(cell.getNumericCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_STRING:
                        cellValue.append(cell.getStringCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_BLANK:
                        cellValue.append("" + ",");
                        break;

                    default:
                        cellValue.append(cell + ",");

                }
            }
        }

        fos.write(cellValue.toString().getBytes());
        fos.close();

    } catch (Exception e) {
        System.err.println("Exception :" + e.getMessage());
    }
}

static void convertToXls(File inputFile, File outputFile) {

    StringBuffer cellDData = new StringBuffer();
    try {
        FileOutputStream fos = new FileOutputStream(outputFile);

        // Get the workbook instance for XLS file
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
        // Get first sheet from the workbook
        HSSFSheet sheet = workbook.getSheetAt(0);
        Cell cell;
        Row row;

        // Iterate through each rows from first sheet
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            row = rowIterator.next();

            // For each row, iterate through each columns
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                cell = cellIterator.next();

                switch (cell.getCellType()) {

                    case Cell.CELL_TYPE_BOOLEAN:
                        cellDData.append(cell.getBooleanCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_NUMERIC:
                        cellDData.append(cell.getNumericCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_STRING:
                        cellDData.append(cell.getStringCellValue() + ",");
                        break;

                    case Cell.CELL_TYPE_BLANK:
                        cellDData.append("" + ",");
                        break;

                    default:
                        cellDData.append(cell + ",");
                }
            }
        }

        fos.write(cellDData.toString().getBytes());
        fos.close();

    } catch (FileNotFoundException e) {
        System.err.println("Exception" + e.getMessage());
    } catch (IOException e) {
        System.err.println("Exception" + e.getMessage());
    }
}

public static void main(String[] args) {
    File inputFile = new File("C:\input.xls");
    File outputFile = new File("C:\output1.csv");
    File inputFile2 = new File("C:\\Users\\lendvaigy\\Desktop\\AKK\\DOWNLOAD TEST\\legjobb-eladasi-es-veteli-hozamok-arfolyamok.xlsx");
    File outputFile2 = new File("C:\\Users\\lendvaigy\\Desktop\\AKK\\DOWNLOAD TEST\\legjobb-eladasi-es-veteli-hozamok-arfolyamok.csv");
    convertToXls(inputFile, outputFile);
    convertToXlsx(inputFile2, outputFile2);
}

The main problem is that I am not a professional one, just a DIY rookie trying to create small programs.

A: The problem in your code is in convertToXls(). For converting xls to csv file use XSSFWorkbook instead of HSSFWorkbook.
Try changing following in convertToXls().
static void convertToXls(File inputFile, File outputFile) throws IOException {
    Workbook wb = new XSSFWorkbook(inputFile.getPath());
    DataFormatter formatter = new DataFormatter();
    PrintStream out = new PrintStream(new FileOutputStream(outputFile), true, "UTF-8");
    Sheet sheet =wb.getSheetAt(0);
        for (Row row : sheet) {
            boolean firstCell = true;
            for (Cell cell : row) {
                if (!firstCell)
                    out.print(',');
                String text = formatter.formatCellValue(cell);
                out.print(text);
                firstCell = false;
            }
            out.println();
    }
}

And rest should work as it is.


text:
Q: Select a proportionate stratified random sample, where stratification is based on sites and gender I have three IDBs and this is the number of people registered from each
Site     female  Male  Total
IDB_A     46      14    60
IDB_B     17      23    40
IDB_C     79      21    100
Total     142     58    200

And this is the sample I want to select from each site
Site     female  Male  Total
IDB_A     20      6     26
IDB_B     7       10    17
IDB_C     34      9    43
Total     60     25    85

And I used the following code by creating three different strata (one for each site) and then selected a random sample from each stratum
str1 <- FBF_PDM[FBF_PDM$Sites=="IDB_A",]
str2 <- FBF_PDM[FBF_PDM$Sites=="IDB_B", ]
str3 <- FBF_PDM[FBF_PDM$Sites=="IDB_C", ]

sample1 <- str1[sample(1:nrow(str1), 26, replace = FALSE), ]
sample2 <- str2[sample(1:nrow(str2), 17, replace = FALSE), ]
sample3 <- str3[sample(1:nrow(str3), 43, replace = FALSE), ]

overall <- rbind(sample1, sample2, sample3)

write.table(overall, "overall2.csv", row.names = FALSE, sep = ",")

However, Am struggling to specify the gender (male, female) to be selected from each site.

A: Using Map you could apply a subsetted sample function to your desired plan. Together with a splited data set by site, provide sample sizes for the respective sex.
plan
#    Site female Male Total
# 1 IDB_A     20    6    26
# 2 IDB_B      7   10    17
# 3 IDB_C     34    9    43
# 4 Total     60   25    85

set.seed(42)  ## you should set a seed here to make it reproducible
samp <- Map(\(x, y, z)
            rbind(
              x[x$female == 1, ][sample(sum(x$female == 1), y), ],
              x[x$female == 0, ][sample(sum(x$female == 0), z), ]
            ), split(dat, dat$site), plan[-4, ]$female, plan[-4, ]$Male)

## check
lapply(samp, \(x) with(x, table(female)))
# $IDB_A
# female
# 0  1
# 6 20
#
# $IDB_B
# female
# 0  1
# 10  7
#
# $IDB_C
# female
# 0  1
# 9 34

Data:
dat <- structure(list(site = c("IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A",
"IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_A", "IDB_B",
"IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B",
"IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B",
"IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B",
"IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B",
"IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_B",
"IDB_B", "IDB_B", "IDB_B", "IDB_B", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C",
"IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C", "IDB_C"), female = c(1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0), X = c(-1.80440994496324, -1.12182260635522,
-0.34792960655914, 1.23890214863198, -0.274197564852279, 0.162380715558193,
-0.0646069097530627, -0.705237097025142, 1.36219726875099, -1.09651318808332,
-0.228433518546891, -0.347828080610269, 0.532128619506733, 1.60723456226119,
0.513814526116594, 1.38237316057303, 0.763097048549903, -0.624584544634111,
0.0815438004289869, 1.37607911136477, -1.56126578615704, 0.324770660594699,
-0.156790316952238, 0.877783860734352, 0.750166575180638, 0.30105340384283,
1.49281111722931, -1.5254938001697, 0.910717558486022, -1.57953202785754,
0.587716257118581, 0.0896422960007244, 0.96726165694984, 0.0788123529148234,
-1.56869983648609, -2.00782318401609, 0.540973524238763, -0.0733765981084255,
-0.571018393558081, -0.311068459853641, -0.671415067101365, -0.157340452080979,
-0.931305070999869, -1.98300947947013, -0.219599804249378, 1.04527586946239,
1.87732956629967, 0.00260619595716637, -0.0806699347091655, 0.96298228123987,
0.0535710165465174, -0.434898408910037, -1.73729725534231, -1.26369559978243,
0.406308512069273, -1.45965396777976, 1.0484573701547, -1.3464305394502,
-0.193570558113494, -0.00233595711367605, -0.0128297338671881,
0.151947321984398, 0.598511131401079, -0.126212437298279, -0.248535565846776,
0.160327394904622, -0.433641941597269, 1.53741241910027, -2.17024657661608,
1.02700461929143, -0.248482933189933, 0.422320385832393, 0.987653293639674,
0.835568172035023, -0.660521859045705, 1.56406949329184, -1.62297593529155,
0.863896373478988, -0.5116027734362, -1.9173650254454, -1.86581384861995,
0.245179063439689, 2.22353430190807, 0.273376064144465, 1.13078479452828,
0.838669374060099, -0.654615277878206, 0.953960978479396, 0.352951465489323,
0.206599292649613, 1.00111323431025, 0.747451991640276, -0.626574836723139,
0.395223685936714, -0.892167954045577, 0.630818410091773, -0.432705183284567,
0.452138644218517, 0.367999045196345, -0.270387489661909, 0.465512617712979,
0.574356225626969, -0.230699990157411, 1.17224250830245, 1.39270270673312,
-0.661991255709585, -0.777369206725014, 0.51353857890878, -0.913312238041272,
-0.449423805250301, 0.802932699103618, -0.573476850981104, -1.92812516784833,
0.664390833822148, -1.60254022379425, -1.35460025745385, -3.0179326794179,
0.831237822230063, 0.251097088847344, 0.462293465941329, 0.844792223223237,
-0.0419715243215621, -1.10557590570003, 0.563775652330874, 1.30336475581967,
-1.50022093779466, -0.606989235119036, -0.292245065656577, -1.2896833433236,
0.694105848774699, -0.599181902897119, 1.25690664397164, 0.053508013627363,
0.728092517671852, 1.56109806821061, 0.26562475359719, 1.07672625920727,
0.210697931679245, -1.51167352582237, 0.022402259913625, 0.718136206042103,
0.48945701784227, -0.17388834587827, -1.2176994886684, 0.646398368709462,
-0.91645602834789, -1.25182344242557, 0.594927718405501, -1.23281066518983,
0.244364414906138, 0.00277218534359506, -1.32820968602556, 1.17969641183277,
-0.592804999148929, 1.19997831633667, -0.475033679612135, -0.575057096150816,
-0.031226024608499, -0.358056995978456, -0.356601077647731, -0.877664383433726,
-1.21289712517796, 0.613286618687034, -0.806203341462477, -1.3764569299089,
-0.507847899163547, -0.800935486737338, -2.19278568567007, -0.290937149267675,
0.167174121160518, 0.294692356485688, 0.392741265420726, -1.00084371300082,
-0.325727119823434, -1.00834880542884, -0.635431482033766, -1.20984068798734,
-1.11646380065269, 0.629881162575935, -0.272521570178626, -0.258841168378671,
1.72955817989149, -0.0583921654073717, -0.537063784608919, 0.74728669616574,
-0.487257835389733, 1.3729077814795, -0.377672360646221, -0.616152614118394,
-1.16812505107469, 0.328640358591086, 1.46651062744016, -0.356009545088913,
0.261467641877431, 0.333328855175731, 1.42219324030954, 0.663876600666173,
-1.07365515569531, -0.69690177466674, -0.746130456934561)), row.names = c(NA,
-200L), class = "data.frame")

plan <- read.table(header=TRUE, text='Site     female  Male  Total
IDB_A     20      6     26
IDB_B     7       10    17
IDB_C     34      9    43
Total     60     25    85')


text:
Q: capacitor value substitution I have an audio circuit im building from schematics. . The schematic calls for 30nF, 220nF, 6.8nF, 22nF, 5nF, and 2.2nF capacitors ...all of which I cannot find to order. . I even converted these values into microfarads and picofarads and can't locate these parts either. . Can I substitute a closer more common value capacitor for each of these?  I can send you the schematic if it helps answer my question

A: You must be looking in the wrong place. Go to digikey.com and enter the appropriate parametric search, and you'll find all the components you want:
http://www.digikey.com/product-search/en/capacitors/ceramic-capacitors/131083?k=capacitor
Substituting capacitors used for bypassing can work just fine; typically more is better in those cases (as long as ESR and voltage rating is sufficient.) Substituting capacitors used as part of a tuned filter is much less straightforward. Thus, to answer your question, we need to know the role of each of those capacitors.

A: If these capacitors form filters etc. then its not a good idea to just change values. The original design specified them for a reason. You could make up the values by series/parallel connections e.g. a 5nF can be made with 2 x 10nF connected in series, a 30nF can be made with three 10nF in parallel.


text:
Q: Provide a permalink to a query with parameters I've noticed that sometimes I get a "permalink" for a query that includes the parameters I gave. This is very inconsistent, and I failed to find out when it's provided and when it isn't.
So I have to construct the necessary URL by hand if I need to share the query results. I don't even know the syntax for this unless I accidentally came across a permalink with parameters in the past. (I did, and already forgot the syntax.)
So, I propose to either

*

*Always provide a permalink to a query, complete with parameters, that would give the same result that you've got, or

*Change the active page URL when I change the parameters so that I can copy it instead (I'll probably have to chop off #resultSets though, so this look inferior at first glance).


text:
Q: How to use a for loop to create new dataframes on each iteration of the loop? Currently, each iteration of the for loop is fed into the "sector" dataframe, which uses boolean indexing, and the results are exported to excel.
"ia sectors" is a list comprising string values e.g. healthcare, consumer_staples, property etc.
for item in ia_sectors:
 sector = all_data[all_data["IA Sector"] == item]
 sector.to_excel(str(item)+".xlsx")

Is it possible to modify the code such that each iteration of the for loop creates a new dataframe with the iterative names in item and their respective iterative results from the boolean indexing? e.g.
for item in ia_sectors:
 item0 = all_data[all_data["IA Sector"] == item0]
 sector.to_excel(str(item0)+".xlsx")
 item1 = all_data[all_data["IA Sector"] == item1]
 sector.to_excel(str(item1)+".xlsx")
 item2 = all_data[all_data["IA Sector"] == item2]
 sector.to_excel(str(item2)+".xlsx")

I would like to work with these new dataframes later on in the code.
Many thanks in advance.

A: IIUC,
dd = {}
ia_sector_data = all_data[all_date['IA Sector'].isin(ia_sectors)]

for n, g in ia_sector_data.groupby('IA Sector'):
    dd[n] = g
    g.to_excel(f'{n}.xls')

Now, your dataframes are accessible in a dictionary, dd.
Using dd['Sec1'] and so on.


text:
Q: group_by tidyverse in R I'm trying to create some baseball statistics and I'm looking to group some data by league. So I'm looking for runs/inning surrendered by relief pitchers, by league.
relief_pitching_stats %>%
  group_by(League) %>%
  summarise(
    total_inn = sum(IP),
    runs_per_inn = sum(total_ER) / sum(total_inn)
  )

I would expect the output to look something like
League  total_inn   runs_per_inn
AL      500         .5
NL      700         .4

Instead, I'm getting:
 total_inn runs_per_inn
1   18205.2    0.4630835

Can you tell me what I've done wrong here to not get the grouping correct. I expect given the differences in rules between the two leagues for the run/inning to be different, so I do want to group the stat by league.
thanks.
Here's what the df looks like when I load it into R.

> dput(head(relief_pitching_stats))
structure(list(Team = c("TBR", "CHW", "NYY", "SEA", "LAD", "SFG"
), League = c("AL", "AL", "AL", "AL", "NL", "NL"), W = c(58L,
32L, 48L, 45L, 41L, 49L), L = c(32L, 29L, 30L, 27L, 28L, 22L),
    SV = c(42L, 43L, 47L, 51L, 56L, 56L), G = c(531L, 512L, 512L,
    584L, 600L, 599L), GS = c(0L, 0L, 0L, 0L, 0L, 0L), IP = c(703,
    548, 606, 618.2, 608.2, 623.2), K.9 = c(9.46, 10.58, 10.02,
    9.06, 9.64, 8.37), BB.9 = c(2.82, 3.45, 3.36, 3.13, 3.98,
    2.73), HR.9 = c(1, 1.15, 1.08, 0.93, 0.89, 0.95), BABIP = c(0.278,
    0.298, 0.282, 0.286, 0.257, 0.262), LOB. = c("74.60%", "72.70%",
    "72.70%", "69.40%", "73.60%", "74.30%"), GB. = c("41.50%",
    "42.40%", "46.50%", "42.40%", "47.30%", "43.40%"), HR.FB = c("10.70%",
    "12.90%", "13.40%", "10.10%", "11.40%", "10.00%"), vFA..pi. = c(93.7,
    96, 95.5, 93.7, 94.2, 93.6), ERA = c(3.24, 3.97, 3.56, 3.88,
    3.16, 2.99), xERA = c(NA, NA, NA, NA, NA, NA), FIP = c(3.59,
    3.75, 3.76, 3.72, 3.83, 3.71), xFIP = c(3.98, 3.83, 3.78,
    4.18, 4.07, 4.2), WAR = c(7.9, 7.8, 7.5, 7, 6.5, 5.4), games_pitched = c(78.1111111111111,
    60.8888888888889, 67.3333333333333, 68.6888888888889, 67.5777777777778,
    69.2444444444445), total_ER = c(253.08, 241.728888888889,
    239.706666666667, 266.512888888889, 213.545777777778, 207.040888888889
    )), row.names = c(NA, 6L), class = "data.frame")
>


text:
Q: Exporting a native C function from a .net DLL? I have a .net assembly written in C#, and I'm looking to export a native C function from the assembly.
I have an application which will perform a 'LoadLibrary()' on any DLL's found in a 'plugin' folder.  After loading the DLL, the application performs a 'GetProcAddress' looking for a function named 'Register'.  The application expects this function to follow the C calling convention.
How can I export a function named 'Register' from my .net assembly, so I can successfully hookup with the plugin system for this application?
Thanks,
Andrew

A: Write a .Net library in Managed C++ and there you can export a "Native" method/function.

A: Have a look at Unmanaged Exports.

A: Sadly Microsoft does not support this feature, and you have to change the msil after the build to expose those methods.
It is possible as one guy has shown a reasonable solution
on codeproject or here,
but it requires a post build step and you are on your own after that.
I don't know if this hack will work on .net 4.0 or later though.
Hopefully Microsoft will listen to us and support this simple feature in C# since the CLR support is already there.

A: What you want is a Reverse P/Invoke. You can't actually embed a C function in a C# dll, if by that you mean a function actually implemented in C, but by following the tutorials given on the linked page you can create a DLL export that's callable by unmanaged C/C++ code.


text:
Q: how to solve $2(2y-1)^{\frac{1}{3}}=y^3+1$ how can I solve $2(2y-1)^{\frac{1}{3}}=y^3+1$
I got by $x=\frac{y^3+1}{2}$ that $y=\frac{x^3+1}{2}$ but I was told earlier that can't say that $x=y$.
So I can I solve this equation?
Thanks.

A: You correctly set $x^3=2y-1$, so the equation becomes
$$
\begin{cases}
2y=x^3+1\\
2x=y^3+1
\end{cases}
$$
Subtract them:
$$
2(y-x)=x^3-y^3
$$
or
$$
(x-y)(x^2+xy+y^2)+2(x-y)=0
$$
This factors as
$$
(x-y)(x^2+xy+y^2+2)=0
$$
but the second factor is positive for all $x$ and $y$, because $x^2+xy+y^2\ge0$.
Therefore you conclude $x=y$, so plugging in the equation $2y=x^3+1$ you get
$$
x^3-2x+1=0
$$
that's easy to solve because it factors as $(x-1)(x^2+x-1)=0$.

There is a different way to solve the particular problem, but using more general principles (thanks to ivancho for having suggested it).
Your equation is in the form
$$
f^{-1}(y)=f(y)
$$
where
$$
f(y)=\frac{y^3+1}{2}
$$
is an increasing function (hence invertible) taking on every real value. Decreasing would be the same, of course.
If $y$ is a solution of your equation and we set $x=f(y)$, then from $f^{-1}(y)=f(y)$ we get $f^{-1}(y)=x$ and so $y=f(x)$.
Suppose $(x,y)$ is a solution of $x=f(y)$ and $y=f(x)$. If we had $x<y$, then, by the fact that $f$ is increasing, we would have
$$
f(x)<f(y)
$$
so $y<x$. Similarly, from $x>y$ we get $f(x)>f(y)$ or $y>x$. In both cases we get a contradiction.

A: By cubing you get
$$ y^9+3 y^6+3 y^3 - 16 y + 9 = 0$$
It factors (using Wolfram alpha) into
$$ (y-1) (y^2+y-1) (y^6+2 y^4+2 y^3+4 y^2+2 y+9) = 0$$
According to WA, all the roots of the last polynomial are complex. The second one has $ \frac{(-1-\sqrt{5})}{2}$ and $ \frac{(\sqrt{5}-1)}{2}$ as roots. I don't know if you can get exact forms for the other (complex) roots.

A: Letting $t=\sqrt[3]{2y-1}$ we have $y=\dfrac{t^3+1}2$ . Replacing, we have a nonic equation in t, which has $t=1$ and $t=\dfrac{-1\pm\sqrt5}2$ among its roots, the remaining six belonging to an irreducible sextic, all of which are complex.


text:
Q: Create a new Controller manually and face with "View not Found" error in Yii I use basic template of yii, i create a new controller manually in Controllers Folder and name it CountryController.php and put bellow codes in it.
<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;

class CountryController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }
}

But when i type http://localhost/sites/basic/web/index.php?r=country%2Findex in browser i get following Exception:

View not Found yii\base\ViewNotFoundException

This is image of the error
On the other side when i type http://localhost/sites/basic/web/index.php?r=site%2Findexin the browser it renders index view correctly.
Why this happen? can i create a Controller manually? How?

A: The error message is not saying it can't find the page, just that it can't find the view file. Along with your controller, you should also have created a view file app\views\country\index.php This is the file you are referring to when you call `$this->render('index').


text:
Q: Picking a port for listening to a response/keeping socket open? I've got a client app which has to connect to a server and register for waiting, that is, it wants to be notified when the server is done with some processing. Ideally, I want to keep this client as simple as possible, but the question is, how to "register for waiting". I could keep the socket open and do a blocking read, and as soon as the server is done, it'll send some data to the client and I'm done; unfortunately this blocks one port on the server for quite some time.
What alternatives are there? I could pick a random port on the client side, and listen for a connection there, but this requires me to pick a free random port -- and I'm not sure how to do this best in C#? I thought about checking the local port used while sending to the server, and re-using this; I wonder if there is some recommended way to solve this. Polling from the client is out of question, as the time between finish and notification shouldn't be too long.

A: Pass 0 as the port number to the IPEndPoint constructor:

Socket.Bind Remarks on MSDN:
If you do not care which local port is used, you can create an IPEndPoint using 0 for the port number. In this case, the service provider will assign an available port number between 1024 and 5000.
If you use the above approach, you can discover what local network address and port number has been assigned by calling the LocalEndPoint. If you are using a connection-oriented protocol, LocalEndPoint will not return the locally assigned network address until after you have made a call to the Connect or EndConnect method. If you are using a connectionless protocol, you will not have access to this information until you have completed a send or receive.


text:
Q: Why does using conditional logic in gravity forms break the form when placed using php I have a form built using gravity forms...
I am placing this form onto my page using PHP like this...
// set our form ID 'Order Checkout'
$form_id = 1;

// enqueue the necessary styles and scripts into head
gravity_form_enqueue_scripts($form_id,true);

...

// place my form onto page
gravity_form($form_id,false,true,false,null,true);

This works nicely and submits nicely...

But then when I apply conditional logic to a field, which validates and saves ok. The output on the page is this...

Form appears missing.
But in the inspector you can see all the scripts/styles and the form html have loaded ok, but for some reason on #gform_wrapper_1 it has style="display:none;" applied to it.

If remove the inline style, all the conditional logic fields are visible and the conditional logic doesn't work.
Absolutely no console errors.
Any ideas why I might be seeing this. Thanks


text:
Q: Excel VBA Click Cell to Fire Macro - Not working with Merged Cells I am using the code below to fire a macro on the click of a cell. The cell in question is a header "Mitch's Macro" but it on merged cells B5 through J5. I have tried naming this merged range to MITCH, but it still doesnt run on click... Any ideas? Thank you in advance!
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("MITCH")) Is Nothing Then
            MsgBox ("Hello World")
        End If
    End If
End Sub

A: The problem is Selection.Count = 1.
The merged cells have more than one cells so once you select any cell in the merged area, the code doesn't get executed.
Please give this a try...
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("MITCH")) Is Nothing Then
        MsgBox ("Hello World")
    End If
End Sub

Edit:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rng As Range
    Set rng = Range("MITCH")
    If Target.CountLarge > rng.Cells.Count Then Exit Sub
    If Not Intersect(Target, rng) Is Nothing And Target.Cells(1).Address = rng.Cells(1).Address Then
        MsgBox ("Hello World")
    End If
End Sub

A: After a little more thinking I realised that most answers have a few drawbacks, and I think this is what we're really after:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rng As Range
    Set rng = Range("MITCH")
    If Target.Address = rng.MergeArea.Address Then 'check if what's selected matches the named range entirely
        MsgBox ("Hello World")
    End If
End Sub

As this checks whether the cells you have selected perfectly map onto the named area - specifically the MergeArea of the named range.
Matching with Intersect just checks if the selection contains the named Range
Matching by TL cell means any selection with the same TL as the named Range will also return a positive. E.g, if [B2:D3] is your merged named range, then matching by [B2] will return positive if [B2:D3] is selected (as expected), but also when [B2:XX100] is selected
This code only returns positive when the areas are identical, i.e. only the merged cell is selected.

A: If you have named the range you could use the code below
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim tName As String
    On Error Resume Next
    tName = Target.Name.Name
    On Error GoTo 0
    If Len(tName) > 0 Then
        If tName = "MITCH" Then
            MsgBox ("Hello World")
        End If
    End If
End Sub


text:
Q: How to represent direction in a route in google maps? In a project I'm displaying a route using PolylineOptions for drawing rects from one POI to the next POI.
Also in each POI I'm drawing a circle.
The objective is to represent the direction of the route in some way, for example, drawing an arrow in the middle of each PolylineOptions rect. The problem is that I can't find how to do this.
This is my code:
    PolylineOptions rectOptions = new PolylineOptions();
    float[] prevHSV = new float[3];
    Color.colorToHSV(getResources().getColor(R.color.colorPrimary), prevHSV);
    rectOptions.color(Color.HSVToColor(255, prevHSV));

    String[][] routeInformation = ((MyApplication)getApplication()).getLineInformation(line);
    ArrayList<Double[]> routeStops = Util.getFullRouteFromLine(this, line);
    final LatLngBounds.Builder builder = new LatLngBounds.Builder();

    for (int i=0; i<routeInformation.length; i++){
        LatLng latlng = new LatLng(Double.parseDouble(routeInformation[i][0]),Double.parseDouble(routeInformation[i][1]));
        builder.include(latlng);
        mMap.addCircle(new CircleOptions().center(latlng).radius(15).strokeColor(Color.HSVToColor(255, prevHSV)).fillColor(Color.HSVToColor(255, prevHSV)).zIndex(7777));
    }

    for (Double[] pos : routeStops){
        rectOptions.add(new LatLng(pos[0],pos[1])).width(5);
    }
    mMap.addPolyline(rectOptions);

Is there a easy way to represent the direction of a route?
Something similar to this, but this is for the web version of google maps, not for the android version: http://jsfiddle.net/nX8U8/2/

A: IMHO easiest way is to use flat "north-oriented" direction marker (arrow) like that:

created via vector drawable ic_arrow_up.xml:
<vector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:viewportHeight="560"
    android:viewportWidth="560"
    android:height="24dp"
    android:width="24dp"
    >
    <path android:fillColor="#0000FF"
        android:pathData="M0,559.43C0,557.943 279.994,-0.561 280.458,0C282.014,1.884 560.512,559.569 559.999,559.776C559.665,559.911 496.562,532.823 419.77,499.581C419.77,499.581 280.15,439.14 280.15,439.14C280.15,439.14 140.756,499.57 140.756,499.57C64.089,532.807 1.056,560 0.681,560C0.307,560 0,559.743 0,559.43C0,559.43 0,559.43 0,559.43Z"
    />
</vector>

placed on each path polyline segment middle point with angle calculated on segment bearing. Both polyline segment middle and bearing you can determine via SphericalUtil class of Google Maps Android API Utility Library . Bearing can be found via SphericalUtil.computeHeading() with first and second points of segment as arguments and LatLng of segment middle point - via SphericalUtil.interpolate() also with first and second points of segment as arguments from and to and constant 0.5 (half) as fraction argument.
So, with source like this:
...
@Override
public void onMapReady(GoogleMap googleMap) {
    mGoogleMap = googleMap;
    mGoogleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
        @Override
        public void onMapLoaded() {
            List<LatLng> sourcePoints = new ArrayList<>();
            PolylineOptions polyLineOptions;

            sourcePoints.add(new LatLng(-35.27801,149.12958));
            sourcePoints.add(new LatLng(-35.28032,149.12907));
            sourcePoints.add(new LatLng(-35.28099,149.12929));
            sourcePoints.add(new LatLng(-35.28144,149.12984));
            sourcePoints.add(new LatLng(-35.28194,149.13003));
            sourcePoints.add(new LatLng(-35.28282,149.12956));
            sourcePoints.add(new LatLng(-35.28302,149.12881));
            sourcePoints.add(new LatLng(-35.28473,149.12836));

            polyLineOptions = new PolylineOptions();
            polyLineOptions.addAll(sourcePoints);
            polyLineOptions.width(10);
            polyLineOptions.color(Color.BLUE);
            mGoogleMap.addPolyline(polyLineOptions);
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sourcePoints.get(0), 15));

            for (int i = 0; i < sourcePoints.size() - 1; i++) {
                // get first and second points of polyline segment
                LatLng segmentP1 = sourcePoints.get(i);
                LatLng segmentP2 = sourcePoints.get(i+1);

                // calculate middle point
                LatLng segmentMiddlePoint = SphericalUtil.interpolate(segmentP1, segmentP2, 0.5);
                // calculate bearing
                float segmentBearing = (float) SphericalUtil.computeHeading(segmentP1, segmentP2);

                // add flat marker at segment middle
                addDirectionMarker(segmentMiddlePoint, segmentBearing);
            }

    });

}
...
public void addDirectionMarker(LatLng latLng, float angle) {
    Drawable circleDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_arrow_up);
    BitmapDescriptor markerIcon = getMarkerIconFromDrawable(circleDrawable, 30, 30);

    mGoogleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .anchor(0.5f, 0.5f)
            .rotation(angle)
            .flat(true)
            .icon(markerIcon)
    );
}

you'll got something like that:

Also you can change size of arrows markers by set other values than 30, 30 in
BitmapDescriptor markerIcon = getMarkerIconFromDrawable(circleDrawable, 30, 30);
line.


text:
Q: WaitForExit() activates on UAC or Security Warning I'm fairly new to c# and this forum in general but as far as I'm concerned, I haven't seen any question like mine that will solve my problem.
I'm calling the method Process.WaitForExit() to wait until an installation file finishes to install. However, the method seems to consider the UAC as the 'process' and activates after I click OK on the UAC. Is there a better way to wait for an installation process to finish before the code proceeds? Or am I doing it wrong? Disabling the UAC manually (if that's possible) is a no go unless it's done programmatically as well.
Here's the part of the code:
Edit: proper calling of process
Process netInstall = Process.Start(filePath + "\\Installer.exe");
netInstall.WaitForExit();
Console.WriteLine("Installation Finished!");

Edit 2: Would it help if I say I'm installing MySQL Server 5.6? It seems that, besides the Security Warning, it pops up and close some windows before it starts too. Regards.

A: The code is not correct. You create an instance of the Process class, but then you call the static method Process.Start, which creates a new instance of Process.
Your code should look like this:
Process netInstall = Process.Start(filePath + "\\Installer.exe");
netInstall.WaitForExit();
Console.WriteLine("Installation Finished!");

A: Run your your application with elevated privileges:
<requestedExecutionLevel level="requireAdministrator">

Also consider BasyStallion answer and correctly start netInstall


text:
Q: Sharepoint 2010 HTTP 500 The website cannot display the page I created an aspx page in the _layouts folder just to test it and when I try to view it in the browser I get the following error:
The website cannot display the page
HTTP 500
Most likely causes:
•The website is under maintenance.
•The website has a programming error.
I have been looking on the web for a solution but nothing is helping so far.
This is what I have done so far based on the sugestions on the web:

*

*i don't see any message when I disable the Show Friendly Error Message.

*reset IIS

*Nothing descriptive in the Event Viewer

*Reinstalled SharePoint

The site itself is working fine.


text:
Q: Developing RESTful API and getting error while using Postman framework to test web API I have written a small demo program to develop RESTful API and I am using Postman framework to test my web API. The GET request works fine but the POST request gives an error.  I have added the error message by Postman framework at the end of the code.
This is my model class named Message

package com.abc.model;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Message {

private long id;
private String msg;
private String author;
private Date date;

public Message() {

}

public Message(long id, String msg, String author, Date date) {
    this.id = id;
    this.msg = msg;
    this.author = author;
    this.date = date;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public Date getDate() {
    return date;
}

public void setDate(Date date) {
    this.date = date;
}

}

Instead of using Hibernate/Database tables, I have created a class called Database class

package com.abc.database;

import java.util.HashMap;
import java.util.Map;

import com.abc.model.Message;

public class DatabaseTable {
//Any class in the application can access map of messages and profiles by calling these static methods( getMessages())

private static Map<Long, Message> messages =new HashMap<>();

public static Map<Long,Message> getMessages() {
    return messages;
    }

}

This is my service class

package com.abc.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Date;

import com.abc.database.DatabaseTable;
import com.abc.model.Message;

public class MessageService {

    private Map<Long, Message> messages = DatabaseTable.getMessages();

    public MessageService(){
    messages.put(1L, new Message(1,"This is a message from Ridh","Ridhi", new Date()));
    messages.put(2L, new Message(2,"Message from Steve", "Steve", new Date()));
}

    public List<Message> fetchMessages() {
        return new ArrayList<Message>(messages.values());
    }

    public Message retrieveMessage(long id) {
        return messages.get(id);
    }

    public Message addMessage(Message message) {
        message.setId(messages.size() + 1);
        messages.put(message.getId(), message);
        return message;
    }

    public Message updateMessage(Message message){
        messages.put(message.getId(),message);
        return message;
    }

    public Message deleteMessage(long id){
        return messages.remove(id);
    }
}

This is my Resource class calling the service

package com.abc.resource;

import javax.ws.rs.Path;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import com.abc.service.MessageService;

@Path("/messages")
public class MainResource {

    MessageService ms = new MessageService();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Message> display()
    return ms.fetchMessages();
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Message addMessage(Message message) {
        return ms.addMessage(message);
    }
}

This is the web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>RestWebService</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>Rest Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Rest Web Application</servlet-name>
        <url-pattern>/HelloREST/*</url-pattern>
    </servlet-mapping>
</web-app>

This is the pom.xml of my project

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>RestWebService</groupId>
    <artifactId>RestWebService</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
     <properties>
        <java-version>1.6</java-version>
        <org.springframework-version>4.0.3.RELEASE</org.springframework-version>
        <org.aspectj-version>1.7.4</org.aspectj-version>
        <org.slf4j-version>1.7.5</org.slf4j-version>
        <hibernate.version>4.3.5.Final</hibernate.version>
    </properties>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-servlet-api</artifactId>
    <version>8.5.0</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.2.5.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.2.6.RELEASE</version>
</dependency>

<dependency>
     <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <version>2.3.3</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

<dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

    <dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>2.3.3</version>
</dependency>

        <dependency>
            <groupId>asm</groupId>
            <artifactId>asm</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-bundle</artifactId>
            <version>1.18.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20140107</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.18.1</version>
        </dependency>
    </dependencies>
</project>
Error message( Postman framework)
<!DOCTYPE html>

        <title>Apache Tomcat/8.0.32 - Error report</title>

HTTP Status 500 - Servlet execution threw an exception

            type Exception report

            message
            Servlet execution threw an exception

            description
            The server encountered an internal error that prevented it from fulfilling this request.

            exception

javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

            root cause

java.lang.NoClassDefFoundError: org/codehaus/jackson/JsonFactory
    com.sun.jersey.json.impl.reader.JsonXmlStreamReader.create(JsonXmlStreamReader.java:110)
    com.sun.jersey.json.impl.Stax2JsonFactory.createReader(Stax2JsonFactory.java:137)
    com.sun.jersey.json.impl.Stax2JsonFactory.createReader(Stax2JsonFactory.java:127)
    com.sun.jersey.json.impl.BaseJSONUnmarshaller.createXmlStreamReader(BaseJSONUnmarshaller.java:116)
    com.sun.jersey.json.impl.BaseJSONUnmarshaller.unmarshalJAXBElementFromJSON(BaseJSONUnmarshaller.java:111)
    com.sun.jersey.json.impl.BaseJSONUnmarshaller.unmarshalFromJSON(BaseJSONUnmarshaller.java:100)
    com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider.readFrom(JSONRootElementProvider.java:154)
    com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.readFrom(AbstractRootElementProvider.java:111)
    com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
    com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
    com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:86)
    com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
    com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:183)
    com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

            root cause

java.lang.ClassNotFoundException: org.codehaus.jackson.JsonFactory
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1308)
    org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1142)
    com.sun.jersey.json.impl.reader.JsonXmlStreamReader.create(JsonXmlStreamReader.java:110)
    com.sun.jersey.json.impl.Stax2JsonFactory.createReader(Stax2JsonFactory.java:137)
    com.sun.jersey.json.impl.Stax2JsonFactory.createReader(Stax2JsonFactory.java:127)
    com.sun.jersey.json.impl.BaseJSONUnmarshaller.createXmlStreamReader(BaseJSONUnmarshaller.java:116)
    com.sun.jersey.json.impl.BaseJSONUnmarshaller.unmarshalJAXBElementFromJSON(BaseJSONUnmarshaller.java:111)
    com.sun.jersey.json.impl.BaseJSONUnmarshaller.unmarshalFromJSON(BaseJSONUnmarshaller.java:100)
    com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider.readFrom(JSONRootElementProvider.java:154)
    com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.readFrom(AbstractRootElementProvider.java:111)
    com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:490)
    com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:123)
    com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:86)
    com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153)
    com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:183)
    com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
    com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

            note
            The full stack trace of the root cause is available in the Apache Tomcat/8.0.32 logs.

Apache Tomcat/8.0.32

A: Could you please add the dependency for jackson-mapper-asl in the dependency section of your pom.xml. For example you may add the following in pom.xml:
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>


text:
Q: Компилятор не видит файл "wnspool.lib" Хотел написать игру на C++ с помощью SFML.
Библиотеки все есть:
sfml-graphics-d.lib;sfml-window-d.lib;sfml-system-d.lib;sfml-audio-d.lib;%(AdditionalDependencies)
Конфигурация: Debug
Путь к библиотекам и включаемых файлов настроен
!!!: файл "wnspool.lib" есть в дополнительных зависимостях, также, как и библиотеки для SFML
Мне компилятор выдал ошибку:
Сборка начата…
1>------ Сборка начата: проект: FIrstISFML, Конфигурация: Debug Win32 ------
1>LINK : fatal error LNK1104: не удается открыть файл "wnspool.lib"
1>Сборка проекта "Project1.vcxproj" завершена с ошибкой.
========== Сборка: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Я пробовал менять конфигурацию, вставлять DLL-файлы в папку проекта, а также в папку Debug и Release, убирать какие-либо файлы с расширением .lib в дополнительных зависимостях
Я взял код с оф. сайта для проверки:
    #include <SFML/Graphics.hpp>
    using namespace sf;

    int main()
    {
        RenderWindow window(VideoMode(200, 200), "SFML works!");
        CircleShape shape(100.f);
        shape.setFillColor(Color::Green);

        while (window.isOpen())
        {
            Event event;
            while (window.pollEvent(event))
            {
                if (event.type == Event::Closed)
                    window.close();
            }

            window.clear();
            window.draw(shape);
            window.display();
        }

        return 0;
}

И он не создаёт:


text:
Q: Is it possible to install rpm package from a Nexus yum repo using Maven? I would like to create a zip with some files and rpm packages using Maven assembly plugin and I would like to know if there is a way to download the rpm from a Nexus yum repository with the pom.xml (as a dependency or anything else).
I have found the rpm-maven-plugin but it can only create an rpm, it can't download it from Nexus.

A: I have found the solution, I used mvn wagon:
mvn wagon:upload-single -Dwagon.serverId=<ServerID> -Dwagon.url=http://<ServerUrl>/repository/<NexusReposirory>/<RPM file name> -Dwagon.fromFile=<RPM file>


text:
Q: Microsoft Graph Java API - Filter Groups based on a boolean value I am trying to filter the groups using java sdk based on the parameters like mailEnabled or securityEnabled.
I am trying out the following code to perform the same as suggested in the Graph Explorer interface. (https://developer.microsoft.com/en-us/graph/graph-explorer)
LinkedList requestOptions = new LinkedList();
requestOptions.add(new QueryOption("$filter", "mailEnabled+eq+true"));
IGroupCollectionPage groups = graphClient.groups()
.buildRequest(requestOptions)
.get();
But this throws an exceptio saying that "Invalid filter"
I can filter out the groups using the "startsWith" paramter as mentioned in "https://stackoverflow.com/questions/60417041/microsoft-graph-api-java-get-group-using-displayname"
Looks like there is some issue with + sign here.
Any suggestions ?

A: You can use the below code to get a filtered data for mailEnabled property.
List<Option> requestOptions = new ArrayList<Option>();
requestOptions.add(new QueryOption("$filter", "mailEnabled eq true"));
IGroupCollectionPage data = graphClient.groups()
                            .buildRequest(requestOptions)
                            .get();


text:
Q: Grails 3 rest profile 422 Unprocessable Entity result on show action I am having troubles with that and I am not being able to handle it and I didn´t find any answer here.
I have an application in Grails 3.1.10, with rest profile, I have some Domain Classes and their respective Controllers, I can create new objects with POST to save action, update them with PUT to update action and list them with GET to index action, but I am not being able to get a proper response in a GET to show action.
I am not sure if the issue that I have is in the request or in the application
My UrlMappings is like this:
"/$controller/$action?/$id?(.$format)?"{
       constraints {
           // apply constraints here
       }

I also tried with
get "/resources/$id"(controller:"resource", action:"show")

And same result: 422: Unprocessable Entity, "errors": [10] 0:  {
"message": "Property [] of class [class ] cannot be null" "path": "/1" "_links": { "self": { "href": "http://localhost:8080/1" }- }-}
For every single property different to id.
I am doing an http get request to http://localhost:8080/resource/show/1 (or http://localhost:8080/resources/1 in the second configuration), with the followings headers: "Content-Type: application/json" and "Authorization: Bearer " (I am using spring security rest plugin to secure the application). The same request to http://localhost:8080/resource/index (or to http://localhost:8080/resources/ in the second configuration) worked perfect and returned me a json with all the objects.
Cheers!

A: I think you should check one of this two options:

*

*Use @Resource in your domain class and do nnot create a controller(grails generates it automatically in this case)

*If you want to have a bit more control, you can use an url mapping resource +  a Controller that extends RestfulController as described in the documentation section 10.1.5.1 (http://docs.grails.org/latest/guide/single.html#webServices)
In this second options you will need something like this in the URlMappings:
"/books"(resources:"book")

and also a controller like:
class BookController extends RestfulController {
  static responseFormats = ['json', 'xml']
  BookController() {
    super(Book)
  }
}


text:
Q: Возврат значений из функции Скажите, пожалуйста, есть ли какая-то видимая разница в работе 2-х функций?
int & func1(int & b)
{
    return b;
}

int func2(int & b)
{
return b;
}

С объектами классов я разобрался (про создание копий объектов, работу конструкторов копирования и деструкторов).
Как я понял, в func2 при возврате значения будет создаваться временная копия объекта и удаляться. В func1 этого происходить не будет.
Это как-то влияет на работу программы?
A: Немножко побуду Капитаном Очевидность. Из первой функции вы возвращаете ссылку на int, из второй - просто int. С результатом первой функции вы можете работать как со ссылкой (Кэп не даст соврать), в частности, использовать его как lvalue.
Скажем, вы можете сделать так:
int & func1(int & b)
{
    return b;
}

int func2(int & b)
{
    return b;
}

int main() {
    int i = 10;

    // можно инкрементить результат выполнения функции
    // выглядит странновато, однако работает
    cout << func1(i)++ << endl;     // выведет 10

    // а тут можно увидеть результат предыдущего инкремента
    cout << i << endl; // выведет 11

    return 0;
}


text:
Q: Mock email payload on python I'm writing unit tests for a function that should get all valid attachments in email message. My function has the following behaviour:
def extract_attachments(local_file):
    email_file = open(local_file, "r")
    msg = email.message_from_file(email_file)
    attchs = [x for x in msg.get_payload() if x.get_filename() is not None]
    for attch in attchs:
        filename = attch.get_filename()
        if filename not in VALID_ATTACHMENTS:
            raise Exception('Invalid attachment', filename)
    return attchs

How can I make this function return some object with a function get_filename()?
I'm trying to patch it but I'm getting an error 'list' object has no attribute 'get_payload'.
@patch("mail_extractor.process_email.email")
@patch("builtins.open")
def test_extract_attachments(open, email):
    email.message_from_file.return_value = []
    email.get_payload.return_value = ['1.xml']
    result = process_email.extract_attachments('mock')
    assert len(result) == 1

A: The notation you've described is specific to objects, and what you're trying to give it is a method. You'll need to define a class:
class MyClass:
    def get_filename():
        # some logic

Then you'll be able to instantiate your object:
x = MyClass()
x.get_filename()

Does that answer your question?

A: The way you've configured your mocks isn't quite right. The message_from_file() call needs to return a message, whereas you're returning a list - hence the error you're seeing.
You should set up a mock message along with a mock attachment in order to satisfy the calls the code expects to make.
For example:
@patch("mail_extractor.process_email.email")
@patch("builtins.open")
def test_extract_attachments(open, email):
    # Configure the mock message and its attachment
    mock_message = Mock()
    mock_attachment = Mock()
    mock_attachment.get_filename.return_value = '1.xml'
    mock_message.get_payload.return_value = [mock_attachment]

    # Configure message_from_file to return the mock message
    email.message_from_file.return_value = mock_message

    result = process_email.extract_attachments('mock')
    assert len(result) == 1


text:
Q: stop groupby from making 2 combination same pair in python dataframe I am working on IPL dataset from Kaggle (https://www.kaggle.com/manasgarg/ipl).
I want to sum up the runs made by two people as pair and I have prepared my data.
When I am trying a GROUPBY on the dataframe columns (batsman and non_striker) it is making 2 combination of the same pair.
like (a,b) and (b,a) - rather I wish it should consider it as same.
As I can't drop rows any further.
import pandas as pd

df = pd.read_csv("C:\\Users\\Yash\\AppData\\Local\\Programs\\Python\\Python36-32\\Machine Learning\\IPL\\deliveries.csv")
df = df[(df["is_super_over"] != 1)]
df["pri_key"] = df["match_id"].astype(str) + "-" + df["inning"].astype(str)
openners = df[(df["over"] == 1) & (df["ball"] == 1)]
openners = openners[["pri_key", "batsman", "non_striker"]]
openners = openners.rename(columns = {"batsman":"batter1", "non_striker":"batter2"})
df = pd.merge(df, openners, on="pri_key")
df = df[["batsman", "non_striker", "batter1", "batter2", "batsman_runs"]]
df = df[((df["batsman"] == df["batter1"]) | (df["batsman"] == df["batter2"]))
    & ((df["non_striker"] == df["batter1"]) | (df["non_striker"] == df["batter2"]))]

df1 = df.groupby(["batsman" , "non_striker"], group_keys = False)["batsman_runs"].agg("sum")
df1.nlargest(10)

Result:
batsman      non_striker
DA Warner    S Dhawan       1294
S Dhawan     DA Warner       823
RV Uthappa   G Gambhir       781
DR Smith     BB McCullum     684
CH Gayle     V Kohli         674
MEK Hussey   M Vijay         666
M Vijay      MEK Hussey      629
G Gambhir    RV Uthappa      611
BB McCullum  DR Smith        593
CH Gayle     TM Dilshan      537

and, I want to keep 1 pair as unique
for those who don't understand cricket
I have a dataframe
batsman    non_striker    runs
a              b            2
a              b            3
b              a            1
c              d            6
d              c            1
d              c            4
b              a            3
e              f            1
f              e            2
f              e            6

df1 = df.groupby(["batsman" , "non_striker"], group_keys = False)["batsman_runs"].agg("sum")
    df1.nlargest(30)

output:
batsman    non_striker    runs
  a            b            5
  b            a            4
  c            d            6
  d            c            5
  e            f            1
  f            e            8

expected output:
batsman    non_striker    runs
  a            b            9
  c            d            11
  e            f            9

what should I do? Please advise....

A: You can sort the batsman and non_striker and then group the data
df[['batsman', 'non_striker']] = df[['batsman', 'non_striker']].apply(sorted, axis=1)
df.groupby(['batsman', 'non_striker']).batsman_runs.sum().nlargest(10)

Edit: You can also use numpy for sorting the columns, which will be faster than using pandas sorted
df[['batsman', 'non_striker']] = np.sort(df[['batsman', 'non_striker']],1)
df.groupby(['batsman', 'non_striker'], sort = False).batsman_runs.sum().nlargest(10).sort_index()

Either way, you will get,
batsman         non_striker
CH Gayle        V Kohli        2650
DA Warner       S Dhawan       2242
AB de Villiers  V Kohli        2135
G Gambhir       RV Uthappa     1795
M Vijay         MEK Hussey     1302
BB McCullum     DR Smith       1277
KA Pollard      RG Sharma      1220
MEK Hussey      SK Raina       1129
AT Rayudu       RG Sharma      1121
AM Rahane       SR Watson      1118

A: Craete a new DataFrame using np.sort. Then groupby and sum.
import pandas as pd
import numpy as np

df1 = pd.DataFrame(np.sort(df[['batsman', 'non_striker']].values,1),
                   index=df.index,
                   columns=['player_1', 'player_2']).assign(runs = df.runs)

df1.groupby(['player_1', 'player_2']).runs.sum()

Output:
player_1  player_2
a         b            9
c         d           11
e         f            9
Name: runs, dtype: int64

A: I hope I understand you right...
What you can do is something like put the smaller value always in column A and the greater value always in column B.
import pandas as pd
import numpy as np

# generate example
values = ['a', 'b' , 'c', 'd', 'e', 'f', 'g']
df = pd.DataFrame()
df['batsman'] = np.random.choice(values, size=10)
df['no_striker'] = np.random.choice(values, size=10)

# column evaluation
df['smaller'] = df['batsman'].where(df['batsman'] < df['no_striker'], df['no_striker'])
df['greater'] = df['batsman'].where(df['batsman'] > df['no_striker'], df['no_striker'])


text:
Q: Using stored procedure in crystal report 8.5? I have made a new report using Crystal Reports 8.5 (report1) which uses a stored procedure as its data source. The stored procedure has 2 input parameters (@p1 and @p2) and when I enter some test data for @p1 and @p2 within crystal report IDE , every thing is all right. Then, I added the report1 in visual basic 6.0 IDE and added a new form (form1) and a crystal report viewer control on form1. Now please help me: I wanna to show the report1. What codes exactly should I write to show it?How send data user has entered to the stored procedure parameters via application?
I also get this error messsage:  the server has not been opened yet"
What's  wrong?

A: Specifying a report
Assumes that SampleReport has been added to your .Net project:
Dim parameter1 As CrystalDecisions.Shared.ParameterField
Dim parameter2 As CrystalDecisions.Shared.ParameterField

With SampleReport
    .SetDatabaseLogon("user", "password", "server", "database")
    'locate first parameter in report
    parameter1 = .ParameterFields.Find("@p1", "")
    'locate second parameter in report
    parameter2 = .ParameterFields.Find("@p2", "")
End With

'create a new discrete-parameter value
Dim stringValue As New CrystalDecisions.Shared.ParameterDiscreteValue()
stringValue.Value = "USA"

'assign it to the parameter's current values collection
parameter1.CurrentValues.Add(stringValue)

'create a new discrete-parameter value
Dim numberValue As New CrystalDecisions.Shared.ParameterDiscreteValue()
numberValue.Value = 100

'assign it to the parameter's current values collection
parameter2.CurrentValues.Add(numberValue)

With Me.CrystalReportViewer1
    .ReportSource = SampleReport
End With

A: write the below code in vb6
With rptControl
    .ReportFileName = "MyCrystalReport1.rpt"
    .WindowAllowDrillDown = True
    .WindowMaxButton = True

    .ParameterFields(0) = "@p1;"& p1Value & ";true"
    .ParameterFields(1) = "@p2;"& p2Value & ";true"

    .Connect = MyDatabaseConnectionString;
    .Action = 1
End With


text:
Q: How to migrate to new React lifecycle API? As you know some lifecycle methods like componentWillReceiveProps are now deprecated.
Well, my code used this lifecycle method and now I have no idea how to migrate to the new API of React.
Here is how I used:
componentWillReceiveProps(nextProps) {
    if (nextProps.newPost) {
        this.props.posts.unshift(nextProps.newPost);
    }
}

In the react blog I could read that...

Together with componentDidUpdate, this new lifecycle should cover all
  use cases for the legacy componentWillReceiveProps.

... but how to implement this?

A: componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

Note that it must be wrapped in a condition like in the example above, or you'll cause an infinite loop.

A: you can use getDerivedStateFromProps or componentDidMount, there is sequence to running lifecycles :

*

*getDerivedStateFromProps

*shouldComponentUpdate

*render

*getSnapshotBeforeUpdate

*componentDidUpdate


text:
Q: SQL Multiple Left Joins on Same Parent Key I have 3 tables that join onto each other:

*

*TableA(ID, name, amount) (1 row)

*TableB(ID, title) (3 rows)

*TableC(ID, name, title) (3 rows)

The query:
Select *
from TableA a Left Join
     TableB b
     on a.ID = b.ID Left Join
     TableC c
     on a.ID = c.ID and a.name = c.name

This produces many duplicates because the second left join is joining onto the result of the first one.
E.g. 1st left join leaves you with 3 rows (1x3), then second the second joins onto this result to get 9 (3x3).
How would I produce a result that would list the ID, Name, Title, Amount in each row distinctly?
eg:
TableA.ID, TableA.Name ,TableB.Title1, TableA.Amount
TableA.ID, TableA.Name ,TableB.Title2, TableA.Amount
TableA.ID, TableA.Name ,TableB.Title3, TableA.Amount
TableA.ID, TableA.Name ,TableC.Title1, TableA.Amount
TableA.ID, TableA.Name ,TableC.Title2, TableA.Amount
TableA.ID, TableA.Name ,TableC.Title3, TableA.Amount

I initially tried spiting these tables joins into seperate tables and then unioning them together, this works but I think there must be a simpler way

A: You would use union all:
select a.id, a.name, b.title, a.amount
from TableA a Left Join
     TableB b
     on a.ID = b.ID
union all
Select a.id, a.name, b.title, a.amount
from TableA a Left Join
     TableC c
     on a.ID = c.ID and a.name = c.name

A: Just use inner join(left join is not needed) with union all
Select a.ID, a.Name ,b.Title, b.Amount
  from TableA a
  join TableB b on a.ID = b.ID
union all
Select a.ID, a.Name ,c.Title, c.Amount
  from TableA a
  join TableC c on a.ID = c.ID