text:
Q: How to insert backslash into my string in java? I have string, and I want to replace one of its character with backslash \
I tried the following, but no luck.
engData.replace("'t", "\\'t")

and
engData = engData.replace("'t", String.copyValueOf(new char[]{'\\', 't'}));

INPUT : "can't"
EXPECTED OUTPUT : "can\'t"
Any idea how to do this?

A: Try this..
    String s = "can't";
    s = s.replaceAll("'","\\\\'");
    System.out.println(s);

out put :
    can\'t

This will replace every ' occurences with \' in your string.

A: Try like this
engData.replace("'", "\\\'");

INPUT : can't
EXPECTED OUTPUT : can\'t

A: String is immutable in Java. You need to assign back the modified string to itself.
engData = engData.replace("'t", "\\'t"); // assign the modified string back.

A: This is possible with regex:
engData = engData.replaceAll("('t)","\\\\$1");

The ( and ) specify a group. The 't will match any string containing 't. Finally, the second part replaced such a string with a backslash character: \\\\ (four because this), and the first group: $1. Thus you are replacing any substring 't with \'t

The same thing is possible without regex, what you tried (see this for output):
engData = engData.replace("'t","\\'t"); //note the assignment; Strings are immutable

See String.replace(CharSequence, CharSequence)

A: The following works for me:
class Foobar {
  public static void main(String[] args) {
    System.err.println("asd\\'t".replaceAll("\\'t", "\\\'t"));
  }
}

A: For String instances you can use, str.replaceAll() will return a new String with the changes requested:
String str = "./";
String s_modified = s.replaceAll("\\./", "");


text:
Q: How to transform this piece of code using Java Stream In order to defend against XSS attacks, I wrote a class that extends from HttpServletRequestWrapper and overrides the getParameterValues method, the code is shown below:
    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameters = super.getParameterMap();
        LinkedHashMap<String, String[]> map = new LinkedHashMap<>();
        if (parameters != null) {
            for (String key : parameters.keySet()) {
                String[] values = parameters.get(key);
                for (int i = 0; i < values.length; i++) {
                    String value = values[i];
                    if (!StrUtil.hasEmpty(value)) {
                        value = HtmlUtil.filter(value);
                    }
                    values[i] = value;
                }
                map.put(key, values);
            }
        }
        return map;
    }

I'm wondering if this piece of code could be transformed using Java Stream because I see a lot of if condition judgement and for loop.
Methods:StrUtil.hasEmpty and HtmlUtil.filter are come from here: Hutool
Any suggestions to improve the performance of this code are welcome.

A: Yes you can make elegent solution with streams plus map / filter but it will be re-allocating the memory footprint of the request data creating many new for objects for Map, N * Map.Entry, N * String[], and filtered strings and other intermediate steps.
Alternatively consider simplifying the logic of your existing loop just to fix each String[] value in place and return the existing map:
public Map<String, String[]> getParameterMap() {
    Map<String, String[]> parameters = super.getParameterMap();
    if (parameters != null) {
        for (String[] values : parameters.values()) {
            for (int i = 0; i < values.length; i++) {
                String value = values[i];
                if (!StrUtil.hasEmpty(value)) {
                    values[i] = HtmlUtil.filter(value);
                }
            }
        }
    }
    return parameters;
}

A:     @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameters = super.getParameterMap();
        LinkedHashMap<String, String[]> map = new LinkedHashMap<>();
        if (parameters != null) {
            map = parameters.entrySet().stream().collect(Collectors.toMap(
                    Map.Entry::getKey,
                    v -> Arrays.stream(v.getValue())
                            .filter(val -> !StrUtil.hasEmpty(val))
                            .map(HtmlUtil::filter).collect(Collectors.toList()).toArray(new String[0]),
                    (x, y) -> y, LinkedHashMap::new
            ));
        }
        return map;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: SVG fill figure and its negative in different colours I'm having trouble creating a gardient in a svg image. I need to fill the figure as its progress increase (0~100% or 0~1) but also the negative of the figure path.
Let me show what I need with some images to be more clear.
This is what I can achieve:
Already Done
And this is what I need:
Hope to achieve
Is there a simple way to achieve this?
EDIT: Sorry, this is  my SVG code:
<svg id="Capa_1" enable-background="new 0 0 503.353 503.353" height="512" viewBox="0 0 503.353 503.353" width="512" xmlns="http://www.w3.org/2000/svg">
<defs>
  <linearGradient id="gradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop stop-color="#aaa" offset="0" />
            <stop stop-color="#aaa" offset="1">
                <animate dur="2s" by="-0.5" attributeName="offset" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.4, 0, 0.2, 1" />
            </stop>
            <stop stop-color="green" offset="1">
                <animate dur="2s" by="-0.5" attributeName="offset" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.4, 0, 0.2, 1" />
            </stop>
            <stop stop-color="green" offset="1" />
        </linearGradient>
    </defs>
<path class="kiwi" d="m483.142 269.401-1.281-12.05-12.05-1.281c-1.145-.121-9.029-.899-21.262-.838-.005-.412-.001-.824-.009-1.236-1.83-95.103-83.035-161.783-86.491-164.575l-9.426-7.616-9.426 7.616c-.768.621-5.382 4.403-12.108 10.948-24.406-55.352-67.489-90.736-69.986-92.753l-9.426-7.616-9.426 7.616c-2.49 2.011-45.318 37.183-69.764 92.245-6.44-6.232-10.835-9.835-11.583-10.439l-9.426-7.616-9.426 7.616c-3.456 2.792-84.661 69.472-86.491 164.575-.008.414-.004.826-.009 1.24-12.662-.098-20.841.71-22.01.834l-12.05 1.281-1.281 12.05c-.47 4.418-10.74 108.988 55.213 177.53 36.076 37.492 87.354 56.422 152.663 56.422 7.668 0 15.537-.269 23.59-.791 8.057.523 15.917.791 23.59.791 65.303 0 116.589-18.932 152.663-56.422 65.952-68.543 55.682-173.113 55.212-177.531zm-130.519-148.024c19.981 19.489 64.799 70.155 65.927 133.393.013.733.002 1.465.004 2.198-23.708 2.614-52.747 8.816-80.739 22.639-10.149-29.958-26.595-55.141-41.675-73.83 14.488-39.789 42.01-70.284 56.483-84.4zm-100.946 345.907c-44.573-42.071-66.743-86.537-65.926-132.316 1.127-63.242 45.954-113.913 65.926-133.392 19.981 19.489 64.799 70.155 65.927 133.392.815 45.779-21.354 90.244-65.927 132.316zm-.001-427.713c14.614 14.254 42.507 45.186 56.882 85.514-12.001 14.807-24.912 33.756-34.854 55.966-6.991-6.838-11.814-10.794-12.601-11.43l-9.426-7.616-9.426 7.616c-.767.62-5.371 4.395-12.082 10.923-10.056-22.312-23.091-41.309-35.146-56.097 14.441-40.021 42.123-70.704 56.653-84.876zm-166.124 215.199c1.127-63.242 45.954-113.913 65.926-133.393 14.402 14.047 41.701 44.292 56.249 83.765-15.218 18.751-31.923 44.168-42.187 74.464-27.697-13.677-56.423-19.896-79.991-22.557 0-.76-.011-1.519.003-2.279zm11.625 171.501c-43.922-45.516-48.054-113.042-47.706-140.938 21.81-.277 67.78 2.211 108.551 24.244-1.303 7.968-2.101 16.179-2.264 24.619-.936 48.66 19.036 95.238 59.414 138.849-50.56-2.269-90.153-17.923-117.995-46.774zm308.999 0c-27.843 28.855-67.441 44.526-118.002 46.781 40.382-43.613 60.357-90.193 59.42-138.856-.162-8.44-.961-16.651-2.263-24.619 40.783-22.038 86.768-24.519 108.55-24.245.348 27.909-3.787 95.426-47.705 140.939z"/>
</svg>

