text:
Q: What are best practices to manage different Resolution with Timescale DB I am pretty new to TSDB and especially with TimeScale DB. I have successfully managed to store the 1Min OHLCV in Materialized with, setup continous aggregation and everything is running fine.
I am using TradingView Charting library on the FE which automatically creates 5min, 15min, 30min and other charts from the 1min OHLCV data.
My response object for TradingView /history request :
{
"s":"ok",
"t":[1666703100,1666703160,1666703220],
"o":[19288.1,19285.4,19289.1],
"h":[19294.8,19289.1,19289.1],
"l":[19285.4,19285.4,19288.7],
"c":[19285.4,19289.0,19288.8],
"v":[180.10899999999992,83.95100000000004]
}

the Result I get from TimeScale DB :
{
"day": 2022-10-22 13:35:00+05:30,
"open": 19230.326,
"high":19500,
"low":19200.20,
"close":19250.68,
"volume":2.658
}

So I have to loop through ResultSet from DB -> map to my response object -> send to TV.
Now as the data grows, 1min candles take up lot of processing due to this loop.

*

*What should be an ideal way from performance and resource optimization point of view
to manage multiple resoution with TimeScale DB ?

*Any better way to map the DB result to my required response without looping ? Bit allergic to loop with large data sets.

A: Timescaledb is testing an experimental set of functions to cover ohlc and soon ohlcv will also be available.
You can rollup it over ohlc data but not use materialized views over materialized views (at least for now).
Let me share a small example that maybe can help.
First, a simple ticks table to store the trade events:
CREATE TABLE ticks
( time TIMESTAMPTZ NOT NULL,
    symbol varchar,
    price double precision,
    volume int);

SELECT create_hypertable('ticks', 'time', chunk_time_interval => INTERVAL '1 day');

Now, let's create the base ohlcv from 1 minute being the most granular pre-calculated materialized view:

CREATE MATERIALIZED VIEW _ohlcv_1m
WITH (timescaledb.continuous) AS
    SELECT time_bucket('1 minute'::interval, time),
      symbol,
      toolkit_experimental.ohlc(time, price),
      sum(volume) as volume
    FROM ticks
    GROUP BY 1,2 WITH DATA;

As the continuous aggregates in the top of another continuous aggregates is not allowed, we can create a simple view and benefit from rollup that will "merge" the previous ohlc structures.

CREATE VIEW _ohlcv_1h AS
    SELECT time_bucket('1 hour'::interval, time_bucket),
      symbol,
      toolkit_experimental.rollup(ohlc) as ohlc,
      sum(volume) as volume
    FROM _ohlcv_1m
    GROUP BY 1,2;

The views don't have access to the values directly, so, we can create views to access the ohlcv values and the time of each event.

CREATE VIEW ohlcv_1m as
SELECT time_bucket,
  symbol,
  toolkit_experimental.open(ohlc),
  toolkit_experimental.open_time(ohlc),
  toolkit_experimental.high(ohlc),
  toolkit_experimental.high_time(ohlc),
  toolkit_experimental.low(ohlc),
  toolkit_experimental.low_time(ohlc),
  toolkit_experimental.close(ohlc),
  toolkit_experimental.close_time(ohlc),
  volume
FROM _ohlcv_1m;

CREATE VIEW ohlcv_1h as
SELECT time_bucket,
  symbol,
  toolkit_experimental.open(ohlc),
  toolkit_experimental.open_time(ohlc),
  toolkit_experimental.high(ohlc),
  toolkit_experimental.high_time(ohlc),
  toolkit_experimental.low(ohlc),
  toolkit_experimental.low_time(ohlc),
  toolkit_experimental.close(ohlc),
  toolkit_experimental.close_time(ohlc),
  volume
FROM _ohlcv_1h;

Now, seeding some data for tests:

INSERT INTO ticks
SELECT time, 'SYMBOL', (random()*30)::int, 100*(random()*10)::int
FROM generate_series(TIMESTAMP '2000-01-01 00:00:00',
                 TIMESTAMP '2000-01-02 00:00:00' + INTERVAL '1 hour',
             INTERVAL '1 second') AS time;

Testing the final views:
playground=# select time_bucket, open, high, low, close, volume from ohlcv_1h ORDER BY time_bucket LIMIT 1;
┌────────────────────────┬──────┬──────┬─────┬───────┬─────────┐
│      time_bucket       │ open │ high │ low │ close │ volume  │
├────────────────────────┼──────┼──────┼─────┼───────┼─────────┤
│ 2000-01-01 00:00:00-02 │   13 │   30 │   0 │     8 │ 1809600 │
└────────────────────────┴──────┴──────┴─────┴───────┴─────────┘
(1 row)

playground=# select time_bucket, open, high, low, close, volume from ohlcv_1m ORDER BY time_bucket LIMIT 60
;
┌────────────────────────┬──────┬──────┬─────┬───────┬────────┐
│      time_bucket       │ open │ high │ low │ close │ volume │
├────────────────────────┼──────┼──────┼─────┼───────┼────────┤
│ 2000-01-01 00:00:00-02 │   13 │   30 │   0 │    25 │  32700 │
│ 2000-01-01 00:01:00-02 │    0 │   30 │   0 │     2 │  33000 │
│ 2000-01-01 00:02:00-02 │    1 │   30 │   0 │     6 │  26300 │
│ 2000-01-01 00:03:00-02 │    4 │   30 │   1 │    28 │  30300 │
│ 2000-01-01 00:04:00-02 │   30 │   30 │   0 │    27 │  29200 │
│ 2000-01-01 00:05:00-02 │   24 │   29 │   2 │    16 │  27500 │
│ 2000-01-01 00:06:00-02 │    9 │   28 │   0 │    15 │  30200 │
│ 2000-01-01 00:07:00-02 │   21 │   30 │   2 │     3 │  30300 │
│ 2000-01-01 00:08:00-02 │   10 │   29 │   1 │     3 │  35300 │
│ 2000-01-01 00:09:00-02 │    6 │   30 │   0 │    16 │  26700 │
│ 2000-01-01 00:10:00-02 │   10 │   30 │   0 │    24 │  30300 │
│ 2000-01-01 00:11:00-02 │   30 │   30 │   1 │    27 │  29800 │
│ 2000-01-01 00:12:00-02 │    6 │   30 │   1 │    26 │  25500 │
│ 2000-01-01 00:13:00-02 │   13 │   29 │   0 │    22 │  30400 │
│ 2000-01-01 00:14:00-02 │    2 │   30 │   1 │    21 │  30800 │
│ 2000-01-01 00:15:00-02 │   22 │   30 │   0 │    15 │  31400 │
│ 2000-01-01 00:16:00-02 │   10 │   30 │   1 │     8 │  33700 │
│ 2000-01-01 00:17:00-02 │    3 │   30 │   1 │    22 │  27600 │
│ 2000-01-01 00:18:00-02 │   13 │   29 │   0 │     5 │  31400 │
│ 2000-01-01 00:19:00-02 │   17 │   29 │   1 │    16 │  30900 │
│ 2000-01-01 00:20:00-02 │   24 │   29 │   1 │    10 │  26500 │
│ 2000-01-01 00:21:00-02 │   16 │   29 │   1 │     9 │  34100 │
│ 2000-01-01 00:22:00-02 │   14 │   30 │   0 │    22 │  31500 │
│ 2000-01-01 00:23:00-02 │   10 │   30 │   1 │     1 │  28700 │
│ 2000-01-01 00:24:00-02 │    1 │   30 │   1 │     1 │  32900 │
│ 2000-01-01 00:25:00-02 │   11 │   30 │   1 │    24 │  25700 │
│ 2000-01-01 00:26:00-02 │   21 │   28 │   0 │     1 │  32100 │
│ 2000-01-01 00:27:00-02 │    1 │   30 │   0 │    23 │  33800 │
│ 2000-01-01 00:28:00-02 │    1 │   30 │   1 │    22 │  30100 │
│ 2000-01-01 00:29:00-02 │   15 │   30 │   0 │     6 │  26900 │
│ 2000-01-01 00:30:00-02 │   15 │   29 │   1 │     7 │  32800 │
│ 2000-01-01 00:31:00-02 │    9 │   30 │   0 │     7 │  30200 │
│ 2000-01-01 00:32:00-02 │   16 │   30 │   0 │    10 │  28000 │
│ 2000-01-01 00:33:00-02 │    6 │   30 │   1 │     9 │  28800 │
│ 2000-01-01 00:34:00-02 │    6 │   30 │   1 │     9 │  30300 │
│ 2000-01-01 00:35:00-02 │   20 │   29 │   0 │    17 │  30800 │
│ 2000-01-01 00:36:00-02 │   27 │   29 │   0 │    21 │  28400 │
│ 2000-01-01 00:37:00-02 │   29 │   30 │   0 │    20 │  30100 │
│ 2000-01-01 00:38:00-02 │   23 │   30 │   0 │     5 │  30300 │
│ 2000-01-01 00:39:00-02 │    1 │   30 │   0 │    24 │  34000 │
│ 2000-01-01 00:40:00-02 │   10 │   30 │   0 │    30 │  27500 │
│ 2000-01-01 00:41:00-02 │    3 │   30 │   0 │    20 │  32200 │
│ 2000-01-01 00:42:00-02 │    2 │   29 │   0 │    12 │  29400 │
│ 2000-01-01 00:43:00-02 │    5 │   29 │   0 │     4 │  31800 │
│ 2000-01-01 00:44:00-02 │   22 │   30 │   0 │     6 │  32700 │
│ 2000-01-01 00:45:00-02 │   11 │   29 │   1 │     9 │  30400 │
│ 2000-01-01 00:46:00-02 │   10 │   30 │   0 │     1 │  26700 │
│ 2000-01-01 00:47:00-02 │   12 │   30 │   0 │    17 │  28400 │
│ 2000-01-01 00:48:00-02 │   15 │   30 │   0 │    16 │  30800 │
│ 2000-01-01 00:49:00-02 │    6 │   30 │   0 │    29 │  27900 │
│ 2000-01-01 00:50:00-02 │   20 │   30 │   0 │    28 │  26500 │
│ 2000-01-01 00:51:00-02 │    7 │   30 │   0 │    14 │  30500 │
│ 2000-01-01 00:52:00-02 │   23 │   29 │   0 │     4 │  31200 │
│ 2000-01-01 00:53:00-02 │   26 │   30 │   1 │    10 │  31000 │
│ 2000-01-01 00:54:00-02 │   24 │   30 │   1 │     3 │  30200 │
│ 2000-01-01 00:55:00-02 │    3 │   30 │   0 │    20 │  32800 │
│ 2000-01-01 00:56:00-02 │   24 │   30 │   1 │    12 │  27300 │
│ 2000-01-01 00:57:00-02 │   19 │   30 │   0 │    26 │  30600 │
│ 2000-01-01 00:58:00-02 │    8 │   29 │   1 │    21 │  33500 │
│ 2000-01-01 00:59:00-02 │   10 │   30 │   1 │     8 │  28900 │
└────────────────────────┴──────┴──────┴─────┴───────┴────────┘
(60 rows)

For the part 2 of your question, you can use array_agg from postgresql to be concatenating the data. Example:
select array_agg(time_bucket) as t,
array_agg(open) as o,
array_agg(high) as h,
array_agg(low) as l,
array_agg(close) as c,
array_agg(volume) as v from ohlcv_1m group BY time_bucket('5 m', time_bucket) limit 3 ;

