text:
Q: How to return multiple values from a function in C# (ASP.NET)? I have a page where some products and textfields where the user enters a number. I first use JavaScript to calculate the total cost. Based on how many users they enter they get a different rate (as shown in code below). When the user types or paste a number into a textfield the function CalculateCost gets called which calls the other functions (only showing two in the example, CDCOst and DVDCost) to make sure the fields Monthly Cost and Annual Cost are displaying the correct value.
I of course want to do the final calculation in the code behind as well before I insert into the database. How can I achieve something similiar in C#?
function CDCost() {
                var monthlyAmount;
                var annualAmount;
                var amount;
                var users = $('#txtCD').val();

            if (users > 0 && users < 100) {
                amount = users * 14.95;
                monthlyAmount = amount;
                annualAmount = monthlyAmount * 12;
                return [monthlyAmount, annualAmount];
            }
            if (users >= 100 && users <= 250) {
                amount = users * 12.95;
                monthlyAmount = amount;
                annualAmount = monthlyAmount * 12;
                return [monthlyAmount, annualAmount];
            }
            if (users == 0) {
                monthlyAmount = 0;
                annualAmount = 0;
                return [monthlyAmount, annualAmount];
            }
        }

function DVDCost() {
                var monthlyAmount;
                var annualAmount;
                var amount;
                var users = $('#txtDVD').val();

            if (users > 0 && users < 100) {
                amount = users * 16.95;
                monthlyAmount = amount;
                annualAmount = monthlyAmount * 12;
                return [monthlyAmount, annualAmount];
            }
            if (users >= 100 && users <= 250) {
                amount = users * 14.95;
                monthlyAmount = amount;
                annualAmount = monthlyAmount * 12;
                return [monthlyAmount, annualAmount];
            }
            if (users == 0) {
                monthlyAmount = 0;
                annualAmount = 0;
                return [monthlyAmount, annualAmount];
            }
        }

        function CalculateCost() {
            var cd = CDCost();
            var dvd = DVDCost();

            var monthlyCost = cd[0] + dvd[0];
            var annualCost = cd[1] + dvd[1];

            return [monthlyCost, annualCost];
        }

        $('#txtCD').bind('keyup change', function (ev) {
            var cost = CalculateCost();
            var monthly = cost[0];
            var annual = cost[1];

            $('#MonthlyCostSum').text(monthly);
            $('#AnnualCostSum').text(annual)
        });

How would I go on doing this in C#?
Something like:
protected double CDCost()
    {
        double monthlyAmount;
        double annualAmount;
        double amount;
        double users = Convert.ToDouble(txtCD.Text);

        if (users > 0 && users < 100)
    {
        amount = users * 14.95;
        monthlyAmount = amount;
        annualAmount = monthlyAmount * 12;
        return //how do I return the values here to a CalculateCost function?
    }

}

A: Either use out parameters or create a new type wrapping all the things you would like to return (a so-called "property bag"):
class ReportData
{
    public double MonthlyAmount { get; set; }
    public double AnnualAmount { get; set; }
    public double Amount { get; set; }
}

...

protected ReportData CDCost()
{
    return new ReportData()
        {
            Amount = users * 14.95
            MonthlyAmount = amount,
            AnnualAmount = amount * 12.0,
        };
}

A: The tuple class in .NET 4 does the job perfectly.
protected Tuple<double, double, double, double> CDCost()
    {
        double monthlyAmount;
        double annualAmount;
        double amount;
        double users = Convert.ToDouble(txtCD.Text);
   if (users > 0 && users < 100)
    {
        amount = users * 14.95;
        monthlyAmount = amount;
        annualAmount = monthlyAmount * 12;
        return //how do I return the values here to a CalculateCost function?
    }
    return new Tuple<double, double, double, double>(monthlyAmount, annualAmount, amount, users);
}

A: You could either use out parameters to return multiple values
OR
You could return a collection (e.g. a double array) or custom object which contains all the objects that you want to return.
class MyCustomType
{
  double AnnualAmount{get; set;}
  double MonthlyAmount{get; set;}
}

// and in your function you could go
return new MyCustomType{ AnnualAmount = 4.5d, MonthlyAmount = 5.5d  };

A: You can use an array, like this:
protected double[] CDCost() {
    //a lot of code
    return new double[2] { annualAmount, monthlyAmount };
}

and then use it like this:
double cdCost = CDCost();
annualAmount = cdCost[0];
monthlyAmount = cdCost[1];

A: Would have changed the way you do it now, to return a CDCost object:
public Class CDCost
{
  public double Monthly {get;set;}
  public double Annually {get return Monthly*12;}

  public CDCost(double monthly)
  {
    Monthly=monthly;
  }
}

But if you're interested in c# syntax - you can use out or an array for example (Although I think both of them are bad design in this case).

A: In a technical, somewhat smartass sense, the answer is that you can't return more than one value from a function. A function either returns one value or doesn't return anything. This goes for your Javascript example--it's not actually returning two values, it's returning one value, which is an array of two elements.
That said, here are your options, as already pointed out by others:
1) Return an array. This is what you did in the Javascript example, and it would work anywhere else, too. The problems I see are two: one, you're limited to one type (and, if applicable, its subtypes). If you want to return, say, a double and a string, you'd need to make it return an array of Objects and cast to the appropriate type. Two, it makes for a fairly difficult-to-use API, because ordering is crucial. Any code consuming your function would need to know that returnValue[0] represented, say, the monthly amount and returnValue[1] represented the annual amount. Sure, you could say that in the documentation, but it's still a tricky API to use. And God help you if you (or someone else) changes the order of the return values for some reason (possibly through carelessness). That would be a horrible bug to track down.
2) Return a dictionary. This avoids the ordering problem, but it makes up for that by adding the key problem--anyone using your code would need to know that the dictionary returned used some specific set of keys (say, "monthlyAmount" and "annualAmount"). A typo, either in consuming code or in the method's body, would be a pain in the ass. And just like the array solution, you'd have to be sure to document the key values. It also suffers from the same type issue that the array solution poses. It would probably also be a bit less performant than the array solution, although it's questionable whether it would really make a noticable difference.
3) out parameters. This avoids the previous problems in that they can each be of any type and the compiler/IDE will catch any typos/bad assignments. However, in general I try to avoid out parameters (as does FxCop). Personally, they seem to be abusing the parameter syntax--parameters are for passing data into the function, and out parameters, while they do technically do that, are being used for return values rather than values to be used by the function. It also pollutes the method signature--it's n more parameters you need to pass, which is particularly annoying if you want a bunch of overloads (and you're not using .NET 4.0's optional/named parameters). On a much more minor note, it's a bit annoying to have to declare return values before they can be returned, i.e.
double outparam1, outparam2;
SomeFunction(out outparam1, out outparam2);
//use out parameters