And the CSS class:
.kiwi {
    fill: url(#gradient);
    position: absolute;
    height: auto;
}

Thanks!

A: Well the easy way based on what your path looks like is just to copy part of the shape that draws the outline, put it underneath your existing shape and animate it using a different gradient.
(A slightly better way would have been to draw the shape using a fat stroke rather than a fill and put a different gradient on the stroke and the fill using gradientUnits= userSpaceOnUse.)

.kiwi {
    fill: url(#gradient1);
    position: absolute;
    height: auto;
}

.anzac {
    fill: url(#gradient2);
    position: absolute;
    height: auto;
}
<svg id="Capa_1" enable-background="new 0 0 503.353 503.353" height="512" viewBox="0 0 503.353 503.353" width="512" xmlns="http://www.w3.org/2000/svg">
<defs>
  <linearGradient id="gradient1" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop stop-color="#aaa" offset="0" />
            <stop stop-color="#aaa" offset="1">
                <animate dur="2s" by="-0.5" attributeName="offset" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.4, 0, 0.2, 1" />
            </stop>
            <stop stop-color="green" offset="1">
                <animate dur="2s" by="-0.5" attributeName="offset" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.4, 0, 0.2, 1" />
            </stop>
            <stop stop-color="green" offset="1" />
        </linearGradient>

    <linearGradient id="gradient2" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop stop-color="#aaa" offset="0" />
            <stop stop-color="#aaa" offset="1">
                <animate dur="2s" by="-0.5" attributeName="offset" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.4, 0, 0.2, 1" />
            </stop>
            <stop stop-color="blue" offset="1">
                <animate dur="2s" by="-0.5" attributeName="offset" fill="freeze" calcMode="spline" keyTimes="0;1" keySplines="0.4, 0, 0.2, 1" />
            </stop>
            <stop stop-color="blue" offset="1" />
        </linearGradient>

    </defs>

    <path class="anzac" d="m483.142 269.401-1.281-12.05-12.05-1.281c-1.145-.121-9.029-.899-21.262-.838-.005-.412-.001-.824-.009-1.236-1.83-95.103-83.035-161.783-86.491-164.575l-9.426-7.616-9.426 7.616c-.768.621-5.382 4.403-12.108 10.948-24.406-55.352-67.489-90.736-69.986-92.753l-9.426-7.616-9.426 7.616c-2.49 2.011-45.318 37.183-69.764 92.245-6.44-6.232-10.835-9.835-11.583-10.439l-9.426-7.616-9.426 7.616c-3.456 2.792-84.661 69.472-86.491 164.575-.008.414-.004.826-.009 1.24-12.662-.098-20.841.71-22.01.834l-12.05 1.281-1.281 12.05c-.47 4.418-10.74 108.988 55.213 177.53 36.076 37.492 87.354 56.422 152.663 56.422 7.668 0 15.537-.269 23.59-.791 8.057.523 15.917.791 23.59.791 65.303 0 116.589-18.932 152.663-56.422 65.952-68.543 55.682-173.113 55.212-177.531z"/>

<path class="kiwi" d="m483.142 269.401-1.281-12.05-12.05-1.281c-1.145-.121-9.029-.899-21.262-.838-.005-.412-.001-.824-.009-1.236-1.83-95.103-83.035-161.783-86.491-164.575l-9.426-7.616-9.426 7.616c-.768.621-5.382 4.403-12.108 10.948-24.406-55.352-67.489-90.736-69.986-92.753l-9.426-7.616-9.426 7.616c-2.49 2.011-45.318 37.183-69.764 92.245-6.44-6.232-10.835-9.835-11.583-10.439l-9.426-7.616-9.426 7.616c-3.456 2.792-84.661 69.472-86.491 164.575-.008.414-.004.826-.009 1.24-12.662-.098-20.841.71-22.01.834l-12.05 1.281-1.281 12.05c-.47 4.418-10.74 108.988 55.213 177.53 36.076 37.492 87.354 56.422 152.663 56.422 7.668 0 15.537-.269 23.59-.791 8.057.523 15.917.791 23.59.791 65.303 0 116.589-18.932 152.663-56.422 65.952-68.543 55.682-173.113 55.212-177.531zm-130.519-148.024c19.981 19.489 64.799 70.155 65.927 133.393.013.733.002 1.465.004 2.198-23.708 2.614-52.747 8.816-80.739 22.639-10.149-29.958-26.595-55.141-41.675-73.83 14.488-39.789 42.01-70.284 56.483-84.4zm-100.946 345.907c-44.573-42.071-66.743-86.537-65.926-132.316 1.127-63.242 45.954-113.913 65.926-133.392 19.981 19.489 64.799 70.155 65.927 133.392.815 45.779-21.354 90.244-65.927 132.316zm-.001-427.713c14.614 14.254 42.507 45.186 56.882 85.514-12.001 14.807-24.912 33.756-34.854 55.966-6.991-6.838-11.814-10.794-12.601-11.43l-9.426-7.616-9.426 7.616c-.767.62-5.371 4.395-12.082 10.923-10.056-22.312-23.091-41.309-35.146-56.097 14.441-40.021 42.123-70.704 56.653-84.876zm-166.124 215.199c1.127-63.242 45.954-113.913 65.926-133.393 14.402 14.047 41.701 44.292 56.249 83.765-15.218 18.751-31.923 44.168-42.187 74.464-27.697-13.677-56.423-19.896-79.991-22.557 0-.76-.011-1.519.003-2.279zm11.625 171.501c-43.922-45.516-48.054-113.042-47.706-140.938 21.81-.277 67.78 2.211 108.551 24.244-1.303 7.968-2.101 16.179-2.264 24.619-.936 48.66 19.036 95.238 59.414 138.849-50.56-2.269-90.153-17.923-117.995-46.774zm308.999 0c-27.843 28.855-67.441 44.526-118.002 46.781 40.382-43.613 60.357-90.193 59.42-138.856-.162-8.44-.961-16.651-2.263-24.619 40.783-22.038 86.768-24.519 108.55-24.245.348 27.909-3.787 95.426-47.705 140.939z"/>

</svg>


text:
Q: How to implement the below feature using java8 How to implement this in java8 and anyone please help me,i tried using streams but not working may be syntactically i was wrong.
I have tried:
list.stream().map(res->.get(s)).filter(res->res!=null && res.equalIgnoreCase("something"))

A: You can use a new java8 Collection.removeIf() method. The method works by applying the condition provided in the Predicate instance to all the elements in the Collection on which it is invoked. The elements which satisfy the condition are retained while the remaining are removed from the Collection.
list.removeIf(item -> {
  String res = map.get(item);

  return res != null && res.equalsIgnoreCase("smt");
});


text:
Q: replace only exact words with a list of words from a table this question is a part of this one
limit records in cursor by using a variable
the original question was a 2 part question, 1 part being, IS THERE A BETTER WAY TO DO THIS
i have code that works but it's EXTREMELY slow, about 2 seconds for each record.
so i have a table, NR_POSTAL_ABBR, that has 2 fields and about 400 records
ReplaceWhat       ReplaceWith
Ave               Avenue
St                Street

i want to be able to replace the Address field in another table with the valules from the table above
so if i have an address 123 Main St - it should say 123 Main Street
if i have 123 Main Street - it should stay 123 Main Street, it shouldn't become 123 Main Streetreet
the table with addresses has a few million rows, is there a fast way of doing this?
thank you

A: So as you asked. My suggestion is go through regular expressions So here is un update code for your case.
Suppose you have a table test with the field address, what you have to do is very simple, create an regular expression that match your requirements.
So: You need to replace every St for Street and Av for Avenue this is what you should do.
update test
   set address =
   regexp_replace(
           regexp_replace(address, 'Av | Av$| Av ', ' Avenue ' ),
                           'St | St$| St ', ' Street ');

Here is a SQLFiddle example
Explaining the regex:
The regexp_replace replaces a string for another based on a regular expression pattern, see the docs: REGEXP_REPLACE
About the regular expressions you can see it here Regular Expressions Wiki Almost every language follow the POSIX pattern, so once you learn it you will be good.
So I've used to regexp_replace to achieve what you want because you gave two requirements. I will not write about the parameters of the function just the expressions.
At the first expression you have 'Av | Av$| Av ' which means:
PS.: I put the - just to you see the space (so ignore it). SO wont let me put it.

*-Av - (with a space at end) = Find every Av with a space after it on the string

*-|- (pipe sign) = Equals an or statement

*- Av$- = Find all Av with a space before it and when Av is at the end of the string. $

*- Av - = Find all Av with a space before and a space after
Then The function replace any of theese ocurrences with the word Avenue. Notice that I put a space before and one after to avoid something like Peer HarborAvenue
The same explanation goes to St string
If you like the regular expressions function you can see more with it here: Oracle Regular Expressions Functions

A: just posting the automated version based on Jorge's reply, in case someone needs it.
    DECLARE
     ReplOrder NUMBER;
BEGIN
     ReplOrder := 1;

     DECLARE
       CURSOR getReplsStrng IS
         SELECT replacewhat
            ,replacewith
           FROM analyst.NR_POSTAL_ABBR
          WHERE ReplaceOrder = ReplOrder;
     BEGIN
       FOR getInnerRec IN getReplsStrng LOOP
         --        DBMS_OUTPUT.put_line('replace what ' || getInnerRec.replacewhat);
         --        DBMS_OUTPUT.put_line('Replace Order ' || ReplOrder);

         UPDATE NR_TMP_106 tmp
            SET NewAddress = LOWER(REGEXP_REPLACE(LOWER(NewAddress)
                                  ,   '$'
                                || getInnerRec.replacewhat
                                || ' | '
                                || getInnerRec.replacewhat
                                || '$| '
                                || getInnerRec.replacewhat
                                || ' '
                                  ,' ' || getInnerRec.replacewith || ' '))
          WHERE     1 = 1
             AND (   tmp.NewAddress LIKE '%' || CHR(32) || '' || getInnerRec.replacewhat || '' || NULL || '%'
                  OR tmp.NewAddress LIKE '%' || CHR(32) || '' || getInnerRec.replacewhat || '' || CHR(32) || '%'
                  OR tmp.NewAddress LIKE '%' || NULL || '' || getInnerRec.replacewhat || '' || CHR(32) || '%');

         COMMIT;
       END LOOP;
     END;

     ReplOrder := 2;

     DECLARE
       CURSOR getReplsStrng IS
         SELECT replacewhat
            ,replacewith
           FROM analyst.NR_POSTAL_ABBR
          WHERE ReplaceOrder = ReplOrder;
     BEGIN
       FOR getInnerRec IN getReplsStrng LOOP
         --        DBMS_OUTPUT.put_line('replace what ' || getInnerRec.replacewhat);
         --        DBMS_OUTPUT.put_line('Replace Order ' || ReplOrder);

         UPDATE NR_TMP_106 tmp
            SET NewAddress = LOWER(REGEXP_REPLACE(LOWER(NewAddress)
                                  ,   '$'
                                || getInnerRec.replacewhat
                                || ' | '
                                || getInnerRec.replacewhat
                                || '$| '
                                || getInnerRec.replacewhat
                                || ' '
                                  ,' ' || getInnerRec.replacewith || ' '))
                WHERE     1 = 1
                      AND (   tmp.NewAddress LIKE '%' || CHR(32) || '' || getInnerRec.replacewhat || '' || NULL || '%'
                           OR tmp.NewAddress LIKE '%' || CHR(32) || '' || getInnerRec.replacewhat || '' || CHR(32) || '%'
                           OR tmp.NewAddress LIKE '%' || NULL || '' || getInnerRec.replacewhat || '' || CHR(32) || '%');

         COMMIT;
       END LOOP;
     END;
END;


text:
Q: Delphi: How to get data from this website? I'm trying to get data from a website:

http://site2.aesa.pb.gov.br/aesa/monitoramentoPluviometria.do?metodo=listarMesesChuvasMensais (translated via Google Translate)

In Delphi I know working with XML based Webservices (SOAP, WSDL), but this site does not provide such kind of services.
But I do not have knowledge in languages like PHP and HTML, not even web languages in general.
My question is, is there any way to get data from that site with the knowledge I do (not) have? Is there a tool to do this in Delphi? What are the common first steps to study the ability to do this?
Input January and 2014:
http://site2.aesa.pb.gov.br/aesa/monitoramentoPluviometria.do?metodo=listarMesesChuvasMensais
Output:
a generic method url
http://site2.aesa.pb.gov.br/aesa/monitoramentoPluviometria.do

A: First you need to use a HTTP client such as Internet Direct (Indy) or Synapse to get the web page as text.
Then you can either a HTML parser library or plain string routines to extract the table data.
How to perform HTTP requests is shown in many articles and Stackoverflow questions.


text:
Q: HighCharts error #18: Requested Axis Does not exist I am new to HighCharts and I am trying to display 2 graphs on the same x-axis) axis like shown here: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/combo-multi-axes/.
However, I get an error message: This error happens when you set a series' xAxis or yAxis property to point to an axis that does not exist.
The error occurs in "chart1"
The html and JAVASCRIPT code is as follows:

$(function updat() {
  var url = "https://xpm4zyor39.execute-api.us-west-2.amazonaws.com/prod/entries";
  var humid = [],
    date = [],
    high=[],
    day=[],
    chanceOfRain=[],
    humid_final = [],
    day_final=[],
    high_final=[],
    chanceOfRain_final=[]

  $.getJSON(url, function (json) {

    $(json['Items']).each(function(i, data) {
      //Store indicator name

      // fill the date array
      humid.push(data.humidity);
      // fill the string data array
      date.push(data.Date);

      high.push(data.high);
      day.push(data.Day);
      chanceOfRain.push(data.chanceOfRain);

    });

    console.log(date);
    // query send string that we need to convert into numbers
    for (var i = 0; i < humid.length; i++) {
      if (humid[i] != null) {
        humid_final.push(parseFloat(humid[i]));
        high_final.push(parseFloat(high[i]));
        day_final.push(parseFloat(day[i]));
        chanceOfRain_final.push(parseFloat(chanceOfRain[i]));
      } else {
       humid_final.push(null)
      };
    }

    console.log("day_final", day_final);

    var chart = new Highcharts.chart({
      chart: {
        type: 'spline',
        renderTo: 'light',
        marginBottom: 200
      },
      title: {
        text: 'indicatorName'
      },
      tooltip: {
        valueDecimals: 2,
        pointFormat: '\u25CF {series.name}: {point.y}%
'
      },
      plotOptions: {
        series: {
          marker: {
            enabled: false
          }
        }
      },
      subtitle: {
        text: 'Ambient Light Level'
      },
      xAxis: {
        categories: day_final //.reverse() to have the min year on the left
      },
      series: [{
        name: 'light level',
        data: high_final //
      }]
    });

 var chart1= Highcharts.chart('temp&humid',{
      chart: {
        zoomType:'xy'
      },
      title:{
        text:'Humidity and temperature'
      },

      xAxis:{
        categories: [1,2,3],
        crosshair: true
      },

      yAxis: [{
        labels:{
          format: '{value}°C',
          style: {
            color: Highcharts.getOptions().colors[2]
          }
        },
        title:{
          text: 'Temperature',
          style:{
            color: Highcharts.getOptions().colors[2]
          }
        },
        opposite: true
      },
      { //secondary Y AXIS
        gridLineWidth: 0,
        title:{
          text: 'Humidity',
          style:{
            color: Highcharts.getOptions().colors[0]
          }
        },
        labels:{
          format: '{value}%',
          style:{
            color:Highcharts.getOptions().colors[0]
          }
        }
      }]
     ,

      tooltip:{shared:true},

      legend:{
      layout: 'vertical',
      align:'left',
      x:80,
      verticalAlign: 'top',
      y: 55,
      floating:true,
      backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
      },

      series:[{
        name:'Humidity',
        type: 'column',
        yAxis:1,
        data:[12,3],
        tooltip:{valueSuffix: ' %'}
      },
      {
        name:'Temperature',
        type:'spline',
        yAxis:2,
        data: [1,2,3],
        tooltip:{valueSuffix: ' °C'}
      }]

    });

  }); //getJSON method
  setTimeout(updat, 3000);
});

A: You are doing the following:
series:[{
    yAxis:1,
  },
  {
    yAxis:2,
  }]

You need to do:
series:[{
    yAxis:0,
  },
  {
    yAxis:1,
  }]

The problem is that axes start indexing at 0. So your index where you set temperature to axis 2 does not work because there is no axis 2. In the demo there are 3 axes, which is why it works with these definitions.


text:
Q: Terminal shows garbled characters with same settings as other terminal showing correct characters I have vim setup with NerdTree on a remote machine. I have two local machines. When I ssh to remote machine from one of the local machines (say A), it displays all the symbols in NerdTree correctly. However, when I ssh from the other local machine (say B) to remote machine, those symbols show up as some garbled characters. I tried to do some search on this and tried various locale and encoding things I could find. Following are the settings of the two local machines and the remote machine.
Local machine A:
$ stty
speed 38400 baud; line = 0;
eol = M-^?; eol2 = M-^?; swtch = M-^?;
ixany iutf8

$ echo $LANG
en_US.UTF-8

$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

Local machine B:
$ stty
speed 38400 baud; line = 0;
eol = M-^?; eol2 = M-^?; swtch = M-^?;
ixany iutf8

$ echo $LANG
en_US.UTF-8

$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

The settings on local machines seem to be the same. Both of them run CentOS style OS. Both of the terminals are Gnome Terminals set to use character encoding UTF-8. Only difference I can see is machine A uses version 2.16.0 with font Courier and machine B uses version 2.31.3 with font monospace. So machine B actually uses newer version.
Remote machine:
λ echo $LANG
en_US.UTF-8

λ stty
speed 38400 baud; line = 0;
eol = M-^?; eol2 = M-^?;
-brkint ixany

λ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

The λ symbol which is my $PS1 on remote machine is displayed correctly on both terminals.
How do I proceed from here? Do the fonts installed on local machines matter?
Thanks

A: I figured this out. This looks like font problem. As soon as I installed the fonts from machine A to machine B, it started working fine.
To install fonts, I copied everything from /usr/share/fonts from machine A to machine B and then ran fc-cache /usr/share/fonts as described here


text:
Q: Akka-Http Java: Implementing a Custom Unmarshaller I'm trying to implement my own Unmarshaller for akka-http that converts an HttpEntity object into an object representing the incoming XML. It's not very obvious how you do it. The documentation for akka-http unmarshallers is still incomplete. The documentation references that akka-http comes with its own Jackson marshaller and unmarshaller but from looking at the jars, I don't see those classes anywhere.
I see an example of how to implement your own Unmarshaller from looking at the akka.http.javadsl.unmarshalling.Unmashaller object.
val requestToEntity: Unmarshaller[HttpRequest, RequestEntity] =
  unmarshalling.Unmarshaller.strict[HttpRequest, RequestEntity](_.entity)

Here, it's using the scaladsl's Unmarshaller object's strict function to create a synchronous Unmarshaller according to the scaladocs of strict.
I took this approach and what I got isn't very pretty.
private static final ObjectMapper mapper = new XmlMapper();

private <T> Unmarshaller<HttpEntity, T> unmashaller(Class<T> clazz) {
  Function1<HttpEntity, T> scalaConverter = new AbstractFunction1<HttpEntity, T>() {
    public T apply(HttpEntity entity) {
      T s = null;
      // TODO: performing async operation in sync matter. figure out how to do this better
      try {
        String body = Unmarshaller.entityToString()
          .unmarshal(entity, materializer)
          .toCompletableFuture()
          .get();
        s = mapper.readValue(body, clazz);
      } catch (Exception e) {
        e.printStackTrace();
      }
      return s;
    }
  };

  return (Unmarshaller<HttpEntity, T>) Unmarshaller$.MODULE$.strict(scalaConverter);
}

The strict function takes a scala Function1 object. I first convert the HttpEntity to a String. Once I get the string, I convert it to the object using an external Jackson library.
Is there a better way to do this? I'm more or less doing this as a POC.


text:
Q: Stop Acrobat Pro from opening docs with expanded windows When I open a PDF file in Acrobat Pro DC (2015 Classic), it opens with a window the size of my 27" monitor. This is not very usable. I'd like to suppress this feature, which was not present on previous versions of Acrobat. Is there any way to disable it?
Architecture: x86_64
Build: 15.6.30174.187974
AGM: 4.30.64
CoolType: 5.14.5
JP2K: 1.2.2.36256


text:
Q: Scss : different background on hover on different div I have a div with different images having different backgrounds.
When I hover on it I should get the background color of respective image background.
i.e. If there is black background in the image then I should get the overlay_div background as black , if there is blue then I should get blue background overlay_div.
I am using scss to maintain the variable but I don't know how can I achieve?
Here is JSFiddle
Any help would be great.

A: If I understood right, then you want to get the dominant color of the image and set it to the overlay_div, then, in this case, I recommend this plugin ...
Colorify.js
But if you just going to have solid color images as background-image, then you just remove the $black_bg_color; altogether from the overlay_div


text:
Q: Apache Tika and character limit when parsing documents Could please anybody help me to sort it out?
It can be done like this
   Tika tika = new Tika();
   tika.setMaxStringLength(10*1024*1024);

But if you don't use Tika directly, like this:
ContentHandler textHandler = new BodyContentHandler();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();

ParseContext ps = new ParseContext();
for (InputStream is : getInputStreams()) {
    parser.parse(is, textHandler, metadata, ps);
    is.close();
    System.out.println("Title: " + metadata.get("title"));
    System.out.println("Author: " + metadata.get("Author"));
}

There is no way to set it up, because you don't interact with the WriteOutContentHandler. Btw it is set to -1 by default which means no restrictions. But the resulting restriction is  100000 characters.
/**
 * The maximum number of characters to write to the character stream.
 * Set to -1 for no limit.
 */
private final int writeLimit;

/**
 * Number of characters written so far.
 */
private int writeCount = 0;

private WriteOutContentHandler(Writer writer, int writeLimit) {
    this.writer = writer;
    this.writeLimit = writeLimit;
}

/**
 * Creates a content handler that writes character events to
 * the given writer.
 *
 * @param writer writer
 */
public WriteOutContentHandler(Writer writer) {
    this(writer, -1);
}

A: You must have overlooked that the content handler has constructor with writelimit.
ContentHandler textHandler = new BodyContentHandler(int writeLimit);


text:
Q: Silverlight 4 Project - Web Request.GetResponse Not Available I am having trouble with my HttpWebRequest type. I am trying to use HttpWebRequest.GetResponse() and it doesn't seem to exist on my HttpWebRequest object. I have this code in my silverlight project:
HttpWebRequest req1 = WebRequest.Create(MyUrlString) as HttpWebRequest;
req1.Method = "Get";
req1.ContentType = "text/xml";
req1.Accept = "application/xml";

using (HttpWebResponse resp = req1.GetResponse() as HttpWebResponse)
{

}

Can anyone tell me why "req1.GetResponse()" is not valid c# code? I've been seeing it used a lot of times on my searches in google for how to do this however I can't get it to work for me.

A: It's not valid because it's synchronous. Silverlight team made the decision to use only asynchronous network calls, because it's better for overall user experience (application is more responsive when UI thread is not blocked).
You should use BeginGetResponse which is asynchronous.


text:
Q: LINQ to SQL Select Distinct by Multiple Columns and return entire entity I am working with a third party database and need to select a distinct set of data for the specific market that I am looking into. The data is the same for each market, so it is redundant to pull it all in, and I don't want to hardcode any logic around it as we are working with the vendor to fix the issue, but we need a fix that will work with the vendors fix as well as the way the database is currently as it could be some time before thier fix goes live.
I do not want to group by anything as I want to get the data at the lowest level, but I don't want any redundant data. My current query looks similar to this...
determinantData = (from x in dbContext.Datas
                   where x.Bar.Name.Equals(barName) &&
                         x.Something.Name.Equals(someName) &&
                         FooIds.Contains(x.Foo.Id) &&
                         x.Date >= startDate &&
                         x.Date <= endDate
                   select x).Distinct();

This does not do what I expect. I would like to select the distinct records by three properties, say Foo, Bar, and Something but return the entire object. How can I do this using LINQ?

A: You could use group by with the properties that you want to be distinct, then select the first item of each group:
determinantData = (from x in dbContext.Datas
                   where x.Bar.Name.Equals(barName) &&
                         x.Something.Name.Equals(someName) &&
                         FooIds.Contains(x.Foo.Id) &&
                         x.Date >= startDate &&
                         x.Date <= endDate
                   group x by new { x.Foo, x.Bar, x.Something } into market
                   select market).Select( g=> g.First());


text:
Q: ROS PTAM: cannot locate rosdep definition I am trying to install the latest PTAM (Parallel Tracking and Mapping) as described on the Installation page (http://wiki.ros.org/ethzasl_ptam#Installation). However, when running "rosdep install ptam" it yields the following error:
    ERROR: the following packages/stacks could not have their rosdep keys resolved
    to system dependencies:
    ptam: Cannot locate rosdep definition for [ptam_com]

I have followed the exact same procedure on a different system one month ago (before PTAM was changed to catkin) and it worked. The reason for changing the system is that the GUI of PTAM is said to be successfully loaded but it is actually not showing. So we changed to a new system with an nvidia graphics card.
I tried to retrieve the old version from Github on the new system but it yields the same error.
Many thanks.

A: ROS has its own very active answer forum. So questions like this should better be answered there. Besides,
Cannot locate rosdep definition for

This indicates that "ptam" is not yet registered as the rosdep key (I'm looking at Ubuntu).
The process for adding new keys may not be documented, but you could refer to thread like this and see if you can pick up.


text:
Q: Coldfusion 10 cookie data missing I am transitioning from a Coldfusion 9 to Coldfusion 10 server.  I have noticed an issue that my login cookie (generated from .NET) is losing data when I read it in Coldfusion.  IE, a cookie that is supposed to read:

EMAIL=user@hotmail.com&ID=9994171&CONTENT_SECURITY=MBR CO CFO PFS MC CL RE STF PA SP SC HCC&FIRST_NAME=Jack&LAST_NAME=Smith&FULL_NAME=Jack Smith&CHAPTER=047&TITLE_SEGMENT=Mid-Level/Execu&TITLE_SEGMENT_DESC=Other&PAID_THRU=5/31/2014 12:00:00 AM&MEMBER_TYPE=STF&MEMBER_STATUS=A&IS_MEMBER=False&ELIGIBLETOJOIN=False&IS_STAFF=Yes

is only reading in CF10 as:

EMAIL

It seems that any special character causes this as I'm seeing it on spaces, =, etc.  Has anyone had this issue or have some input on the cause of this?  I don't want to have to re-write my security due to this but I'm having a hard time understanding this switch.

A: Use the GetHTTPRequestData() method.
_cookie = GetHttpRequestData().headers.cookie;

A: Just figured this same issue out.  We are working with a cookie value with a fixed length.  For some reason CF10 isn't displaying an individual cookie value, so we grabbed a string of all the cookies, then did a search on that for where the cookie value starts and extracted the value.
(credit to Sanjeev for getting me started in the right direction)
<cfset allcookies = GetHttpRequestData().headers.cookie>

<!--- Finds the string where your cookie starts --->
<cfset yourCookie = Find("sampleSting", allcookies) >

<!--- Grabs a six digit number after the seven digit cookie string. --->
<cfset yourVariable = MID(allcookies,(sampleString+7),6)>


text:
Q: Cannot assign LinkedList to List, why? I'm using Java in Eclipse on Mac OS X 10.5 (JDK Compliance level 5.0) with and I'm getting very strange compilation problems that I wasn't getting before (and I don't think I've updated my compiler or Eclipse, but maybe an update was installed that I wasn't aware of). For example if I have the following line in my code:
List foo = new LinkedList();

I get a warning that says:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from LinkedList to List

Anyone know what's wrong?
Thanks

A: I would check which List has been imported by Eclipse for you.  If it is a GUI java.awt.List, it is not the java.util.List interface that LinkedList implements and would therefore cause that compile-time error.


text:
Q: How to count the frequent occurrence of distinct substring (Math symbols) in a string using Java or R I have the following String (Sometimes there is no space between the substrings):
str = "<= < / + * + cos sin (service <= service)+ * hello)rate"

The substring is already predefined like :
mathsubstring = {<=, <, / , +, cos, sin }

and the normal substring is predefined as well:
substring[]= {"service","hi","rate","world"};

and I want to count the frequent occurrence of each specific substring for instance:
The output will be :
<= = 2
<  = 1
/ = 1
+ = 3
* = 2
cos = 1
sin = 1

I managed to find substring from string so far see the following java code:
String substring[]= {"service","hi","rate","world"};

        int count=0;
        for (int j=0; j< substring.length; j++)
        {
            count=0;
            Pattern p = Pattern.compile("\\b"+substring[j]+"\\b");
            Matcher m = p.matcher(str);
            while(m.find()) {
            count++;
            }
            Countsubstring = Countsubstring + count;
        }

Thanks in advance.

A: A way with R, splitting the string at each space and then counting occurrences of different elements:
EDIT
With your third string and the new constraint, considering elements can be separated by space or opening or closing bracket:
str <- "<= < / + * + cos sin (service <= service)+ * hello)rate"
mathsubstring <- c("<=", "<", "/", "+", "cos", "sin")

t_elt <- table(strsplit(str, " |\\(|\\)"))
t_elt[mathsubstring]

<=   <   /   + cos sin
 2   1   1   3   1   1

If you want to know the total of occurrences of the math substrings:
sum(t_elt[mathsubstring])
#[1] 9

Previous code with former str
table(strsplit(str, " "))

       *       /       +       <      <=     cos service     sin
      2       1       3       1       2       1       2       1

You can remove service(or other non math symbols) afterwards if you wish to, with something like:
tab <- table(strsplit(str, " "))
mathsubstring <- c('<=', '<', '/', '+', 'cos', 'sin')
tab[names(tab) %in% mathsubstring]

With your second string:
str = "<= < / + * + cos sin service <= service + * hello rate"
table(strsplit(str, " "))

      *       /       +       <      <=     cos   hello    rate service     sin
      2       1       3       1       2       1       1       1       2       1

A: This is what I made:
String str = "<= < / + * + cos sin service <= service + *";
    String[] split = str.split(" ");
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    for (String subString : split) {
        if (!map.containsKey(subString)) {
            map.put(subString, 0);
        }
        Integer current = map.get(subString);
        map.put(subString, ++current);
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(String.format("%s = %s",entry.getKey(),entry.getValue()));
    }

A: You can use a grouping and counting collectors.
Arrays.stream(str.split(" "))
      .collect(Collectors.groupingBy(Function.identity(),
                   Collectors.counting()));

Which results in a Map<String, Long> with the following content:
{<==2, service=2, cos=1, sin=1, *=2, +=3, <=1, /=1}


text:
Q: Connecting to MySQL from Java to WAMP / MAMP Pro I am trying to connect from java to a MySQL database from an external computer on a machine hosting WAMP and other hosting MAMP Pro. The connection to WAMP is fine but on MAMP Pro, I get the following error.
              String userName = "user";
              String password = "pass";
              String url1="jdbc:mysql://<IP Address>:3306/dbname";
              Class.forName ("com.mysql.jdbc.Driver").newInstance ();
              conn1=DriverManager.getConnection (url1, userName, password);

The last packet sent successfully to the server was 0 milliseconds ago.
The driver has not received any packets from the server.

I had changed the privellages in both the server by going to Privellages in PhpMyAdmin and chaning host to any host under Login Information. Worked for WAMP but didn't work for MAMP Pro.
Any suggestions?

A: I'm answering my own question but after some struggle I found the solution. Hopefully it will help people like me in future.
I opened MAMP Pro and on Server - General tab I clicked
File => Edit Template => MySql my.conf and changed
line no 37 from
bind-address=127.0.0.1 to bind-address = <my server's IP Address>


text:
Q: Where can I get the key to create a Telemetry Reporter at Visual Studio Code? I am working on a Visual Studio Code extension, and I would like to use Telemetry to have some insights about the use of the extension.
The Telemetry repository explains how to create a Reporter. I believe how the Python extensions use it is much better though. The problem is that documentation is quite bad at how to get the key or where is the dashboard to see the data.
Do you know if the Telemetry of a VS Code extension works with Azure Application Insights? It could make sense, but I'm new to Microsoft world and I wouldn't like start creating a lot of accounts or expend too much time working on that and being wrong :-)
Thank you for your answers.

A: After some research and more new accounts at Azure. The answer to this question is yes, at least partially. I don't know if there are other ways, but Telemetry with Application Insights (at Azure) works quite well.
Telemetry configuration is something the Microsoft documentation doesn't explain, actually there is not too much información about all the Telemetry usage.


text:
Q: How can I remove the exceeding parts in the buildings in this image? original unfiltered imageI have a problem with the detected areas of the rooftops in this image. I already made dilation and open morphological operations and this is the best result I got.
Any ideas on how can I optimize the areas and remove the exceeding parts??
Thanks in advance.
The approach I used was as follows:
1-shadow masking and vegetation masking were done first
2- Gaussian blur and mean-shift segmentation followed by K-means clustering
3- connected components algorithm to produce regions for pixels with similar spectral properties. but the sidewalk and footpaths were segmented together with the rooftops so I used the dilation and open morphological transformation to separate them as best as I could and applied SVM to detect the rooftops in the end but the results were not very good as shown in the attached image: areas of the facade were included together with the areas of the roofs in some buildings.
Buildings with exceeding parts in the areas of rooftops


text:
Q: The Query (LINQ) expression could not be Translated Entity Framework Core I am using EntityFrameworkCore 3.1.11 and having below query
 var list = _context.Table1
                  .Include(i => i.ListofGroupIds)
                  .Where(i =>
                          i.ListofGroupIds.Select(x => x.GroupId).Any(m =>
                          SelectedIds.Where(z => z.CreatedDate <= i.SentDate).Select(y => y.Id).Contains(m)
                       ))
                   );

Here i need to check whether any of the item(Id) present in SelectedIds(list having properties like {Id,CreatedDate and other fields}) is a part of ListOfGroupIds, According to this i need to fetch the rows. But i am getting run time exception as

The Query (LINQ) expression could not be Translated Entity Framework Core,Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

I checked different post related to this and even tried enter link description here
I got only one solution which is working is by adding AsEnumerable to the query.But i dont want it to be AsEnumerable because i am dealing with huge data, and i can't split the contains query seprate because i need to check one condition(i.SentDate) inside that ANY.
So if there is any way to do this in a single query without making AsEnumerable.

A: Assuming this is the structure you have (I'm ignoring all the foreign keys you may have on purpose, this is just an example!)
public class Table1
{
    public int Id { get; set; }

    public virtual ListofGroupIds ListofGroupIds { get; set; }
}

public class ListofGroupIds
{
    public int GroupId { get; set; }
    public DateTime SentDate { get; set; }
}

public class SelectedIds
{
    public int Id { get; set; }
    public DateTime CreatedDate { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Table1> Table1 { get; set; }
    public DbSet<ListofGroupIds> ListofGroupIds { get; set; }
    public DbSet<SelectedIds> SelectedIds { get; set; }
}

You can rewrite your query as
var query = from tab1 in _context.Table1
                    join logi in _context.ListofGroupIds on tab1.Id equals logi.GroupId
                    join sids in _context.SelectedIds on logi.GroupId equals sids.Id
                    where sids.CreatedDate <= logi.SentDate
                    select new { tab1.Id, logi.GroupId, sids.CreatedDate }; //You can select any other columns within the tables joined

Or, if possible, simply join the two tables needed
var query2 = from logi in _context.ListofGroupIds
                     join sids in _context.SelectedIds on logi.GroupId equals sids.Id
                     where sids.CreatedDate <= logi.SentDate
                     select new { logi.GroupId, logi.SentDate, sids.Id, sids.CreatedDate };

Or
var query3 = _context
            .ListofGroupIds.Join(_context.SelectedIds, logi => logi.GroupId, sids => sids.Id, (logi, sids) => new { logi.GroupId, logi.SentDate, sids.Id, sids.CreatedDate })
            .Where(result => result.CreatedDate <= result.SentDate);


text:
Q: How to visualize 3D cloud from Openni Kinect Grabber using QVTK I am using PCL to buld an application for viewing the registered depth cloud from the Openni Grabber alongside a panel with some buttons for some added functionality. I figured out QVTK could help with this purpose. I tried this basic implementation. It works fine. I used this approach to modify the openni_viewer example to visualize in a Qt window. However I am getting segfaults. I would really appreciate any help.
template <typename PointType>
class OpenNIViewer
{
  public:
typedef pcl::PointCloud<PointType> Cloud;
typedef typename Cloud::ConstPtr CloudConstPtr;

OpenNIViewer (pcl::Grabber& grabber, int argc, char** argv)
  : cloud_viewer_ (new pcl::visualization::PCLVisualizer ("PCL OpenNI cloud", false))
  , grabber_ (grabber)
  , rgb_data_ (0), rgb_data_size_ (0), cloud_init(false), argc(argc), argv(argv)
{
}

void
cloud_callback (const CloudConstPtr& cloud)
{
  FPS_CALC ("cloud callback");
  boost::mutex::scoped_lock lock (cloud_mutex_);
  cloud_ = cloud;
  if (cloud)
  {
    FPS_CALC ("drawing cloud");

    if (!cloud_init)
    {
      cloud_viewer_->setPosition (0, 0);
      cloud_viewer_->setSize (cloud->width, cloud->height);
      cloud_init = !cloud_init;
    }

    if (!cloud_viewer_->updatePointCloud (cloud, "OpenNICloud"))
    {
      cloud_viewer_->addPointCloud (cloud, "OpenNICloud");
      cloud_viewer_->resetCameraViewpoint ("OpenNICloud");
    }
  }
}

void
keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*)
{
  if (event.getKeyCode ())
    cout << "the key \'" << event.getKeyCode() << "\' (" << event.getKeyCode() << ") was";
  else
    cout << "the special key \'" << event.getKeySym() << "\' was";
  if (event.keyDown())
    cout << " pressed" << endl;
  else
    cout << " released" << endl;
}

void
mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void*)
{
  if (mouse_event.getType() == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton() == pcl::visualization::MouseEvent::LeftButton)
  {
    cout << "left button pressed @ " << mouse_event.getX () << " , " << mouse_event.getY () << endl;
  }
}

/**
* @brief starts the main loop
*/
void
run ()
{
  cloud_viewer_->registerMouseCallback (&OpenNIViewer::mouse_callback, *this);
  cloud_viewer_->registerKeyboardCallback(&OpenNIViewer::keyboard_callback, *this);
  boost::function<void (const CloudConstPtr&) > cloud_cb = boost::bind (&OpenNIViewer::cloud_callback, this, _1);
  boost::signals2::connection cloud_connection = grabber_.registerCallback (cloud_cb);

  grabber_.start ();

  QApplication app(argc, argv);
  QMainWindow* window = new QMainWindow;
  window->resize(640,480);
  QHBoxLayout *layout = new QHBoxLayout;

  QVTKWidget widget1;
  widget1.resize(640, 480);
  layout->addWidget(&widget1);

  vtkSmartPointer<vtkRenderWindow> renderWindow = cloud_viewer_->getRenderWindow();
  widget1.SetRenderWindow(renderWindow);

  QWidget* center = new QWidget();
  window->setCentralWidget(center);

  window->centralWidget()->setLayout(layout);
  window->show();
  app.exec();

  grabber_.stop ();

  cloud_connection.disconnect ();

  if (rgb_data_)
    delete[] rgb_data_;
}

boost::shared_ptr<pcl::visualization::PCLVisualizer> cloud_viewer_;

pcl::Grabber& grabber_;
boost::mutex cloud_mutex_;

CloudConstPtr cloud_;

unsigned char* rgb_data_;
unsigned rgb_data_size_;

bool cloud_init;
int argc;
char** argv;
};

boost::shared_ptr<pcl::visualization::PCLVisualizer> cld;
boost::shared_ptr<pcl::visualization::ImageViewer> img;

int
main (int argc, char** argv)
{
  XInitThreads();
  std::string device_id("");
  pcl::OpenNIGrabber::Mode depth_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
  pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
  bool xyz = false;

  if (argc >= 2)
  {
device_id = argv[1];
if (device_id == "--help" || device_id == "-h")
{
  printHelp(argc, argv);
  return 0;
}
else if (device_id == "-l")
{
  if (argc >= 3)
  {
    pcl::OpenNIGrabber grabber(argv[2]);
    boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice();
    cout << "Supported depth modes for device: " << device->getVendorName() << " , " << device->getProductName() << endl;
    std::vector<std::pair<int, XnMapOutputMode > > modes = grabber.getAvailableDepthModes();
    for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it)
    {
      cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
    }

    if (device->hasImageStream ())
    {
      cout << endl << "Supported image modes for device: " << device->getVendorName() << " , " << device->getProductName() << endl;
      modes = grabber.getAvailableImageModes();
      for (std::vector<std::pair<int, XnMapOutputMode > >::const_iterator it = modes.begin(); it != modes.end(); ++it)
      {
    cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
      }
    }
  }
  else
  {
    openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance();
    if (driver.getNumberDevices() > 0)
    {
      for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices(); ++deviceIdx)
      {
    cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName(deviceIdx) << ", product: " << driver.getProductName(deviceIdx)
      << ", connected: " << driver.getBus(deviceIdx) << " @ " << driver.getAddress(deviceIdx) << ", serial number: \'" << driver.getSerialNumber(deviceIdx) << "\'" << endl;
      }

    }
    else
      cout << "No devices connected." << endl;

    cout <<"Virtual Devices available: ONI player" << endl;
  }
  return 0;
}
  }
  else
  {
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance();
if (driver.getNumberDevices() > 0)
  cout << "Device Id not set, using first device." << endl;
  }

  unsigned mode;
  if (pcl::console::parse(argc, argv, "-depthmode", mode) != -1)
depth_mode = pcl::OpenNIGrabber::Mode (mode);

  if (pcl::console::parse(argc, argv, "-imagemode", mode) != -1)
image_mode = pcl::OpenNIGrabber::Mode (mode);

  if (pcl::console::find_argument (argc, argv, "-xyz") != -1)
xyz = true;

  pcl::OpenNIGrabber grabber (device_id, depth_mode, image_mode);

  if (xyz || !grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ())
  {
OpenNIViewer<pcl::PointXYZ> openni_viewer (grabber, argc, argv);
openni_viewer.run ();
  }
  else
  {
OpenNIViewer<pcl::PointXYZRGBA> openni_viewer (grabber, argc, argv);
openni_viewer.run ();
  }

  return (0);
}