I'm limiting to 3 records just for the sake of readability, here are the results:
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┬─────────────────┬──────────────────┬─────────────┬────────────────┬─────────────────────────────────┐
│                                                               t                                                                │        o        │        h         │      l      │       c        │                v                │
├────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┼─────────────────┼──────────────────┼─────────────┼────────────────┼─────────────────────────────────┤
│ {"2000-01-01 00:02:00-02","2000-01-01 00:00:00-02","2000-01-01 00:01:00-02","2000-01-01 00:03:00-02","2000-01-01 00:04:00-02"} │ {16,0,27,29,14} │ {30,30,30,29,30} │ {1,0,2,1,0} │ {27,14,23,1,0} │ {29500,32400,32100,28500,25400} │
│ {"2000-01-01 00:07:00-02","2000-01-01 00:08:00-02","2000-01-01 00:05:00-02","2000-01-01 00:09:00-02","2000-01-01 00:06:00-02"} │ {22,26,9,17,5}  │ {30,30,29,30,29} │ {0,2,0,1,0} │ {21,5,18,14,5} │ {29000,28700,31600,30700,31200} │
│ {"2000-01-01 00:12:00-02","2000-01-01 00:11:00-02","2000-01-01 00:13:00-02","2000-01-01 00:10:00-02","2000-01-01 00:14:00-02"} │ {29,20,27,19,2} │ {30,30,29,30,30} │ {0,0,0,1,0} │ {1,17,21,9,16} │ {28400,31500,30800,25900,32100} │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┴─────────────────┴──────────────────┴─────────────┴────────────────┴─────────────────────────────────┘```


text:
Q: Slow rendering of Angular table with 1,000 rows and 5,000 inputs I am displaying an Angular table with approx ~1,000 rows and 5 inputs per row (total of 5,000 input fields). It is a standard Angular table with ng-repeat for the rows.
The data is downloaded to the client quickly. BUT - the problem is slow Angular rendering.
On a MacBook Pro, it takes 10 seconds to load. On a Chromebook, it takes over 40 seconds.
I'm looking for a way to lazy RENDER. I'm sure that many of you have had this problem - can anyone point me to possible solutions?

A: *

*Use pagination

*Only add inputs per row using edit template and an edit button

*User $compileProvider.debugInfoEnabled(false) to remove debug classes

*Try utilising the ID of your items by adding "track by"

*If you have values that you only read, use bind once {{::property}}

*If you have many form fields try ng-model-options="{ debounce: 250 }

*Use ng-if instead of ng-show where possible to avoid adding many things that are not displayed

*Use limitTo with your ng-repeat to limit the number of items displayed

*Use chrome dev toolbar timeline to identify bottlenecks in your functions

One of many good resources on our lovely web
And another one

A: Because the problem is with the rendering you could use a filter to limit the number of fields that ng-repeat returns. Then just paginate the extra rows.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ko.mapping.fromJS and Date objects I've asked questions about knockout in the past but haven't had a chance to work on knockout since the last question was addressed. My latest question is specifically about the use of ko.mapping.fromJS where a Date object is involved.
When I use ko.mapping.fromJS to map an object that has a nested Date object that Date object gets translated to...I don't know what it is.
Here is my jsfiddle: http://jsfiddle.net/L5sgW/46/
HTML:

 Name:

    <button id="update" data-bind="click: Update">Update!</button>

Javascipt:
var ViewModel = function (data) {
    var me = this;
    ko.mapping.fromJS(data, {}, me);

    me.Update = function () {
        alert(stuff2.IntroData.TestDate.toString('yyyy-MM-dd'));
        ko.mapping.fromJS(stuff2, {}, me);
        alert(me.IntroData.TestDate.toString('yyyy-MM-dd'));
    };

    return me;
};

var stuff = {
    IntroData: {
        Name: 'Test'
    }
};

var stuff2 = {
    IntroData: {
        TestDate: new Date('2013-09-01'),
        Name: 'Test2'
    }
};

window.viewModel = ko.mapping.fromJS(new ViewModel(stuff));
ko.applyBindings(window.viewModel);

When you click the "Update!" button "Stuff2.IntroData.TestDate" is displayed in the alert. Then the mapping occurs. When the alert for "me.IntroData.TestDate" happens it results in: "function d(){if(0

Why doesn't the date value get preserved? How do I preserve it?

A: : )
Remember that you need the parentheses to get the property of TestDate -
http://jsfiddle.net/L5sgW/47/
alert(me.IntroData.TestDate().toString('yyyy-MM-dd'));

That was the only line I changed.


text:
Q: Page reload in Chrome unnecessarily triggers bound events just prior to reloading the page Hope someone has a good answer to this:
Why does Chrome (14.0) triggers the document ready and window load events when I refresh the page? Note that I am not talking about what happens when the new page loads, but before it has loaded. See the following code:
<form name="form1" method="post" action="tmp.aspx?a=1" id="form1">

tmp
</form>

When I first visit page I get two outputs on console, one for document/ready and one for window/load. When I refresh page two more are quickly output, and instantly after that two more (from new page view). If I instead just click the link (tmp.aspx) which goes directly back to same page, this does not happen.
I am sure there is a good explanation for this.
EDIT:
The additional calls to $(document).ready() and $(window).load() are made BEFORE that page has refreshed. So when I first load the page they methods are called once, then I hit refresh and BEFORE the page has reloaded the methods are called again. After that, when the page just have been reloaded, the methods are called a THIRD time.

A: Behavior observed on 14.0.835.202. edit : (on Windows Seven x64)
It's not the jquery fault : The DOMContentLoaded is fired another time just before page unload.
Simple test to check this :
 function startpage() {
     console.log('page loaded');
   }

   function unloadPage(){
       console.log("page unloaded");
   }
document.addEventListener("DOMContentLoaded", startpage, false);
window.onbeforeunload = unloadPage;

You should see after a refresh:
page loaded
page loaded // should not be here and is not on Firefox.
page unloaded
loaded

In your console (with persistence on)
I think it's simply a Chrome bug. Not a console one, as timestamping proves it's not a duplicate.
Edit : the same Chrome version but running OSX seems ok (see comment below). It tends to confirm that it's a bug.

A: In Chrome 13 for Mac I am not seeing this behavior.  After you load the page for the first time, and before you hit refresh, do you clear out the console? Is there a chance you are seeing the old console output (I know some browsers like to keep a previous page's console output around)?
I would not expect those two events to be fired twice on a refresh, so my guess would be stale console, either by design because it was a manual refresh or perhaps Chrome 14 has bugs with their dev console.

A: Just to add some notes on testing, using chrome 15.0.874.102 and windows 7 x86:
This is the script I used for testing from my understanding of the question:

        <title>Testing Chrome</title>

        Reload Page

The following is a cumulative log, each new addition highlighted in bold:

*On initial page load I get:
---Loaded. ID: 68 Time: Tue Oct 25 2011 21:35:18 GMT+0100 (GMT Daylight Time)

*Pressing F5 whilst focused on the HTML page:
---Loaded. ID: 68 Time: Tue Oct 25 2011 21:35:18 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 68 Time: Tue Oct 25 2011 21:35:18 GMT+0100 (GMT Daylight Time) <-----
Un-loaded. ID: 68 Time: Tue Oct 25 2011 21:36:12 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 78 Time: Tue Oct 25 2011 21:36:12 GMT+0100 (GMT Daylight Time)

*Pressing the link on the HTML page to reload the page:
---Loaded. ID: 68 Time: Tue Oct 25 2011 21:35:18 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 68 Time: Tue Oct 25 2011 21:35:18 GMT+0100 (GMT Daylight Time)
Un-loaded. ID: 68 Time: Tue Oct 25 2011 21:36:12 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 78 Time: Tue Oct 25 2011 21:36:12 GMT+0100 (GMT Daylight Time)
----Reload Link----
Un-loaded. ID: 78 Time: Tue Oct 25 2011 21:38:25 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 22 Time: Tue Oct 25 2011 21:38:25 GMT+0100 (GMT Daylight Time)

*Pressing F5 whilst focused on the console:
---Loaded. ID: 68 Time: Tue Oct 25 2011 21:35:18 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 68 Time: Tue Oct 25 2011 21:35:18 GMT+0100 (GMT Daylight Time)
Un-loaded. ID: 68 Time: Tue Oct 25 2011 21:36:12 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 78 Time: Tue Oct 25 2011 21:36:12 GMT+0100 (GMT Daylight Time)
----Reload Link----
Un-loaded. ID: 78 Time: Tue Oct 25 2011 21:38:25 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 22 Time: Tue Oct 25 2011 21:38:25 GMT+0100 (GMT Daylight Time)
Un-loaded. ID: 22 Time: Tue Oct 25 2011 21:41:53 GMT+0100 (GMT Daylight Time)
---Loaded. ID: 15 Time: Tue Oct 25 2011 21:41:54 GMT+0100 (GMT Daylight Time)
As you can see the anomaly only occurs when directly reloading the page (I have highlighted the anomaly with an arrow), whilst focused on the page itself.
Also, if you notice both the ID and the timestamp of the anomaly they are the same even after waiting several seconds before hitting F5 - so it appears the code isn't running for a second time so to speak, but the console is logging a copy for some reason.

Adding further to the conclusion:
If you select the timeline tab, and record both an initial page load, and an F5 reload, you will notice the two functions to write to the console are only run once, further compounding it looks like a possible error on chromes console:

Show Image - Timeline 1 (initial load)

Show Image - Timeline 2 (F5 reload)

A: As far as I know, clicking an #xxx link (or link to the same page, with or without #xxx) does not trigger window.load and document.ready events.
If you want the link to trigger an event, do something like
$('a#xxx').click(function(){
    //Your code here
}

where xxx is the ID of the link.
If the link was meant to reload the page, use
window.location.reload()

in the click event handler.

A: I have tested this on Chromium 14 on Windows. Behavior is not observed.

A: It seems like a chrome/webkit developer console bug. Using chrome 14 on Ubuntu i can reproduce the bug by following the next steps.
First create a page containing the following js code
var timesLoaded = 0;

function loadHandler() {
    console.log(timesLoaded, "times loaded");
    timesLoaded++;
}

function unloadHandler(){
    console.log("unload after ", timesLoaded, " loads");
}

$(document).ready(loadHandler);
$(window).unload(unloadHandler);

*

*Open the page with google chrome

*Press F12 to open the console and see the 0 "times loaded" message

*Add a breakpoint on the first line of the unloadHandler function

*To see the double message appear you should click somewhere on the page (like giving focus out of the console and to the loaded page)

*Refresh the page

*You will probably see the 0 "times loaded" message again

The important thing is that your code is not executed twice. Its just that for some reason the webkit dev console displays the same message again. To further investigate the bug you can do the following,

*

*Load the previous html page

*Add the unload breakpoint again (just to be sure the page will not actually refresh)

*Right click on the console first entry (0 "times loaded")

*Click inspect element (yes console is just an html/js app)

*Locate the element the entry belongs to (it should be a div.console-group-message element

*Right click on the element and click on Break on Subtree Modifications

*Refresh the page (again after clicking somewhere on the html page to unfocus console window

*Just before the second annoying message appears the debugger will show up to the console code that tries to append the message.


text:
Q: Strugling to scrape titles with scrapy I am currently trying to scrape a title via Scrapy's shell. https://cineb.art/movies is the website,
the title is located in :
   <h3 class="film-name">

When i type response.css("film-name").get() i get nothing in return

fetch('https://cineb.art/movies')
2022-11-01 12:17:24 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://cineb.art/movies> (referer: None)>>> response.css('film-title').get()
response.css('film-name').get()

this is my log. Help me out! Thanks in advance!

A: there is an "a" tag under "h3" tag and you need to get text
response.css("h3.film-name a::text").get()


text:
Q: Automapper - Bestpractice of mapping a many-to-many association into a flat object I have two entities: Employee and Team.

What I want is an EmployeeForm that has the Name of the Team.

How can I achieve this using AutoMapper?
My current "solution" is the following:
Mapper.CreateMap<Employee, EmployeeForm>()
                           .ForMember(dest => dest.TeamName, opt => opt.MapFrom(x => x.GetTeams().FirstOrDefault() != null ? string.Join(", ", x.GetTeams().Select(y=>y.Name)) : "n/a"));

In my opinion this is bad readable.
What I would like to have is a generic method where I can pass an entity, choosing the collection and saying if collection is null return a default value or otherwise choose the property of the collection via lambda expressions.

A: I rethinked my whole design starting to change the domain model:

I changed the many-to-many association into two one-to-many associations using a relation table.
With this more easier domain model, I can easily map this into a flat DTO using AutoMapper.
public class TeamEmployeeMapperProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<TeamEmployee, TeamEmployeeForm>();
    }
}

Yes that's all :)
Here is the flat view model object.

A: You could create a read-only string property on Employee called "TeamNames".  Put the list-building logic in there.  That way, you've got a property that is testable (vs. the lambda expression) and it will make your mapping easier.


text:
Q: Kubuntu - Missing Menu Entries after installation I just installed Kubuntu 14.10 new, because of some issues with it before. And I installed some software like Thunderbird, Google Chrome and Skype. But none of the Software is listed in the menu. Even search won't show it. I installed it with:
sudo apt-get install ...

Just like I always do. But it is nothing in the menu. I can start the Applications from the terminal, so they are definitely installed.
What can I do to find the Applications through the menu? Do I need to change settings, or is it a new "feature" that new installed applications won't show in the menu?
I hope someone can help.
Edit:
Errormessage I got for kbuildsycoca4 --noincremental
kbuildsycoca4 running...
kbuildsycoca4(2821) VFolderMenu::loadDoc: Parse error in  "/home/svenja/.config/menus/applications-merged/xdg-desktop-menu-dummy.menu" , line  1 , col  1 :  "unexpected end of file"

A: At here
Installing the Thunderbird:
sudo apt-get install thunderbird

After the installation is done the KDE Menu is updated.

The Thunderbird can be find from the 'Recently Installed ', 'Internet' and through the 'Search' bar.
Something to try
:~$ kbuildsycoca4 --help
Usage: kbuildsycoca4 [Qt-options] [KDE-options] [options]

Rebuilds the system configuration cache.

Generic options:
  --help                    Show help about options
  --help-qt                 Show Qt specific options
  --help-kde                Show KDE specific options
  --help-all                Show all options
  --author                  Show author information
  -v, --version             Show version information
  --license                 Show license information
  --                        End of options

Options:
  --nosignal                Do not signal applications to update
  --noincremental           Disable incremental update, re-read everything
  --checkstamps             Check file timestamps
  --nocheckfiles            Disable checking files (dangerous)
  --global                  Create global database
  --menutest                Perform menu generation test run only
  --track <menu-id>         Track menu id for debug purposes

Try to rebuild the system configuration cache with the 'noincremental' option.
kbuildsycoca4 --noincremental

Any error messages ?
----EDIT----
The xdg-desktop-menu-dummy.menu is made by the xdg-desktop-menu
man xdg-desktop-menu

NAME
       xdg-desktop-menu - command line tool for (un)installing desktop menu items

At here it doesn't prevent the KDE menu update.


text:
Q: c - writing to shared memory segment causes segmentation fault I'm having problems with writing to shared memory segment. Here's the code:
EDIT: after I removed that == (mistake), now I'm getting Bus Error (Core Dumped), here's the edited code:
// Struct for data from shared memory
typedef struct {
     pthread_mutex_t shared_mutex;
     int last_used_job_id;
} shared1;

static void *job_generator(void *param)
{
     int J = *((int *) param);
     shared1 *shd;
     int shm;
     int job_id;

     // Open shared memory, don't create it if doesn't exist
     shm = shm_open("/lab5", O_RDWR, 00600);

     // Check
     if (shm == -1) {
          // Open shared memory, create it if doesn't exist (O_CREAT)
         shm = shm_open(q_name, O_RDWR | O_CREAT, 00600);

         // Map space for struct
         shd = mmap(NULL, sizeof(shared1), PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0);
         if (shd == (void *) -1) {
              perror ( "mmap" );
              exit(1);
         }

         // Initialize mutex
         if (pthread_mutex_init(&(shd->shared_mutex), NULL) != 0)
         {
              printf("Mutex initialization failed!\n");
              exit(1);
         }
     }

     else
     {
          // Map space for struct
          shd = mmap(NULL, sizeof(shared1), PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0);
          if (shd == (void *) -1) {
              perror ( "mmap" );
              exit(1);
          }
     }

     // Lock mutex
     pthread_mutex_lock(&(shd->shared_mutex));

     job_id = shd->last_used_job_id + 1;
     shd->last_used_job_id = job_id + J;
     printf("a: %d\n", shd->last_used_job_id);

     return NULL;
}

it's caused by any of the instructions which are using shd, so any of these:
// Lock mutex
pthread_mutex_lock(&(shd->shared_mutex));

job_id = shd->last_used_job_id + 1;
shd->last_used_job_id = job_id + J;
printf("a: %d\n", shd->last_used_job_id);

A: I think this is where your problem lies:
shd == mmap(NULL, sizeof(shared1), PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0);

You're comparing shd to the return value of mmap with '=='. I think you meant to use a single '=' which would assign the return value to shd.


text:
Q: (DIFF EQ) Can functions be neither linearly dependent or independent over an interval? Confusing definition.
This definition of linear independence of functions is very confusing to me because what if functions fit neither definition over an interval.
Like number 5 says it's linearly dependent, but I feel like that's only true for specific numbers of t, not for the whole interval.

A: The functions from number 5 are linearly dependent because$$\color{red}{1}\times(t+1)+\color{red}{(-1)}\times(t^2+1)+\color{red}{1}\times(t^2-t)=0.$$Note the the numbers in red don't depend on $t$.


text:
Q: how to use sudo pip3 install --target to install package and recognize the dependencies I want to use pip3 to install rise package. I use the command
sudo pip3 install rise

Then the rise package is installed in /usr/local/lib/python3.5/dist-packages and print out:
Collecting rise
Downloading rise-4.0.0b1-py2.py3-none-any.whl (359kB)
100% |████████████████████████████████| 368kB 4.0MB/s
Requirement already satisfied (use --upgrade to upgrade): notebook>=4.2 in /usr/lib/python3/dist-packages (from rise)
Installing collected packages: rise
Successfully installed rise

Now I want to install rise in different directory, so I write
sudo pip3 install --target /usr/lib/python3/dist-packages rise

then it print out:
Collecting rise
Downloading rise-4.0.0b1-py2.py3-none-any.whl (359kB)
100% |████████████████████████████████| 368kB 4.8MB/s
Collecting notebook>=4.2 (from rise)
Downloading notebook-4.2.2-py2.py3-none-any.whl (6.7MB)
100% |████████████████████████████████| 6.7MB 290kB/s
Collecting nbconvert (from notebook>=4.2->rise)
Downloading nbconvert-4.2.0-py2.py3-none-any.whl (319kB)
100% |████████████████████████████████| 327kB 5.8MB/s
Collecting ipython-genutils (from notebook>=4.2->rise)
Downloading ipython_genutils-0.1.0-py2.py3-none-any.whl
Collecting jupyter-client (from notebook>=4.2->rise)
Downloading jupyter_client-4.3.0-py2.py3-none-any.whl (76kB)
100% |████████████████████████████████| 81kB 16.0MB/s

well because I already install notebook nbconvert and other dependencies via apt-get and they satisfies the version requirement. Why pip3 need to reinstall them? But in the first case, without --target, pip3 can recognize all the dependencies. Also, if I just use
pip3 install rise

pip3 also not recognize all the dependencies and will download all of them. I want to ask what is the default searching path of dependencies in pip3. If pip3 can not recognize the searching path of dependencies, how to tell it?


text:
Q: ScrollingViewBehavior for ListView I have two activities using AppBarLayout with a Toolbar and TabLayout from support library 22.
The layout of both is pretty similar: A Toolbar at the top, below it TabLayout, below it a ViewPager containing 3 Fragments.
The first activity's Fragment has a RecyclerView,
the second activity's Fragment is using a ListView instead.
The scrollable Toolbar example from https://github.com/chrisbanes/cheesesquare is working fine on the first activity using the RecyclerView, but on with the ListView.
I've tried created a custom ListViewScrollBehavior that extends AppBarLayout.ScrollingViewBehavior, but so far no luck.
The TouchEvents are passed to the custom class only for horizontal scrolling, but not when scrolling the ListView (vertically).
Any way to use a CoordinatorLayout with ListView?

A: To a view able to react on AppBarLayout, it need to implement NestedScrollingChild. ListView is not. But it could be implement by a delegate class easily. Use it, it will do like what RecyclerView did
public class NestedScrollingListView extends ListView implements NestedScrollingChild {
private NestedScrollingChildHelper mNestedScrollingChildHelper;

public NestedScrollingListView(final Context context) {
    super(context);
    initHelper();
}

public NestedScrollingListView(final Context context, final AttributeSet attrs) {
    super(context, attrs);
    initHelper();
}

public NestedScrollingListView(final Context context, final AttributeSet attrs, final int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initHelper();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public NestedScrollingListView(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    initHelper();
}

private void initHelper() {
    mNestedScrollingChildHelper = new NestedScrollingChildHelper(this);
    setNestedScrollingEnabled(true);
}

@Override
public void setNestedScrollingEnabled(final boolean enabled) {
    mNestedScrollingChildHelper.setNestedScrollingEnabled(enabled);
}

@Override
public boolean isNestedScrollingEnabled() {
    return mNestedScrollingChildHelper.isNestedScrollingEnabled();
}

@Override
public boolean startNestedScroll(final int axes) {
    return mNestedScrollingChildHelper.startNestedScroll(axes);
}

@Override
public void stopNestedScroll() {
    mNestedScrollingChildHelper.stopNestedScroll();
}

@Override
public boolean hasNestedScrollingParent() {
    return mNestedScrollingChildHelper.hasNestedScrollingParent();
}

@Override
public boolean dispatchNestedScroll(final int dxConsumed, final int dyConsumed, final int dxUnconsumed, final int dyUnconsumed, final int[] offsetInWindow) {
    return mNestedScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);
}

@Override
public boolean dispatchNestedPreScroll(final int dx, final int dy, final int[] consumed, final int[] offsetInWindow) {
    return mNestedScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
}

@Override
public boolean dispatchNestedFling(final float velocityX, final float velocityY, final boolean consumed) {
    return mNestedScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
}

@Override
public boolean dispatchNestedPreFling(final float velocityX, final float velocityY) {
    return mNestedScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY);
}

}

A: The only solution to make it work now is to use this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
     listView.setNestedScrollingEnabled(true);
}

It will obviously only work on Lollipop.

A: Alternative solution to Nicolas POMEPUY's answer is to use ViewCompat.setNestedScrollingEnabled(View, boolean)
ViewCompat.setNestedScrollingEnabled(listView, true);

Of course nested scrolling behavior will only work from Lollipop.

A: I believe that the CoordinatorLayout works only with RecyclerView and NestedScrollView. Try wrapping your ListView in a NestedScrollView or convert it to a RecyclerView with a LinearLayoutManager

A: ListView ScrollingViewBehavior supports only >= 21.
Otherwise you should to write code as below way:
private int mPreviousVisibleItem;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    listView.setNestedScrollingEnabled(true);
} else {
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (firstVisibleItem > mPreviousVisibleItem) {
                appBarLayout.setExpanded(false, true);
            } else if (firstVisibleItem < mPreviousVisibleItem) {
                appBarLayout.setExpanded(true, true);
            }
            mPreviousVisibleItem = firstVisibleItem;
        }
    });
}

A: You can add
    android:nestedScrollingEnabled="true"

to the ListView from XML, just note that this only supports API 21+. Alternatively, you can swap out your ListView for a RecyclerView, and that should work better.


text:
Q: Making a search List using DatagridView I want to make a search list using datagridview in c#. I have a text box where one can enter the customer name. When the "search" button is clicked, i will hide all the rows where the CustomerName is not equal to the searchValue.
The problem is that when the user want to search for the second time, how can I search through the hidden rows of the dgv. Do i need to make visible the rows hidden.
Thanks.
Here is the Code.
   private void search_Click(object sender, EventArgs e)
    {
         arrayList= new ArrayList();
        String searchValue = searchBox.Text;
        for (int i = 0; i < dataGridView1.RowCount-1; i++)
        {
            if ( (dataGridView1.Rows[i].Cells[1].Value.ToString().Trim() ).Equals (searchValue.Trim()) )
            {
                //dataGridView1.Visible = true;
                arrayList.Add(i);
            }
            else
            {
                dataGridView1.Visible = false;
            }
        }
        dataGridView1.Refresh();

    }

A: Are you using a datatable to bind the datagridview?
If you are, when you are searching you could iterate the datatable and delete the rows that do not match your search criteria. When you search you can rejectchanges on your datatable to have the original data again. Afterwards you can use the same process that was used in the first place (mark the datarows that do not match the search criteria as deleted).
Another alternative can be using a DataRowView and filter with your search criteria and use the that datarowview to bind the datagridview. I would prefer this last one.


text:
Q: Binding inside an ItemsSource defined in XAML I want to define the ItemsSource of an ItemsControl in XAML and in those items use data binding to the DataContext of my view, but I cannot get it to work.
Here is what a simplified version would look like:
<ComboBox DisplayMemberPath="Label" DataContext="Item 3">
    <ComboBox.ItemsSource>
        <x:Array Type="{x:Type local:Item}">
            <local:Item Label="Item 1" />
            <local:Item Label="{Binding}" />
        </x:Array>
    </ComboBox.ItemsSource>
</ComboBox>

with the Item defined like this:
public class Item : DependencyObject
{
    public static readonly DependencyProperty LabelProperty =
        DependencyProperty.Register(nameof(Label), typeof(string), typeof(Item));

    public string Label
    {
        get { return (string)GetValue(LabelProperty); }
        set { SetValue(LabelProperty, value); }
    }
}

I am expecting to see two items in the ComboBox with "Item 1" and "Item 2" as text, but the second item has a blank text. Why?

A: You want to override the ItemTemplate for the ComboBox, an example is shown below:
<ComboBox x:Name="ExampleComboBox"
          Height="24"
          Width="200"
          HorizontalContentAlignment="Stretch">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="10" />
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="10" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <TextBlock Grid.Column="0"
                               Text="{Binding FirstName}" />
                    <TextBlock Grid.Column="2"
                               Text="{Binding LastName}" />
                    <TextBlock Grid.Column="4"
                               HorizontalAlignment="Right"
                               Text="{Binding Country}" />
                </Grid>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

The example output is shown below:

A: I finally found an explanation! The ItemsSource is not in the visual tree, that's why the binding is not working. I have found a great explanation and a workaround here: https://stackoverflow.com/a/7661689, that led me to another (similar) workaround here: http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/.
Using the latter, my code now looks like this (in this somewhat overly simplified and rather stupide example):
<ComboBox DisplayMemberPath="Label" DataContext="Item 3">
    <ComboBox.Resources>
        <local:BindingProxy x:Key="proxy" Data="{Binding}" />
    </ComboBox.Resources>
    <ComboBox.ItemsSource>
        <x:Array Type="{x:Type local:Item}">
            <local:Item Label="Item 1" />
            <local:Item Label="{Binding Data, Source={StaticResource proxy}}" />
        </x:Array>
    </ComboBox.ItemsSource>
</ComboBox>

And it works.


text:
Q: vba better way to set all values in array to same thing This is a matter of personal curiosity.
In VBA, if I have an array of size 2:
Dim r(1) as Variant

And I want both values in the array to be -1. I can do this:
r(0)=-1
r(1)=-1

Or I could iterate through both with a loop and set them to -1.
So my question is, is there any way I can set all the values in an array to the same thing without iterating?
Or, is there any way I can do something like:
r = array(-1,-1)

This might be a really stupid question but I can't seem to find the answer.

A: I'm not very good at drawing images. But this should give you and make clear the concepts associated with variant arrays.

A: Yes you can do it. But then you have to take care while declaring the array
Example
Option Explicit

Sub Sample()
    Dim r As Variant '<~~

    r = Array(-1, -1)

    Debug.Print r(0)
    Debug.Print r(1)
End Sub

FOLLOWUP
See the Excel Help File :) The Array Function returns a Variant containing an array. You cannot assign an array to another array directly. To assign an array to another array you have to use this method.
Option Explicit

Sub Sample()
    Dim r(1) As Variant
    Dim s As Variant
    Dim i As Long

    s = Array(-1, -1)

    For i = LBound(r) To UBound(r)
       r(i) = s(i)
    Next

    Debug.Print r(0)
    Debug.Print r(1)
End Sub


text:
Q: Mediacodec and camera, color space incorrect By referring Aegonis's work 1 and work 2, I also got the H.264 stream , but the color is not correct. I am using HTC Butterfly for development. Here is part of my code:
Camera:
parameters.setPreviewSize(width, height);
parameters.setPreviewFormat(ImageFormat.YV12);
parameters.setPreviewFrameRate(frameRate);

MediaCodec:
mediaCodec = MediaCodec.createEncoderByType("video/avc");
MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", 320, 240);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 500000);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar);
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5);
mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mediaCodec.start();

When using COLOR_FormatYUV420Planar the error shows "[OMX.qcom.video.encoder.avc] does not support color format 19,"  so I can only use "COLOR_FormatYUV420SemiPlanar". Does anyone know the reason why no support?
Got it, by using :
int colorFormat = 0;
    MediaCodecInfo.CodecCapabilities capabilities = codecInfo.getCapabilitiesForType(mimeType);
    for (int i = 0; i < capabilities.colorFormats.length && colorFormat == 0; i++) {
        int format = capabilities.colorFormats[i];
        Log.e(TAG, "Using color format " + format);
    }

we can have color format 21 (COLOR_FormatYUV420SemiPlanar) and 2130708361 (no corresponding format), I think the format will change depends on device.
Then, I tried the color transform provided from the suggestions in work 1 and work 2:
public static byte[] YV12toYUV420PackedSemiPlanar(final byte[] input, final byte[] output, final int width, final int height) {
    /*
     * COLOR_TI_FormatYUV420PackedSemiPlanar is NV12
     * We convert by putting the corresponding U and V bytes together (interleaved).
     */
    final int frameSize = width * height;
    final int qFrameSize = frameSize/4;

    System.arraycopy(input, 0, output, 0, frameSize); // Y

    for (int i = 0; i < qFrameSize; i++) {
        output[frameSize + i*2] = input[frameSize + i + qFrameSize]; // Cb (U)
        output[frameSize + i*2 + 1] = input[frameSize + i]; // Cr (V)
    }
    return output;
}

public static byte[] YV12toYUV420Planar(byte[] input, byte[] output, int width, int height) {
    /*
     * COLOR_FormatYUV420Planar is I420 which is like YV12, but with U and V reversed.
     * So we just have to reverse U and V.
     */
    final int frameSize = width * height;
    final int qFrameSize = frameSize/4;

    System.arraycopy(input, 0, output, 0, frameSize); // Y
    System.arraycopy(input, frameSize, output, frameSize + qFrameSize, qFrameSize); // Cr (V)
    System.arraycopy(input, frameSize + qFrameSize, output, frameSize, qFrameSize); // Cb (U)

    return output;
}

public static byte[] swapYV12toI420(byte[] yv12bytes, int width, int height) {
    byte[] i420bytes = new byte[yv12bytes.length];
    for (int i = 0; i < width*height; i++)
        i420bytes[i] = yv12bytes[i];
    for (int i = width*height; i < width*height + (width/2*height/2); i++)
        i420bytes[i] = yv12bytes[i + (width/2*height/2)];
    for (int i = width*height + (width/2*height/2); i < width*height + 2*(width/2*height/2); i++)
        i420bytes[i] = yv12bytes[i - (width/2*height/2)];
    return i420bytes;
}

Obviously, the color transform of YV12toYUV420PackedSemiPlanar performs better than the other two. It is relatively better but still looks different in comparison with the real color. Is there something wrong with my code? Any comment will be appreciated.

A: Got it, now the color looks good, the test is based on HTC Butterfly.
When set the resolution to 320x240, your color transform should looks like:
    System.arraycopy(input, 0, output, 0, frameSize);
    for (int i = 0; i < (qFrameSize); i++) {
        output[frameSize + i*2] = (input[frameSize + qFrameSize + i - 32 - 320]);
        output[frameSize + i*2 + 1] = (input[frameSize + i - 32 - 320]);
    }

for resolution 640x480 and above,
System.arraycopy(input, 0, output, 0, frameSize);
    for (int i = 0; i < (qFrameSize); i++) {
        output[frameSize + i*2] = (input[frameSize + qFrameSize + i]);
        output[frameSize + i*2 + 1] = (input[frameSize + i]);
    }

For the frame rate issue, we can use the getSupportedPreviewFpsRange() to check the supported frame rate range of our device as:
List<int[]> fpsRange = parameters.getSupportedPreviewFpsRange();
for (int[] temp3 : fpsRange) {
System.out.println(Arrays.toString(temp3));}

And the following setting works correct when play the encoded H.264 ES,
parameters.setPreviewFpsRange(29000, 30000);
//parameters.setPreviewFpsRange(4000,60000);//this one results fast playback when I use the FRONT CAMERA

A: After reading this discussion it turns out that more generalised way for encoding frames
of various resolutions is to align chroma plane by 2048 bytes before sending frame to the MediaCodec. This is actual for QualComm (OMX.qcom.video.encoder.avc) encoder which I believe HTC Butterfly has, but still does not works well for all resolutions. 720x480 and 176x144 are still have chroma  plane misaligned according to the output video. Also, avoid resolutions which sizes can't be divided by 16.
The transformation is pretty simple:
int padding = 0;
if (mediaCodecInfo.getName().contains("OMX.qcom")) {
  padding = (width * height) % 2048;
}
byte[] inputFrameBuffer = new byte[frame.length];
byte[] inputFrameBufferWithPadding = new byte[padding + frame.length];

ColorHelper.NV21toNV12(frame, inputFrameBuffer, width, height);
# copy Y plane
System.arraycopy(inputFrameBuffer, 0, inputFrameBufferWithPadding, 0, inputFrameBuffer.length);
int offset = width * height;
# copy U and V planes aligned by <padding> boundary
System.arraycopy(inputFrameBuffer, offset, inputFrameBufferWithPadding, offset + padding, inputFrameBuffer.length - offset);


text:
Q: The set of discontinuous points is countable union of closed sets Im reading chapter9 Category, Real Analysis, Carothers, 1ed, talking about discontinuous functions of metric space. Here is a proof for a theorem that the set of discontinuous points is the countable union of closed sets in R:

Definition of D(f) is:

Definition of $ω_f(a)$ is:

Definition of ω(f; I) is:

Actually, I have some questions,:

*

*Let $F_n= \{a : ω_f(a) \geq 1/n \}$, then $F_1$ belongs to $F_2$, $F_2$ belongs to $F_3$, $F_3$ belongs to $F_4$ and so forth, is that right?

*What's the reason for "why"? I mean if question1 is yes, then union of $F_n$ seems to be no sense cos union of $F_n$ will = $lim F_n$ when $n$ goes to infinity.

*In $\{a : ω_f(a) \geq \xi \text{ for some } \xi > 0\}$, $\xi$ should as small as possible(basically, $\xi>0$), is that right?

*Is {a:$ω_f(a) < r$} a subset of or equivalent to ${I: ω(f:I) < r}$ in $\mathbb{R}$?

A: *

*Yes: if $\omega_f(a)\ge\frac1n$, then certainly $\omega_f(a)\ge\frac1{n+1}$, so $F_n\subseteq F_{n+1}$ for each $n$.

*The statement that $D(f)=\bigcup_{n\ge 1}F_n$ really does require proof, though the proof is very easy. First off, it's clear that if $\omega_f(a)\ge\frac1n$ then $\omega_f(a)>0$, so $F_n\subseteq D(f)$ for each $n\ge 1$. Thus, $D(f)\supseteq\bigcup_{n\ge 1}F_n$. Now suppose that $a\in D(f)$. Then $\omega_f(a)>0$, so there is some positive integer $k$ such that $\frac1k<\omega_f(a)$. But then $a\in F_k\subseteq\bigcup_{n\ge 1}F_n$, and since $a$ was any element of $D(f)$, this implies that $D(f)\subseteq\bigcup_{n\ge 1}F_n$. Combining the inclusions, we see that $D(f)=\bigcup_{n\ge 1}F_n$, as claimed.

*Do you mean in the equality $\{a:\omega_f(a)>0\}=\{a:\omega_f(a)\ge\epsilon\text{ for some }\epsilon>0\}$? That step could just as well be omitted: in (2) above I showed directly that $D(f)=\bigcup_{n\ge 1}F_n$ without using $\{a:\omega_f(a)\ge\epsilon\text{ for some }\epsilon>0\}$ at all. I don't think that it contributes anything to one's understanding of the argument.

*$\{a:\omega_f(a)<r\}$ is a set of real numbers, a subset of $\Bbb R$; $\{I:\omega(f;I)<r\}$ is a set of bounded intervals in $\Bbb R$. These two sets don't even have the same kind of elements: the elements of the first set are individual real numbers, while the elements of the second set are bounded intervals of real numbers. Thus, the two sets are very different: not only is it impossible for them to be equal to each other, it's impossible for either of them to be a subset of the other.


text:
Q: PHP Fatal error: Cannot make non static method WC_Shipping_Method::is_enabled() static in class enda_woocommerce_bundlerate_shipping I have updated wooCommerce plugin that broke my wordpress site and getting this error in log.
PHP Fatal error:  Cannot make non static method WC_Shipping_Method::is_enabled() static in class enda_woocommerce_bundlerate_shipping in server_path/wp-content/plugins/woocommerce-bundle-rate-shipping-1.3.8/bundle_rate.class.php on line 6

Any Help?

A: The plugin you're using, WooCommerce Bundle Rate Shipping, needs to be updated.
A quick Google search reveals that support for WooCommerce 2.6 (the current version of WooCommerce which you've updated to) was added to that plugin in version 2.0.0.
The error shows you're running version 1.3.8 of the plugin therefore you're missing the WC2.6 support, hence the issue.
The changelog for the plugin can be viewed here: https://codecanyon.net/item/woocommerce-ecommerce-bundle-rate-shipping/1429243


text:
Q: Debian 8.2 computer freezing+crashing randomly I have a Debian media server which seems to be crashing several times daily for no apparent reason at all. It simply freezes up, without restarting, until you manually restart it. I have uploaded the syslog here and the kern.log here
Any restart indications in the log file were done manually by me and not as a direct result of the crash.

A: I don't see any explicit question here, but here's what I would do to start debugging this issue.
The first thing I do in cases like this is to run memtest86 or memtest86+ a few hours on the machine. This will rule out a lot of the common hardware errors.
If that passes, I run mprime for good measure. It will check that the CPU continues to calculate most things correctly under stress. I've had subtle errors after several hours running this, although I have not had to use it in a couple of years.
Now, if these tests passes, your hardware and cooling should be fine. After this I'd try running the system from a live CD if possible, perhaps trying an i386 version instead of amd64, to see if there's something wrong there.
If this does not give any insight, feel free to update the question with any new information!


text:
Q: Adjust WebView when keyboard is opened in Android I created an app in which I used WebView for navigation on site pages.
   browser = (WebView) findViewById(R.id.customWebBrowser);

   browser.setWebViewClient(new CustomWebViewClient());
   browser.setWebChromeClient(new CustomWebChromeClient());
   browser.setOnTouchListener(new OnTouchBrowser());

The problem is when I tap link "login" and a pop-up window is opened for input of login/password. When keyboard has risen it coves login/password pop-up and I can`t see what symbols I entered, content of visible WebView is not adjusted.
I tried to fix this issue by using windowSoftInputMode parameter in AndroidManifest.xml but it hasnt any effect. I think that's because of using pop-up window on server side.
How to fix this issue so screen will be adjusted when keyboard has risen?