4) Return an instance of a custom class. It's a bit ugly to add an entire class specifically for the return value of a single method, but this is probably the most elegant solution, in that it tells people using the method exactly what's returned and you can mix types (and the method doesn't have to take extra parameters just to be able to return things, as with out parameters, which makes the method calls a little cleaner). However, I wouldn't go overboard with this--if you find yourself with lots of methods that need to return multiple (very different) values (you shouldn't find yourself this way), then adding a new return class for each method would, I think, make your life much more hellish.
5) Not return multiple values. This may not always be an option, but if you find yourself wanting to return multiple values, I'd look hard at whether the values need to be returned together, or if you can split it into two calls (GetMonthlyAmount() and GetAnnualAmount(), for instance). Sometimes this wouldn't make sense, particularly if your method is does expensive things like make a database call.
tl;dr: when you want to return multiple values, first make sure that you can't split it into separate methods, then for a custom return class. Within reason.

A: I know this thread is old but just thought I'd add my 2 cents:
What about some read-only class properties in the same class that contains the function (which could be turned into a Sub at that point)? This is to me the cleanest solution that makes sense....
in VB:
Private iAmount  As Integer
Public ReadOnly Property Amount() As Integer
    Get
        Return iAmount
    End Get
End Property

Private iMonthlyAmount  As Integer
Public ReadOnly Property MonthlyAmount() As Integer
    Get
        Return iMonthlyAmount
    End Get
End Property

Private iAnnualAmount  As Integer
Public ReadOnly Property AnnualAmount() As Integer
    Get
        Return iAnnualAmount
    End Get
End Property

A: I would say named touple is the new way to go (since C#7, apparently)
protected (double amount, double monthlyAmount, double annualAmount) CDCost()
    {
        double monthlyAmount;
        double annualAmount;
        double amount;
        double users = Convert.ToDouble(txtCD.Text);

        if (users > 0 && users < 100)
        {
            amount = users * 14.95;
            monthlyAmount = amount;
            annualAmount = monthlyAmount * 12;
            return (amount, monthlyAmount, annualAmount);
        }
        throw new NotImplementedException();
    }

and then you can call it implicitly using the deconstructor
    var (amount, monthlyAmount, annualAmount) = CDCost();

A: The best way to do this is to return a dictionary with the values
protected Dictionary<string, double> CDCost()
    {
        Dictionary<string,double> values = new Dictionary<string,double>();
        double monthlyAmount;
        double annualAmount;
        double amount;
        double users = Convert.ToDouble(txtCD.Text);

        if (users > 0 && users < 100)
    {
        amount = users * 14.95;
        values["monthlyAmount"] = amount;
        values["annualAmount"] = monthlyAmount * 12;
        return values
    }

}


text:
Q: wordpress redirect to subdomain after login I have my  wordpress blog at www.mysite.com , also I have my own php application at a subdomain l.mysite.com
I want the login credentials of WordPress in my PHP application. I figured out that by including the wp-blog-header.php from the root to my app.
I can use the user info OK.
I wanted to redirect users to www.mysite.com/wp-login.php?redirect_to=l.mysite.com . You can see here that I am specifying the redirect_to parameter. Wordpress ignores this and redirects to admin panel.
I  think that worpdress doesn't allow redirect to an "external domain" , which I think is specified in wp_safe_redirect() function in wordpress. Is there any plugin which could ignore some domain to which redirect can happen?
I see that there are many login specific redirect plugins but none which could do to a new doamin.

A: Check this Plugin: http://www.theblog.ca/wplogin-redirect
Looks like it does what you want. Probably it's outdated, however, it should be trivial to create a plugin that fits your need.
A filter to start with is login_redirect, there is another filter in wp_safe_redirect() so you can prevent the domain you want to use being blocked.
To monitor redirects, checkout my Better HTTP Redirects Plugin.

A: +1 to @hakre . I don't have 15 rep so I can't upvote. Repost incase his
function cleanup_allowed_redirect_hosts( $hosts )
{
    $allowed_hosts = array('first.domain.com', 'second.domain.com', 'etc.domain.com');
    return array_merge( $hosts, $allowed_hosts );
}

add_filter( 'allowed_redirect_hosts', 'cleanup_allowed_redirect_hosts', 10, 1 );

redpajama_set_name: RedPajamaStackExchange


text:
Q: Automatically define fields when parsing XMLs with logstash Is there any way in logstash to define fields automatically based on the XML contents when parsing an XML file with logstash's XML filter?
For example, let's say I have the following XML (copied from https://www.w3schools.com/xml/xml_xpath.asp):
<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>

I would like to parse it with logstash where logstash automatically defines for example a field called bookstore.book.title with the value "Everyday Italian" and a field called bookstore.book.title.lang with the value "en" and so on without having to define all of this manually (using xpath). The problem is that I'm trying to parse various XML files with different and complicated structures so defining a seperate structure for each file is not an option.

A: I found the problem. Logstash natively breaks down the attributes of the xml file (so what I needed is actually supported by logstash out of the box). The problem was that in my xml files, the end of an xml attribute (e.g. </book>) was in a seperate line so for logstash the attribute <book> was "broken" and this was causing an xml parse failure. To resolve the problem I needed to add a multiline codec to the input so that each attribute that needs to be parsed is located completely in one single line.


text:
Q: Python regex to match subreddit names I'm just learning python and trying to pull subreddits out of a file with a regex, but not having much luck..
import re

string1 = "asdf asdf 587985 (*&(*& /r/whatever3/fjfjfjjrr /r/whatever2 jfdnhkjv43$#$"
matches = re.search(r"/r/+(\S)+[/ ]", string1)
if matches:
    print matches.groups()

Doesn't seem work work properly at all, though the syntax looks correct to me (it should match a string without whitespace (\S) followed by a space or a forward slash [/ ]
This version might be matching 'whatever3' -- it returns the 3 which is the last character at least:
import re

string1 = "asdf asdf 587985 (*&(*& /r/whatever3/fjfjfjjrr /r/whatever2 jfdnhkjv43$#$"
matches = re.search(r"/r/+(\S)+/", string1)
if matches:
    print matches.groups()

I'm also having trouble figuring out from the docs how I pull the variable (like the subreddit name itself) out of the match..

A: (\S)+ captures the last repetition of \S. Use  (\S+) instead to capture all the non-spaces.
The above includes intervening slashes. To exclude them, change \S to [^\s/].
>>> re.findall(r"/r/([^\s/]+)", string1)
['whatever3', 'whatever2']

A: The accepted answer will match any string prefixed with /r/, but we can be a lot stricter than that.
Reddit's site says this if you enter an invalid subreddit name during creation:

Community names must be between 3–21 characters, and can only contain letters, numbers, or underscores

Furthermore, I noticed that a subreddit name cannot begin with an underscore, and that not all users use the leading slash in /r/ (r/). Here is a regex that matches only valid subreddits, starting /r/ or r/:
regex = r"\/?r\/([a-z0-9][_a-z0-9]{2,20})(?:\Z|\s)"

Regex101 Link. Here, we are also using a non-capturing group with \Z, which indicates the end of a string, in addition to \s, which indicates any whitespace.
If the desire is just to validate a single subreddit name without the prefix, the regex is simpler:
regex = r"^([a-z0-9][_a-z0-9]{2,20})$"

Regex101 Link.


text:
Q: select onchange update php value I want to "connect" a select with a input text without refresh the page
This is my example
<select name="name_select" id="my_select">
  <option value="1">first</option>
  <option value="2">first</option>
  <option value="3">first</option>
</select>

<?php ...query(SELECT name FROM table WHERE id = value) ?>

Then in var $name there is value from db
<input type="text" value="<?php echo $name; ?>" />

I think I must use jquery post/get but how to update only var that I need to check db?

A: Like Thamizhan say in comment, you need to use AJAX.
Here is a simple example :
HTML (index.html)
<select name="name_select" id="my_select">
  <option value="1">first</option>
  <option value="2">first</option>
  <option value="3">first</option>
</select>

JS
$('#my_select').on('change', function () {
    var selectData = $(this).val();
    $.ajax({
        type: "POST",
        url: "custom.php",
        data: {'selectData': selectData },
        success: function (json) {
            // do things
        }
    });
}

PHP (custom.php)
if (isset($_POST['selectData'])) {
    var_dump($_POST['selectData']); // $_POST['selectData'] is the selected value
    // query here
    // and you can return the result if you want to do some things cool ;)
}

A: $("#my_select").on("change", function () {
   $.ajax({
        url: "phpfile.php",
        method: 'POST',
        data: {val: $(this).val()},
        success: function (data) {
            $("[type='text']").val(data);

        }
    });
});

In phpfile.php
include("db.php");

// ... your code ...

// execute sql(SELECT name FROM table WHERE id = value) and return value.

A: Please clear one thing why you need sql query here.
<option value="1">first</option>

first is name and 1 is option there. then we can put first or 1 into input box without using sql and ajax.
use only jquery for this
$(document).ready(function(){
  $("#my_select").change(function(){

    var thisval = $(this).val();
    $("input").val(thisval);
  });
});


text:
Q: How do i turn my frequency table into a dataframe to make a bar chart graph? I think that the title doesn't really help, but... let's go.
I have data about a candidates tweets. Its a dataframe and one of the columns its named "Tweets" (each row I have a different tweet). I've used the following functions to make a frequency table:
frequencytable <- candidate$Tweets %>%
  na.omit() %>%
  tolower() %>%
  strsplit(split = "[ .,!]") %>% # or strsplit(split = "\\W")
  unlist() %>%
  gsub('[.?:!,"\n"]', '', .) %>%
  table() %>%
  sort(decreasing = TRUE)

after that, I got results like these (a large table, without column names, where the rows are different words with their corresponded frequency below):
hello   bye  good money   red
  567   321    22    61    98

In dput format:
frequencytable <-
c(hello = 567L, bye = 321L, good = 22L, money = 61L, red = 98L)

(imagine that the numbers are below the words) and so on (I think that I have about ~500 occurrences)........
And now I want to show these results in a simple bar chart graph, but I'm struggling a lot.
I've tried something like:
ggplot(data = candidate$Tweets) +
  geom_bar(mapping = aes(x = frequencytable))

It doesn't work...
I've done some research and I found some tips like: turn it into a dataframe and after that proceed with the ggplot but I'm really stuck.

A: Here are three solutions starting with the frequency table.
Make up a data set.
set.seed(2020)
frequencytable <- table(sample(letters[1:4], 100, TRUE))

Base R.
barplot(frequencytable)

Now, ggplot2 solutions. Load the package first.
library(ggplot2)

df1 <- as.data.frame(frequencytable)
ggplot(df1, aes(Var1, Freq)) + geom_col()

df2 <- stack(frequencytable)
ggplot(df2, aes(ind, values)) + geom_col()


text:
Q: Iterate through a html file and extract data to CSV file I have searched high and low for a solution, but non have quite fit what I need to do.
I have an html page that is saved, as a file, lets call it sample.html and I need to extract recurring json data from it. An example file is as follows:
I need to get the info from these files regulary, so the amount of objects change every time, an object would be considered as "{"SpecificIdent":2588,"SpecificNum":29,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false}"
I need to get each of the values to a CSV file, with column headings being SpecificIdent, SpecificNum, Meter, Power, WPower, Snumber, isI. The associated data would be the rows from each.
I apologize if this is a basic question in Python, but I am pretty new to it and cannot fathom the best way to do this. Any assistance would be greatly appreciated.
Kind regards
A

<meta name="color-scheme" content="light dark">
[{"SpecificIdent":2588,"SpecificNum":29,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":3716,"SpecificNum":39,"Meter":1835,"Power":11240.0,"WPower":null,"SNumber":"0703-403548","isI":false},{"SpecificIdent":6364,"SpecificNum":27,"Meter":7768,"Power":29969.0,"WPower":null,"SNumber":"467419","isI":false},{"SpecificIdent":6583,"SpecificNum":51,"Meter":7027,"Power":36968.0,"WPower":null,"SNumber":"JE1449-521248","isI":false},{"SpecificIdent":6612,"SpecificNum":57,"Meter":12828,"Power":53918.0,"WPower":null,"SNumber":"JE1509-534327","isI":false},{"SpecificIdent":7139,"SpecificNum":305,"Meter":6264,"Power":33101.0,"WPower":null,"SNumber":"JE1449-521204","isI":false},{"SpecificIdent":7551,"SpecificNum":116,"Meter":0,"Power":21569.0,"WPower":null,"SNumber":"JE1449-521252","isI":false},{"SpecificIdent":7643,"SpecificNum":56,"Meter":7752,"Power":40501.0,"WPower":null,"SNumber":"JE1449-521200","isI":false},{"SpecificIdent":8653,"SpecificNum":49,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":9733,"SpecificNum":142,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":10999,"SpecificNum":20,"Meter":7723,"Power":6987.0,"WPower":null,"SNumber":"JE1608-625534","isI":false},{"SpecificIdent":12086,"SpecificNum":24,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":14590,"SpecificNum":35,"Meter":394,"Power":10941.0,"WPower":null,"SNumber":"BN1905-944799","isI":false},{"SpecificIdent":14954,"SpecificNum":100,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"517163","isI":false},{"SpecificIdent":14995,"SpecificNum":58,"Meter":0,"Power":38789.0,"WPower":null,"SNumber":"JE1444-511511","isI":false},{"SpecificIdent":15245,"SpecificNum":26,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"430149","isI":false},{"SpecificIdent":18824,"SpecificNum":55,"Meter":8236,"Power":31358.0,"WPower":null,"SNumber":"0703-310839","isI":false},{"SpecificIdent":20745,"SpecificNum":41,"Meter":0,"Power":60963.0,"WPower":null,"SNumber":"JE1447-517260","isI":false},{"SpecificIdent":31584,"SpecificNum":11,"Meter":0,"Power":3696.0,"WPower":null,"SNumber":"467154","isI":false},{"SpecificIdent":32051,"SpecificNum":40,"Meter":7870,"Power":13057.0,"WPower":null,"SNumber":"JE1608-625593","isI":false},{"SpecificIdent":32263,"SpecificNum":4,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":33137,"SpecificNum":132,"Meter":5996,"Power":26650.0,"WPower":null,"SNumber":"459051","isI":false},{"SpecificIdent":33481,"SpecificNum":144,"Meter":4228,"Power":16136.0,"WPower":null,"SNumber":"JE1603-617807","isI":false},{"SpecificIdent":33915,"SpecificNum":145,"Meter":5647,"Power":3157.0,"WPower":null,"SNumber":"JE1518-549610","isI":false},{"SpecificIdent":36051,"SpecificNum":119,"Meter":2923,"Power":12249.0,"WPower":null,"SNumber":"135493","isI":false},{"SpecificIdent":37398,"SpecificNum":21,"Meter":58,"Power":5540.0,"WPower":null,"SNumber":"BN1925-982761","isI":false},{"SpecificIdent":39024,"SpecificNum":50,"Meter":7217,"Power":38987.0,"WPower":null,"SNumber":"JE1445-511599","isI":false},{"SpecificIdent":39072,"SpecificNum":59,"Meter":5965,"Power":32942.0,"WPower":null,"SNumber":"JE1449-521199","isI":false},{"SpecificIdent":40601,"SpecificNum":9,"Meter":0,"Power":59655.0,"WPower":null,"SNumber":"JE1447-517150","isI":false},{"SpecificIdent":40712,"SpecificNum":37,"Meter":0,"Power":5715.0,"WPower":null,"SNumber":"JE1502-525840","isI":false},{"SpecificIdent":41596,"SpecificNum":53,"Meter":8803,"Power":60669.0,"WPower":null,"SNumber":"JE1503-527155","isI":false},{"SpecificIdent":50276,"SpecificNum":30,"Meter":2573,"Power":4625.0,"WPower":null,"SNumber":"JE1545-606334","isI":false},{"SpecificIdent":51712,"SpecificNum":69,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":56140,"SpecificNum":10,"Meter":5169,"Power":26659.0,"WPower":null,"SNumber":"JE1547-609024","isI":false},{"SpecificIdent":56362,"SpecificNum":6,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":58892,"SpecificNum":113,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":65168,"SpecificNum":5,"Meter":12739,"Power":55833.0,"WPower":null,"SNumber":"JE1449-521284","isI":false},{"SpecificIdent":65255,"SpecificNum":60,"Meter":5121,"Power":27784.0,"WPower":null,"SNumber":"JE1449-521196","isI":false},{"SpecificIdent":65665,"SpecificNum":47,"Meter":11793,"Power":47576.0,"WPower":null,"SNumber":"JE1509-534315","isI":false},{"SpecificIdent":65842,"SpecificNum":8,"Meter":10783,"Power":46428.0,"WPower":null,"SNumber":"JE1509-534401","isI":false},{"SpecificIdent":65901,"SpecificNum":22,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":65920,"SpecificNum":17,"Meter":9316,"Power":38242.0,"WPower":null,"SNumber":"JE1509-534360","isI":false},{"SpecificIdent":66119,"SpecificNum":43,"Meter":12072,"Power":52157.0,"WPower":null,"SNumber":"JE1449-521259","isI":false},{"SpecificIdent":70018,"SpecificNum":34,"Meter":11172,"Power":49706.0,"WPower":null,"SNumber":"JE1449-521285","isI":false},{"SpecificIdent":71388,"SpecificNum":54,"Meter":6947,"Power":36000.0,"WPower":null,"SNumber":"JE1445-512406","isI":false},{"SpecificIdent":71892,"SpecificNum":36,"Meter":15398,"Power":63691.0,"WPower":null,"SNumber":"JE1447-517256","isI":false},{"SpecificIdent":72600,"SpecificNum":38,"Meter":14813,"Power":62641.0,"WPower":null,"SNumber":"JE1447-517189","isI":false},{"SpecificIdent":73645,"SpecificNum":2,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":77208,"SpecificNum":28,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":77892,"SpecificNum":15,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false},{"SpecificIdent":78513,"SpecificNum":31,"Meter":6711,"Power":36461.0,"WPower":null,"SNumber":"JE1445-511601","isI":false},{"SpecificIdent":79531,"SpecificNum":18,"Meter":0,"Power":0.0,"WPower":null,"SNumber":"","isI":false}]

I have tried examples from bs4, jsontoxml, and others, but I am sure there is a simple way to iterate and extract this?

A: There is a python library, called BeautifulSoup, that you could utilize to parse the whole HTML file:
# pip install bs4
from bs4 import BeautifulSoup

html = BeautifulSoup(your-html)

From here on, you can perform any actions upon the html. In your case, you just need to find the
 element, and get its contents. This can be achieved easily:
pre = html.body.find('pre')
text = pre.text

Finally, you need to parse the text, which it seems is JSON. You can do with Python's internal json library:
import json

result = json.loads(text)

Now, we need to convert this to a CSV file. This could be done, using the csv library:
import csv

with open('GFG', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=[
        "SpecificIdent",
        "SpecificNum",
        "Meter",
        "Power",
        "WPower",
        "SNumber",
        "isI"
    ])

    writer.writeheader()
    writer.writerows(result)

Finally, your code should look something like this:
from bs4 import BeautifulSoup
import json
import csv

with open('raw.html', 'r') as f:
    raw = f.read()

html = BeautifulSoup(raw)
pre = html.body.find('pre')
text = pre.text
result = json.loads(text)

with open('result.csv', 'w') as f:
    writer = csv.DictWriter(f, fieldnames=[
        "SpecificIdent",
        "SpecificNum",
        "Meter",
        "Power",
        "WPower",
        "SNumber",
        "isI"
    ])

    writer.writeheader()
    writer.writerows(result)

A: I would harness python's standard library following way
import csv
import json
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    def handle_data(self, data):
        if data.strip():
            self.data = data

parser = MyHTMLParser()
with open("sample.html","r") as f:
    parser.feed(f.read())
with open('sample.csv', 'w', newline='') as csvfile:
    fieldnames = ['SpecificIdent', 'SpecificNum', 'Meter', 'Power', 'WPower', 'SNumber', 'isI']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(json.loads(parser.data))

which creates file starting with following lines
SpecificIdent,SpecificNum,Meter,Power,WPower,SNumber,isI
2588,29,0,0.0,,,False
3716,39,1835,11240.0,,0703-403548,False
6364,27,7768,29969.0,,467419,False
6583,51,7027,36968.0,,JE1449-521248,False
6612,57,12828,53918.0,,JE1509-534327,False
7139,305,6264,33101.0,,JE1449-521204,False
7551,116,0,21569.0,,JE1449-521252,False
7643,56,7752,40501.0,,JE1449-521200,False
8653,49,0,0.0,,,False

Disclaimer: this assumes JSON array you want is last text element which is not empty (i.e. contain at least 1 non-whitespace character).


text:
Q: Can you trigger custom HTML5 form errors with JavaScript? If i have an input like <input type="text"> and i want to trigger a native error on the input, can you do that? Like (faux code) ele.triggerError('Error Message');
It would then look like:

(source: tylergaw.com)
But with a custom message and for it's own validation function. Needed for AJAX validations for example.

A: The only way to trigger the native error is to submit the form.  Although you can set a custom message with  setCustomValidity (as described in my answer here) and you can trigger the invalid event with checkValidity, this only provides hooks for you to create your own validation UI.  Here's a simple example you can play around with to verify.
Note that if you submit the form with the submit() method that will bypass the validation API.  But if you trigger the click event of the submit button that will work in Firefox and Opera, but not Chrome.  I'd avoid doing it right now.

A: You can now use the HTMLFormElement.reportValidity() method, at the moment it's implemented in Chrome, Firefox, Opera, and Android browsers, but not supported in Internet Explorer (check caniuse.com to see supported browsers).


text:
Q: Magnetizing current in switching converter I have a question about the magnetizing current in a forward switching converter (image from "ON Semiconductor: Am improved 2-switch forward converter application").

From the picture it looks like there is a finite current in the primary, when the switch Q1 is off. My question is, how is that possible, since the primary is made out of a single wire ? How can you physically have a current in an open wire ?

A: That picture is incorrect for anything other than what it is intended for i.e. to demonstrate that you need to reset the flux in an inductor or transformer.
What happens in reality with the circuit shown is that the energy built up (by the rising current) creates a high voltage when the MOSFET turns off and destroys it. They are using this circuit as a "device" to explain the problem.
If you'd shown the full picture and read the subsequent pages you might have made more sense of it: -


text:
Q: Leaflet Map Exported Using Export Web Map Task Looks Stretched I'm running an Angular application that displays a map using Leaflet, and has a custom print where the user can set some options before sending a request to the ArcGIS Online print service (https://utility.arcgisonline.com/arcgis/rest/services/Utilities/PrintingTools/GPServer/Export%20Web%20Map%20Task/execute). The issue is that the resultant exported map always appears stretched horizontally, so that a polygon that was square will be clearly rectangular. The entire map - basemap and all polygons - are all stretched the same amount, not just the polygons.
Here is the the code that builds the request:
let requestParams: any = {
  f: 'json',
  Web_Map_as_JSON: {
    "mapOptions":
      {
        "showAttribution": true,
        "extent": {
          "xmin": map.getBounds().getWest(),
          "ymin": map.getBounds().getSouth(),
          "xmax": map.getBounds().getEast(),
          "ymax": map.getBounds().getNorth(),
          "spatialReference": {"wkid": 4326}
        },
        "spatialReference": {"wkid": 4326},
      },
    "operationalLayers": this.getOperationalLayers(map),
    "exportOptions": {"dpi": printOption.printQualityDPI},
    "layoutOptions":
      {
        "titleText": printOption.title,
        "authorText": printOption.author,
        "copyrightText": printOption.copyright,
        "customTextElements": [{"Date": new DateTimePipe(this.userPreferencesService).transform(new Date())}],
        "legendOptions": {"operationalLayers": []}
      }
  },
  Format: printOption.format,
  Layout_Template: printOption.getParsedLayout(),
  printFlag: true
};

switch (printOption.scalebarUnit) {
  case 'Feet':
  case 'Meters':
    requestParams.Web_Map_as_JSON.layoutOptions.scaleBarOptions = {
      "metricUnit": "esriMeters", "metricLabel": "m", "nonMetricUnit": "esriFeet", "nonMetricLabel": "ft"
    };
    break;
  case 'Kilometers':
  case 'Miles':
  default:
    requestParams.Web_Map_as_JSON.layoutOptions.scaleBarOptions = {
      "metricUnit": "esriKilometers", "metricLabel": "km", "nonMetricUnit": "esriMiles", "nonMetricLabel": "mi"
    };
    break;
}

switch (printOption.preserveOpt) {
  case 'extent':
    // don't do anything. We always set the extent as all options require it (scale uses the center)
    break;
  case 'forceScale':
    requestParams.Web_Map_as_JSON.mapOptions.scale = printOption.forceScaleValue;
    break;
  case 'scale':
  default:
    requestParams.Web_Map_as_JSON.mapOptions.scale = MapUtil.SCALE_ZOOM_LEVEL_MAP[map.getZoom() + 3];
    break;
}

if (requestParams.Layout_Template == 'MAP_ONLY') {
  if (printOption.mapOnlyWidth && printOption.mapOnlyHeight) {
    requestParams.Web_Map_as_JSON.exportOptions.outputSize = [printOption.mapOnlyWidth, printOption.mapOnlyHeight];
  } else {
    requestParams.Web_Map_as_JSON.exportOptions.outputSize = [map.getContainer().clientWidth, map.getContainer().clientHeight];
  }
}

The code that builds the operational layers is as follows:
  getOperationalLayers(map) {
let pointLayerSpec = {
  "layerDefinition": {
    "name": "pointLayer",
    "geometryType": "esriGeometryPoint",
    "drawingInfo": {
      "renderer": {
        "type": "simple",
        "symbol": {
          "type": "esriPMS",
          // The following is the map pin icon, converted first to a PNG then to base64. Map Print hates SVG.
          "imageData": "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAABwlBMVEUAAAAAAAAAAABAQEAzMzMrKyskJCQgICBAQEA5OTkzMzMuLi4rKysnJyc3NzcrKysoKCgxMTEuLi4zMzMvLy8uLi4zMzMwMDAtLS0zMzMyMjIvLy8uLi4yMjIxMTEvLy8uLi4tLS0yMjIxMTEwMDAvLy8uLi4yMjIxMTEwMDAvLy8uLi4uLi4yLi4xLS0xMTEwMDA0MDAvLy8uLi4yMjI2LjJBMTVFMTVILjVIMTlTLThRMDtPLzlOKzVRLjVcLjxQLTRULThXLThbLTtTLTdaLTtYLDpmLT1rLD9vK0F3LEGQKUiRKUeWK0mXKkiYKkqbKUqrKU2uKU+6JlG8JlG8JVC+JVLEJVLFJVPFJlTIJlTKJVXJJVTMJFTOJFXPJVbRJFbSJlbTJVfUJVjVJFfXJFbXI1fZI1ffJFneIljfJFjeI1jgI1rgI1ngJFniJFriJFriI1nkI1vlJFvnI1vpJFzrIlvsIlzuIl3uIlzvI13vI13wI17xI17yI17yI17yIl3yIl7yIl3yI13zIl7zIl30Il7zI170I1/1I171Il72Il/2I1/1Il72Il/2Il72Il73Il/4Il/4Il/4Il/////ycNrEAAAAlHRSTlMAAQIEBQYHCAgJCgsMDQ4SExUWGRscHiAiIyQmJykqKywtLi8wMTIzNDU2Nzg4OTk6Ozw9PT0/Q0NDREVHSEhISUlJSUpKS1BRU1ZjZGZnaGt3d4WIiYmPkJKVlpianKCho6SmqKutrbe5uby8vb/AwcLEx8zQ19re4ODh5OXm5+nq6+zt7vHy8vP09ff4+Pn7/f3+W5jqtQAAAAFiS0dElQhgeoMAAAGASURBVBgZfcGLO1NhAAfgn9lWwyZJK81t1rIZlrt0cSukdKGrUnRxydwiJo5UVkqK/f7gvvM9Ht85Z5v3hYGjqDJSXx8JnHEgHXtx21BsPfFT+/jkxrlspPDUPdrioR/Pa3JhkdM6TYPJZhdMbFUxmkyFs2HkHabF0HkY2K98o6TNz2uUvrY7oBQ+pi450uT3N71IUjdcCKVigbpXATvguDhO3VwZlGqNQqLNCcHZ/Y/CxiUojXsUloKQgmsU/lRDafhNYbkKUmiDwq8wlNAKhd2bbgju20kKn/xQfBPUzdS4AU/tInVvvVBO3af0oTca7Y1RuuuGknV5ndLB5uYBpc8hGBWP0uLlWRjl3dqhyU6XEyblb2gydgFmnv6/NNjrc8EiME6D12Wwyuvc5pHv13OQouQZjzz1IZWrJc5Dqy0nkYb33j6l/UEv0rGF31N6F7EhrfyeLxS0qwXIoPwhhQeVyMQenSNnG04go9Md8fi1IhzDd2egBMfJKi21weQ/SGPVKkttvyQAAAAASUVORK5CYII=",
          "contentType": "image/png",
          "width": 16,
          "height": 16
        }
      }
    }
  },
  "featureSet": {"features": []}
};
let polygonLayerSpec = {
  "layerDefinition": {
    "name": "polygonLayer",
    "geometryType": "esriGeometryPolygon",
    "drawingInfo": {
      "renderer": {
        "type": "simple",
        "symbol": {
          "type": "esriSFS",
          "color": MapUtil.PRINT_FILL_COLOR,
          "outline": {"color": MapUtil.PRINT_LINE_COLOR, "width": 1}
        }
      }
    }
  },
  "featureSet": {"features": []}
};
let lineLayerSpec = {
  "layerDefinition": {
    "name": "lineLayer",
    "geometryType": "esriGeometryPolyline",
    "drawingInfo": {
      "renderer": {
        "type": "simple",
        "symbol": {
          "type": "esriSLS",
          "color": MapUtil.PRINT_LINE_COLOR,
          "width": 1
        }
      }
    }
  },
  "featureSet": {"features": []}
};
let layers = [pointLayerSpec, polygonLayerSpec, lineLayerSpec];

let addPointFeature = (geoJSON) => {
  pointLayerSpec.featureSet.features.push({
    "geometry": {
      "x": geoJSON.geometry.coordinates[0],
      "y": geoJSON.geometry.coordinates[1],
      "spatialReference": {
        "wkid": 4326
      }
    }
  });
};
let addPolygonFeature = (geoJSON) => {
  polygonLayerSpec.featureSet.features.push({
    "geometry": {
      "rings": geoJSON.geometry.coordinates,
      "hasZ": false,
      "hasM": false,
      "spatialReference": {
        "wkid": 4326
      }
    }
  });
};
let addMultiPolygonFeature = (geoJSON) => {
  geoJSON.geometry.coordinates.forEach(coordinates => {
    polygonLayerSpec.featureSet.features.push({
      "geometry": {
        "rings": coordinates,
        "hasZ": false,
        "hasM": false,
        "spatialReference": {
          "wkid": 4326
        }
      }
    });
  });
};
let addLineFeature = (geoJSON) => {
  lineLayerSpec.featureSet.features.push({
    "geometry": {
      "paths": geoJSON.geometry.coordinates,
      "hasZ": false,
      "hasM": false,
      "spatialReference": {
        "wkid": 4326
      }
    }
  });
};
let addFeature = (geoJSON) => {
  if (geoJSON.geometry.type === "Point") {
    addPointFeature(geoJSON);
  } else if (geoJSON.geometry.type === "Polygon") {
    addPolygonFeature(geoJSON);
  } else if (geoJSON.geometry.type === "MultiPolygon") {
    addMultiPolygonFeature(geoJSON);
  } else if (geoJSON.geometry.type === "LineString" || geoJSON.geometry.type === "MultiLineString") {
    addLineFeature(geoJSON);
  }
};

map.eachLayer((layer) => {
  if (layer.toGeoJSON) {
    let geoJSON = layer.toGeoJSON();
    if (geoJSON.type === "Feature") {
      addFeature(geoJSON);
    } else if (geoJSON.type === "FeatureCollection") {
      _.forEach(geoJSON.features, (geoJSONFeature) => {
        addFeature(geoJSONFeature);
      });
    }
  }
});
return [
  {
    "id": "defaultBasemap",
    "title": "World Topographic Map",
    "opacity": 1,
    "minScale": 0,
    "maxScale": 0,
    "url": "https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer"
  },
  {
    "id": "map_graphics",
    "featureCollection": {
      "layers": layers
    }
  }
];
}

I don't think there's anything wrong with the request, but every single time the map is exported it is stretched. Is there something I need to be doing to the leaflet map before this stage to prevent the stretching? I'm pretty new to these plugins, I don't know where to start.

A: I decided to project the Extent coordinates to Web Mercator.  This solved the "stretched" problem I was having.  It appears the same issue you are having.
Here is a Javascript function I built that converts the current bounds of the map to 3857 and sets up the "mapOptions" part of the Export Web Map JSON.
getMapOptions() {
    const bounds = map.getBounds();
    // convert from 4326 to 3857
    let northEast = bounds.getNorthEast();
    let southWest = bounds.getSouthWest();

    let extent = {
        "xmin": L.CRS.EPSG3857.project(southWest).x,
        "ymin": L.CRS.EPSG3857.project(southWest).y,
        "xmax": L.CRS.EPSG3857.project(northEast).x,
        "ymax": L.CRS.EPSG3857.project(northEast).y,
        "spatialReference": {
            "wkid": 3857
        }
    };

    return {
        "extent": extent,
        "scale": 7000,
        "rotation": 0
    };
}


text:
Q: Simple Web Application Bundle(WAB) in tomcat osgi implementation I am having trouble accessing a simple WAB deployed in tomcat using servletbridge osgi implementation.
I was able to programmatically register jsp/servlets/html using HttpService using pure osgi bundles and can access this bundle. The next thing i tried was creating a separate WAB containing one html and one servlet resource, but running into some issues accessing the bundle. I tried both jarred and unjarred bundle. What I am assuming right now is that for a WAB I am not required to register my resources either programmatically or in a declarative way ???
Below is the WAB bundle which I have created. It does not contain any Http Service Tracker, just an activator to show an activation and deactivation message on console.
sample.http1

   helloworld.html

   |META-INF
       MANIFEST.MF

   |WEB-INF
      web.xml
      |classes
           |sample
                 |http
                      Activator.class
                      HelloWorldServlet.class

Below is the MANIFEST.MF file
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: sample.http1
Bundle-SymbolicName: sample.http1
Bundle-Version: 1.0.0
Bundle-Activator: sample.http.Activator
Import-Package: javax.servlet,javax.servlet.http,org.osgi.framework, org.osgi.service.http, org.osgi.util.tracker
Bundle-ClassPath: WEB-INF/classes
Web-ContextPath: /samplehttp

Below is the code for Activator class
package sample.http;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {

    public void start(BundleContext context) throws Exception {
    System.out.println("Starting Hello World");
}
        public void stop(BundleContext context) throws Exception {
          System.out.println("Stopping Hello World");
}
}

Below is the content of web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>helloworld</servlet-name>
<servlet-class>sample.http.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloworld</servlet-name>
<url-pattern>/helloworld</url-pattern>
</servlet-mapping>
</web-app>

I then activated this bundle. And tried accessing the WAB resources as below, but i am getting a 404 page resource not found error.
http://localhost/bridge/samplehttp/helloworld.html   --for the static html
http://localhost/samplehttp/helloworld.html
http://localhost/bridge/samplehttp/helloworld   --for the HelloWorldServlet
http://localhost/samplehttp/helloworld
Tomcat is hosted on port 80. and i can access my other osgi bundles which are registered programmatically using HttpService. The Below osgi bundle works perfectly.
e.g  http://localhost/bridge/jsp-examples/helloworld.jsp
Please advice. I have referred the osgi specification document and an another blog at
http://www.javabeat.net/2011/11/writing-an-osgi-web-application/

A: Does your embedded OSGi container setup support WABs? What kind of osgi framework is running? Is there only the HttpService available. As long as you don't have a support for WABs (e.g. the Felix HTTP-Service doesn't support this) you're in vain. If it's possible to change the HTTP-Service, you might consider using the Pax-Web implementation of it, it supports std. HTTP-Service, a WhiteBoard Extender for it and of course full support for WABs. The latest one even supports Servlets 3.0.
Though if you're bound to an existing infrastructure, which you're not allowed to change there is nothing you can do to deploy a WAB.
It's kind of "strange" to deploy a WAB in a OSGi container which itself runs inside a WAR container :-)
So basically if you want to use this scenario you probably need to do something like the following:
Have a WAR application running in the Tomcat, have your OSGi services running inside the OSGi-Container inside the other WAR. Do remote HTTP calls to the services inside your OSGi-War.


text:
Q: python ObjectListView has a single un-editable column I have a ObjectListView that I have made editable with
self.TrackOlv.cellEditMode = ObjectListView.CELLEDIT_SINGLECLICK
The gives me 2 odd issues.
1) I can't edit the first cell/column.  Is this due to OLV treating it like a primary key or something to that effect?  I assume I can get around it by creating another attribute to my object and then just not displaying it, but that seems kind of cheesy.
2) I have about 4 chars worth of white space before the first char of my first column.  Is this normal?  This includes the standard blue/yellow line color effect.  I have the white space, then the column text and color effect will begin.  Its not a big deal, just wonder if its normal.

A: 1.) For each column have you added isEditable=True?
first_col = ColumnDefn('Name', 'left', -1, 'name', isEditable=True)

This works perfectly for me in my OLV, along with having;
self.TrackOlv.cellEditMode = self.TrackOlv.CELLEDIT_SINGLECLICK

2.) You can read why this is the case here. Basically, if you don't need sorting, you can get rid of this gap.