text:
Q: Execute shell command and retrieve stdout in Python In Perl, if I want to execute a shell command such as foo, I'll do this:
#!/usr/bin/perl
$stdout = `foo`

In Python I found this very complex solution:
#!/usr/bin/python
import subprocess
p = subprocess.Popen('foo', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = p.stdout.readlines()
retval = p.wait()

Is there any better solution ?
Notice that I don't want to use call or os.system. I would like to place stdout on a variable

A: An easy way is to use sh package.
some examples:
import sh
print(sh.ls("/"))

# same thing as above
from sh import ls
print(ls("/"))

A: Read more of the subprocess docs. It has a lot of simplifying helper functions:
output = subprocess.check_output('foo', shell=True, stderr=subprocess.STDOUT)

A: You can try this
import os
print os.popen('ipconfig').read()
#'ipconfig' is an example of command


text:
Q: Tensorflow: how to look up and average a different amount of embedding vectors per training instance, with multiple training instances per minibatch? In a recommender system setting: let's say I want to learn to predict future item purchases based on user past purchases using an approach inspired by Youtube's recommender system:

Concretely, let's say I have a trainable content-based network that receives as input an item and, based on its content, returns an embedding for such item. Now, let's say each user has purchased a variable number of items in the past (some users might have purchased 5 items, others maybe 1, others maybe 10, some outliers maybe 100, etc.). I want to generate a user vector, a candidate item vector and then a user-item match score as follows:

*

*I map each item purchased by that user to its embedded item vector using the trainable content-based network

*I calculate the average of all those embedded item vectors (as illustrated in the picture)

*I apply a couple of ReLu layers on top of this average, thus obtaining a user vector

*I map a candidate item (to be recommended) to its embedded item vector using the same trainable content-based network of step 1 (the weights of this network are always shared, like a Siamese network so to speak)

*Finally, I compute the dot product between the user vector and the candidate item vector, apply a cross entropy loss during training, etc.

So my question is about the technical details of how to implement the embedding lookup and average of a variable number of embedded item vectors per user using Tensorflow. For example, think of a mini-batch with, say, 100 training instances. Each training instance in the mini-batch possibly consists of a different user with a different amount of purchased items in the past. Although the context is different, my question is very similar to this one, but unfortunately nobody has answered that question up to now.


text:
Q: How do you add more than one cases for a expected exception Test methods? I am working one a school program that requires me to test a custom defined exceptions.
There are 5 Calculator.java files and my job is to add more cases and find which runs perfectly right.
However when I try to use Expected exception test to test the excetion, it seems that the as long as the first case works well, the program will automatically be thrown and stop there. The other cases behind //TODO will not run at all.
 /**
 * The calculate method have to return the Grade based on :
 *
 * "lab", "ass1" and "ass2" marks are between 0 and 10 (inclusive).
 * + "final" is between 0 and 100 (inclusive).
 *
 * If any of these components are not within the expected range
 * then an OutOfRangeException is thrown.
 *
 */
//Here is the interface of MarkCalculator
public interface Calculator {
    Grade calculate(int lab, int ass1, int ass2,
                            int final, boolean attended) throws OutOfRangeException;
}

Can someone please tell me how to prevent this from happening, thanks
@Test(expected = OutOfRangeException.class)
public void testException() throws OutOfRangeException {
    calculator.calculateMark(-1, 0, 0, 0, true);
    //TODO: write more test cases if you need

    calculator.calculateMark(100 , 0 , 0 , 0 , true);
    calculator.calculateMark(0 , 11 , 0 , 0 , true)
}

A: An easier way is to extract calculation to another method in the test class itself.
private Class cauculate(int lab, int assignment1, int assignment2, int finalexam, boolean attendedFinal){
    try{
        calculator.calculateMark(lab, assignment1, assignment2, finalexam, attendedFinal);
    } catch (Exception e){
        return e.getClass();
    }
    return Void.class;
}

@Test
public void testException() {
    Assert.assertEquals(ComponentOutOfRangeException.class, calculate(-1, 0, 0, 0, true));
    Assert.assertEquals(ComponentOutOfRangeException.class, calculate(11, 0, 0, 0, true));
//....
}

A: Unit testing purpose is to test 1 specific thing and that is why it doesn't support a cool handling for multiple exceptions ( as it is invalid for java itself to ignore exception without a try-catch or some other handling ) and that is why you need a workaround as the previous answer suggested.
My suggestion is to write different @test functions and name each one after what they are testing (for example test_firstParameterNull , test_secondParameterNull etc ). that way when you will finally run the tests they will be able to provide feedback on what exactly failed instead of a general "your calculator failed".
And to be fair your unit tests will look like this. Only 1 of the x will change per scenario so you can copy paste it as many times as you wish and test very specific cases.
@Test(expected = ComponentOutOfRangeException.class)
public void testException() {
    calculator.calculateMark(x,x,x,x,x);
}


text:
Q: CakePHP 2.x using PHP in CSS Could someone please advise me on the current methods available for using PHP in a CSS file in CakePHP 2.x
I have currently separated my stylesheet into a php file and wish to parse my data via the URL but I cannot seem to work out how to link it using
$this->Html->css('dynamic-stylesheet')

as it always appends .css to the name.
Your help is much appreciated.

A: You can generate the tag by using HtmlHelper::meta()
echo $this->Html->meta(array(
    'link' => '/css/test.php',
    'rel' => 'stylesheet',
    'type' => 'text/css'
));

Note that you need to explicitly direct it to the /css directory, as you are no longer using a helper method specifically for CSS.

A: Looking at the Html helper file in the CakePHP library located at lib/Cake/View/Helper/HtmlHelper.php, check out line 427, looks like the .css extension is set automatically unless there are two slashes in the CSS file name. I GUESS that is to catch external resources?
From the aforementioned library file:
if (strpos($path, '//') !== false) {
    $url = $path;
} else {
    $url = $this->assetUrl($path, $options + array('pathPrefix' => CSS_URL, 'ext' => '.css'));

    if (Configure::read('Asset.filter.css')) {
        $pos = strpos($url, CSS_URL);
        if ($pos !== false) {
            $url = substr($url, 0, $pos) . 'ccss/' . substr($url, $pos + strlen(CSS_URL));
        }
    }
}

So this..
echo $this->Html->css('http://whatever.com/css/dynamic-stylesheet.php');

Would render the dynamic-stylesheet.php file rather than defaulting to 'dynamic-stylesheet.css.
Not sure that is what this was intended for but maybe that file will help you.


text:
Q: Process is not defined in dependency package Recently i had to create a new project in react using typescript / webpack. I have included the package "sass-loader" which has a dependency of chalk (1.1.3).
When I try to npm start, the console shows this error:
Uncaught ReferenceError: process is not defined
    at Object../node_modules/chalk/index.js (main.js:62661)
    at __webpack_require__ (main.js:228732)
    at fn (main.js:228970)
    at Object../node_modules/@babel/highlight/lib/index.js (main.js:403)
    at __webpack_require__ (main.js:228732)
    at fn (main.js:228970)
    at Object../node_modules/@babel/code-frame/lib/index.js (main.js:19)
    at __webpack_require__ (main.js:228732)
    at fn (main.js:228970)
    at Object../node_modules/parse-json/index.js (main.js:120631)

I don't know if this could be a problem with this package or maybe is my webpack configuration... I'm new in webpack.
Here is my webpack conf:
{
  mode: "development",
  output: {
    publicPath: "/",
  },
  entry: "./src/index.tsx",
  module: {
    rules: [
      {
        test: /\.(ts|js)x?$/i,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: [
              "@babel/preset-env",
              "@babel/preset-react",
              "@babel/preset-typescript",
            ],
          },
        },
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          {
            loader: 'css-loader',
            options: {
              modules: {
                localIdentName: 'styles_[local]_[hash:base64:5]'
              }
            },
          },
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
      {
        test: /\.css$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          {
            loader: 'css-loader',
            options: {
              modules: {
                localIdentName: 'styles_[local]_[hash:base64:5]'
              }
            },
          }
        ],
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js", ".jsx"],
    alias: {
      '@': '/src',
    },
  },
  plugins: [
    new Dotenv(),
    new HtmlWebpackPlugin({
      template: "public/index.html",
    }),
    new webpack.HotModuleReplacementPlugin(),
    new ForkTsCheckerWebpackPlugin({
      async: false,
    }),
    new ESLintPlugin({
      extensions: ["js", "jsx", "ts", "tsx"],
    })
  ],
  devtool: "inline-source-map",
  devServer: {
    contentBase: path.join(__dirname, "build"),
    historyApiFallback: true,
    port: 4000,
    open: false,
    hot: true,
    stats: 'errors-only'
  },
}

Thanks in advance.


text:
Q: $_POST array returning empty on live site - fine on localhost. I have a codeigniter application on an Amazon EC2 server. The server is set up using Apache2 and php5. I have tested the application on localhost and it works fine however on he EC2 server it does not. The problem is this. Whenever I pass form data to the controller and print the $_POST variable it returns empty. This only occurs on the live site but not in localhost. I have absolutely no idea why would cause this. I have checked the config settings for the below and see nothing out of the ordinary:

This of course would lead me to believe there might be something wrong on the server side but it could equally be a codeigniter setting I may be overlooking.


text:
Q: Extract fields from Structure Array to put into another Structure Array I have a structure array with a large number of fields that I don't care about, so I want to extract the limited number of fields I DO care about and put it into a separate structure array.
For a structure array of size one, I've done this by creating the new array from scratch, for example:
structOld.a = 1;
structOld.b = 2;
structOld.usefulA = 'useful information';
structOld.usefulB = 'more useful information';
structOld.c = 3;
structOld.d = 'words';

keepFields = {'usefulA','usefulB'};

structNew = struct;
for fn = keepFields
    structNew.(fn{:}) = structOld.(fn{:});
end

which gives
structNew =

    usefulA: 'useful information'
    usefulB: 'more useful information'

Is there a more efficient way of doing this? How can I scale up to an structure array (vector) of size N?
N = 50;
structOld(1).a = 1;
structOld(1).b = 2;
structOld(1).usefulA = 500;
structOld(1).usefulB = 'us';
structOld(1).c = 3;
structOld(1).d = 'ef';
structOld(2).a = 4;
structOld(2).b = 5;
structOld(2).usefulA = 501;
structOld(2).usefulB = 'ul';
structOld(2).c = 6;
structOld(2).d = 'in';
structOld(3).a = 7;
structOld(3).b = '8';
structOld(3).usefulA = 504;
structOld(3).usefulB = 'fo';
structOld(3).c = 9;
structOld(3).d = 'rm';
structOld(N).a = 10;
structOld(N).b = 11;
structOld(N).usefulA = 506;
structOld(N).usefulB = 'at';
structOld(N).c = 12;
structOld(N).d = 'ion';

In this case, I'd like to end up with:
structNew =

1x50 struct array with fields:

    usefulA
    usefulB

Keeping elements with empty usefulA/usefulB fields is fine; I can get rid of them later if needed.
Using rmfield isn't great because the number of useless fields far outnumbers the useful fields.

A: You can create a new struct array using existing data as follows:
structNew = struct('usefulA',{structOld.usefulA},'usefulB',{structOld.usefulB});

If you have an arbitrary set of field names that you want to preserve, you could use a loop as follows. Here, I'm first extracting the data from strcutOld into a cell array data, which contains each of the arguments the the struct call in the previous line of code. data{:} is now a comma-separated list of these arguments, the last line of code below is identical to the line above.
keepFields = {'usefulA','usefulB'};
data = cell(2,numel(keepFields));
for ii=1:numel(keepFields)
   data{1,ii} = keepFields{ii};
   data{2,ii} = {structOld.(keepFields{ii})};
end
structNew = struct(data{:});


text:
Q: Angular 2 to 6 Upgrade WrappedError Missing I am trying to upgrade a project from Angular 2 to Angular 6 and the import { WrappedError } from '@angular/core/src/facade/errors'; is throwing the Cannot find module... error in my Custom Error Handler implementation. I use the WrappedError in the following contexts:
this.findContext((error as WrappedError).originalError);

let e = (error as WrappedError).originalError;
    while (e && (e as WrappedError).originalError) {
        e = (e as WrappedError).originalError;
    }

let e: any = error;
    let stack: string = e.stack;
    while (e instanceof Error && (e as WrappedError).originalError) {
        e = (e as WrappedError).originalError;
        if (e instanceof Error && e.stack) {
            stack = e.stack;
        }
    }

Can anyone point me in the direction of where it has been moved to and how to include it or a work around?

A: Did you upgrade npm, node, and angular cli?  I'm pretty sure you will need to in order to go from 2 to 6.
Did you try look at this?
https://update.angular.io/


text:
Q: MutableMessageBuilderFactory in Spring Integration I have a spring cloud stream consumer getting messages from Kafka. I want to modify the message headers, but currently the message I get is of type GenericMessage.
I saw this post and this code from spring integration core so I added to my configuration a bean of type MutableMessageBuilderFactory but I'm still getting the message as GenericMessage. Actually, the bean creating code doesn't even seem to get called, the getMessageBuilderFactory(BeanFactory beanFactory) in IntegrationUtils classs gets called multiple times and everytime beanFactory.getBean("messageBuilderFactory", MessageBuilderFactory.class) returns DefaultMessageBuilderFactory.
What might be the problem causing the factory I defined as bean not to work and the message to keep coming as GenericMessage?
Spring versions:

*

*spring-boot: 1.5.21

*spring-integration: 4.3.12

A: Messages are immutable and there are many reasons for that, but it's out of scope of this question. What you can do is create a new Message in your handler and return it. If you want to copy most of the previous message and then modify the header you can do this:
Message resultMessage = MessageBuilder.fromMessage(sourceMessage).setHeader("myExistingHeader", "foo").build();


text:
Q: How to add JSESSIONID as optional cookie as parameter using post in Java Spring Boot How to add JSESSIONID as optional cookie when posting username and password for login in controller?
LoginController:
@PostMapping("/login")
@ResponseBody
public ResponseEntity<Account> login(@RequestParam(name ="username") String name, @RequestParam(name ="password") String password) {
    if(name == "user" || password == "password")
    {
        System.out.println("Matched!");
        return new ResponseEntity<>(HttpStatus.OK);
    }
    return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}

A: Spring Framework provides the @CookieValue annotation to read any cookie by specifying the name.
So you can use this annotation with required property set to false.
If you use don't set required property default value will be true,and  an exception will be thrown if the cookie is missing in the request.
Alternatively, provide a defaultValue(), which implicitly sets this flag to false.
@PostMapping("/login")
    @ResponseBody
    public ResponseEntity<Account> login( @CookieValue(name = "JSESSIONID", required=false) String cookie,@RequestParam(name ="username") String name, @RequestParam(name ="password") String password) {
        if(name == "user" || password == "password")
        {
            System.out.println("Matched!");
            return new ResponseEntity<>(HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
    }


text:
Q: Uploading video recorded with Expo Camera to server I am recording video using expo camera, the recorded video is saved in the cache and I want to upload the recorded video to the server. I have the uri to the video, but to upload it to the server I need the file itself. How can I add the file to the body of the request? (I can't use rn-fletch-blob or react-native-fs, because it 's an expo project)

A: Ok so you have the uri
Now we have to create a form-data as it is a file.
to create form-data follow these steps
Create A function
const CreateFormData = (uri) => {
  // Here uri means the url of the video you captured
  const form = new FormData();
  form.append("File", {
    name: "SampleVideo.mp4",
    uri: uri,
    type: "video/mp4",
  });

  // Now perform a post request here by adding this form in the body part of the request
  // Then you can handle the file you sent in the backend i.e server
};


text:
Q: SCNScene load with textures from pod I am trying to create pod which contains SCNScene with textures and got an error:
SceneKit Error: Failed loading : C3DImage
src:file:///Users/.../Example.app/Templates.scnassets/grid.png

Texture and scene are in the same folder.
I've tried to load with SCNSceneSource
let sceneData = try Data(contentsOf: sceneUrl)
let options = [.overrideAssetURLs: true,
               .assetDirectoryURLs: MYPod.bundle().bundleURL
               ] as [SCNSceneSource.LoadingOption : Any]
let source = SCNSceneSource(data: sceneData, options:options)
scene = (source?.scene(options: options))!

but got same result (path not changing)

A: You should go trough all of the materials with the code and (sorry for pseudo code)
If material.contents.type == String.type {
material.contents = UIImage(named: <path tofolder>/material.contents)
}


text:
Q: Table columns with display:flex are misaligned I've created a table and for whatever(important) reason (because i dont know how many cells in a row are coming from back end and thats why i cant use colspan for that, can be one row with 2 cells and second one with 4 for example) i need to use flexbox for that.
But the problem occurs when text in one cell is longer - then all layout ia broken

How can i fix that?
I've applied:
tr {
display: flex;
flex-direction: row;
}

td {
display: flex;
width: 100%;
}

Thanks a lot for help!

A: You can override overflow behavior by setting min-width of cell:
td {
  flex: 1;
  min-width: 0;
}

A: The problem here is that your td tags have a display:  flex; property but not a flex value set.
When the flex property is not defined, each will take the most space they can while not wrapping.
Use the next CSS:
td {
  flex:  1;
}

I would suggest that for longer fields, you use a higher flex value (ex. flex: 4), and for shorter fields, a lower flex value (ex. flex: 1).
I am attaching a codepen that has the desired behaviour.
https://codepen.io/elujambio/pen/WMXjjL
When you don't have a value for said cell, just use an td containing an  .


text:
Q: entire function with $f(n) = f'(n)$ for every integer $n$ Show that there exists an entire function $f$ such that $f(n) = f'(n)$ for every integer $n$, and such that the range of $f$ includes both $0$ and $1$.
I have tried quite a few different things but did not make any significant progress. Assuming the converse and trying to reach a contradiction did not work. Also using Weierstrass factorization theorem for the entire function $f(z)-f'(z)$ with zeroes at the integers did not get me anywhere as well. Can someone help please?

A: Let $f(z)=\sin(\pi z)+\pi \cos(\pi z)$.  Then $f'(z) = \pi \cos(\pi z) - \pi^2 \sin(\pi z)$.  So $f(n) = \pi (-1)^n = f'(n)$ for all $n\in \mathbb{Z}$.  Since $f$ can also be expressed as a single $\cos$ form it takes all complex values.

A: Consider $$f(z) = \exp(z) \cdot \cos(2\pi \cdot z).$$
Then
$$f'(z) = \exp(z) \cdot \cos(2\pi \cdot z)- 2\pi \cdot \exp(z) \cdot \sin (2\pi \cdot z)$$
In particular,
$$f'(z) = \exp(z) \cdot \cos(2\pi \cdot z)$$
for any $z \in \mathbb{Z}$. Moreover, $f(0)=1$, $f(1/4)=0$.


text:
Q: Application of corollary of Banach-Steinhaus theorem Here is the corollary of the Banach-Steinhaus theorem:

Corollary A: Let $A\subseteq X$ be a set in $X$ such that for every $f\in X^*$ there exists a constant $C(f)$ such that $\sup_{x\in A}|f(x)|\leq C(f)$. Then $A$ is norm bounded, i.e., there exists a constant $C$ such that $\|x\|\leq C$ for all $x\in A$.

The author then applies Corollary A via the following theorem and proof:

Theorem 1: Let $H$ be a Hilbert space and let $A\colon H\to H$ be a linear operator with $\text{Dom}A=H$ (not necessarily bounded) and $A=A^*$, i.e.,
$\langle Ax,y \rangle= \langle x,Ay \rangle$. Then $A$ is bounded.
Proof. We have
$$
|\langle Ax,y \rangle| = |\langle x,Ay \rangle|\leq\|x\|\cdot\|Ay\|\leq\|Ay\|
$$
for all $x\in H$ with $\|x\|\leq1$ and for all $y\in H$. By Corollary A we conclude that the set $\{Ax:\|x\|\leq1\}$ is bounded which implies $\|Ax\|\leq C\|x\|$.

However this proof confused me. Can anyone really explain what is going on in this proof, i.e., what is the set $A$ supposed to be from Corollary A. Also, why does this even finish the proof? Don't we have to show the operator $A$ is bounded for every $x\in H$, not just those $x$ with $\|x\|\leq1$? Or does this finish to proof since it's enough to show the operator $A$ is bounded for $x=0$, and clearly $\|x=0\|\leq1$...?

I should add that, I take it the set $A$ is supposed to be $A:=\{Ax:\|x\|\leq1\}$; however, then this set being norm bounded means there exists $C>0$ such that $\|Ax\|\leq C$ for all $Ax\in A$, so also $\|x\|\leq 1$. But how does $\|Ax\|\leq C$ together with $\|x\|\leq1$ give $\|Ax\|\leq C\|x\|$?

A: It's unfortunate that $A$ is overloaded to be both a set and an operator. Let me call the linear operator $T$ instead.
Define the set $A = \{Tx: \|x\| \leq 1\}$. Since every linear functional on $H$ is of the form $\langle \cdot, y\rangle$ by the Riesz Representation Theorem, the calculation in the proof of Theorem 1 tells you that for every $f \in H^*$, $sup_{\{Tx: \|x\| \leq 1\}} |f(Tx)| \leq C(f) = \|Ty\|$ where $y$ is the element of $H$ corresponding to $f$ via the Riesz Representation Theorem.
Hence, by Corollary A, $\{Tx: \|x\| \leq 1\}$ is a bounded set. Therefore the operator norm of $T$ is finite.

Rereading the question, it seems you might not have seen the various equivalent representations of the operator norm. In this case, for arbitrary $x \neq 0$, let $z = \|x\|^{-1} x$. Then $z$ has norm at most $1$ so that $\|Tz\| \leq C$ for the constant $C$ bounding the set above. Multiplying through by $\|x\|$ yields $\|Tx\| \leq C\|x\|$ as desired.
In general, it might be worth googling/checking a standard text to see the various equivalent forms of the operator norm if you have not seen these before.


text:
Q: What happened to Rita at the end of Vampire in Brooklyn? For almost half its run time the movie makes a big deal out of how Maximillian just needs one dance with Rita to convert her, and how he is thwarted at the last minute every time. However, he finally gets a dance with her and manages to bite and convert her into a full vampire. But then conveniently it turns out she also needs to bite and feed on someone to actually become a vampire? She seems to have converted into a monster by the end of the movie. But Maximillian was destroyed before she got a chance to bite anyone. So is she completely cured now? Was it ever mentioned destroying Maximillian would cure her in the movie earlier? Or can she still be converted if she goes and bites someone?
What happened to her vampire ability at the end of the movie?


text:
Q: In Numbers can a chart follow a table's increasing range? I'm growing a table and also have a chart associated with it but when I add columns I have to go back to the chart and "edit data references". When I was growing the chart from right to left, I didn't have this issue. The chart would continue to grow because I was adding rows within the range. Wondering if this can be automated or handled differently.
This is the way I was doing it and graph didn't need to be edited.
tell application "Numbers"
    tell the table 1 of sheet 1 of document "The Doc"
        delay 1
        add column before the range "E1:E2"
        set the value of cell "E1" to time string of (current date)
        repeat with i from 2 to the count of cells of column "E"
            set the value of cell i of column "E" to (the value of cell i of column "C")
        end repeat

    end tell
end tell

This is the way I'm doing it now but I have to always edit the data references.
tell application "Numbers"
    activate
    tell the table 1 of sheet 1 of document "The Doc"
        set column count to column count + 1
        set myLastColumn to column count
        set the value of cell 1 of column myLastColumn to time string of (current date)
        repeat with i from 2 to the count of cells of column "A"
            set the value of cell i of column myLastColumn of rows to (the value of cell i of column "D")
        end repeat
    end tell
end tell

A: Not sure if there is a better way but this is working.
tell application "Numbers"
    tell the table 1 of sheet 1 of document "The Doc"
        set myColumn to column count
        add column before the column column count
        set the value of cell 1 of column myColumn to time string of (current date)

        repeat with i from 2 to the count of cells of column "A"
            set the value of cell i of column myColumn of rows to (the value of cell i of column "D")
        end repeat

    end tell
end tell


text:
Q: Game engine development question I am thinking of making a simple game engine for my course final year project. I want it to be modular and expandable so that I can add new parts if I have time. For example I would make a graphics engine that would be completely independent of the other systems, once that was finished I could add a physics engine etc.
I would also want to make a tool set to go with this engine. For the tools I would like to use C# but I am not sure about the libraries. My question is, if I want a C# GUI program, can I reference a library written in C++? Also would there be any performance problems etc. if I made some of the libraries in C# but wanted to use them from a C++ game.
I would like to avoid C++ as much as possible, my experiences have shown that development time can be a lot higher for a project over that of using C# or Java etc. My graphics development would be in OpenGL, this is all I have been taught. We have only done this in C++ but I have seen that projects such as SharpGL allow for the development with C#. Is there any performance issues with this. I am not looking for a blindingly fast, top graphics game. It will most likely be something simple to show my engine working. My engine probably won't be that great either as I only have a year and am working on my own.
Any advice on this would be appreciated. I am still really in the planning stages so it wouldn't be too much work to completely change what I want to do. I would just like to preempt any major problems I might have.
Thanks

A: You should look into XNA. It performs quite well, and from what I've heard, is quite easy to work with.
About referencing C++ code from C#: It's perfectly doable, though it will take some effort from your side to get it right. C++/CLI can work as an intermediate wrapper or you can use P/Invoke. Just remember that C++ is unmanaged and that you will need to do some manual garbage collection, which can be somewhat icky in a managed environment like .Net. Perfomance in the C++ -> C# bridge is okayish, but I'm unsure how it will perform if you need do 100.000 calls to a math-library each second. I guess a small test would be good.. I'll see if I get time to do this later today, though I somewhat doubt it :)

A: When creating a graphics engine (I'll only really speak about graphics as that is my area of expertise), these are a few of the choices you need to make EARLY in the project:
1) Is it an indoor and/or outdoor engine?
2) What sort of visibility system are you going to use?
3) Forward or deferred renderer?
4) How will you have animation hierarchies?
5) Dynamic or static lighting?
6) How are you going to handle transparency?
7) How will you handle a 2D overlay?
8) What mesh formats will you use?  Roll your own?
Bear in mind you need a GOOD solid vector/matrix library and preferably a full maths library that will help with things from eulers to quaternions to axis-aligned bounding boxes.
Do a lot of research as well.  Try to find out what the potential problems you are going to face are.  Remember things like changing a texture or a shader can have HUGE impacts on your pipelining.  You need to minimise these as much as possible.
Bear in mind that getting a rotating bump mapped mesh on the screen is simple by comparison to getting an engine running.  Don't let this put you off.  It should be no problem to write a fairly simple game rendering engine in a matter of months :)
Also ... find communities specific to this area.  You will get a lot of good (though non-OpenGL-centric) information off DirectXDev.  There is a fair bit of general game development algorithm information available at GDAlgorithms.  There is also an OpenGL specific mailing list here.
Its worth noting that DirectXDev and GDAlgorithms, at least (I don't know so much on the GL mailing list) are populated by some VERY experienced 3D engine and game developers.  Don't post up lots of "beginner" questions as this does tend to breed contempt among the members.  Though the odd query or 2 at whatever level (beginner to advanced) will get amazing answers.
Good luck!  I wish I'd had the chance to do this at University.  I might not have gone off and joined the games industry and enjoyed an extra year of sleeping late ;) hehehe

A: Why do you need any C++ code?
There are already several wrapper libraries exposing OpenGL or DirectX to .NET, such as SlimDX (which, as the name implies, is a much thinner, more light-weight wrapper than something like XNA)
If you're more comfortable with C#, there's no reason why you couldn't write your entire game in that.
Performance generally won't be a problem. In most cases, the performance of C# code is comparable to C++. Sometimes it's faster, sometimes it's slower. But there are few cases where C# isn't fast enough. (However, there is a significant performance cost to interfacing between native and .NET code -- so doing that too often will hurt performance -- so the trick is, if you use native code at all, to have sufficiently big native operations, so the jump to/from .NET isn't done too often)
Apart from that, a word of advice: Don't bother writing an "engine".
You'll be wasting your time producing a big monolithic chunk of code which, ultimately, doesn't work, because it was never tested against the requirements of an actual game, only what you thought your future game would need.
If you want to experiment with game development, make a game. And then, by all means, refactor it and clean it up and try to extract reusable parts of the code. But if the code hasn't already been used in a game, you won't be able to use it to build a game in the future either.
The engines used in commercial games are just this, code extracted from previous games, code which has been tested, and which works.
By contrast, hobbyist engines pretty much always end up taking 2+ years of the developer's time, without ever offering anything usable.
The whole concept of a  "game engine" is flawed. In every other field of software development, you'd frown at the idea of one vaguely-defined component doing basically "everything I need to make my product". You'd be especially suspicious of the idea that it is a separate entity that can be developed separate from the actual product it's supposed to support.
Only in game development, which is by and large stuck in 80's methodologies, is it a common approach. Even though it doesn't actually work.
If this is a school project, I'm sure whoever is supposed to grade it will appreciate it if you apply common good software practices to the field. Just because many newcomers to game development don't do that (and prefer to stick to some kind of myth about "engines"), there's no reason why you shouldn't do better.

A: If you can pull this off even under a relaxed set of goals, you're set for a great project. First, you need to get a grasp of scope:

*

*How long do you have to work on the project?

*How many people are working on the project?

*If you can only create one "piece of the pie" on your own, which one would you pick? Use this to establish a working plan to make sure if you don't get as far as you'd like, you still have enough to make the work show as a great project.

A game engine is a big development task. A game engine with a toolchain is an enormous development task. In a lot of ways, choosing a smaller but more challenging task is preferable because it shows higher-level thinking about problem solving, which is greatly preferred by academics - double that if you are CS and not [Area of] Engineering. Since you are working in managed languages, things you may want to consider are:

*

*Expressing gameplay logic (rules of the game) in a clean manner so as to provide an efficient and reliable path from designer->developer->tester. If you want, this could absolutely include the manner in which you describe the rules (Custom editor? Code API? DSL?)

*Game AI has no shortage of extremely challenging problems.

*Physics and graphics are interesting and I believe managed languages will eventually be used in these areas, but you may find yourself a bit more limited in your ability to solve these problems. If I were going to work in this area now, I would be trying to answer: "If I could use a managed language for writing [graphics|physics] code without hurting performance, what kinds of [language|runtime] features make the most difference in improving the expressiveness, correctness, maintainability, and reliability of the resulting programs." This goes way past simply having garbage collection and pointer safety.

A: Make sure your scope is feasible.
As a teenager I went through the build-my-own-engine phase, a few years later I realized I would have gotten a whole lot more done if I had just used pygame and pyopengl and not wasted the effort.
Check out the forums at gamedev.net.

A: Sounds to me like you have a pretty good plan for your project. (I get your point about XNA in your comment to @Meeh)
You can interop with C++ via P/Invoke directly or COM, you could also I guess come up with some SOA way of doing it, but to be honest as yucky as this sounds I would be inclined to target COM as your API lever of choice...why? because then you open up your API to a lot of common client language's not just C# and VB.NET you will also get Delphi, VBA, Powerbuilder etc.
Performance should not be a problem as the API entry points are just to kick of the work and transport data structures, the real work is done in your library in native code, so don't worry too much about the perf. ATL will be your friend with creating COM Classes that provide entry to your Library.

A: Whilst it's certainly do-able to bridge between C++ and C# (Via managed C++ is a good way to go if the interface is complex, P/Invoke for a very simple one), for tool<->engine communication I might suggest instead a network based interface. This is ideal for a high-ish level interface, such as you might want for a level editor/model viewer or such. An actual object modeller is not such a good target. What tools do you envision?
If you do it this way you gain the ability to connect to remote instances of the engine, or multiple instances, or even instances running on different hardware platforms. It'll also teach you a bit about sockets if you don't know them already.


text:
Q: Check if object has key, if so, add new key: value to said object I have a loop that goes over an array of data plotData. Out of plotData I build another array called visiblePoints. Then I loop over visiblePoints to build an object thisRow, then I add thisRow to an array outside of the loop, called dataArray:
var dataArray = []

for (i = 0; i < plotData.length; i++) {

    // This filters datapoints array into another array
    var visiblePoints = filterPoints(plotData[i].datapoints)

    // Get the string for the thisRow object key name
    var selectedParameter = plotData[i].label

    for (k = 0; k < visiblePoints.length; k++) {
        // Convert visiblePoint first value from ms to date
        var timestamp = new Date(visiblePoints[k][0])

        // Form the thisRow object that will go into dataArray
        // for each loop of visiblePoints
        var thisRow = {}
        thisRow["Time"] = msToTime(timestamp)
        thisRow[selectedParameter] = visiblePoints[k][1]
        dataArray.push(thisRow)
    }
}

Let's simplify and say I only have 2 element in sub array visisblePoints for each plotData array, like so (each plotData array can have many visiblePoints but I'm simplifying to just 2 for each):
plotData[0].visiblePoints = [[00:00:01, 1], [00:00:02, 4] ...]
plotData[1].visiblePoints = [[00:00:01, 27], [00:00:02, 31] ...]

plotData looks like this on the console:

The visiblePoints array for the k loop is derived off of plotData.datapoints and looks like:

Where visiblePoints[n][0] is a value in ms (that I convert into seconds) and visiblePoints[n][1] is just a float value.
visiblePoints =
[0, 0.0500466109191]
[100, 0.0548114598135]
[200, 0.0550143573252]
[300, 0.0549408536766]
[400, 0.0546117305419]
[... repeat 300+ times...]

After looping over plotData[i] and visiblePoints[k] I end up with:
dataArray = [
    {
        "Time": 00:00:01,
        "foo": 1
    },
    {
        "Time": 00:00:01,
        "bar": 27
    },
    {
        "Time": 00:00:02,
        "foo": 4
    },
    {
        "Time": 00:00:02,
        "bar": 31
    },
]

When I had meant to end up with:
dataArray = [
    {
        "Time": 00:00:01,
        "foo": 1,
        "bar": 27
    },
    {
        "Time": 00:00:02,
        "foo": 4,
        "bar": 31
    }
]

I think in loop k I need to go over dataArray, check all objects there to see if there is a Time key that matches thisRow["Time"] = msToTime(timestamp), and if so, add thisRow[selectedParameter] = visiblePoints[k][1] to that, if not, create a new object.
Problems:

*

*I'm not sure how to check for this in JS (I'm more experience at Python, and not that much at that

*It seems like I'm doing a heck of a lot of loops. I'm not sure adding yet another one to go over the entire dataArray and check all objects to see if a key exists in one of them is best solution here. A plotData.visiblePoints array can be 500+ long.

[EDIT] Simplified the question. Added picture examples. Added text examples of the k array.

A: You could take a Map or a hash table which keeps the reference to the object with the same time.
var map = new Map,
    timestamp,
    row;

// later in loop
timestamp = msToTime(new Date(visiblePoints[k][0]));
row = map.get(timestamp);
if (!row) {
    map.set(timestamp, row = { Time: timestamp });
}
row[selectedParameter] = visiblePoints[k][1];

// at the end assign the array
dataArray = Array.from(map.values())

A: You can build an object keyed to the grouping — in this case the timestamp. This will let you randomly access the item you want without searching the array. When you'r done the Object.values of the object will be an array of your grouped objects:

let plotData = [
    {
        label: 'foo',
        visiblePoints: [[`00:00:01`, 1], [`00:00:02`, 4]]
    },
    {
        label: 'bar',
        visiblePoints: [[`00:00:01`, 27], [`00:00:02`, 31]]
    }
]

let groups = plotData.reduce((obj, {label, visiblePoints}) => {
    visiblePoints.forEach(([time, val]) => {
        if(!obj[time]) obj[time] = {Time: time}  // if we haven't seen this time make a new object at that key
        obj[time][label] = val
    })
    return obj
},   {})
console.log(Object.values(groups))

A: You could find if an Object has a specific key by calling hasOwnProperty method.

const obj = {
  "bar": [1,2,3],
  "foo": "im foo"
};

console.log(obj.hasOwnProperty("bar"))
console.log(obj.hasOwnProperty("bar2"))

And you need to follow this pattern.

var dataArray = []

for (i = 0; i < 1; i++) {

    for (k = 0; k < 2; k++) {

        thisRow = {};
        thisRow["Time"] = k+1 * i+1
        thisRow["foo"] = i+1
        thisRow["var"] = k+1
        dataArray.push(thisRow)
    }
}

console.log(dataArray)