A: Catch events from IME and manually adjust the WebView height

A: I found solution for my issue. It`s based on yghm's workaround.
http://code.google.com/p/android/issues/detail?id=5497
public class AndroidBug5497Workaround {

    // For more information, see https://code.google.com/p/android/issues/detail?id=5497
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    public static void assistActivity (Activity activity) {
        new AndroidBug5497Workaround(activity);
    }

    private View mChildOfContent;
    private int usableHeightPrevious;
    private FrameLayout.LayoutParams frameLayoutParams;

    private AndroidBug5497Workaround(Activity activity) {
        FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
        mChildOfContent = content.getChildAt(0);
        mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
        frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
    }

    private void possiblyResizeChildOfContent() {
        int usableHeightNow = computeUsableHeight();
        if (usableHeightNow != usableHeightPrevious) {
            int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
            int heightDifference = usableHeightSansKeyboard - usableHeightNow;
            if (heightDifference > (usableHeightSansKeyboard/4)) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightSansKeyboard;
            }
            mChildOfContent.requestLayout();
            usableHeightPrevious = usableHeightNow;
        }
    }

    private int computeUsableHeight() {
        Rect r = new Rect();
        mChildOfContent.getWindowVisibleDisplayFrame(r);
        return (r.bottom - r.top);
    }

}

Using this class in OnCreate-method of Activity:
AndroidBug5497Workaround.assistActivity(this);


text:
Q: How to select multiple photos? I can select one photo at a time, using a UIImagePickerController but I need to select more than one Photo Album using Xamarin?
    UIImagePickerController picker = new UIImagePickerController();
picker.AllowsEditing = false;
        picker.SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum;
        this.PresentModalViewController(picker, true);

A: ...there is ELCImagePickerController  which allows multiple images selection
example
// Create the image picker
ELCImagePickerController *imagePicker = [[ELCImagePickerController alloc] initImagePicker];
imagePicker.maximumImagesCount = 4; //Set the maximum number of images to select, defaults to 4
imagePicker.returnsOriginalImage = NO; //Only return the fullScreenImage, not the fullResolutionImage
imagePicker.imagePickerDelegate = self;

//Present modally
[self presentViewController:elcPicker animated:YES completion:nil];

// Release if not using ARC
[imagePicker release];

Code can be found  here!


text:
Q: Color a radius of patches Netlogo im trying to show a cultivation process. At setup im creating the farmers and giving them a random farm size (with the splotch) then, at go, im telling them that if they have enought money all patches near them that are the splotch turn into green, representing cultivation. But its just changing one pixel and not all round it. It most be someting small but i cant see it. Thanks in advance for the help
.
breed [cercas cerca]
breed [medios medio]
breed [lejos lejo]

patches-own[calidad
  cercanialago
  cultivado
]
turtles-own [ingresos
  gastos]
create-cercas 10 + random 10

 [ set size 1        ;; easier to see
    set color 135
setxy random xcor random ycor
move-to one-of patches with [not any? other turtles in-radius 3 and pcolor = 57]
    set heading random 45 + 45
    set ingresos 1000000 + random 6000000

 ]

ask turtles
  [ ask patches in-radius (1 + random 3)
    [ set pcolor 35 ] ]

to go

  ask cercas [
    ifelse ingresos > 2000000 [if any? patches in-radius 4 with [pcolor = 35] [if ticks mod 3 = 0 [set pcolor 62]  ]]
      []
  ] ```