text:
Q: Windows + VPN + port forward or proxy I have two computers on LAN:

*

*192.168.0.2 (windows 7 workstation)

*192.168.0.3 (debian linux server)

My windows 7 workstation (.0.2) is connected to external VPN and has also IP 10.0.15.5 and can connect to SQL server at 10.0.15.2 port 1433 ...
I also want to connect from my debian linux server (.0.3) to the same SQL database. Unfortunately I am not able to make a VPN connection from linux server because VPN is windows-only.
So I was wondering if I could somehow make a port forward or proxy or tunnel or whatever that would allow me to connect from linux box to DB server over windows workstation's VPN..
e.g.:
192.168.0.3 (linux) -> 192.168.0.2, port 8888 (or whatever) -> 10.0.15.2, port 1433


text:
Q: addFileAttachmentAsync call successful but Outlook 2016 says "Download failed" The add-in I am developing uses the addFileAttachmentAsync() function to attach a text file. This function works correctly in OWA, but when I test the add-in in Outlook 2016 I am seeing some strange behavior.
The addFileAttachmentAsync() call appears to succeed passing the asyncResult.status == Office.AsyncResultStatus.Succeeded check and the code within that block is executed. However, underneath the file name instead of seeing the file size Outlook says Download failed, but strangely it is still possible to click on the "failed" attachment and open it.
The URL used is a publicly accessible S3 bucket. I have one computer running Outlook 2016 where the addFileAttachmentAsync() call adds the attachment without problems, but two others display the Download failed string after adding the attachment. This behavior is consistent so it does not appear to be any type of network issue.
Is this a problem with the code in my add-in? Or is something going wrong with the Outlook 2016 clients on the other computers?