A: Your cercas are a breed of turtles.
A useful feature of NetLogo is that any turtle can directly read and modify the variables of the patch it is on (i.e. without the need to invoke such patch).
So when you ask a turtle to set pcolor 62, it will automatically refer to pcolor of the patch it is on.
If we eliminate all of the conditions from your last block of commands, we have:
ask cercas [set pcolor 62]. This is what you are asking cercas to do: simply changing the pcolor of the patch they are on.
The fact that you use patches in-radius 4 in the condition for the first if statement does not influence the ask cercas [set pcolor 62] part. The condition is one thing, the command to be executed if the condition holds true is a separate thing.
Therefore you should make cercas ask patches in-radius 4 to change their pcolors.


text:
Q: Problems with k-NN example in C++(OpenCV) I have found the following example in the OpenCV documentation for using k-NN. Now my task is to convert the following code to Java and to do some changes on it because my data is not image.
I have some difficulties to understand what is happening in the example.
First have is a look at the code:
#include "ml.h"
#include "highgui.h"

int main( int argc, char** argv )
{
    const int K = 10;
    int i, j, k, accuracy;
    float response;
    int train_sample_count = 100;
    CvRNG rng_state = cvRNG(-1);
    CvMat* trainData = cvCreateMat( train_sample_count, 2, CV_32FC1 );
    CvMat* trainClasses = cvCreateMat( train_sample_count, 1, CV_32FC1 );
    IplImage* img = cvCreateImage( cvSize( 500, 500 ), 8, 3 );
    float _sample[2];
    CvMat sample = cvMat( 1, 2, CV_32FC1, _sample );
    cvZero( img );

    CvMat trainData1, trainData2, trainClasses1, trainClasses2;

    // form the training samples
    cvGetRows( trainData, &trainData1, 0, train_sample_count/2 );
    cvRandArr( &rng_state, &trainData1, CV_RAND_NORMAL, cvScalar(200,200), cvScalar(50,50) );

    cvGetRows( trainData, &trainData2, train_sample_count/2, train_sample_count );
    cvRandArr( &rng_state, &trainData2, CV_RAND_NORMAL, cvScalar(300,300), cvScalar(50,50) );

    cvGetRows( trainClasses, &trainClasses1, 0, train_sample_count/2 );
    cvSet( &trainClasses1, cvScalar(1) );

    cvGetRows( trainClasses, &trainClasses2, train_sample_count/2, train_sample_count );
    cvSet( &trainClasses2, cvScalar(2) );

    // learn classifier
    CvKNearest knn( trainData, trainClasses, 0, false, K );
    CvMat* nearests = cvCreateMat( 1, K, CV_32FC1);

    for( i = 0; i < img->height; i++ )
    {
        for( j = 0; j < img->width; j++ )
        {
            sample.data.fl[0] = (float)j;
            sample.data.fl[1] = (float)i;

            // estimate the response and get the neighbors' labels
            response = knn.find_nearest(&sample,K,0,0,nearests,0);

            // compute the number of neighbors representing the majority
            for( k = 0, accuracy = 0; k < K; k++ )
            {
                if( nearests->data.fl[k] == response)
                    accuracy++;
            }
            // highlight the pixel depending on the accuracy (or confidence)
            cvSet2D( img, i, j, response == 1 ?
                (accuracy > 5 ? CV_RGB(180,0,0) : CV_RGB(180,120,0)) :
                (accuracy > 5 ? CV_RGB(0,180,0) : CV_RGB(120,120,0)) );
        }
    }

    // display the original training samples
    for( i = 0; i < train_sample_count/2; i++ )
    {
        CvPoint pt;
        pt.x = cvRound(trainData1.data.fl[i*2]);
        pt.y = cvRound(trainData1.data.fl[i*2+1]);
        cvCircle( img, pt, 2, CV_RGB(255,0,0), CV_FILLED );
        pt.x = cvRound(trainData2.data.fl[i*2]);
        pt.y = cvRound(trainData2.data.fl[i*2+1]);
        cvCircle( img, pt, 2, CV_RGB(0,255,0), CV_FILLED );
    }

    cvNamedWindow( "classifier result", 1 );
    cvShowImage( "classifier result", img );
    cvWaitKey(0);

    cvReleaseMat( &trainClasses );
    cvReleaseMat( &trainData );
    return 0;
}

Link to the source
Now the questions.
1. What is cvRNG's type. Couldn't find it in Java version of OpenCV
2. CvMat sample = cvMat( 1, 2, CV_32FC1, _sample ); - needs a four field constructor which is not available in java.
3. Why do i need to form the training samples? And how do i do this?
Here is a mention that "Only CV_ROW_SAMPLE data layout is supported." What does it mean?
All kinds of additional working examples are welcome besides the answers.=)

A: The example starts by generating random training data. It builds an Nx2 matrix of training samples (N=100 2D points), along with corresponding class labels (Nx1 matrix). Thus the samples have a "row layout", each row being one sample.
The generated data is split in two; in the first half (N/2)x2 samples are generated from a normal-distribution with mean=200 and variance=50 (both X and Y coordinates), belonging to the first class class=1. Similarly the second half is generated from X~N(300,50) and tagged as having class=2.
So you could imagine the data looking like two blobs of points in 2D space diametrically opposed.
Next we create the K-nearest neighbor classifier (K=10 in the example), and we feed it our training set.
Then the code loops over the grid of points in the range 500x500 (i.e we go over the 2D points [0,0], [0,1], ..., [1,0], [1,1], ... [499,499]). For each point, we use the classifier to find the K-nearest neighbors (based on Euclidean distance) and their corresponding class labels, as well as predicting the label of the grid point (based on a majority vote from the nearest neighbors). It computes a "confidence" measure (by counting how many of the K=10 nearest neighbors have the same class as the predicted one).
We store the predictions in an image of the same size as the grid (500x500), color-coded to represent the class (1 or 2), with the color intensity representing the prediction confidence.
Finally, it plots the original data samples on top of the image, with points colored with their true class label, and shows the resulting image.
Now I didn't run that exact same code, but I imagine it would give something like the following:

I wrote this in matlab. Here is my code in case you're interested (I'm using mexopencv, a toolbox of MATLAB wrappers for OpenCV):
% random training set generated from two normal distributions
N = 100;  % number of training samples
trainData = [randn(N/2,2)*50+200; randn(N/2,2)*50+300];
trainClass = int32([ones(N/2,1)*1; ones(N/2,1)*2]);

% kNN classifier
K = 10;
knn = cv.KNearest();
knn.train(trainData, trainClass);

% build grid of 2D points, predict and find K nearest neigbords
sz = [500 500];
[X,Y] = ndgrid(1:sz(1), 1:sz(2));
[pred,IDX] = knn.findNearest([X(:) Y(:)], K);

% compute prediction confidence
conf = sum(bsxfun(@eq, IDX, pred),2) ./ K;

% evaluate classifier on training set
acc = nnz(knn.predict(trainData) == trainClass) * 100 / N;

% plot (color-coded by class, transparency indicates confidence)
clr1 = lines(2);
clr2 = brighten(clr1, -0.6);
imagesc(ind2rgb(reshape(pred,sz), clr1), 'AlphaData',reshape(conf,sz))
hold on
scatter(trainData(:,1), trainData(:,2), [], clr2(trainClass,:), 'filled')
hold off; xlabel X; ylabel Y;
title(sprintf('kNN Classification Accuracy = %.1f%%',acc))


text:
Q: About the special linear group $SL(n,\,\mathbb{Z})$ I found the following relation: $$SL_n(\mathbb{Z})=\langle e+e_{12},\, e_{12}+\dots+e_{n-1, n}+(-1)^{n-1}e_{n1}\rangle$$
where $e_{ij}$ is the matrix with its $(i,\, j)$th entry $1$, and all other entries $0$; and $e$ is the identity.
How one can prove that? Can you give me any clue about it?
References

*

*This is the problem 2.5 of Kargapolov's Fundamentals of Group Theory

*It is stated here on page $5$.