text:
Q: Trying to inject a dll into an already running JVM? I've created a Windows registry entry in HKEY_CLASSES_ROOT* with the value: "C:\test.exe" "%1" to create a new right-click context menu entry that passes the filepath of the clicked file to the registered test.exe. Inside the test.exe a dll-file is loaded that should inject into an already running jvm to call a method and pass the filepath. The problem is that the .dll does not find a JVM instance although it is running in a while-loop (prototype). Could you please help me to solve that problem? How do I have to access the JVM? Thanks
.java:
public class Main
{
    public static void main(String[] args)
    {
        while(true)
        {

        }
    }

    public static void readAndOutputFilePath(String result)
    {
        System.out.println("Java result: "+result);
        try
        {
            System.in.read();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

.dll:
HMODULE m_hDllInstance = LoadLibrary("jvm.dll");
if( m_hDllInstance == 0)
{
    printf("The jvm.dll could not be found");
    getchar();
}
else
    printf("jvm.dll found");

JavaVM *jvm;
JNIEnv *env;

typedef jint (JNICALL * GetCreatedJavaVMs)(JavaVM**, jsize, jsize*);
GetCreatedJavaVMs jni_GetCreatedJavaVMs = (GetCreatedJavaVMs)GetProcAddress(m_hDllInstance, "JNI_GetCreatedJavaVMs");

jint size = 1;
jint vmCount;

jint ret= jni_GetCreatedJavaVMs(&jvm, size, &vmCount);

cout << endl << "GetCreated: " << vmCount << endl;
getchar();

jint rc = jvm->AttachCurrentThread((void **) & env, NULL);

jclass cls = env->FindClass("Main");
jmethodID mid = env->GetStaticMethodID(cls, "readAndOutputFilePath", "(Ljava/lang/String;)V");

jstring resultString = env->NewStringUTF(path);
env->CallStaticVoidMethod(cls, mid, resultString);
...

A: There is nothing special about communications with a Java program running in an independent, separate process. Any IPC facility supported by Java can be used. Local sockets is the first thing that comes to mind, but also shared memory and plain old filesystem.
JNI is probably irrelevant, as your Java program is in a separate process - unless you want to use some windows-specific communication modes such as OLE. In that case you'll need to write your communication protocol in another language an load them into your Java program.

A: You don't seem to understand what a JVM actually is. It is itself a DLL that is loaded into the process. It isn't a 'thing' that's just 'out there'. Using the JNI Invocation API you can start one, and you won't find 'the' JVM in a .exe that you just started yourself unless you do so.


text:
Q: How to enable slow genie effect in macOS 10.13 High Sierra? In the past, we can hold shift and press minimize button to get slow genie effect. But in macOS 10.13 High Sierra, I can't use this trick anymore. How to enable this feature?

A: Thanks to @etaionshrd on Reddit we have this Terminal command:
defaults write com.apple.dock slow-motion-allowed -bool true && killall Dock

If it doesn't work, try copy-pasting it. There is no auto-correct in Terminal and spelling counts. Works for me macOS 10.13.2 High Sierra.
https://www.reddit.com/r/apple/comments/6jeefp/in_the_latest_high_sierra_beta_a_small_relic_from/#t1_dmpcle3

A: I think they set this feature disabled by default after 10 plus years, what a shame.


text:
Q: Creating a straight line motion path using the Maya API I'm working on a project and for it I need to be able to create a straight line motion path and attach a camera to it. Once the camera moves along that path completely, I also need to render it from the camera's view, all with the Maya API.
Could anyone help me out with this ?


text:
Q: How to change agents roles I am new to netlogo and I really need somebodys help.My issue is: I am trying to do simulation with 3 sets of agents: firms, officers and citizens. The thing is: Together,I have 10 persons / turtles  and I need them to be divided into these 3 sets, but I also need than, at the beginnig,each turtle can choose to which set of agents he wants to belong.......... So each time I will click on setup bottom, agents can change their role.
Thanks for a help. Erika
My code is:
breed [firms firm]
breed [ officers officer]
breed [ citizens citizen]

to setup
  clear-all
  create-turtles num-of-firms[
    set color blue
    set xcor random-xcor
    set ycor random-ycor
    ]
  create-turtles num-of-officers [
   set color green
   set xcor random-xcor
   set ycor random-ycor
   ]
  create-turtles num-of-citizens [
   set color white
   set xcor random-xcor
   set ycor random-ycor
  ]
 set-default-shape turtles "person"
 reset ticks

end

A: Each NetLogo turtle has a built-in breed variable that you can use to dynamically change the breed of a turtle.
If you wanted to create some total number of agents (e.g., 100) and have each them choose at random which breed it belongs to, you could do:
breed [ firms firm]
breed [ officers officer]
breed [ citizens citizen]

to setup
  clear-all
  set-default-shape turtles "person"
  create-turtles 100 [
    set xcor random-xcor
    set ycor random-ycor
  ]
  ask turtles [
    set breed one-of (list firms officers citizens)
  ]
  ask firms [ set color blue ]
  ask officers [ set color green ]
  ask citizens [ set color white ]
  reset-ticks
end


text:
Q: Using HTML.EditFor for an viewmodel inside a parent viewmodel I'm new to MVC3 and razor so this might be obvious but no amount of googlefu has found an answer for me.
I have a ViewModel called user, inside of user i have a 2nd viewmodel called address.
Address is used all over the place so i planned on having the following\
ViewModels:

*

*User -> {Fname, lname, Address}

*Business -> {companyname, Address}

*House -> {Number, Address}

*Address -> {addyline1, addyline2, city, state, zip}

Ala...
user.address.addyline1, business.address.addyline1
All of these will have the Address inside them.
@Html.EditorFor(model => model.address)

Works fine but doesn't use the template I have created in

views->shared->editortemplate->address.cshtml

@Html.EditorFor(model => model.address, "Address")

Does not work at all.

A: Well you don't use put "cshtml" portion in typically when you put the template name probably "_AddressPartial" would work for you, but i'd think you want to just omit that argument and put your custom razor template in "~/Views/Shared/EditorTemplates/address.cshtml"

A: I agree with @jbtule. just remove the file extension from the partial view's name and you should be fine.
Another thing you can do to control how your Address objects get rendered without having to specify the partial view template every time is create what's called an EditorTemplate. Here's how you do it:
Create a folder called EditorTemplates under the Views->Shared folder in your ASP.NET MVC solution.
In that folder, create a strongly typed view whose name matches the name of the type you want the editor for (in your case it should be called Address.cshtml), and you can also set the scaffolding template to Edit to have a ready-to-go editor generated for you. and you're all set! all is left is to have add
here's an example on how to do this (note that it uses ASP.NET MVC2, and of course, the ASPX view engine, however the idea is the same).
Hope this helps ;)

A: The name of the folder to place your Address.cshtml is
EditorTemplates

and not EditorTemplate (one small s can make a lot of difference).


text:
Q: 2 cols, 1 fixed, the other fluid? (dilemma) Can anyone explain to me this code because it seems to beat my logic?

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test CSS Lay 2 col, 1 fix 1 fluid</title>

My questions rely on the facts that #left holds a margin-left: -100px attribute, the position of the div's within the main div suggest that the left column would rather be a right column and why is the "col" column floated to the left within the "colWr" div?
For a 1_fixed-1_liquid css layout, the code is quite a mind-twister.

A: The order of the divs doesn't matter as colWr has a width of 100% which means anything floated after it will appear on a new line anyway, if the left column came first it would force the colWr column on to a new line and it would have to be given a negative margin. The left div has a negative margin of 100% which brings it back on top of colWr.
As to why the page was laid out this way I have no idea, the same effect could be just as easily achieved by putting the left next to the col div and removing the colWr div (doesn't do any harm but it serves no purpose).
You should also note that the center tag in HTML has been deprecated and I recommend you give centre a div by specifying in it's css margin: auto. The code also lacks a DOCTYPE declaration which is required to trigger standards mode in most browsers - you can find more information about browser modes here.
My suspicion is that the code you have was written pre-dating the release of HTML 4.01. It will work in most browsers due to their legacy support but that doesn't mean it works well, I wouldn't use it. I would however use this:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Test CSS Lay 2 col, 1 fix 1 fluid</title>


text:
Q: Displaying web page when running WCF service I have a WCF service that operates on a database. When running this project in Visual Studio, a browser page opens that simply shows the project's file structure.
I have an HTML file that displays a user interface for the service. How can I make it so that this file is automatically displayed in the browser when running the project? Thanks in advance!

A: Right click on the HTML file on the project explorer and select "Set as Start Page".It will display this while running the project.

A: The other answers will do the trick. If you want your file to be displayed without having to redirect to the actual file, you can do the following.
Add this to your WCF service's web.config:
<system.webServer>
<defaultDocument enabled="true">
  <files>
    <clear />
    <add value="Index.html" />
  </files>
</defaultDocument>
</system.webserver>

Index.html will now be automatically loaded when running the project.

A: In Project Properties -> Web -> StartAction -> select "Specific Page" and specify the page you want to be displayed instead of the default service view


text:
Q: Trying to find gsl library, the only thing I can find is a loop in the system I am working currently a little bit with wind data and I am using GSL and PlPlot to visualize and work with it.
When I try to add GSL or PlPlot libraries:
#include <gsl/gsl_errno.h>
#include <gsl/gsl_spline.h>

I get this message:
inter.c:4:27: fatal error: gsl/gsl_errno.h: No such file or directory
#include <gsl/gsl_errno.h>
                       ^

Far as I know, this means that I need to add the complete path to my library file, when I search for gsl then I get this:
find: File system loop detected; '/.snapshots/1/snapshot' is part of the     same file system loop as '/'.
/.snapshots/2/snapshot/usr/share/doc/packages/gsl
/.snapshots/93/snapshot/usr/share/doc/packages/gsl
/.snapshots/94/snapshot/usr/share/doc/packages/gsl

I have read a little bit (still searching on the web), something went wrong with the installation of gsl? and plplot?. Strange as it appears is the same with math.h. There is a main difference here, because math.h is detected but gsl/plplot are not. How can I find my path to the library files and how can I eliminate that recursion?.
By the way, gsl and math were installed by default on SuSE at the begining and plplot was installed after using yast. Also I can find the GSL and PlPlot directories but the files are missing.
Thanks for any help guys.


text:
Q: Please prevent creation of tags that could trigger the IIS file extension filter Someone created user32.dll the other day.  Being a dutiful member of the New Tag Deletionist Cabal, I dove in to try and see if there could be a better, existing tag for the question, only to be greeted with nothing.  The server returned 404, a Date header, and a content length of zero.
This is a known behavior with IIS that has bit SO before.
Given that this is known IIS behavior, the tagging system should make an effort to block users from creating new tags that will result in the site breaking.
(As for user32.dll, I was able to find the question and replace the tag with user32)

A: After the next build we will allow extensions that were previously restricted.  We have updated to ASP.NET MVC4 and it appears to handle them correctly.


text:
Q: Reconstructing Topological Spaces by Algebraic Images of Functors. At the beginning paragraph of chapter 1 in Hatcher's Algebraic Topology it says:

Algebraic topology can be roughly defined as the study of techniques for forming algebraic images of topological spaces. Most often these algebraic images are groups, but more elaborate structures such as rings, modules, and algebras also arise. The mechanisms that create these images — the 'lanterns' of algebraic topology, one might say — are known formally as functors and have the characteristic feature that they form images not only of spaces but also of maps. Thus, continuous maps between spaces are projected onto homomorphisms between their algebraic images, so topo- logically related spaces have algebraically related images.
With suitably constructed lanterns one might hope to be able to form images with enough detail to reconstruct accurately the shapes of all spaces, or at least of large and interesting classes of spaces.This is one of the main goals of algebraic topology, and to a surprising extent this goal is achieved.

I attempted to search for more information about this method of reconstruction but failed to find anything. Could anyone please give some details of this reconstruction of topological spaces?

A: I am not an algebraic topologist, but to me it seems like the more accurate word would be 'identify' rather than 'reconstruct'. Assume you are interested in a certain class of 'shapes' (e.g. orientable closed surfaces) and you already have collection of basic examples of those shapes $X_1,X_2,\dots$ (e.g. a sphere, a torus, $\dots$). Now, if I hand you another of those shapes  $Y$, can you identify it with one of these $X_i$? In the example at hand you might want to suggest to just count the holes of $Y$: If it has zero holes, then it is a sphere, if it has one hole, then it is a torus and so on.
Counting holes can be formalized by one of the techniques that Hatcher refers to and  indeed for this class of shapes (orientable closes surfaces) it is the only thing you need to successfully identify objects.
For other classes of shapes (e.g. higher dimensional manifolds, arbitrary toplogical spaces, knots, graphs, ...) you need more tools (lanterns) to identify objects. Unfortunately it is rarely possible to give an exhaustive list of all possible shapes (like the $X_1,X_2,\dots$), but often you can still use your lanterns to at least tell whether two given shapes $X$ and $Y$ can be the same. A typical argument is to say that if they appear differently under a certain lantern, they cannot be the same. (The question of whether you have enough lanterns to conclude that they are the same once you you have checked under each of it is much harder, though.)


text:
Q: Is every finite quantum group a quantum symmetry group? This post is basically a quantum extension of Is every finite group a group of "symmetries"?
Here finite quantum group means finite dimensional Hopf ${\rm C}^{\star}$-algebra.
Frucht's theorem states that every finite group is the automorphism group of a finite graph. Wang defined here a notion of quantum automorphism group. The application to a finite space of $n$ elements is called "the quantum permutation group of $n$ symbols", and its quantum subgroups are called quantum permutation groups of degree $n$. Bichon introduced here the quantum automorphism groups of finite graphs, these are quantum permutation groups. See also this survey of Banica-Bichon-Collins.
Kojima proved here that every finite group is realized as the full isometry group of some compact hyperbolic $3$-manifold.
This book of Goswami-Bhowmick introduces the notion of quantum isometry group.
General question: Is every finite quantum group a quantum symmetry group?
Sub-question 1: Is a finite quantum permutation group a twisted finite group?
Sub-question 2: Is every finite quantum group a quantum permutation group?
Answer: no, the smallest counter-example has dim. $24$ (see this paper of Banica-Bichon-Natale).
Sub-question 3: Is every finite quantum permutation group of dimension $n$ a quantum permutation group of degree $n$?
Sub-question 4: Is every finite quantum permutation group a quantum automorphism group of a finite graph?
Sub-question 5: Is every finite quantum group $\mathbb{G}$ a quantum subgroup of the quantum automorphism group of a finite dimensional ${\rm C}^{\star}$-algebra $\mathcal{A}$? Ok for $\mathcal{A} = C(\mathbb{G})$?
Answer (Bhowmick): yes, it follows trivially from the definition, using Haar state.
Sub-question 6: Is every finite quantum group a quantum isometry group?

A: The answer to sub-question 4 is no.
See here, The Frucht property in the quantum group setting.
To expand slightly, this paper gives four explicit finite quantum permutation groups which are not the quantum automorphism groups of a finite graph: the duals of $S_3$, $A_4$, and $A_5$, and the Kac--Paljutkin quantum group of order eight, denoted $G_0$.
If the dual of $S_3$ is the quantum automorphism group of a graph, then, taking abelianisations, the (classical) automorphism group of the graph must be $\mathbb{Z}_2$. The paper above shows that if the dual of $S_3$ acts on a graph then a (classical) abelian group larger than $\mathbb{Z}_2$ acts on the graph too. Therefore the dual of $S_3$ is not the quantum automorphism group of a graph.
In fact it is shown that if the dual of $S_3$ acts on a graph then the dual of a(n infinite) free product acts on the graph too.
A similar story holds for the duals of $A_4$ and $A_5$.
If $G_0$ is the quantum automorphism group of a graph, then the graph has classical automorphism group $\mathbb{Z}_2\times\mathbb{Z}_2$. The above shows that if $G_0$ acts on a graph then so does the dihedral group of order eight. Therefore $G_0$ is not the quantum automorphism group of a graph.


text:
Q: Equating $\partial_{t_r}$ = $\partial_{t}$ in the retarded potentials? Im reading Griffiths E/M (4th edition) and came across something I don't understand: Page 446, footnote 8 which reads:
"Note that $\frac{\partial }{\partial t_r} = \frac{\partial }{\partial t}$ since $t_r = t - \frac{R}{c}$ and $R$ is independent of $t$"
And I do not understand this at all because we know that the present time, $t$, and the retarded time, $t_r$, do not scale uniformly. Instead the scale:
$$ \frac{dt}{dt_r} = 1- \vec{n}\cdot\vec{\beta}$$
In addition, in another textbook I referenced, in deriving the electric field from the partial time derivative of the vector potential, we cannot just equate two partial time derivative:
$$ \frac{\partial \vec{A}}{\partial t} \ne \frac{\partial \vec{A}}{\partial t_r}$$
We need to apply the change of variables:
$$ \frac{\partial \vec{A}}{\partial t} = \frac{dt_r}{dt}\frac{\partial \vec{A}}{\partial t_r}$$
I do not think Griffiths is wrong since he gets the right answer at the end, but I just don't understand the logic of equating the partial derivatives. My guess is that since the time derivative is taken out from the gradient operation (where we keep both the present time and retarded time constant and only vary the spatial dimensions of the system) we can equate the two partial derivatives under the gradient operation.
Any feedback?

A: You are confusing two different concepts here. In the case of Griffiths' treatment, the partial derivative $\partial / \partial t$ refers to the variation in $t$ when $\mathbf x$ is held constant with time. In this case, since the retarded time is
$$t_r(\mathbf x,t) = t - \frac{|\mathbf x |}{c} ,$$
(or more generally $t-|\mathbf x - \mathbf x'|/c$), $\partial/\partial t = \partial/\partial t_r$ since $\mathbf x$ is kept constant by assumption. Note that I've written $t_r\equiv t_r(\mathbf x,t)$ as a function of $\mathbf x$ and $t$ to clarify something later.
But what does your $dt/dt_r = 1- \hat{\mathbf n}\cdot \boldsymbol \beta$ correspond to? First, note that the very fact that you have $\boldsymbol \beta = \dot{\mathbf x}(t)/c$ in this equation implies that $\mathbf x$ is not kept constant! The derivative in your other textbook is probably a completely different type of derivative. Note that when the observation point is fixed in time ($\dot{\mathbf x}(t) = 0$), you get $dt/dt_r = 1$, which again tells you that $\partial/\partial t = \partial/\partial t_r$.
Personally, I always like to write my functions with their arguments to avoid confusing these things. For example, for a fixed $\mathbf x$, it is true that:
$$\frac{\partial}{\partial t}  \mathbf A \Big(\mathbf x,t_r(\mathbf x,t) \Big) \equiv \frac{\partial}{\partial t_r}  \mathbf A(\mathbf x,t_r).$$
But now we can let $\mathbf x$ vary with time like $\mathbf x(t)$. For example, maybe we're looking at the trajectory of a particle, and we want to see how the vector potential changes with time as experienced by that moving particle, meaning that $\mathbf x(t)$ needs to be the particle's instantaneous position. Then, the derivative you want is
$$\frac{d}{dt} \mathbf A\Big(\mathbf{x}(t), t_r\big(\mathbf x(t),t \big)\Big) \neq \frac{\partial}{\partial t_r} \mathbf A(\mathbf x(t),t_r).$$
The two are not equal because as you can see, $\mathbf A$ changes with time both because of the variation of $t_r(\mathbf x(t),t)$, as well as the time-dependence of $\mathbf x(t)$ itself.
In conclusion, you're calculating two completely different quantities here, which are of course not going to be equal in general.


text:
Q: Use data from one variable in the title of another - javascript Is there any way to use the data from one variable in the declaration of another variable? It is the same concept of coercing strings, just in the variable declaration. For example, if I wanted to create a variable called user1, is there any way to do it somehow like this:
var i = 1; // Creates variable with value of 1
var user + i = "John"; // Creates variable with name of user1 (because i has a value of 1)

A: You can do something like
var i = 1;
var username = 'John';
var users = {};
users[username + i] = username

And after this you can use
users.John1

Is this acceptable ?

A:  var i = 1; // Creates variable with value of 1

Instead of
     var user + i = "John"; // Creates variable with name of user1 (because i       has a value of 1) you should
use:
 window['user'+i] ="John";

 alert(user1);

https://jsfiddle.net/6x0uLbe8/


text:
Q: Why is part of my path rendering thicker? I'm trying to get the basics of paths understood, and I'm trying to make an hourglass shape. When I try and draw the top part, kind of an upside-down U, the right-hand side part is thicker. What have I got wrong?

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportHeight="24"
        android:viewportWidth="24">

    <group>
        <path
            android:pathData="M0,5L0,0M0,0L10,0M10,0L10,5"
            android:strokeColor="@color/ColorPrimary"
            android:strokeWidth="3"/>
    </group>
</vector>

A: Stroke extends either side of the line.
You see the entire stroke of the right hand part but only half of the stroke of the left hand part as it extends outside of the visible area since the x co-ordinate is 0, which makes the stroke occupy x co-ordinates from -1.5 to +1.5


text:
Q: change ftpd password viassh pure-ftpd Hi my cpanel license just ended up needed to change an user's ftp password via ssh
logged on as root and changed password by
passwd username

command but still i can login by old password to ftp :/
i use pure-ftpd / centos
what should i do for able to change ftp password
thanks

A: You need to use the following:

pure-pw passwd user

Man page:
http://linux.die.net/man/8/pure-pw

A: I've just done this on Debian-based Raspberry Pi OS with success:
sudo pure-pw passwd {username}
[ENTER NEW PASSWORD WHEN PROMPTED x 2]
sudo pure-pw mkdb
sudo service pure-ftpd restart


text:
Q: Can I clean install Ubuntu over top of existing Ubuntu install partition on a Windows dual-boot drive without reformatting whole drive? I have Windows 7 and Ubuntu dual-booted on my hard drive. My Ubuntu installation became kind of messed up and I don't know how to fix it. So it would just be easier for me to just do a fresh install of Ubuntu over the existing partition. Is there a way for me to do this without reformatting the whole drive and having to reinstall Windows?

A: Sure. Just choose "something else" during installation for manual partitioning and reformat the partitions that Ubuntu is supposed to use. Obviously, all their data will be lost in the process, but no need to touch Windows partitions.
Relevant comment by TrailRider:

The answer is correct but may have be more complicated that needed. You should be able to boot from the cd/usb and after clicking the install button, the choices window should give you the option to "Erase Ubuntu and reinstall" . Selecting that would format the Ubuntu partition only and do a clean install of Ubuntu.


text:
Q: Strange glitch on ListView: text dissapears after pressing search action button I've a ListView screen that is driving me mad.
Each row has three TextViews. The adapter is a custom ArrayAdapter that makes use of the view recycling mechanism: if the row is first requested, a new view is inflated, otherwise the recycled view is used. Everything works ok. I'm not showing it but for now assume it is correctly implemented.
This is how it looks normally:

There is a search button in the right upper corner of the screen. When clicked, every text view in the list is "cleared"! I've debugged the code and the textviews are there, the text is set and everything is ok except the text is barely or not shown. Here's a view dump taken with DDMS:

Looks like only the first letters of the text are shown. This only happens in certain devices, and only when the adapter's getView method returns the recycled view for the row, BUT only after pressing the search button, which makes the keyboard to show up (If i close it, the text is still missing). If I modify the getView method to always inflate every row this does not happen, but of course this is not an option since my list should be able to handle a large number of items.
Looks like a bug, but I need to do something about it.
I've also tested an alternative recycling mechanism based on a map (basically I put the view for each row in a map). Still the behavior is observed.
Device is a Samsung Galaxy SII running 4.1.2. Not happening in Galaxy SIII mini for instance.
Do you know what could be causing this glitch? Something related to the TextView's width?
Thanks in advance

A: I finally found the cause.
It was one of the TextViews in the adapter xml file. It was contained in a fixed-width LinearLayout. Its width was set to fill_parent, and changing it to wrap_content fixed the issue.


text:
Q: Como controlar as bordas em vídeo do Youtube Como embedar um video do Youtube sem deixar essa bordar preta dos lados.
Gostaria de deixar ele com 100% de largura porém com uma altura definida alguém poderia me ajudar?

A: Depender da proporção do formato do vídeo.
Se você estiver colocando o player em um formato 4:3 ex: 640x480 e o vídeo for nesse formato, não terá borda.
Agora se o seu player é 16:9 (720p) e seu vídeo 4:3 como no caso da sua foto terá borda.
(OBS: para ser exato esse player deve estar 21:9 e o seu vídeo 16:9, ambos widescreen mas com proporções diferentes)
Para entender formatos de tela:
Wikipedia : http://goo.gl/ZxTmU4
Soluções:
Você terá sempre um padrão de vídeo? se sim, então coloque o player com as dimensões exatas. No caso a altura que você quer.
<iframe width="640" height="480" src="//www.youtube.com/embed/Ipsi5aJzXBc" frameborder="0" allowfullscreen></iframe>

 width="640"  //largura
 height="480"  //altura

A: Essa borda em alguns vídeos é problema da própria é edição, sendo assim impossível você resolver o problema dimensionando o player, se dimensionar o player por width e height poderá prejudicar a execução de outros.


text:
Q: Access inherited member I have this LoanWithClient Model that inherits from Loan:
public class LoanWithClient : Loan
{
    public Client Client { get; set; }
}

How can I access the entire inherited Loan object without having to explicitly write its properties?

LoanWithClient does not contain a definition for Loan

return new LoanWithClient
{
     **Loan** = loan, //The Loan is erroring: LoanWithClient does not contain a definition for Loan
     Client = client
};

Class Loan:
public class Loan
{
    public int ID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    //etc..
}

A: The class LoanWithClient inherits from Loan. Which means that the child class have all the properties of parent class. But this doesn't mean that the child class contains a parent class as a property. You can write the class like this-
public class Loan
{
    public int ID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    //etc..
}

public class LoanWithClient
{
    public Loan Loan { get; set; }
    public Client Client { get; set; }
}

return new LoanWithClient
{
     Loan = loan,
     Client = client
};

If you want to keep your class architecture, you can return like the below way-
return new LoanWithClient
{
     ID = loan.ID,
     Address = loan.Address,
     City = loan.City,
     //etc..
     Client = client
};

A: You want to

Access inherited member

Loan is not a member, it's the parent.
Access Loan's members like this:
return new LoanWithClient
{
     ID = loan.ID,
     Address = loan.Address,
     City = loan.City,
     //etc...
     Client = client
};


text:
Q: Salesforce to salesforce using enterprise WSDL files I am trying to connect salesforce to salesforce using enterprise wsdl file.I have been able to login and then I have assigned returned session id to the session header object through which request will be send to access further salesforce API such as query.However,It gives me an error ,Destination URL not set and i have tried whatever I could think of it is not working,Can somebody please help.Below is the code Which I have executed in Anonymous block and down below it is given Classes generated from WSDL files.Can somebody please help.?
enterpriseSoapSforceCom.soap asp=new enterpriseSoapSforceCom.soap();
enterpriseSoapSforceCom.LoginResult lap=asp.login('jack@yahoo.com','Champion');
System.debug('The value in the Url has been'+lap);
enterpriseSoapSforceCom.SessionHeader_element SessionHeader=new enterpriseSoapSforceCom.SessionHeader_element();
sessionheader.sessionid=lap.sessionid;
asp.sessionheader=sessionheader;
asp.inputHttpHeaders_x = new Map<String, String>();
string u=lap.serverurl;
//Setting a basic authentication header
asp.inputHttpHeaders_x.put('URL',u);
//asp.endpoint_x='https://na15.salesforce.com/services/Soap/c/28.0/00Di0000000J1Tf/0DFi0000000PCEo';
enterpriseSoapSforceCom.QueryResult l=asp.query('Select name from opportunity limit 3');
//System.debug('The values which have been returned after querying opportunity object has been'+l);

public class enterpriseSoapSforceCom
     {
        public class getUserInfo_element
     {
            private String[] apex_schema_type_info = new String[]
                 {
                   'urn:enterprise.soap.sforce.com','true','false'};
                    private String[] field_order_type_info = new String[]{};
                  }
        public class LoginResult
           {
            public String metadataServerUrl;
            public Boolean passwordExpired;
            public Boolean sandbox;
            public String serverUrl;
            public String sessionId;
            public String userId;
            public enterpriseSoapSforceCom.GetUserInfoResult userInfo;
            private String[] metadataServerUrl_type_info = new String[]{
    {'metadataServerUrl','http://www.w3.org/2001/XMLSchema','string','1','1','true'};
            private String[] passwordExpired_type_info = new String[]{'passwordExpired','http://www.w3.org/2001/XMLSchema','boolean','1','1','false'};
            private String[] sandbox_type_info = new String[]{'sandbox','http://www.w3.org/2001/XMLSchema','boolean','1','1','false'};
            private String[] serverUrl_type_info = new String[]{'serverUrl','http://www.w3.org/2001/XMLSchema','string','1','1','true'};
            private String[] sessionId_type_info = new String[]{'sessionId','http://www.w3.org/2001/XMLSchema','string','1','1','true'};
            private String[] userId_type_info = new String[]{'userId','urn:enterprise.soap.sforce.com','ID','1','1','true'};
            private String[] userInfo_type_info = new String[]{'userInfo','urn:enterprise.soap.sforce.com','GetUserInfoResult','0','1','false'};
            private String[] apex_schema_type_info = new String[]{'urn:enterprise.soap.sforce.com','true','false'};
            private String[] field_order_type_info = new String[]{'metadataServerUrl','passwordExpired','sandbox','serverUrl','sessionId','userId','userInfo'};
        }

     public class Soap {
            public String endpoint_x = 'https://login.salesforce.com/services/Soap/c/28.0/0DFi0000000PCEo';
            public Map<String,String> inputHttpHeaders_x;
            public Map<String,String> outputHttpHeaders_x;
            public String clientCertName_x;
            public String clientCert_x;
            public String clientCertPasswd_x;
            public Integer timeout_x;
            public enterpriseSoapSforceCom.QueryOptions_element QueryOptions;
            public enterpriseSoapSforceCom.EmailHeader_element EmailHeader;
            public enterpriseSoapSforceCom.DebuggingInfo_element DebuggingInfo;
            public enterpriseSoapSforceCom.MruHeader_element MruHeader;
            public enterpriseSoapSforceCom.PackageVersionHeader_element PackageVersionHeader;
            public enterpriseSoapSforceCom.SessionHeader_element SessionHeader;
            public enterpriseSoapSforceCom.UserTerritoryDeleteHeader_element UserTerritoryDeleteHeader;
            public enterpriseSoapSforceCom.LoginScopeHeader_element LoginScopeHeader;
            public enterpriseSoapSforceCom.AllowFieldTruncationHeader_element AllowFieldTruncationHeader;
            public enterpriseSoapSforceCom.DebuggingHeader_element DebuggingHeader;
            public enterpriseSoapSforceCom.AllOrNoneHeader_element AllOrNoneHeader;
            public enterpriseSoapSforceCom.LocaleOptions_element LocaleOptions;
            public enterpriseSoapSforceCom.OwnerChangeOptions_element OwnerChangeOptions;
            public enterpriseSoapSforceCom.AssignmentRuleHeader_element AssignmentRuleHeader;
            public enterpriseSoapSforceCom.DisableFeedTrackingHeader_element DisableFeedTrackingHeader;
            public enterpriseSoapSforceCom.StreamingEnabledHeader_element StreamingEnabledHeader;
            private String QueryOptions_hns = 'QueryOptions=urn:enterprise.soap.sforce.com';
            private String EmailHeader_hns = 'EmailHeader=urn:enterprise.soap.sforce.com';
            private String DebuggingInfo_hns = 'DebuggingInfo=urn:enterprise.soap.sforce.com';
            private String MruHeader_hns = 'MruHeader=urn:enterprise.soap.sforce.com';
            private String PackageVersionHeader_hns = 'PackageVersionHeader=urn:enterprise.soap.sforce.com';
            private String SessionHeader_hns = 'SessionHeader=urn:enterprise.soap.sforce.com';
            private String UserTerritoryDeleteHeader_hns = 'UserTerritoryDeleteHeader=urn:enterprise.soap.sforce.com';
            private String LoginScopeHeader_hns = 'LoginScopeHeader=urn:enterprise.soap.sforce.com';
            private String AllowFieldTruncationHeader_hns = 'AllowFieldTruncationHeader=urn:enterprise.soap.sforce.com';
            private String DebuggingHeader_hns = 'DebuggingHeader=urn:enterprise.soap.sforce.com';
            private String AllOrNoneHeader_hns = 'AllOrNoneHeader=urn:enterprise.soap.sforce.com';
            private String LocaleOptions_hns = 'LocaleOptions=urn:enterprise.soap.sforce.com';
            private String OwnerChangeOptions_hns = 'OwnerChangeOptions=urn:enterprise.soap.sforce.com';
            private String AssignmentRuleHeader_hns = 'AssignmentRuleHeader=urn:enterprise.soap.sforce.com';
            private String DisableFeedTrackingHeader_hns='DisableFeedTrackingHeader=urn:enterprise.soap.sforce.com';
            private String StreamingEnabledHeader_hn='StreamingEnabledHeader=urn:enterprise.soap.sforce.com';
            private String[] ns_map_type_info = new String[
    {'urn:fault.enterprise.soap.sforce.com', 'faultEnterpriseSoapSforceCom', 'urn:enterprise.soap.sforce.com', 'enterpriseSoapSforceCom', 'urn:sobject.enterprise.soap.sforce.com', 'sobjectEnterpriseSoapSforceCom'};
            public enterpriseSoapSforceCom.SearchResult search_x(String searchString)
     {
                enterpriseSoapSforceCom.search_element request_x = new enterpriseSoapSforceCom.search_element();
                enterpriseSoapSforceCom.searchResponse_element response_x;
                request_x.searchString = searchString;
                Map<String, enterpriseSoapSforceCom.searchResponse_element> response_map_x = new Map<String, enterpriseSoapSforceCom.searchResponse_element>();
                response_map_x.put('response_x', response_x);
                WebServiceCallout.invoke(
                  this,
                  request_x,
                  response_map_x,
                  new String[]{endpoint_x,
                  '',
                  'urn:enterprise.soap.sforce.com',
                  'search',
                  'urn:enterprise.soap.sforce.com',
                  'searchResponse',
                  'enterpriseSoapSforceCom.searchResponse_element'}
                );
                response_x = response_map_x.get('response_x');
                return response_x.result;
            }

    public class SessionHeader_element
    {
            public String sessionId;
            private String[] sessionId_type_info = new String[]{'sessionId','http://www.w3.org/2001/XMLSchema','string','1','1','false'};
            private String[] apex_schema_type_info = new String[]{'urn:enterprise.soap.sforce.com','true','false'};
            private String[] field_order_type_info = new String[]{'sessionId'};
        }

A: You need to set the enterpriseSoapSforceCom.endpoint_x to the LoginResult.serverUrl.
enterpriseSoapSforceCom.soap binding = new enterpriseSoapSforceCom.soap();
enterpriseSoapSforceCom.LoginResult lr = binding.login('user@example.com','passwordAndToken');

//Update the binding endpoint as per the LoginResult
binding.endpoint_x = lr.ServerUrl;

binding.SessionHeader = new enterpriseSoapSforceCom.SessionHeader_element();
binding.SessionHeader.sessionid=lap.sessionid;

enterpriseSoapSforceCom.QueryResult l = binding.query('Select name from opportunity limit 3');

Also, you may need to add the Salesforce Pod/Server URL to allow outbound web service calls to it.


text:
Q: Inserting double quotes string within formula within VBA - Getting "Application-defined or object-defined error" I'm trying run the following line in a VBA script:
Sheets("sheet1").Range("C13").formula = "=IF(ISERROR(GETPIVOTDATA(""Beloeb"";LikviditetEgenkapitalPivot!$A$3;""Dato"";$B2022;""Dimm4"";C$11))=TRUE;0;(GETPIVOTDATA(""Beloeb"";LikviditetEgenkapitalPivot!$A$6;""Dato"";$B2022;""Dimm4"";C$11)))"

I'm getting an "Application-defined or object-defined error"
I've been looking at the similar questions below (and followed the guide) - but I'm still in "dead water"
I've also tried to use the "chr(34)" method.
Any suggestions?
Inserting double quotes string within formula within VBA (Excel
VBA Application Defined or Object-Defined Error with Formula


text:
Q: android constrait layout overlap with title bar What's wrong with below constraint layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/constraint"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:text="Send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="@+id/constraint"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/txtView" />
    <TextView
        android:id="@+id/txtView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:text="Hello World!"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        />
</android.support.constraint.ConstraintLayout>

The button has been overlapped by title bar!

A:      <Button
         android:id="@+id/toolbar"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_marginEnd="8dp"
         android:layout_marginRight="8dp"
         android:text="SEND"
         app:layout_constraintEnd_toEndOf="parent"
         app:layout_constraintHorizontal_bias="0.05"
         app:layout_constraintStart_toStartOf="parent"
         app:layout_constraintTop_toTopOf="parent" />

     <TextView
         android:layout_width="match_parent"
         android:layout_height="0dp"
         android:layout_marginBottom="8dp"
         android:layout_marginEnd="8dp"
         android:layout_marginLeft="8dp"
         android:layout_marginRight="8dp"
         android:layout_marginStart="8dp"
         android:text="Hello World"
         app:layout_constraintBottom_toBottomOf="parent"
         app:layout_constraintEnd_toEndOf="parent"
         app:layout_constraintStart_toStartOf="parent"
         app:layout_constraintTop_toBottomOf="@+id/toolbar"
         app:layout_constraintVertical_bias="0.0">
     </TextView>

A: Try this...
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:id="@+id/constraint"
  tools:context=".MainActivity">
  <Button
    android:id="@+id/button"
    android:text="Send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginLeft="8dp"
    android:layout_marginStart="8dp"
  />
  <TextView
    android:id="@+id/txtView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_margin="10dp"
    android:text="Hello World!"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button"/>
</android.support.constraint.ConstraintLayout>

Result:


text:
Q: How do I close all Socket objects that have been spawned by a ServerSocket? For a very basic webserver, I have some ServerSocket code that looks roughly like that (in the run() method of a thread), that listens on a specified port and accepts clients:
ServerSocket server = new ServerSocket(port);
while (true) {
    try {
        Socket client = server.accept();
        ClientThread clientThread = new ClientThread(client);
        clientThread.start();
    } catch(Exception e)
    {}
}

Now, this part works, I can access the webserver from my browser and all, and I can close the server with server.close() whenever I want to from the caller.
However, when I do that, if there are spawned client sockets with some kind of keep-alive connection (because I already accessed a page), those Socket objects still exist, and continue to answer requests, which I don't want (the server should stop answering all requests when it is stopped, and cut every established connection).
How can I close all of those spawned client sockets?
My guess is that I could manually keep a reference to every "child" Socket, in an array, then when the server is closed, loop through that array to manually close every socket object that has not yet been closed by the client, but this does not look very optimal to me (nor foolproof).
Is there a simpler, more robust way to do that?


text:
Q: row items against each bars in matplotlib I have plotted like below,
df1
Out[90]:
     feature  OnePlus 2r  iPhone 6s Plusr  OnePlus 2  iPhone 6s Plus
0      Price     23000.0          80000.0   0.287500        1.000000
1     Length       151.8            158.2   0.959545        1.000000
2     Breath        74.9             77.9   0.961489        1.000000
3  Thickness         9.9              7.3   1.000000        0.737374

ax = df1[['OnePlus 2','iPhone 6s Plus']].plot(kind='bar', title ="Lesser the Better",
          figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel(df1.feature,fontsize=12)
ax.set_ylabel("%",fontsize=12)
plt.show()

How could I get price, length,.. against each bar instead of xlabel.
Is there a way without set_index('feature') ?

A: Do you mean to do something like
ax.set_xticklabels(df1.feature,fontsize=12)

to replace the indexes 0, 1, 2,3 with the feature corresponding with your bar-pairs?


text:
Q: Filter pymongo query based on timedelta for two fields for each document I am using MongoDB and Python to work with a collection where each document looks like this:
{_id: 'e82d0b5c-5e38-4442-a678-f29245681238',
start_time: '2020-02-25T20:45:10.623Z',
stop_time: '2020-02-26T21:45:10.623Z',
data: {cost: 3, buyer: 'John'}}

I would like to find all documents in my collection for which the difference between start_time and stop_time is superior to 24 hours. One potential issue I considered is that the format for start_time and stop_time is String, and not Date, but I am able to generate a cursor using:
db['collection'].find({'stop_time':{'$gte': 'start_time'}})

But I cannot generate a cursor using any of the following:
db['collection'].find({'stop_time':{'$gte': 'start_time' + datetime.timedelta(hours=24)}})
TypeError: can only concatenate str (not "datetime.timedelta") to str

db['collection'].find({'stop_time':{'$gte': {'$toDate': 'start_time'} + datetime.timedelta(hours=24)}})
TypeError: unsupported operand type(s) for +: 'dict' and 'datetime.timedelta'

I apologize if this is found to be a duplicate, but I haven't managed to find a post solving my problem. Thank you very much for your time!

A: Here is a solution with an aggregate
[
  {
    "$addFields": {
      "date_diff": {
        "$subtract": [
          {
            "$dateFromString": {
              "dateString": "$stop_time"
            }
          },
          {
            "$dateFromString": {
              "dateString": "$start_time"
            }
          }
        ]
      }
    }
  },
  {
    "$match": {
      "date_diff": {
        "$gte": 86400000 //24*3600*1000
      }
    }
  }
]

I first use $addFields, to create a new field that will contain the difference between the two dates.
To calculate that difference I use $subtract, but before I convert the string to a date format with $dateFromString
Then we can filter only the documents that have a difference greater or equal to 24 hours (or 86400000 milliseconds) with a $match.
try it here