A: Notice how these generators modify a given matrix when you multiply that matrix from the right: The first adds row 2 to row 1 (and its inverse subtracts row 2 from row 1). And the other rotates the rows (while flipping one sign).
Let $S$ be the set of pairs $(i,j)$ such that it is possible to add row $j$ to row $i$ (and by existence of inverses one can also subtract row $j$ from row $i$). The first generator gives us immediately that $(1,2)\in S$. Conjugation with the second generator shows that $(i,j)\in S$ implies $(i+1,j+1)\in S$, so by now $(i,i+1)\in S$ for al $i$ (with $(n,n+1)$ understood to mean $(n,1)$). Assume that $d<n-1$ and we have $(i,j)\in S$ for all $i,j$ with $j=i+d$. Then also $(1,d+2)\in S$: add row $d+2$ to row $2$; then add row $2$ to row $1$; then subtract row $d+2$ from row $2$; then add row $2$ to row $1$. Combinig this we find that $(i,j)\in S$ for all $1\le i<j\le n$. Via conjugation with the rotation generator we obtain that $(i,j)\in S$ whenever $i\ne j$.
This allows you to swap any two rows (at the expense of introducing a sign: $(a,b)\to (a+b,b)\to (a+b,-a)\to (b,-a)$.
Now we have enough tools at hand to run an almost-Gauss algorithm: As long as at least  two rows  have nonzero first column entries, add/subtract one to/from the maximal (in absolute value) one such that $\sum |a_{i,1}|$ decreases. After finitely many steps, decreasing is no longer possible, which means that all but one row has $a_{i,1}=0$ now and the remaining row has a $\pm1$ entry. Swap the nonzeor entry to row $1$ and proceed with simplyfying column 2, then 3, etc. This takes you to an upper triangle matrix, from which you readily obtain a diagonal matrix with all diagonal entries $\in\{1,-1\}$. Since the determinant is positive, the number of $-1$ entries must be even. Swapping two such rows twice flips both signs, thus reducing the number of negative entries. Ultimately we obtain the identity matrix.
This was to be shown (wasn't it?)


text:
Q: Overriding equals() for use with Linked List I have two methods for looking up the index of a particular element in a linked list. I'm trying to use contais() and indexOf() to find the index. I am unsure how to override equals() to suit my need. One method finds the index based on surname and initials the other just the telephone number. Here are my methods:
@Override
public int lookupNumber(String surname, String initials) {
    Entry entry1 = new Entry(surname, initials);
    if (listDirectory.contains(entry1)) {
        int index = listDirectory.indexOf(entry1);
        return index;
    }
    else {
        return -1;
    }
}
@Override
public int lookupName(int extension) {
    Entry entry1 = new Entry(Integer.toString(extension));
    if (listDirectory.contains(entry1)) {
        int index = listDirectory.indexOf(entry1);
        return index;
    }
    else {
        return -1;
    }
}

I've tried to use the equals() and hashCode() that eclipse provides:
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Entry other = (Entry) obj;
    if (extension == null) {
        if (other.extension != null)
            return false;
    } else if (!extension.equals(other.extension))
        return false;
    if (initals == null) {
        if (other.initals != null)
            return false;
    } else if (!initals.equals(other.initals))
        return false;
    if (surname == null) {
        if (other.surname != null)
            return false;
    } else if (!surname.equals(other.surname))
        return false;
    return true;
}

But it won't work for both my methods, as it compares all the variables in the objects not just the ones I need it to compare. What is the correct logic for this?
Help much appreciated, thanks.
Update - here is my full Entry class -
public class Entry {

private String surname;
private String initals;
private String extension;

public Entry(String surname, String initals,String extension) {
    this.surname = surname;
    this.initals = initals;
    this.extension = extension;
}

  public Entry(String surname,String initals){
    this.surname = surname;
    this.initals = initals;
}

public Entry(String extension) {
    this.extension = extension;
}

public String getInitals(){

    return initals;

}

public String getSurname(){

    return surname;
}

public String getExtension(){

    return extension;
}

public void setExtension(String extension) {
     this.extension = extension;
}

public String toString(){
    return surname  + "\t " + initals + "\t" + extension;

}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((extension == null) ? 0 : extension.hashCode());
    result = prime * result + ((initals == null) ? 0 : initals.hashCode());
    result = prime * result + ((surname == null) ? 0 : surname.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Entry other = (Entry) obj;
    if (extension == null) {
        if (other.extension != null)
            return false;
    } else if (!extension.equals(other.extension))
        return false;
    if (initals == null) {
        if (other.initals != null)
            return false;
    } else if (!initals.equals(other.initals))
        return false;
    if (surname == null) {
        if (other.surname != null)
            return false;
    } else if (!surname.equals(other.surname))
        return false;
    return true;
}

}

Update - My problem is in my lookupNumber() method I want to find elements by (initials,surname) whereas in my lookupNumber() I want to find elements by (extension). How would I do this?

A: The Java Object class contains an equals() method of its own, and the Entry class should be the blueprint for objects of type Entry. Java inheritance is such that all classes inherit from the Object class, which is of little use to many of us. Really all you would need is
@Override
public boolean equals(Entry otherEntry)
{
    if(!(this.surname.equals(otherEntry.getSurname()))
        return false;
    else if(!(this.initials.equals(otherEntry.getInitials()))
        return false;
    else if(!(this.extension.equals(otherEntry.getExtension()))
        return false;
    else
        return true;
}

The above code just checks for inequality amongst the instance variables, returning false upon any one not equal.


text:
Q: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.CAR(ID) : While calling the POST service CarController.java
package com.mytaxi.controller;

import java.util.List;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.mytaxi.controller.mapper.CarMapper;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainvalue.Type;
import com.mytaxi.exception.ConstraintsViolationException;
import com.mytaxi.exception.EntityNotFoundException;
import com.mytaxi.service.car.CarService;

@RestController
@RequestMapping("v1/cars")
public class CarController
{

private final CarService carService;

@Autowired
public CarController(final CarService carService)
{
    this.carService = carService;
}

@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CarDTO createCar(@Valid @RequestBody CarDTO carDTO) throws ConstraintsViolationException
{
    CarDO carDO = CarMapper.makeCarDO(carDTO);
    carDTO = CarMapper.makeCarDTO(carDO);
    carService.create(carDO);
    return carDTO;
}

}
CarDO.java
package com.mytaxi.domainobject;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Max;
import com.mytaxi.domainvalue.Type;

@Entity
@Table(
    name = "car",
    uniqueConstraints = @UniqueConstraint(name = "uc_licensePlate", columnNames = {"licensePlate"})
)
public class CarDO
{
@Id
@Column(nullable = false)
@GeneratedValue
private Long id;

@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Type manufacturer;

@Column(nullable = false)
private String licensePlate;

@Column(nullable = false)
private Integer seatCount;

@Column(nullable = false)
private String engineType;

@Column(nullable = false)
@org.hibernate.annotations.Type(type="yes_no")
private Boolean convertible;

@Column
@Max(5)
private Integer rating;

@Column(nullable = false)
@org.hibernate.annotations.Type(type="yes_no")
private Boolean isFunctioning = true;

@Column(nullable = false)
@org.hibernate.annotations.Type(type="yes_no")
private Boolean isBooked = false;

public Boolean getIsFunctioning()
{
    return isFunctioning;
}

public void setIsFunctioning(Boolean isFunctioning)
{
    this.isFunctioning = isFunctioning;
}

public CarDO(Type manufacturer, String licensePlate, Integer seatCount,
    String engineType, Boolean convertible)
{
    this.manufacturer = manufacturer;
    this.licensePlate = licensePlate;
    this.seatCount = seatCount;
    this.engineType = engineType;
    this.convertible = convertible;
}

public Long getId()
{
    return id;
}

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

public Type getManufacturer()
{
    return manufacturer;
}

public void setManufacturer(Type manufacturer)
{
    this.manufacturer = manufacturer;
}

public String getLicensePlate()
{
    return licensePlate;
}

public void setLicensePlate(String licensePlate)
{
    this.licensePlate = licensePlate;
}

public Integer getSeatCount()
{
    return seatCount;
}

public void setSeatCount(Integer seatCount)
{
    this.seatCount = seatCount;
}

public String getEngineType()
{
    return engineType;
}

public void setEngineType(String engineType)
{
    this.engineType = engineType;
}

public Boolean getConvertible()
{
    return convertible;
}

public void setConvertible(Boolean convertible)
{
    this.convertible = convertible;
}

public Integer getRating()
{
    return rating;
}

public void setRating(Integer rating)
{
    this.rating = rating;
}

}
CarDTO.java
package com.mytaxi.datatransferobject;

import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.mytaxi.domainvalue.Type;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class CarDTO

{
@JsonIgnore
private Long id;

@NotNull(message = "license plate can not be null!")
private String licensePlate;

@NotNull(message = "cartype can not be null!")
private Type carType;

@NotNull(message = "seatCount can not be null!")
private Integer seatCount;

@NotNull(message = "engineType can not be null!")
private String engineType;

private Boolean convertible;

private CarDTO()
{
}

public CarDTO(Long id, String licensePlate, Type carType, Integer seatCount, String engineType, Boolean convertible)
{
    this.id = id;
    this.licensePlate = licensePlate;
    this.carType = carType;
    this.seatCount = seatCount;
    this.engineType = engineType;
    this.convertible = convertible;
}

public static CarDTOBuilder newBuilder()
{
    return new CarDTOBuilder();
}

@JsonProperty
public Long getId()
{
    return id;
}

public String getLicensePlate()
{
    return licensePlate;
}

public Type getCarType()
{
    return carType;
}

public Integer getSeatCount()
{
    return seatCount;
}

public String getEngineType()
{
    return engineType;
}

public Boolean getConvertible()
{
    return convertible;
}

public static class CarDTOBuilder
{
    private Long id;
    private String licensePlate;
    private Type carType;
    private Integer seatCount;
    private String engineType;
    private Boolean convertible;

    public CarDTOBuilder setId(Long id)
    {
        this.id = id;
        return this;
    }

    public CarDTOBuilder licensePlate(String licensePlate)
    {
        this.licensePlate = licensePlate;
        return this;
    }

    public CarDTOBuilder setLicensePlate(String licensePlate)
    {
        this.licensePlate = licensePlate;
        return this;
    }

    public CarDTOBuilder setCarType(Type carType)
    {
        this.carType = carType;
        return this;
    }

    public CarDTOBuilder setSeatCount(Integer seatCount)
    {
        this.seatCount = seatCount;
        return this;
    }

    public CarDTOBuilder setEngineType(String engineType)
    {
        this.engineType = engineType;
        return this;
    }

    public CarDTOBuilder setConvertible(Boolean convertible)
    {
        this.convertible = convertible;
        return this;
    }

    public CarDTO createCarDTO()
    {
        return new CarDTO(id, licensePlate, carType, seatCount, engineType, convertible);

    }
}

}
CarMapper.java
package com.mytaxi.controller.mapper;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainobject.CarDO;

public class CarMapper
{
    public static CarDO makeCarDO(CarDTO carDTO)
    {
        return new CarDO(carDTO.getCarType(), carDTO.getLicensePlate(),
            carDTO.getSeatCount(), carDTO.getEngineType(), carDTO.getConvertible());
    }

    public static CarDTO makeCarDTO(CarDO carDO)
    {
        CarDTO.CarDTOBuilder carDTOBuilder = CarDTO.newBuilder()
            .setId(carDO.getId())
            .setCarType(carDO.getManufacturer())
            .licensePlate(carDO.getLicensePlate())
            .setSeatCount(carDO.getSeatCount())
            .setEngineType(carDO.getEngineType())
            .setConvertible(carDO.getConvertible());

        return carDTOBuilder.createCarDTO();
    }

    public static List<CarDTO> makeCarDTOList(Collection<CarDO> cars)
    {
        return cars.stream()
            .map(CarMapper::makeCarDTO)
            .collect(Collectors.toList());
    }
}

CarService.java
    package com.mytaxi.service.car;

    import java.util.List;

    import com.mytaxi.domainobject.CarDO;
    import com.mytaxi.domainvalue.Type;
    import com.mytaxi.exception.ConstraintsViolationException;
    import com.mytaxi.exception.EntityNotFoundException;

    public interface CarService
    {

        CarDO create(CarDO carDO) throws ConstraintsViolationException;

    }

DefaultCarService.java
 @Override
    public CarDO create(CarDO carDO) throws ConstraintsViolationException
    {
        CarDO car;
        try
        {
            car = carRepository.save(carDO);
        }
        catch (DataIntegrityViolationException e)
        {
            LOG.warn("ConstraintsViolationException while creating a driver: {}", carDO, e.getCause());
            throw new ConstraintsViolationException(e.getMessage());
        }
        return car;
    }

CarRepository.java
package com.mytaxi.dataaccessobject;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainvalue.Type;

public interface CarRepository extends CrudRepository<CarDO, Long>
{

    List<CarDO> findByIsFunctioning(Boolean isFunctioning);

    CarDO findByLicensePlate(String licensePlate);

    List<CarDO> findByManufacturer(Type type);
}

When I hit the RESTAPI post service, I get the below exception.
Unique index or primary key violation:
aused by: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.CAR(ID)"; SQL statement:
insert into car (convertible, engine_type, is_booked, is_functioning, license_plate, manufacturer, rating, seat_count, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?) [23505-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.message.DbException.get(DbException.java:179) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.message.DbException.get(DbException.java:155) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.mvstore.db.MVPrimaryIndex.add(MVPrimaryIndex.java:123) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.mvstore.db.MVTable.addRow(MVTable.java:732) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.dml.Insert.insertRows(Insert.java:182) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.dml.Insert.update(Insert.java:134) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.CommandContainer.update(CommandContainer.java:102) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.command.Command.executeUpdate(Command.java:261) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:199) ~[h2-1.4.197.jar:1.4.197]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:153) ~[h2-1.4.197.jar:1.4.197]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-2.7.9.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-2.7.9.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175) ~[hibernate-core-5.2.17.Final.jar:5.2.17.Final]
    ... 93 common frames omitted"PRIMARY KEY ON PUBLIC.CAR(ID) :
Any idea what is wrong in the code?

A: I was encountering the same problem for an @Entity class. My data.sql ids were conflicting with the auto-generated ids from H2.
My solution was to change:
@GeneratedValue(strategy = GenerationType.AUTO)

to
@GeneratedValue(strategy = GenerationType.IDENTITY)

This way I could keep my data.sql file.
The javadoc here indicates that GenerationType.IDENTITY "Indicates that the persistence provider must assign primary keys for the entity using a database identity column."

A: It was generating the sequence from 1, since there were already 3 values in the database which was inserted manually while initializing the application, modifying the auto generated sequences solved the issue.

A: @Eenvincible, if you created a data.sql to populate the data, you need to delete those.

A: The problem is probably given by the fact that you already are initializing data, either through a data.sql file, or CommandLineRunner.
Therefore, if you have
@GeneratedValue(strategy = GenerationType.AUTO)

Spring Data JPA automatically tries to set ID from 1 and then autoincrements of 1 for every new entry. If you already have some entries which start with ID 1 that is the problem (there is a conflict of ids).
You should either remove the data inserted if you want to keep things simple, or you should use other methods for generating the id, for example uuid see here https://thorben-janssen.com/generate-uuids-primary-keys-hibernate/


text:
Q: ToDouble always throws an exception when i want to convert a negative number in string format to Double when i run the following code it always throws an exception
string a = "-12.12";
double b = Convert.ToDouble(a);

An exception of type 'System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code

what is the problem with the code ?

A: I strongly suspect you're running in a locale which uses , as the decimal separator... or which uses a different symbol for negation. You can pass in a CultureInfo to specify how to parse - I usually use double.Parse instead of Convert.ToDouble:
double x = double.Parse(a, CultureInfo.InvariantCulture);

That will be absolutely fine. If it still doesn't work, that suggests your actual string isn't quite "-12.12". For example, if the "-" is actually an en-dash or something like that, it won't parse properly.


text:
Q: Can I have a Django form without Model Can I have a Form in my template which is not backed by a model. I do not need to store the data just need that data to generate a POST request of my own in the view.
Template - The form with text fields.
View - get data from form, and generate another request.
Flow --> Form submit takes to a url which calls the view "
def form_handle(request):
    if request.method=='POST'
    form = request.POST

    #blah blah encode parameters for a url blah blah
    #and make another post request

but this puts only the csrf token into the form variable.
Is there some way I can access those text fields of the template in my form_handle view?
I know how to do it with a model but couldn't figure this out!

A: Yes. This is very much possible. You can read up on Form objects. It would be the same way you would treat a ModelForm, except that you are not bound by the model, and you have to explicitly declare all the form attributes.
def form_handle(request):
    form = MyForm()
    if request.method=='POST':
        form = MyForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            #now in the object cd, you have the form as a dictionary.
            a = cd.get('a')

    #blah blah encode parameters for a url blah blah
    #and make another post request
    #edit : added ": "  after    if request.method=='POST'

and
class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm
    a = forms.CharField(max_length=20)
    #All my attributes here

In the template:
<form action="{% url form_handle %}" method="POST">{% csrf_token %}
    {{form.as_p}}
    <button type="submit">Submit</button>
</form>


text:
Q: Does there exist a surface over a finite field which contains three skew lines? Does there exist an irreducible surface, other than Hermitian surface, in $\mathbb{P}^3 (\mathbb{F}_q)$ containing three skew lines?
I know that this is true for Hermitian surface. In fact, at every point of a generator of a Hermitian surface, it admits a tangent plane containing the generator and at every tangent plane, it has $\sqrt{q}+1$ generators. But can this happen for an irreducible surface of degree at least three which is not a Hermitian surface?
Edit I think it may be useful to define the Hermitian surface. It is given by equation $$\sum_{i=0}^3 x_i^{\sqrt{q} + 1} = 0.$$
Thanks in advance!

A: Let $K$ be any field of characteristic not 3. (I will leave that case for someone more energetic.)
Let $S$ be the Clebsch diagonal surface defined in $\mathbf P^4_K$ by the equations
$$ \sum_{i=0}^4 x_i=0 \\
\sum_{i=0}^4 x_i^3 =0.$$
(Since the first equation defines a hyperplane in $\mathbf P^4$, this is really a cubic surface in $\mathbf P^3$.)
Then $S$ contains the three skew lines
$$ L_1 = \{ [s,t,-s,-t,0] \mid s,  \ t \in K \}\\
L_2 = \{ [s,t,0,-s,-t] \mid s,  \ t \in K \} \\
L_3 = \{ [s,-s,t,0,-t] \mid s,  \ t \in K \}.$$

A: I also don't know what a Hermitian surface is, but it seems to me that there are lots of these surfaces for any given set of lines.
Let $L$ be the union of $m$ pairwise disjoint union of copies of $\mathbb P^r$ in $\mathbb P^n$ over a field $k$ and let $\mathscr I\subseteq \mathscr O_{\mathbb P^n}$ denote its ideal sheaf. A degree $d$ hypersurface in $\mathbb P^n$ containing $L$ corresponds to a global section of $\mathscr I(d)\subseteq \mathscr O_{\mathbb P^n}(d)$. So, (it seems) all you need is that $d$ is large enough so this would not be zero. This will follow as soon as
$$
\dim_k H^0(\mathbb P^n, \mathscr O_{\mathbb P^n}(d)) >
\dim_k \oplus^mH^0(\mathbb P^r, \mathscr O_{\mathbb P^r}(d)),
$$
i.e., when
$$
{n+d \choose d} > m\cdot{r+d \choose d}.
$$
In particular, if $L$ is a disjoint union of $3$ lines in $\mathbb P^3$, then one needs that
$$
{d+3\choose d} > 3 (d+1).
$$
It seems to me that this happens as soon as $d\geq 2$. If most surfaces are not Hermitian, then this should give you plenty of examples as $d$ grows.
Note that this computation does not use that these are lines, only that they are isomorphic to $\mathbb P^1$ (or $\mathbb P^r$ in the general case), so you could include other rational curves. Furthermore, one can easily develop a formula for arbitrary curves where the actual bound on the degree would depend on the genus of the curves involved, but in any case I would expect that for any fixed genus one would get surfaces containing a fixed set of curves if one allows the degree to be sufficiently large.

EDIT: As M.D. correctly points out this procedure might produce reducible hypersurfaces. However, using the same formula one can count those and conclude that, at least for large $d$, there is still enough dimension left so the general member is indeed irreducible.
For simplicity let's do this for $n=3$, but the method is the same in higher dimensions: A reducible degree $d$ surface is a union of smaller degree surfaces. We can just think of a union of two who themselves may be reducible. So how many of those are there?
Let $L_{i,d-i}\subseteq H^0(\mathbb P^3, \mathscr O_{\mathbb P^3}(4))$ denote the images of the product maps
$$
H^0(\mathbb P^3, \mathscr O_{\mathbb P^3}(i))\times H^0(\mathbb P^3, \mathscr O_{\mathbb P^3}(6-i)) \longrightarrow H^0(\mathbb P^3, \mathscr O_{\mathbb P^3}(6))
$$
for $i=1,\dots,\left[d/2\right]$.
Since (as above) $\dim_k H^0(\mathbb P^3, \mathscr O_{\mathbb P^3}(j))={j+3\choose 3}$, we get that
$\dim_kL_{i,d-i}\leq {i+3\choose 3} + {d-i+3\choose 3}$
At the same time, according to the above argument, the subspace of $H^0(\mathbb P^3, \mathscr O_{\mathbb P^3}(d))$ containing three skew lines is at least
$$
{d+3\choose 3} - 3 (d+1),
$$
so as soon as
$$
{d+3\choose 3} - 3 (d+1) - \max_{0<i<d}\left({i+3\choose 3} + {d-i+3\choose 3}\right) >0, \tag{$\star$}
$$
the general such surface will be irreducible. It is easy to see that the left hand side of $(\star)$ is a quadratic polynomial with positive leading coefficient, so this will be positive for $d\gg 0$. In fact, I think it is positive for $d\geq 6$.
Note that this was a very rough calculation as we counted all reducible surfaces, not just the ones containing the three lines, so one can probably do better for smaller degrees, but I leave that to the reader.


text:
Q: Extracting data from an API call Trying to extract data from an object that came back from an API call using request.
When I try info.featrues[0] I get a TypeError
When i use info.features i get undefined
But res.body works perfectly fine.
Can someone point out what I'm doing wrong

A: I figured it out. I needed to be parsed.  Add json: true to the request module. request({url: url, json:true}, (err, res)=>{};


text:
Q: ANT build: [signjar] enter passphrase for keystore: I have created a project in eclipse and while trying to build the project from command prompt the following is asked:
[signjar] jarsigner error: java.lang.RuntimeException: keystore load: C:\Documents
and Settings\Gopakumar\.keystore (The system cannot find the file specified)

[signjar] Enter Passphrase for keystore:
BUILD FAILED
D:\Score\build.xml:556: The following error occurred while executing this line:
D:\Score\build.xml:147: jarsigner returned: 1

I have created keystore file using keytool in the project directory, exactly where build.xml resides.
But it doesn't prompt for the passphrase?

A: Try it:
Make a StoreFile with "keytool" command:
keytool -genkey -keystore YourKeyStoreFileAtPojectDirectory -storepass YourPassStoreString -keyalg rsa -alias YourKeyString -keypass YourPassKeyString -validity 99999  -storepass YourPassStoreString -dname "cn=XXYYZZ, o=XXYYZZ, l=YourCity, S=YourState, c=YourCountry"

and put the signjar block below in your build.xml:
<signjar destDir="signed"
  alias="YourKeyString"
  keypass="YourPassKeyString"
  keystore="YourKeyStoreFileAtPojectDirectory"
  storepass="YourPassStoreString"
  digestalg="SHA1"
  sigalg="MD5withRSA"
>


text:
Q: Smooth way to set all other togglebuttons to unchecked when one is checked I specifically didn't want to use a radiogroup. I know, I know ... a radiogroup is perfect when you need exclusivity like this.
But..given that I'm working with togglebuttons, how can i disable (setChecked(false)) all (3) other toggle buttons when one of them is checked?

A: Here is my code for the group of toggle buttons. You need to put your
buttons in the layout where you want them and then use ToggleButtonsGroup object to put them together in a single group.
private class ToggleButtonsGroup implements OnCheckedChangeListener {

    private ArrayList<ToggleButton> mButtons;

    public ToggleButtonsGroup() {

        mButtons = new ArrayList<ToggleButton>();

    }

    public void addButton(ToggleButton btn) {

        btn.setOnCheckedChangeListener(this);

        mButtons.add(btn);
    }

    public ToggleButton getSelectedButton() {

        for(ToggleButton b : mButtons) {
            if(b.isChecked())
                return b;
        }

        return null;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView,
            boolean isChecked) {

        if(isChecked) {
            uncheckOtherButtons(buttonView.getId());

            mDataChanged = true;

        } else if (!anyButtonChecked()){
            buttonView.setChecked(true);
        }

    }

    private boolean anyButtonChecked() {

        for(ToggleButton b : mButtons) {
            if(b.isChecked())
                return true;
        }

        return false;
    }

    private void uncheckOtherButtons(int current_button_id) {

        for(ToggleButton b : mButtons) {
            if(b.getId() != current_button_id)
                b.setChecked(false);
        }
    }

}

A: I think you'll need to implement your own radiogroup logic for that. It will need to register itself as the OnCheckedChangeListener for each button it manages.
I wish the API wasn't designed with RadioGroup as a LinearLayout. It would have been much better to separate the radio group management from layout.

A: I know this has been answered with very good examples, but the way I set mine up is just a tad different so I thought I'd share. It's on a preference list, no ToggleButtonsGroup involved.
@Override
    public boolean onPreferenceClick(Preference preference) {
        String key = preference.getKey();
        if (key.equals("trailPref") || key.equals("obstaclesPref") || key.equals("insanePref") || key.equals("backgroundBlackPref"))
        {
            if (key.equals("insanePref"))
            {
                endurancebox.setChecked(false);
                prefsEditor.putBoolean("obstaclesPref", false);
                prefsEditor.commit();
            }

            if (key.equals("obstaclesPref"))
            {
                insanebox.setChecked(false);
                prefsEditor.putBoolean("insanePref", false);
                prefsEditor.commit();
            }

            boolean b = ((CheckBoxPreference) preference).isChecked();
            prefsEditor.putBoolean(key, b);
            prefsEditor.commit();
        }

        Log.i(DEBUG_TAG, "Boolean value changed. " + key );
        returnPrefs(c);
        return false;
    }

Also, I'm an Android noob and not too experienced in java either, so it may not be uber efficient, but hey, it works! Could be formatted easily to fit your needs I believe. If the key equals insanePref, I want to turn off obstaclesPref and vice versa. (different game modes, only one can be active at the time.) The other two booleans are unrelated. Also, it puts the preferences into my SharedPreference file, instantiated earlier, along with everything else.
Cheers!


text:
Q: Will a short time period for SyncAdapter's periodic sync, necessarily drain the battery? In this case, "short time period" can be 30 seconds up 5 minutes.
My onPerformSync method does almost nothing most of the times, but I'm concerned that the short sync period might prevent the phone from sleeping, and have a drastic effect on battery life.
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {

    if (!InternetConnectionDetector.isConnectedToInternet())
        return;

    if (/*We have received a push from server indicating update is available*/)
        syncWithServer();
    else
        return;

}

A: Sync adapter will run at specific interval depends on Android system optimization even if you define frequency in your code. From Android 6.0 and above app prevent run sync adapter when device is idle/standby or sleeping/doze mode.
Doze mode optimized to improve battery performance and same for standby.
While android system in doze or standby mode it's prevent to run sync adapyer, sync job, sync scheduler, alarm.
Its gives chance to run all these background that specific interval that we call maintainance window.  This maintenance window perform all pending sync. Initially this window open frequently and later interval get longer in each maintainance window.
If you still want to perform background task irrespective of doze or standby mode you can use priority firebase message to run sync or seek permission from user to perform better intensive task. For mode details refer android developer docs about doze mode and stand by mode