text:
Q: наибольшая средняя стоимость Есть две таблицы, имеют следующий вид
CREATE TABLE company (
    companyId INTEGER PRIMARY KEY,
    companyName VARCHAR (50),
    companyCountry VARCHAR (50)
);

CREATE TABLE phone
(
    phoneId serial PRIMARY KEY,
    phoneModel VARCHAR (50),
    companyId INTEGER REFERENCES company(companyId),
    price NUMERIC
);

составить запросы поиска производителя телефона с наибольшей средней стоимостью телефона этого производителя;
Вот что получилось на данный момент, дальше пока не догоню, как писать(
SELECT companyname, price, phonemodel
  FROM phone
  LEFT JOIN company ON
    company.companyid = phone.companyid

A: Ну почитать про group  by можно, например, тут - https://metanit.com/sql/mysql/4.6.php.

А вот запрос:
SELECT companyName, avg(price)
FROM phone
LEFT JOIN company ON phone.companyId = company.companyId
GROUP BY company.companyId;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serving a page of a pdf on a webpage I've made an application that returns a pdf to a browser. It loads the pdf on a certain page that has to be visable to the user. This is working fine but loading the pdf takes a while.
To do this I give the user an object tag with data a url to google drive. When the user clicks a button the pdf starts downloading and gets displayed.
Since most of the time only 1 page is important to the user I would like to have an option to serve the pdf as a smaller file.
Are there any libraries to load only 1 or x pages of a pdf? The main reason would be to reduce bandwidth usage.
Maybe a google script to split the pdf and serve that as a smaller file,...
I know google has a standard docsviewer but it has many limitations. (no rotation,...) I prefer to user the adobe plugin.
Update:
I've found a project wich covers conversion in appengine.
https://github.com/lookfirst/convert
I'll check if it supports big pdf's and if it can convert pdfs from drive to images for each page. And if this is possible at real time.
I hope converting + downloading image takes less time then downloading the entire file.

A: One solution for a smaller output using the Drive SDK is to convert the PDF to a Google Doc, then export as HTML.
Otherwise see the comment from @mkl.


text:
Q: Always On VPN Windows 10 Multiple Certificates I have a working setup with Server 2012 R2 and Windows 10.
The only issue I have is the auto connect. It tries to auto connect but as there are 2 user certificates it fails saying action is required. Selecting the correct certificate then completes the connection without issue.
Is there a way to code into the VPN Profile, only use a certificate template, or issued by this server or something along those lines?
The other certificate in question is being issued from our Lync server..... Not sure why it is being issued or if its needed. I am also looking into if I can stop it being issued. I've tried deleting it (Lync still works) however it gets regenerated the next time I sign into Lync.

A: You'll do that enabling certificate filtering in your EAP configuration. To do this, right-click the properties of your VPN connection and choose Properties. Click on the Security tab and then click the Properties button below the EAP drop-down list. Click Configure next to Select Authentication Method and then click the Advance button. Here you can choose the specific CA you want the certificate to be issued by, and optionally choose a specific EKU the certificate must contain. Once that works, export the EAP configuration and update your ProfileXML with the new settings. :)


text:
Q: JsonSerializer c# return null struct when try to deserialize an object Goodmorning,
I have two struct:
    struct SingoloParametroFiltro
    {
        public Variabile variabile { get; set; }
        public string operatore { get; set; }
        public bool non { get; set; }
        public object valore { get; set; }

        public static SingoloParametroFiltro CreaSingoloParametroFiltro(int idVariabile, string Operatore, bool Non, object Valore)
        {
            SingoloParametroFiltro s = new SingoloParametroFiltro();
            s.variabile = Variabile.CreaVariabileDaId(idVariabile);
            s.operatore = Operatore;
            s.non = Non;
            s.valore = Valore;
            return s;
        }
    }

    struct Filtro
    {
        public List<SingoloParametroFiltro> parametroFiltro { get; set; }
        public string nomeFiltro { get; set; }

        public static Filtro CreaFiltro(List<SingoloParametroFiltro> _parFiltro, string _nome)
        {
            Filtro f = new Filtro();
            f.parametroFiltro = _parFiltro;
            f.nomeFiltro = _nome;
            return f;
        }
    }

And the struct of the Variabile:
    struct Variabile
    {
        public int id { get; private set; }
        public string NomeColonna { get;  private set; }
        public string TipoDato { get; private set; }
        public object Val { get; private set; }
        public object Default { get; private set; }
        public int ColonnaAccoppiamento { get; private set; }
        public bool Visibile { get; private set; }
        public bool ChiaveAlbero { get; private set; }
        public int Importanza { get; private set; }
        public bool ChiaveImport { get; private set; }
    }

Now.... I serialize List<SingoloParametroFiltro> and save it on DB. The json string seems ok and all work fine.
When i try to Deserialize json string from DB to List<SingoloParametroFiltro> all works great except of Variabile inside SingoloParametroFiltro.
The struct Variabile inside SingoloParametroFiltro have all variable set to null or 0.....
Code to Serialize:
JavaScriptSerializer jsSer = new JavaScriptSerializer();
string json = jsSer.Serialize(parametri);

Where parametri is a List<SingoloParametroFiltro>
Code to Deserialize:
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Deserialize<List<SingoloParametroFiltro>>(json);

Anyone can help me?

A: It's because all the setters of the struct Variabile are private.
...
public int id { get; private set; }
public string NomeColonna { get;  private set; }
public string TipoDato { get; private set; }
...

So the deserializer couldn't assign the correct values to the fields.
You could try by making it public :
...
public int id { get; set; }
...


text:
Q: Is it safe to backup my HDD? Currently I see 2 parameters reaching design limits, namely Reallocated Sector Count as well as Spin Retry Count from the SMART data. The computer boots once out of 10 attempts and I have seen BSODs and GRUB rescue messages too.
My problem is that I see both way over the threshold! What can I do about this? Is it safe to back up my HDD or will that further aggravate the problem by increasing the number of read operations?
SMART screenshot:

link for image

A: The threshold works the other way around: It's gone bad when Current < Threshold. That's why it's only a warning in your case.
Although that many spin retries clearly aren't normal, so do backup your data. :)

A: The question whether it's safe to backup your data is the wrong one. If your disk is going bad (or you think it is), backing up your data should be your first concern. Don't try repairs yet, back up first. Instead of repeating myself, I point to my answer here.


text:
Q: How to create Dynamically Jquery Datatatable with Headers in MVC I'm trying to create a Monthly report in MVC. For that I need to create the days of user selected month as it's heading. But When I try to set it by sing the jquery It show some errors.

Cannot use 'in' operator to search for '61764' in [{"Name":"Abel John","Father Name":John,"Sex":"Male","Date of Birth ....

I'm new to Jquery and MVC . here Is my code . Please help me to solve the issue.
 $.ajax({
            type: "POST",
            url: '@Url.Action("GetLeaveDeatais", "LeaveDetails")?year=' + date,
            contentType: "application/json; charset=utf-8",
            year: { year: '2013' },
            contentType: 'application/html; charset=utf-8',

            success: function () {

                }
        })
            .success(function (result) {
                $('#divDetails').html(function () {

                    var cols = [];

                   var dataSet = result;

                    var my_columns = [];

                    $.each(JSON.parse(JSON.stringify(dataSet)), function (key, value) {
                        var my_item = {};
                        my_item.data = key;
                        my_item.title = key;

                        my_columns.push(my_item);
                    });
                    var table = $('#example').DataTable({
                        columns: my_columns

                    });

                }

                );
        });

My Controler
 public  string GetLeaveDeatais(string year)
    {

        List<DataRow> list = new List<DataRow>();
        DataTable dt = new DataTable();
        MusterRoll mstRoll= new MusterRoll();

        dt = clsBD.GetEmpLeaveDeatils("2019-05-1");

            if (dt != null)
            list=dt.AsEnumerable().ToList();
        JavaScriptSerializer js = new JavaScriptSerializer();

        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;
        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }

        return serializer.Serialize(rows);

    }

Please find me to get a solution soon.
Thanks in Advance


text:
Q: fetch - pass original authentication header Really simple question but I couldn't find anything anywhere about this.
I'm trying to make a fetch request with the original authentication header.
My app is using http basic authentication for all routes which works fine.
with my clientside js I'm trying to create a request to /api/thing which requires the same http basic credentials as the original page request.
How do I pass those original credentials aloing withthe request?
fetch("http://localhost:33507/api/thing")
.then(function(response) {
    return response.text()
})
.then(function(responseText) {
    console.log(responseText);
});

edit: I know I can pass headers like so:
fetch("http://localhost:33507/ssh", {headers: {"Authorization": "basic u:p"}})

But that's not the issue, the issue is getting the username and password. I can't really ask the user to fill them in on every request. Surely there is a way to pass them along without looking at them?
edit2: my flow is like this:
1 user requests page - server asks for http basic credentials.
2 user sends credentials - server replies with page.
3 user presses button to send fetch request - server replies with resource.
The problem here is that I can't find a way to pass those credentials when doing the fetch request

A: I suppose that you should be able to do it without adding your credentials explicitly in the JavaScript code. Adding credentials: 'include' to you fetch request options object should be enough if your client is already authenticated in the same domain:
let url = "some url";
let options = { "credentials": "include" };
fetch(url, options).then( ... ).catch( ... );

A: I believe what you are looking for is a way to not have to set the headers every time.
(I'm going to assume you are programming for the browser)
One options is to is to store the username and password in local storage and just wrap the fetch in your own method.
/**
 * Called after user enters credentials, saves to credentials
 * to localStorage for use in subsequent calls.
 * @param {string} userName
 * @param {string} password
 */
saveCredentials(userName, password) {
  localStorage.setItem('credentials', 'basic '+userName+':'+password);
}

/**
 * Site wide custom fetch wrapper. Appends default headers, calls the
 * standard fetch method, and returns a fetch promise.
 * @param {string} url
 * @param {object} options
 * @returns {Promise}
 */
myFetch(url, options) {
  var options = options || {};
  var options.headers = options.headers || {};
  options.headers['Authorization'] = localStorage.getItem('credentials');
  return fetch(url, options);
}

Another options is to use something like this:
https://github.com/moll/js-fetch-defaults
This allows you to set default headers for fetch once, then all subsequent fetches will use the same ones.


text:
Q: Puzzled with Dependency Injection in PHP (chains of Classes) I'm moving from Globals and Singletons (=bad?) to Dependency Injections (=good?) in PHP and I'm very new to it.
I have read many related topics on Stack Overflow already but I still can't understand the main principles of DI.
Please tell me if I'm doing it right (it's just shortened pseudo-code):
// first connect to DB
$sql = new Sql();

// create logger (I'm writing logs to Database so I need to pass $sql to it)
$log = new Log($sql);

// restore logged in user, get info about user, unread messages...
// class "User" needs  access to Database and Logs:
$user = new User($sql, $log);

// now we need to collect all the data of current section of my Website
// I'm using Model and Controller:
$model = new FrontPageModel($sql, $user, $log);

$pageController = new FrontPageController($model);

Though it may look OK at this step but what if I need to get access to more classes like Config, Session, etc.?
Should my code transform to this?
$model = new FrontPageModel($sql, $user, $log, $config, $session);

Isn't it too much already?
I know someone could advice to use a kind of big "Application" class and put Config, Session, Log, Db objects inside of this class but I feel that it isn't very good idea.
Next question - what if I need to get logged User's ID inside of my FrontPageController? I did not pass an instance of "User" to FrontPageController, but it was passed before (in chain) to FronPageModel.
class FrontPageController{
  private $model;
  function __construct($model){
    $this->model = $model;
  }

  function getData(){
    echo $this->model->user->id; // is it right way?
  }
}

That "$this->model->user->id" seems like overkill to me.

A: It might not be the prettiest, but you're certainly not doing it "wrong".  You're demonstrating classing constructor injection, but you could perhaps refactor to keep some of the disparate objects separated a bit more.
My suggestion would be to look at established PHP DI containers.  See how they work, use them in a few apps, and (1) you'll have much more testable apps and (2) you'll be much more comfortable with DI in general.
Take a look at one or more of the following:

*

*Pimple

*Aura DI

*Symfony DI

A: Like all the joyful stuff, it' depends.
I would put everything inside a factory class, or several factory classes for different sub systems.
class AppFactory {
    protected $_sql;

    public function getSql()
    {
        if (!empty($this->_sql))
            return $this->_sql;

        $this->_sql = new Sql();
    }
}

Then initial it on application run. Configure if needed.
$factory = new AppFactory();
// set config
// $factory->internallyGenerateSingletons = true;

And now every other class can use it. And of course you have injection to put factory inside.
$model = new FrontPageModel($factory);
// or
// $model->useFactory($factory);

Regarding other question. Is this the right way.
...
$this->model->user->id
...

I would say it's ok but batter is to use methods like this:
...
$this->model->getUser()->id
..

So you can mock user class when doing unit testing. And it makes application more flexible.

A: It seems like you have got the idea of dependency injection right. You even question Symfonies idea of DI (in a comment), which shows more mature understanding.
A next step to solving the questions you have is to take a step away from leaking technical information from one layer into another. Eg your controllers don't care that they talk to a model. Your model doesn't care it talks to an sql or nosql database.
Another is about responsabilities. Does the user really need to do all of that? Is the user responsible for logging? It may be a correct choice, but it also seems that you ask it to do a lot of things. Does the user construct itself, update itself? etc
$this->model->user->id; // is it right way? Is not the right way. 1) This is very strong coupling. 2) do you need the id of the user? is the user only put in as dependency to get something from it? perhaps something like $this->user->showUserInfo($userInfoDisplay) can be used?


text:
Q: product import is broke behind cloudflare Im having trouble to resolve my database errors and how to optimize it. Coz of the slowness of my server (mostly querries i believe), my imports turns with a cloudflare error code. (Cloudflare blocks connections over 15 secs as i remember)
Need advises to fix them.
Im hosting my wordpress website at GCP with 1 vcpu, 4gb ram, 20gb ssd. I use OpenLiteSpeed web server, php 7.4.4, mariadb 15.1. Building an affiliate network site. Hosting the images at google cloud storage. Having trouble about the speed of import. Got over 500k products. Barely imported about 200k. Now im not able to import even one by one or do any other edits via backend. Biggest sized xml is comes with 100k products which is stuck at 96k and not keep moving.
My database size is 3.5gb right now with 200k products. Its going to be double of it with +500k products.
Here are my mysql log and slow log, my.cnf setting, mysqltuner advises and global variables.
This morning i realized that i didnt grant privileges for user@127.0.0.1 after setting up the skip-name-resolve and i did it, i just got 1 mysql error i guess.
Coz of the the mysqltuner keeps offering to increase the amount of installed ram everyday, i converted my all innodb tables to myisam.
Also im looking for help to use indexes with wp_postmeta and wp_posts tables.
Preciate that whoever contribute to fix these issues. Thx a lot.
MY.CNF https://gist.github.com/execash/d2add8445e48c26b3e369b18bcf8a18e
MySql Error Log https://gist.github.com/execash/1870e016c5b4794de3a81bc8635d76f9
Slow logs over 2secs https://gist.github.com/execash/30fbdeb7650a824e140ead3080fa1931
Global variables https://gist.github.com/execash/b6b241b5dc607e6f99b322debd1bb11a
Global status https://gist.github.com/execash/604e2b9625f41d31ce9870eda3935ed5
mysqltuner output https://gist.github.com/execash/aa269f91b5b08d1a4609d5c03d75916a

A: Rate Per Second = RPS
Suggestions to consider for your Google Cloud database flags,
log_slow_verbosity=query_plan,explain  # from query_plan for a more useful slow log
read_rnd_buffer_size=128K  # from 2M to reduce handler_read_rnd_next RPS of 67,482
read_buffer_size=512K  # from 4M to reduce handler_read_next RPS of 113,642
key_cache_age_threshold=7200  # from 300 (seconds) to minimize age out, only to read again
key_cache_segments=16  # from 0 to reduce mutex contention

These are only a few of the areas to reduce CPU Busy significantly.  For additional assistance, make contact, please.
Observations:
Import only 50K rows per 'product migration load' to avoid timeout frustration.  Because MyISAM is much slower than innodb for the long term, when migration is completed you will need MORE RAM and cores and additional tuning for innodb data tables.
Unless you are actively using the Slow Query Log, there is no need to have it on for more than 15 minutes, get your table indexes created where identified in the EXPLAIN to improve response time.  Use of mysqldumpslow will summarize your slow log in a helpful manner.  Remember to use multi-column (covering indexes) when appropriate to assist the optimizer.
I will try to find URL to assist with improving wp_postmeta and wp_posts tables.  Will post, when found.


text:
Q: How can I apply filters in elasticsearch NEST functionscore function To control the score of documents based on a field value, I am using filter with function_score in my DSL query and this gets the results ordered as I expect.
However on implementing this in NEST, the results are different; the score is not applied to the filter value. From further investigation I find that some versions of C# NEST Filter is not supported with ScoreFunctionsDescriptor. Is this still the case?
Can you please assist with a working option to implement this with NEST? (I am new to Elastic Search and C# so please excuse if its a noob question).
I am currently using Elasticsearch v7.6, and NEST v7.5.1.
Thanks!
DSL query
GET /help/_search
{
  "query":{
   "function_score": {
     "query": {
     "bool": {
      "must": [
        {
          "multi_match": {
            "query": "AGC",
            "fields": [
              "title^2",
              "description^1"
            ],
            "type":"most_fields",
            "fuzziness": "AUTO:4,8",
            "prefix_length": 2,
            "boost": 5
          }
        }
        ]
  }
  },
**  "functions": [
   {
    "filter": {
     "term":{
       "product":"A"
            }
              },
        "weight": 45
    },
   {
    "filter": {
     "term":{
       "product":"B"
            }
              },
        "weight": 20
    },
   {
    "filter": {
     "term":{
       "product":"C"
            }
              },
        "weight": 10
    }
       ],**
    "score_mode": "max",
    "boost_mode": "multiply"
}
}
}```

A:
From further investigation I find that some versions of C# NEST Filter is not supported with ScoreFunctionsDescriptor. Is this still the case?

The function you're looking for is a weight function with a filter applied. This has been supported for a long time in the client.
The client equivalent would be something like
var response = client.Search<object>(s => s
    .Query(q => q
        .FunctionScore(fs => fs
            .Query(fsq => fsq
                .Bool(b => b
                    .Must(mu => mu
                        .MultiMatch(mm => mm
                            .Query("AGC")
                            .Fields(new[] { "title^2", "description^1" })
                            .Type(TextQueryType.MostFields)
                            .Fuzziness(Fuzziness.AutoLength(4,8))
                            .PrefixLength(2)
                            .Boost(5)
                        )
                    )
                )
            )
            .Functions(fu => fu
                .Weight(w => w
                    .Filter(f => f
                        .Term("product", "A")
                    )
                    .Weight(45)
                )
                .Weight(w => w
                    .Filter(f => f
                        .Term("product", "B")
                    )
                    .Weight(20)
                )
                .Weight(w => w
                    .Filter(f => f
                        .Term("product", "C")
                    )
                    .Weight(10)
                )
            )
            .ScoreMode(FunctionScoreMode.Max)
            .BoostMode(FunctionBoostMode.Multiply)
        )
    )
);

There's a couple of things that you may want to look at:

*

*description^1 can be replaced with simply description as the default boost is 1

*This may be better expressed as a bool query with should clauses for each of the queries in each weight function, with a boost applied similar to how weight is being used. Something like

var response = client.Search<object>(s => s
    .Query(q => q
        .Bool(b => b
            .Must(mu => mu
                .MultiMatch(mm => mm
                    .Query("AGC")
                    .Fields(new[] { "title^2", "description^1" })
                    .Type(TextQueryType.MostFields)
                    .Fuzziness(Fuzziness.AutoLength(4, 8))
                    .PrefixLength(2)
                    .Boost(5)
                )
            )
            .Should(
                sh => sh.Term(t => t
                    .Field("product")
                    .Value("A")
                    .Boost(45)
                ),
                sh => sh.Term(t => t
                    .Field("product")
                    .Value("B")
                    .Boost(20)
                ),
                sh => sh.Term(t => t
                    .Field("product")
                    .Value("C")
                    .Boost(10)
                )
            )
        )
    )
);


text:
Q: Adding prev/next-buttons to "detail fragment" (of master/detail activity) I want to add "prev/next" functionality to my master/detail view. The master loads a GridView (with thumbnails), which -- when clicked -- start a DetailActivity via an URI (essentially containing the corresponding image ID).
What I want is for the detail activity/fragment to be able to jump to previous/next image, directly -- without having to go back and forth through the master view. Ideally, I want to capture swipe gestures.
I've read that the best way to do this is to use a ViewPager, with FragmentStatePagerAdapter to hold the child views. But, I'd like to understand why my first attempt isn't working (below). (Also, I hope to avoid major reworking of the code, unless I have to.) While my attempt does work, I get an OutOfMemory error/crash after only a few swipes:
10-13 13:11:21.441    4149-4149/com.example.android.galleri.app E/art﹕ Throwing OutOfMemoryError "Failed to allocate a 33177612 byte allocation with 12795712 free bytes and 12MB until OOM"
10-13 13:11:21.455    4149-4149/com.example.android.galleri.app I/art﹕ Clamp target GC heap from 195MB to 192MB
10-13 13:11:21.456    4149-4149/com.example.android.galleri.app I/art﹕ Alloc partial concurrent mark sweep GC freed 6(192B) AllocSpace objects, 0(0B) LOS objects, 6% free, 179MB/192MB, paused 903us total 10.248ms
10-13 13:11:21.474    4149-4149/com.example.android.galleri.app I/art﹕ Clamp target GC heap from 195MB to 192MB
10-13 13:11:21.474    4149-4149/com.example.android.galleri.app I/art﹕ Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 6% free, 179MB/192MB, paused 975us total 18.144ms
10-13 13:11:21.474    4149-4149/com.example.android.galleri.app I/art﹕ Forcing collection of SoftReferences for 31MB allocation
10-13 13:11:21.490    4149-4149/com.example.android.galleri.app I/art﹕ Clamp target GC heap from 195MB to 192MB
10-13 13:11:21.490    4149-4149/com.example.android.galleri.app I/art﹕ Alloc concurrent mark sweep GC freed 3(96B) AllocSpace objects, 0(0B) LOS objects, 6% free, 179MB/192MB, paused 1.060ms total 15.295ms
10-13 13:11:21.490    4149-4149/com.example.android.galleri.app E/art﹕ Throwing OutOfMemoryError "Failed to allocate a 33177612 byte allocation with 12795712 free bytes and 12MB until OOM"
10-13 13:11:21.490    4149-4149/com.example.android.galleri.app D/skia﹕ --- decoder->decode returned false
10-13 13:11:21.491    4149-4149/com.example.android.galleri.app D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
10-13 13:11:21.492    4149-4149/com.example.android.galleri.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.android.galleri.app, PID: 4149
    java.lang.OutOfMemoryError: Failed to allocate a 33177612 byte allocation with 12795712 free bytes and 12MB until OOM
            at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
            at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
            at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:635)
            at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:611)
            at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391)
            at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:417)
            at com.example.android.galleri.app.DetailFragment.onLoadFinished(DetailFragment.java:302)
            at com.example.android.galleri.app.DetailFragment.onLoadFinished(DetailFragment.java:43)
            at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:427)
            at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:395)
            at android.support.v4.content.Loader.deliverResult(Loader.java:104)
            at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:73)
            at android.support.v4.content.CursorLoader.deliverResult(CursorLoader.java:35)
            at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:223)
            at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:61)
            at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:461)
            at android.support.v4.content.ModernAsyncTask.access$500(ModernAsyncTask.java:47)
            at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:474)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:211)
            at android.app.ActivityThread.main(ActivityThread.java:5389)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)

Here is the relevant (I hope) code.

*

*Note the public void onItemSelected(Uri contentUri) call from MainActivity, which does the normal loading of an image "into" the DetailFragment.

*This method is called (via callback/interface) from the PhotoFragment: The GridView's onClick handler, created in the onCreate method. That's the normal master-to-detail loading of images, works fine.

*Then the other way: DetailActivity captures the swipe gestures, and calls the changeImage method in the DetailFragment (via member object/reference).

*The DetailFragment's changeImage method fetches the cursor used in the PhotoFragment, via the Utility class (container object). Then, it gets the next/previous row and constructs a new URI with that ID, and starts (restarts?) the DetailActivity with that URI.
These restarts seem to accumulate memory, until the app crashes. The crash (OOM error) always occurs at the same line of DetailFragment, in the part where I load the Bitmap into the PhotoView:
// OOM crash always occurs HERE (after ~5 swipes)
thumbBitmap = BitmapFactory.decodeFile(thumbData);

MainActivity.java
public class MainActivity extends ActionBarActivity implements PhotoFragment.Callback  {

    private static final String DETAILFRAGMENT_TAG = "DFTAG";
    private boolean mTwoPane;
    private PhotoFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (findViewById(R.id.photo_detail_container) != null) {
            mTwoPane = true;

            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.photo_detail_container, new DetailFragment(), DETAILFRAGMENT_TAG)
                        .commit();
            }
        } else {
            mTwoPane = false;
        }

        mFragment = ((PhotoFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_photo));
        mFragment.setTwoPaneUI(mTwoPane);

    }

    @Override
    // this method is called from PhotoFragment (GridView) via a callback interface
    public void onItemSelected(Uri contentUri) {

        if (mTwoPane) {
            Bundle args = new Bundle();
            args.putParcelable(DetailFragment.DETAIL_URI, contentUri);

            DetailFragment fragment = new DetailFragment();
            fragment.setArguments(args);

            fragment.setTwoPane(true);

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.photo_detail_container, fragment, DETAILFRAGMENT_TAG)
                    .commit();
        } else {

            // launch DetailActivity
            Intent intent = new Intent(this, DetailActivity.class)
                    .setData(contentUri);
            startActivity(intent);
        }
    }

}

PhotoFragment.java
public class PhotoFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private final static int LOADER_ID = 87;
    private PhotoAdapter mPhotoAdapter;
    private int mPosition;
    private GridView mGridView;
    private TextView mEmptyView;
    private int count_mem = -1;
    private static final String SELECTED_KEY = "POSITION";
    private boolean mTwoPane;
    private boolean DF_hidden = false;

    // these are the data we want from MediaStore
    private final static String[] THUMBNAIL_COLUMNS = {
            //PhotoContract.ThumbEntry.COLUMN_THUMB_ID,
            PhotoContract.ThumbEntry.COLUMN_THUMB_DATA,
            PhotoContract.ThumbEntry.COLUMN_IMAGE_PK,
            PhotoContract.ThumbEntry.COLUMN_TITLE,
            PhotoContract.ThumbEntry.COLUMN_DESC,
            PhotoContract.ThumbEntry.COLUMN_DATE,
            PhotoContract.ThumbEntry.COLUMN_FILENAME,
            PhotoContract.ThumbEntry.COLUMN_DATA,
            PhotoContract.ThumbEntry.COLUMN_IMAGESEQUENCE
    };

    static final int COL_THUMB_DATA = 0;
    static final int COL_IMAGE_ID = 1;
    static final int COL_TITLE = 2;
    static final int COL_DESC = 3;
    static final int COL_DATE = 4;
    static final int COL_FILENAME = 5;
    static final int COL_DATA = 6;
    static final int COL_IMAGESEQUENCE = 7;

    public void setTwoPaneUI(boolean pTwoPane) {
        mTwoPane = pTwoPane;
    }

    // interfaces
    public interface Callback {
        public void onItemSelected(Uri photoUri);
    }
    public interface FragmentCallback {
        public void onTaskDone(int count);
    }

    public PhotoFragment() {
    }

    public int getPosition() {
       return mPosition;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        getLoaderManager().initLoader(LOADER_ID, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void restartLoader() {
        getLoaderManager().restartLoader(LOADER_ID, null, this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (mPosition != GridView.INVALID_POSITION) {
            outState.putInt(SELECTED_KEY, mPosition);
        }
        super.onSaveInstanceState(outState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        mPhotoAdapter = new PhotoAdapter(getActivity(), null, 0);
        GridView gridView = (GridView) rootView.findViewById(R.id.listview_photo);
        gridView.setAdapter(mPhotoAdapter);

        mEmptyView = (TextView) rootView.findViewById(R.id.list_empty);
        mGridView = gridView;

        // handle user clicking on an image
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Cursor cursor = (Cursor) parent.getItemAtPosition(position);

                if (cursor != null) {
                    Uri baseUri = PhotoContract.PhotoEntry.buildPhotoUriWithId(cursor.getLong(COL_IMAGE_ID));
                    Log.v("gallery", "PhotoFragment.onItemClick() image_id = " + cursor.getLong(COL_IMAGE_ID)
                           + ", baseUri = " + baseUri.toString());

                    // make sure detail fragment is visible
                    if (mTwoPane) showDetailFragment();
                    else Utility.setPosition(position);  // else (single-pane): store position clicked!

                    ((Callback)getActivity()).onItemSelected(baseUri);
                }
                mPosition = position;
            }
        });

        if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
            mPosition = savedInstanceState.getInt(SELECTED_KEY);
        }

        return rootView;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {

        Uri thumbs_uri = PhotoContract.ThumbEntry.CONTENT_URI;
        return new CursorLoader(getActivity(), thumbs_uri, THUMBNAIL_COLUMNS,
                null,null,  // read everything (all thumbnails)
                null
               );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        if (cursor != null) {

            // register observer onto cursor
            cursor.setNotificationUri(getActivity().getContentResolver(), PhotoContract.ThumbEntry.CONTENT_URI);

            mPhotoAdapter.swapCursor(cursor);
            if (mPosition != GridView.INVALID_POSITION) {
                mGridView.setSelection(mPosition);  // scroll into view
            }
        }

        // save (set) cursor in Utility
        Utility.setCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        mPhotoAdapter.swapCursor(null);
    }
}

DetailActivity.java
public class DetailActivity extends ActionBarActivity  {

    private static final String DETAILFRAGMENT_TAG = "DFTAG";
    private float x1,x2, y1,y2;
    static final int MIN_DISTANCE = 150;
    private DetailFragment mFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        if (savedInstanceState == null) {

            Bundle arguments = new Bundle();
            arguments.putParcelable(DetailFragment.DETAIL_URI, getIntent().getData());

            //DetailFragment fragment = new DetailFragment();
            mFragment = new DetailFragment();
            mFragment.setArguments(arguments);

            getSupportFragmentManager().beginTransaction()
                    .add(R.id.photo_detail_container, mFragment, DETAILFRAGMENT_TAG)
                    .commit();
        }
    }

    // http://stackoverflow.com/questions/6645537/how-to-detect-the-swipe-left-or-right-in-android
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {

        switch(event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1 = event.getX();
                y1 = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                x2 = event.getX();
                y2 = event.getY();

                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE) {

                    if (x2 > x1)
                        mFragment.changeImage(-1);  // move backwards
                    else
                        mFragment.changeImage(1);  // move forwards
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_detail, menu);
        return true;
    }

}

DetailFragment.java
public class DetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String PHOTOFRAGMENT_TAG = "PFTAG";
    static final String DETAIL_URI = "URI";
    private static final int DETAIL_LOADER = 0;
    private ImageView mPhotoView, mCloseIcon;
    private TextView mImageSizeView, mImageDateView;
    public String mMemTitle, mMemDesc;

    // data for sharing
    private Long mImageID;

    private ShareActionProvider mShareActionProvider;

    private static final String[] DETAIL_COLUMNS = {
            PhotoContract.PhotoEntry.COLUMN_IMAGE_ID,
            PhotoContract.PhotoEntry.COLUMN_DISPLAY_NAME,
            PhotoContract.PhotoEntry.COLUMN_DATA,
            PhotoContract.PhotoEntry.COLUMN_DESC,
            PhotoContract.PhotoEntry.COLUMN_DATE_TAKEN,
            PhotoContract.PhotoEntry.COLUMN_DATE_ADDED,
            PhotoContract.PhotoEntry.COLUMN_TITLE,
            PhotoContract.PhotoEntry.COLUMN_SIZE,
            PhotoContract.PhotoEntry.COLUMN_ORIENTATION,
            PhotoContract.PhotoEntry.COLUMN_HEIGHT,
            PhotoContract.PhotoEntry.COLUMN_WIDTH
    };

    static final int COL_IMAGE_ID = 0;
    static final int COL_DISPLAY_NAME = 1;
    static final int COL_DATA = 2;
    static final int COL_DESC = 3;
    static final int COL_DATE_TAKEN = 4;
    static final int COL_DATE_ADDED = 5;
    static final int COL_TITLE = 6;
    static final int COL_SIZE = 7;
    static final int COL_ORIENTATION = 8;
    static final int COL_HEIGHT = 9;
    static final int COL_WIDTH = 10;

    static final int COL_THUMB_ID = 0;
    static final int COL_THUMB_DATA = 1;
    static final int COL_THUMB_IMAGE_ID = 2;

    private Uri mUri;

    private boolean noMedia = false;
    private boolean mTwoPane = false;

    public DetailFragment() {
        setHasOptionsMenu(true); // only share button, though
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.detailfragment, menu);
        MenuItem menuItem = menu.findItem(R.id.action_share);
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);

        if (mFilePath != null) {
            mShareActionProvider.setShareIntent(createShareForecastIntent());
        }
    }

    public ImageView getPhotoView() {
        return mPhotoView;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        if (arguments != null) {
            mUri = arguments.getParcelable(DetailFragment.DETAIL_URI);
        }
        // get ID from URI
        if (mUri != null) {
            mImageID = PhotoContract.PhotoEntry.getImageIdFromUri(mUri);
        }

        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);

        mPhotoView = (ImageView) rootView.findViewById(R.id.pic_frame);
        mImageSizeView = (TextView) rootView.findViewById(R.id.imgSize_textview);
        mImageDateView = (TextView) rootView.findViewById(R.id.date_textview);

        return rootView;
    }

    // user swipes; go to prev (direction = -1) or next (direction = 1) image:
    public void changeImage(int direction) {

        Cursor cursor = Utility.getCursor();
        Long oldId = mImageID;
        if (cursor == null)
            return;

        boolean result;
        switch (direction) {
            case -1:
                if (cursor.isFirst()) return;
                result = cursor.moveToPrevious();
                break;
            case 1:
                if (cursor.isLast()) return;
                result = cursor.moveToNext();
                break;
            default:
                return;
        }

        Log.v("gallery", "DetailFragment.changeImage(" + direction + "), old id "
                + oldId + " => IMAGE_ID = " + cursor.getLong(PhotoFragment.COL_IMAGE_ID));

        if (result) {
            mUri = PhotoContract.PhotoEntry.buildPhotoUriWithId(cursor.getLong(PhotoFragment.COL_IMAGE_ID));

            Utility.setPosition(cursor.getPosition());  // store position clicked!

            // re-launch DetailActivity
            Intent intent = new Intent(getActivity(), DetailActivity.class)
                    .setData(mUri);
            startActivity(intent);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        if (mUri != null) {
            return new CursorLoader(getActivity(),
                    mUri, // URI passed in
                    DETAIL_COLUMNS, null, null, null);
        } else {
            mUri = PhotoContract.PhotoEntry.CONTENT_URI;  // means, default (first) image

            return new CursorLoader(getActivity(),
                    mUri, // "default URI": show first image...
                    DETAIL_COLUMNS, null, null, null);
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor data) {

        if (data == null || !data.moveToFirst()) {
            return;
        }

        String thumbData = data.getString(COL_DATA);
        if (thumbData != null) {
            Bitmap thumbBitmap;
            try {
                thumbBitmap = BitmapFactory.decodeFile(thumbData);  // <--- OOM crash always occurs HERE (after ~5 swipes)
                mPhotoView.setImageBitmap(thumbBitmap);
            } catch (Exception e) {
                return;
            }
        }

        String metaDataText = data.getString(COL_WIDTH) + " x " + data.getString(COL_HEIGHT) + ", "
                + Math.round(data.getLong(COL_SIZE) / 1024.0) + "kb";

        mImageSizeView.setText(metaDataText, TextView.BufferType.SPANNABLE);

        mImageDateView.setText(DateFormat.format("d/M-yyyy",
                new Date(data.getLong(COL_DATE_TAKEN))).toString());

        if (mShareActionProvider != null)
            mShareActionProvider.setShareIntent(createShareForecastIntent());
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        getLoaderManager().initLoader(DETAIL_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    public void setTwoPane(boolean b) {
        mTwoPane = b;
    }
}


text:
Q: java arraylist changes value as i add value to it using an instance class I have an instance class called Review that takes in String, String, int, String, boolean.
every time user inputs values for all 5 of those, it adds to an arrayList in the main.
my problem here is that when the user updates the values, it also changes the values inside the arraylist that in the end, all the Review inside the arraylist turns out to be the same. I do not have anything static in the Review class. how can i fix this problem?
public class Review implements Comparable<Review>{
  private String reviewer;
  private String restaurant;
  private int rating;
  private String comment;
  private boolean recommended;
  public Review( String revName, String restName, int rating, String comment, boolean recommended) {
    reviewer = revName;
    restaurant = restName;
    this.rating = rating;
    this.comment = comment;
    this.recommended = recommended;
  }

this is the basic class w/ constructor, they all have their own getter & setter.
private ArrayList<Review> reviews = new ArrayList<Review>();

Review review = new Review(revName, restName, rating, comment, recommended);

public void setReviews(Review review){
  reviews.add(review);
}
public ArrayList<Review> getReviews(){
    return reviews;
}

this is another class for importing and exporting.(i will call this "reader" class from now on)
in the main i just use
    ArrayList<Review> reviews = reader.getReviews();

to set them equal to each other every time there's an update
    reader.setReviews(review);

this is used after all 5 inputs by the user. user uses setters for individual variables from Review class to set the values.

A:  Your issue
When you declare this:
Object o = new Object();

the value that you work with, is the pointer to that object. Not the object itself. So when you're intending on adding several objects to an ArrayList, you're not adding the objects themselves. You're simply adding pointers to those objects. Hence, you need a new object for each item in the ArrayList. Why?
SomeClass s = new SomeClass();
SomeClass a = s;

a.setName("Hello"); // Sets the object's name value that a points to.
s.getName(); // Will return "Hello".

This is because a and s both point to the same object.
 Other stuff
 Your constructor
One of the key elements of readable code is consistency. If you do something one way, always do it that way if it doesn't impact the program's functionality. One example of where you don't follow that principle is here:
reviewer = revName;
restaurant = restName;

And the rest of the constructor looks like this:
this.rating = rating;
this.comment = comment;
this.recommended = recommended;

The latter part is the more commonly used code for a constructor, and I would recommend changing the first part, so that it fits with the pattern, ie:
this.reviewer = reviewer;
this.restaurant = restaurant;

 An object declaration
Review review = new Review(revName, restName, rating, comment, recommended);

I really don't know what this code is for, or at least, it's not obvious from the code you've provided.


text:
Q: Dualboot Ubuntu to VirtualBox VDI migration I'm trying to migrate my current install to a virtualbox so that I can use it to recover some preferences/data when I install Bionic on my laptop. I currently dualboot my system and I have my Ubuntu partition in /dev/sda7. I tried converting it to a vdi by following this answer. However, it looks like my boot partition is separate and I can't boot into the vdi. I used another virtualbox to chroot into this system and do grub-install. It failed due to the lack of a valid directory. How do I fix this issue and migrate my physical Ubuntu to a virtual machine?

A: Have you tried copying the contents of your boot directory to /boot on the root of the drive you want to boot from?
This will copy the various kernels and other files grub may need.
Then try and install grub with grub-install again.


text:
Q: undefined method `map' for nil:NilClass Did you mean? tap New to rails, and walking through part 3 of a four part tutorial (https://www.youtube.com/watch?v=zeCp6IzOrpk). Have worked through a lot of errors, but this error has me stuck for the past day. Hoping someone can help.
I added the paperclip gem to my app and this error happens when I attempt to create a new book with an image file.
The Error is
NoMethodError in Books#Create

Showing /BookReview/app/views/books/_form.html.erb where line #2 raised:
undefined method `map' for nil:NilClass
  Did you mean?  tap
  Trace of template inclusion: app/views/books/new.html.erb

The Application Trace is

app/views/books/_form.html.erb:2:in block in _app_views_books__form_html_erb__680817446_105363440'
  app/views/books/_form.html.erb:1:in_app_views_books__form_html_erb__680817446_105363440'
  app/views/books/new.html.erb:4:in _app_views_books_new_html_erb__1556443805_105196100'
  app/controllers/books_controller.rb:32:increate'

I think the problem is in my create action, within my books controller
def create

    @book = current_user.books.build(book_params)
    @book.category_id = params[:category_id]

    if @book.save
        redirect_to root_path
    else
        render 'new'
    end
end

When I add the following line directly under @book.category_id = params[:category_id] i can submit the form with no errors, but the file is not associated with the book when I look within the console.
@book.book_img = params[:book_img]
The last thing is the private action, which I've added the :book_img to.
def book_params
 params.require(:book).permit(:title, :description, :author,:category_id, :book_img)
end

Hoping someone can help. Thanks ahead of time!
Edit:
_form.html.erb
<%= simple_form_for @book, :html => { :multipart => true } do |f| %>
  <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select a category") %>
  <%= f.file_field :book_img %>
  <%= f.input :title, label: "Book Title" %>
  <%= f.input :description %>
  <%= f.input :author %>
  <%= f.button :submit %>
<% end %>

A: I think @categories in _form.html.erb is probably nil. In your controller that renders the form make sure you define @categories e.g.
@categories = Categories.all

A: I your create action add this also
 @categories = Category.all

because on error...it is rendering same new.html.erb and  @categories are not there

A: Try this:
_form.html.erb
<%= simple_form_for @book, :html => { :multipart => true } do |f| %>

  <%= f.input :category_id do %>
      <%= f.select :category_id, Category.all.map{|c| [c.name,c.id]}, :prompt => "Select a category" %>
  <% end %>

  <%= f.file_field :book_img %>
  <%= f.input :title, label: "Book Title" %>
  <%= f.input :description %>
  <%= f.input :author %>
  <%= f.button :submit %>
<% end %>

books_controller.rb
def create
  if @book = Book.create(book_params)
    redirect_to root_path
  else
    render 'new'
  end
end

private
#strong params
def book_params
 params.require(:book).permit(:title, :description, :author,:category_id, :book_img).merge(user_id: current_user.id)
end

A: Thank you everyone for jumping in with tons of help. I learned a lot. I've solved the issue.
I removed the paperclip gem and installed the most recent version
gem 'paperclip', '~> 4.3', '>= 4.3.6'
I reinstalled ImageMagic and added the PATH to my development.rb.
My development.rb originally had:
Paperclip.options[:command_path] = "/usr/local/bin/"
Since I am on Windows, I had to replace it with Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin' to get it to work.
Now everything is working fine. Thanks again for everyone's help.


text:
Q: Plotly : Heatmap color legend i subplot I'm working in python with plotly, trying to have two heatmap subplot with a custom legend for each.
But here what I see with the following code :
import plotly

fig = plotly.subplots.make_subplots(rows=2, cols=1)

mat = np.array([[1,0],
                [0,1]])

fig.add_trace(go.Heatmap(z=mat, colorscale='Bluered_r'), row=1, col=1)

fig.add_trace(go.Heatmap(z=mat*10, colorscale='Bluered_r'), row=2, col=1)

fig.show()

you can see that both legend are displayed at the same place.
Thanks for your help!

A: Just found a solution hidden in the doc using the colorbar argument:
import plotly

fig = plotly.subplots.make_subplots(rows=2, cols=1)

mat = np.array([[1,0],
                [0,1]])

fig.add_trace(go.Heatmap(z=mat, colorscale='Bluered_r',colorbar=dict(y=.8,len=.5)), row=1, col=1)

fig.add_trace(go.Heatmap(z=mat*10, colorscale='Bluered_r',colorbar=dict(y=.2,len=.5)), row=2, col=1)

fig.show()

This would give:


text:
Q: Cannot assign requested address ::1: I've been trying to push out an opendistro es image out to a node. I've put a yaml script together thats been able to do so, but upon entering the pod and trying to curl localhost and hit the elasticsearch API, I get the error:
curl: (7) Failed to connect to ::1: Cannot assign request address

Here's the yaml script below, maybe I've done something obviously wrong
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: es-opendistro
  labels:
    service: es-opendistro
spec:
  serviceName: es-opendisro
  replicas: 1
  selector:
    matchLabels:
      name: es-opendistro
  template:
    metadata:
      labels:
        service: es-opendistro
        name: es-opendistro
    spec:
      nodeSelector:
        name: es-opendistro
      initContainers:
      - name: init-sysctl
        image: busybox:1.30
        command: ["sysctl", "-w", "vm.max_map_count=262144"]
        securityContext:
          privileged: true
      containers:
      - name: es-opendistro
        image: CM-DEPLOYER:5000/elasticsearch-opendistro:0.10.0
        env:
        - name: ES_JAVA_OPTS
          value: -Xms1024m -Xmx1024m
        - name: discovery.type
          value: single-node
        - name: NETWORK_HOST
          value: "_site_,_lo_"
        ports:
        - containerPort: 9200
          name: http
          protocol: TCP
        - containerPort: 9300
          name: transport
          protocol: TCP
        volumeMounts:
        - name: internal-users
          mountPath: /usr/share/elasticsearch/plugins/opendistro_security/securityconfig/internal_users.yml
          subPath: internal_users.yml
        - name: elasticsearch-log
          mountPath: /var/log/elasticsearch
        - name: elasticsearch-data
          mountPath: /usr/share/elasticsearch/data
        - name: elasticsearch-config
          mountPath: /usr/share/elasticsearch/config/elasticsearch.yml
          subPath: elasticsearch.yml
      volumes:
        - name: internal-users
          configMap:
            name: internal-users
        - name: elasticsearch-log
          hostPath:
            path: elasticsearch-log
        - name: elasticsearch-data
          hostPath:
            path: /mnt/esdata1
        - name: elasticsearch-config
          hostPath:
            path: /usr/share/elasticsearch
---
apiVersion: v1
kind: Service
metadata:
  name: es6
spec:
  type: NodePort
  ipFamily: IPv4
  selector:
    service: es-opendistro
  ports:
  - name: "9200"
    port: 9200
    targetPort: 9200
    nodePort: 30001
  - name: "9300"
    port: 9300
    targetPort: 9300
    nodePort: 30002

At this point I have no idea what's missing

A: Ran logs for Docker Container logs:
See: https://discuss.opendistrocommunity.dev/t/securityadmin-sh-is-not-work-welll/618
This resolved the issue in case anyone comes across it
Lack of SSL caused the container to not accept traffic


text:
Q: Can't see values in console.log() in nativescript I have an js file which includes an array! The js file is like this one
export const appointments = [
{
  "taskID": 9018929,
  "resource_ID": 1,
  "title": "KNDL Thatcham",
  "description": "<Non-Selected>\r\n10:00 - 18:00",
  "startTime": "2018-12-28T00:00:00",
  "endTime": "2018-12-28T23:59:00",
  "statusColour": "#DFDFDF",
  "clientColour": "#FFFDD7"
}]

I have imported this js files in service.ts. And this appointments.js does not show in the console.log.
import { Injectable } from '@angular/core';
        import { appointments } from '../appointments';
        import { Color } from "tns-core-modules/color";
        // >> angular-calendar-require
        import { CalendarEvent } from 'nativescript-ui-calendar';

        @Injectable({
        providedIn: 'root'
        })

    export class CalendarService {

      constructor() {
      //var a="test test etsdhsakdsakd dsddssdsd";
      console.log(appointments);
    }

This is the component where I am importing the service.ts
import { Component, OnInit } from '@angular/core';

import { CalendarService } from "./service/calendar.service";
import { RadCalendar, CalendarEvent, CalendarSelectionEventData } from "nativescript-ui-calendar";
@Component({
  selector: 'ns-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.css'],
  moduleId: module.id,
  providers: [CalendarService]
})
export class CalendarComponent implements OnInit {
}

A: You need to add a private calendarService parameter of type CalendarService to the constructor.
When Angular creates a CalendarComponent , the Dependency Injection system sets the calendarService parameter to the singleton instance of CalendarService .
export class CalendarComponent implements OnInit {
constructor(calendarService : CalendarService ) {}
}


text:
Q: How to permanently set the environment variables for OpenVino I am setting up OpenVino on my system and I get this form the documentation:

(Optional): OpenVINO toolkit environment variables are removed when you close the Command Prompt window. As an option, you can permanently set the environment variables manually.

But there is no information is available on what are the required environment variables and what value they should be set.
I need to know the list of environmental variable needed by OpenVino and the value that they should be set to. I know how to set them in Windows (using GUI or Setx).

A: The environment variables need to be set are given in the setupvars.bat file present at "path_to_computer_vision_sdk_directory\bin".
But I will give a general idea on the paths that need to be set -
Set the following System variables in your Environment Variables

*

*Variable name: INTEL_CVSDK_DIR
Variable value: path_to_computer_vision_sdk_directory i.e.
C:\Intel\computer_vision_sdk_version_number, in case you have the cvsdk setup at the default path for installation

*Variable name: OpenCV_DIR
Variable value: %INTEL_CVSDK_DIR%\opencv\cmake

*Variable name: OPENVX_FOLDER
Variable value: %INTEL_CVSDK_DIR%\openvx

*Variable name: InferenceEngine_DIR
Variable value: %INTEL_CVSDK_DIR%\deployment_tools\inference_engine\share

*Variable name: HDDL_INSTALL_DIR
Variable value: %INTEL_CVSDK_DIR%\deployment_tools\inference_engine\external\hddl

*Now edit the "Path" variable under System Variables to include the following values -
%INTEL_CVSDK_DIR%\opencv\x64\vc14\bin
%INTEL_CVSDK_DIR%\openvx\bin
%INTEL_CVSDK_DIR%\deployment_tools\inference_engine\bin\intel64\Release
%INTEL_CVSDK_DIR%\deployment_tools\inference_engine\bin\intel64\Debug
%HDDL_INSTALL_DIR%\bin
You also nee to set the "PYTHONPATH" to %INTEL_CVSDK_DIR%\python\python_version%


text:
Q: How to update date string in array to date format in mongoDB? My mongoDB collection looks like this:
[
  {
    "id": "myid",
    "field": {
      "total": 1,
      "subfield": [
        {
          "time": "2020-08-06T08:33:57.977+0530"

        },
        {
          "time": "2020-05-08T04:13:27.977+0530"

        }
      ]
    }
  },
  {
    "id": "myid2",
    "field": {
      "total": 1,
      "subfield": [
        {
          "time": "2020-07-31T10:15:50.184+0530"
        }
      ]
    }
  }
]

I need to update all the documents and convert date string in the field time available in the subfieldarray to mongoDB ISO date format.
I have thousands of documents and hundreds of objects in subfield array
I'm aware of the aggregate function $todate and $convert.
But I don't want to use aggregation because,

*

*To use $todate or $convert, I need to unwind the field.subfield  array which is again an expensive operation.

*I want to update my document and save it with the date format.

My MongoDB server version: 4.0.3

I tried the following but it doesn't seem to work and also doesn't return any errors.
db.collection.find().forEach(function(doc) {
doc.field.subfield.time=new ISODate(doc.field.subfield.time);
db.collection.save(doc);
})

A: You missed a loop for subfield, because its an array,
db.collection.find().forEach(function(doc) {
    doc.field.subfield.forEach(function(r) {
        r.time = new ISODate(r.time);
    })
    db.collection.save(doc);
})

If this is for one time then time does not matter, i think both will take same time if you do with aggregation or forEach.

If you are planing to update MongoDb version then form 4.2,
a option you can update with updateMany() using update with aggregation pipeline,
db.collection.updateMany({},
    [{
        $set: {
            "field.subfield": {
                $map: {
                    input: "$field.subfield",
                    as: "r",
                    in: {
                        $mergeObjects: [
                            "$$r",
                            { time: { $toDate: "$$r.time" } }
                        ]
                    }
                }
            }
        }
    }]
)


text:
Q: Problem installing Linux in ASUS R510VX-DM534 I'm having problems installing any Linux distro in a Laptop Asus R510VX-DM534.
First. I was using Linux Mint 18 for months without problem, and, after an update, I had to reboot and then appeared many errors when booting: Errors on Booting
After trying to solve the problem, I decided to reinstall Linux again. And it was impossible for me.
when I tried to install Linux mint 19, I used an image on a USB stick. It started without a problem, but after a few seconds an error message appeared:  "The Computer Has Only 0 Bytes disk space remaining". Strange, because I'm booting from an USB. Ok, I ignore warning, and Try to install anyway.
I try to install anyway, but the installation process stops after choosing where to install Linux, leaving the default option as I want to use the whole disk for the new installation.
Ok, I try with Kubuntu 18
I boot from another USB and it gives me the option to choose to test and install. I choose to try and he just stands there, too.
Tried with Solus. Finally, I got it, but the system hangs a lot and I can't do anything.
A little tired, I use the process of restoring the laptop itself, which leaves the default operating system; Endless Linux. It works fine, at least apparently, but I wanted to install another distribution, Endless Linux seems a little simple for my taste, and I can't install the proprietary nVidia driver.
I don't know what I can do, I don't know if the disk or the disk controller will have some kind of problem, but the thing is that I'm already starting to get desperate.
What can I do?

A: There appears to be a known bug with the intel PCIe chipset, not limited to 8086:a112, that people workaround using either pci=nomsi or pci=noaer kernel boot parameters.
Check it out here PCIe Bus error severity=Corrected
That will hopefully clear the error spam for you, and perhaps enable you to progress further with installing a different distro on your laptop.


text:
Q: Selenium is it ok to use implicit waits alongside explicit waits? (Using Page Object Model) I have written a Selenium Java Framework that uses both implicit waits and explicit waits.
I am using Page Object Model so all of the elements are declared at the top of the page class as shown here:
@FindBy(how = How.ID, using = "firstname")
public WebElement firstname;

The elements are instantiated using Page Factory as shown here:
public BasePage() {
    PageFactory.initElements(driver, this);
}

When I first move to a new webpage I use an explicit wait to check that one of the elements on the page is there. To do this, I temporarily set the implicit wait to 0 (so it doesn't clash) then use a WebDriverWait to wait for the element as shown here:
    CommonUtil.waitForElementVisible(save,properties.getProperty("TimeOutSeconds"));

//This is the actual method in CommonUtil:
public static void waitForElementVisible(WebElement element, String timeoutSecondsAsString) {

    //Temporarily set the default(implicit) timeout to 0 seconds otherwise it will override the timeout specified in this method
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

    WebDriverWait wait = new WebDriverWait(driver, Integer.parseInt(timeoutSecondsAsString));
    wait.until(ExpectedConditions.visibilityOf(element));

    //Set the default (implicit) timeout back to the default
    long timeout = Long.valueOf(properties.getProperty("TimeOutSeconds"));
    driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}

Once I have done the explicit wait for one of the objects, I use the implicit wait for the rest of the objects, so that I can sendKeys, click etc really easily without having to use any wait commands as shown here:
    firstname.sendKeys("firstName");
    lastname.sendKeys("Surname");
    checkout.click();

I have been told that I should not be using implicit waits alongside explicit waits. Is this correct? It seems fine to me and is working perfectly. I would have to write a lot more code if I have to write an explicit wait before clicking or sendingkeys to every field and defeats the object of the Page Object Model being so simple and neat.


text:
Q: How can I create a horizontal bargraph with x= type float and y= type object Data has >400 rows, This is a sample:
TIME    PERSON
0   22.222222   Runner
1   23.796791   Cyclist
2   20.789474   Swimmer
3   21.270718   Pedestrain
4   19.518717   Kid

time is type:float Person is type:Object
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

raw_data = pd.DataFrame({"PERSON": ['PERSON']})

plt.figure(figsize=(16, 10))
raw_data.plot(kind='barh', x=raw_data['TIME'], y="PERSON")
plt.xlabel("TIME")
plt.ylabel("PERSON")

plt.show()

Not sure how to categorize "PERSON" as it has multiple different types, do I have to name one by one? I'd like to group values in 'PERSON' and show average for 'TIME'. Thanks a lot in advance

A: You can use seaborn library, which you already has included in your code. It's developed to do such graphs "from the box":
plt.figure(figsize=(16, 10))
sns.barplot(x='TIME', y='PERSON', data=raw_data)

And for grouping by PERSON and averaging by TIME answer is this simple:
sns.barplot(x='TIME', y='PERSON', data=raw_data.groupby('PERSON').mean().reset_index())


text:
Q: 'git branch -av' showing remote branch that no longer exists This is probably a dumb question, but I'm brand new to git and am seeing a remote branch that no longer exists.
$ git branch -a
* master
  remotes/origin/master
  remotes/origin/production

I don't believe the production branch exists remotely and can't figure out why it still shows locally. How can I delete/remove this branch? Here's what an attempt to remove it looks like:
$ git push origin :production

error: unable to push to unqualified destination: production
The destination refspec neither matches an existing ref on the remote nor
begins with refs/, and we are unable to guess a prefix based on the source ref.
error: failed to push some refs to 'git@IP:puppet.git'

I can checkout the supposedly remote production branch but get this:
$ git checkout origin/production
Note: checking out 'origin/production'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at c323996... added powerdns module, no really

I have no clue what the heck I'm doing. Any help would be appreciated.

A: So there are two problems.  In both cases, remember Git is distributed.
First.  When you do things like

$ git branch -a

the operation is performed on your local repo NOT the remote computer.  In other words, your local repo is reporting all the branches that is knows about.  These could be local branches (like 'master') or remote branches that it has fetched from a remote.  Since the last fetch, the 'production' branch of the remote repo has changed, but your local repo does not know this.  The answer from manojlds, is correct.  Run

$ git remote prune origin

to remove stale branches.
The 'git push origin :production' command is used for deleting the branch from the remote computer's git repo.  Not your local repo.  In this case, someone else has already deleted the branch on the remote computer's git repo, so you see this error message.
Here is a link that summarizes these commands.
The second problem deals with checkout.
When checking out a branch, you want to do so from a local branch, not the remote branch.  That is why you get the error about a detached HEAD.  The git-notes repo has a good explanation of the problem in gory detail.  Basically the key phrase is

However, when you checkout anything that is not a proper, local, branch name, then HEAD is no longer a symbolic reference to anything. Instead, it actually contains the SHA-1 hash (the commit id) of the commit you are switching to.

Now, how to check out a local branch, that is the same as the remote branch?
Easy, you create a local branch, at the time of checkout remote branch.

$ git checkout -b my_local_branch origin/production

A: You have to do:
git remote prune origin

A: git remote prune origin

is right, just adding you can use --dry-run option, that reports what branches will be pruned from your local repo, but doesnt actually prune them
git remote prune origin --dry-run


text:
Q: Accessing json objects with no name I'm struggling to access this json code below. Every json value I've previously seen is something like this:
 var hold = { name: 'alex', job: 'realtor'}

So to access the name I would do something like hold.name. But my json data looks like this
[
[
        {
            "count": "80",
            "countTxt":"Buyer logins",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"523"
        },
        {
            "count": "233",
            "countTxt":"Searches",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"628"
        },
        {
            "count": "533",
            "countTxt":"Views of our member pages",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"2,365"
        }
    ],

[
        {
            "count": "80",
            "countTxt":"Total vists",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"412"
        },
        {
            "count": "53",
            "countTxt":"Unique visitors",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"731"
        },
        {
            "count": "1:12 min",
            "countTxt":"Total time spent on page",
            "participantsTxt":"Total for all participating member companies:",
            "participantCount":"784.2 mins"
        }
    ]

]
The data is nested and it has no name so I don't know how to access. I know the question seems somewhat rudimental but I haven't seen any examples parse code that looks like this. It's always a more simple example like the one above. My .getjson code looks like this ...
var requestURL = 'assets/js/stats.json';
$.getJSON(requestURL, function(data){
        $.each(data, function(key, value) {
            $('body').append($('<div>' + data[0].name, {

            }));
            console.log(data);
        });

    });

My console is returning two objects that look like this
Array[3], Array[3]] Array[3]:
Array[3] [Array[3], Array[3]]

So I know it's getting data back I just need to be able to pick what I want a append it to the DOM. I've tried ten different variations but nothing works. Please help!?

A: You just need to iterate one more time inside first iteration. You have one array that holds array of objects. So try something like this
http://jsfiddle.net/mnth1xe1/5/
$.each(data, function(key, val) {
    $.each(val, function(key, value) {

        console.log(value.countTxt);
    });

});


text:
Q: Можно ли узнать размер реальной программы если в конец её исполняемого файла были дописаны другие данные? При нажатии пользователем на сайте кнопки "Скачать", PHP скрипт берёт с диска болванку установщика, написанного на C++, и дописывает ему в конец шифрованные персональные параметры пользователя (каждый раз новые, пароли меняются). При запуске установщик должен найти этот "хвост", расшифровать и инициализировать свои переменные полученными параметрами.
Сейчас для этой цели используется определённый строковый маркер в конце болванки, после которого и дописываются параметры, но маркер - крайне ненадёжная штука - он может случайным образом повториться в кодированных данных (теоретически это возможно) и... в результате string.rfind() будет не то смещение и в переменные запишется мусор...
Использовать точный размер изначального исполняемого файла для получения нужного смещения - беспроигрышный вариант, вот только как уже "испорченный" установщик поймёт сколько он весил перед добавлением "хвоста"?
Есть ли в C++ способ узнать размер реально рабочего кода? Или может по байтам можно понять куда в прочитанный в буфер с диска файл вписать его размер на момент file_get_contents() в php (объявив в болванке int self_size)?


text:
Q: MUI Override Slider color options with module augmentation I'm trying to solve a typescript error regarding the chosen color on my slider component:
<Slider
  color="brown"
/>

The error is: Type '"brown"' is not assignable to type '"primary" | "secondary" | undefined'.
I have set the brown color on my theme, by augmenting the createPalette file.
declare module '@mui/material/styles/createPalette' {
    interface Palette {
        brown: PaletteColor
    }

    interface PaletteOptions {
        brown: PaletteColorOptions
    }
}

So now that I still have the error I looked in the Slider.d.ts file and found an interface: SliderPropsColorOverrides.
export interface SliderPropsColorOverrides {}
...
color?: OverridableStringUnion<'primary' | 'secondary', SliderPropsColorOverrides>;

I try to merge it with my brown color:
declare module '@mui/material/Slider' {
    interface SliderPropsColorOverrides {
        darkest_blue: PaletteColorOptions
    }
}

But with no luck. Either my IDE (PhpStorm 2021.3) isn't compiling the new typescript code, or I'm missing something.

A: You were very close to something that would work, but the value for the augmentation of SliderPropsColorOverrides should just be true rather than PaletteColorOptions.
In my example sandbox I have the following key pieces:
createPalette.d.ts
import "@mui/material/styles/createPalette";
declare module "@mui/material/styles/createPalette" {
  interface Palette {
    brown: PaletteColor;
  }
  interface PaletteOptions {
    brown: PaletteColorOptions;
  }
}

Slider.d.ts
import "@mui/material/Slider";

declare module "@mui/material/Slider" {
  interface SliderPropsColorOverrides {
    brown: true;
  }
}

There was one other problem that I addressed in a rather ugly fashion. The Slider prop-types were still causing a runtime validation message for the color prop. I found comments in some open issues about color customization that mention this prop-types aspect and I suspect it will eventually be addressed by MUI, but it might not be addressed for a while. In my sandbox, I work around this by creating a SliderPropTypesOverride.ts file in which I copied MUI's SliderRoot.propTypes.ownerState and then modified the color portion to include "brown". This copying of the prop-types definitely isn't ideal from a maintenance standpoint, but at the moment I don't see another way to address the runtime warning in dev mode.
Then this all gets used as follows:
demo.tsx
import React from "react";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import "./SliderPropTypesOverride";
import Slider from "@mui/material/Slider";

const defaultTheme = createTheme();
const theme = createTheme({
  palette: {
    brown: defaultTheme.palette.augmentColor({
      color: {
        main: "#A52A2A"
      },
      name: "brown"
    })
  }
});

export default function Demo() {
  return (
    <ThemeProvider theme={theme}>
      <Slider color="brown" />
    </ThemeProvider>
  );
}

Related answers:

*

*Typescript Module augmentation is not working: Property 'main' does not exist on type 'PaletteColorOptions'

*How to add custom colors name on Material UI with TypeScript?

A: I would review the documentation on this.
https://mui.com/customization/palette/
It doesn't seem that you're able to override the color of the component directly and instead (if you have one) need to create a global theme object with the appropriate declaration files in order to override the color.
Also see this answer:
Extending the color palette with TS


text:
Q: Random array not giving desired result php (laravel 5.3) I have array with 2 indexes 0 and 1 i want when i call it should select random from these indexes
my array is as
'schools' => [
    'records' => [
        'students' => [
            'add' => [
            'text 1',
            'text 2'
            ],
        ],
    ],
],

here my array is as
trans('app.schools.records.students.add')

Its now pick both text 1 and text 2 so i passed it 2 my method in helper as
{{gettitles(trans('app.schools.records.students.add'))}}

My get gettitles method looks as
function gettitles ($array){
  $rand_keys = array_rand($array, 2);
  echo $array[$rand_keys[0]] . "\n";
  echo $array[$rand_keys[1]] . "\n";
}

Its always pick up both if i echo index 0 its only ist text...
But i want only one randomly from both text 1 and text 2
Please Help to fix it
Thanks

A: $rand_keys = array_rand($array, 2);

You're telling it to return 2 elements. The 2 is the number of random elements to return. Change it to a 1.
$rand_keys = array_rand($array, 1);

http://php.net/manual/en/function.array-rand.php
This code is tested and works:
$myArray = array("test 1", "test2");

gettitles($myArray);

function gettitles ($array){
    $rand_keys = array_rand($array, 1);
    echo $array[$rand_keys] . "\n";
}

The function you're choosing to use array_rand returns the key to the random elements, not the content of the element itself.

A: array_rand function
picks one or more random entries out of an array, and returns the key (or keys) of the random entries. It uses a pseudo random number generator that is not suitable for cryptographic purposes.
So, instead of 2 pass 1.
function gettitles ($array){
  shuffle($array);
  $rand_keys= array_values($array);
  echo $array[$rand_keys[0]] . "\n";
  echo $array[$rand_keys[1]] . "\n";
}

It will work.
EDIT
And use combo of shuffle function with array_values it will work.
function gettitles ($array){
  shuffle($array);
  $rand_keys= array_values($array);
  echo $array[$rand_keys[0]] . "\n";
  echo $array[$rand_keys[1]] . "\n";
}

EDIT 2
function gettitles ($array){
  shuffle($array);
  $rand_keys= array_values($array);
  echo $rand_keys[0] . "\n";
  echo $rand_keys[1] . "\n";
}


text:
Q: C# Syntax error in INSERT INTO statement. Am I not seeing something? I'm having a hard time with this SQL Insert command. I've written other insert commands that work fine, but this one keeps giving me an error that says "Syntax error in INSERT INTO statement." Can somebody help me see what I'm missing?
        bool recordSaved;

        // Opens a connection to the database

        OleDbParameter param = new OleDbParameter();
        OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + "");
        conn.Open();
        OleDbCommand command = conn.CreateCommand();

        string strSQL;

        command.Parameters.Add(new OleDbParameter("@Password", Password));
        command.Parameters.Add(new OleDbParameter("@FName", FName));
        command.Parameters.Add(new OleDbParameter("@LName", LName));
        command.Parameters.Add(new OleDbParameter("@Street", StreetAddress));
        command.Parameters.Add(new OleDbParameter("@City", City));
        command.Parameters.Add(new OleDbParameter("@State", State));
        command.Parameters.Add(new OleDbParameter("@Zip", Zip));
        command.Parameters.Add(new OleDbParameter("@Phone", PhoneNumber));
        command.Parameters.Add(new OleDbParameter("@CCType", CCType));
        command.Parameters.Add(new OleDbParameter("@CCNum", CCNumber));

        // Inserts a new user record into the database
        strSQL = "INSERT INTO tblUser (Password, FName, LName, StreetAddress, City, State, Zip, PhoneNumber, CCType, CCNumber) " +
            "VALUES (@Password, @FName, @LName, @Street, @City, @State, @Zip, @Phone, @CCType, @CCNum)";

        // Stores the strSQL insert statement into a command object
        command.CommandText = strSQL;

        // Executes the insert statement
        command.ExecuteNonQuery();
        command.Parameters.Clear();

        // Closes the connection to the database
        conn.Close();

A: It looks like Password might be your problem. Try putting parentheses around it INSERT INTO tblUser ([Password]. From what I just read its a reserved word for the jet.oledb.


text:
Q: Neater presentation of a facet_grid in ggplot? I'm interested in trying to visualize data in ggplot, but I'm sure I'm not approaching it the correct way. I'd like to take this visualization:
library(ggplot2)
ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) + geom_line()

and break it out into a different plot per chick. My very naive approach was to use a facet_grid() for each chick:
ggplot(ChickWeight, aes(x=Time, y=weight)) + facet_grid(Chick ~ .)

But this produces an unusable result:

The result I'm looking for would be something like multiplot(), but I don't want to have to build 50 different plots, then multiplot on those.
I'm sure there's a straight-forward answer that's staring me in the face, but my ggplot hacking skills aren't super finely tuned.


text:
Q: Set permissions for "all" to same permissions as owner I have a very large base of files with varying permissions. I'd like to allow everyone with access to the server the same permissions as I have currently (since I created all of the files).
Is it possible to give the "other" or "all" group the same permissions as are currently set for the "owner" group?
Example:
drwxr-xr-x folder_1
-r-xr--r-- file_1.txt

Becomes:
drwxrwxrwx folder_1
-r-xr-xr-x file_1.txt

This would have to be recursive as it's going to affect many directories and files - can this be done through chmod?

A: You can set all to user by using the a=u:
chmod a=u file1 file2 file3 prefix*


text:
Q: How to perform raw SQLite query (With multiple row result) through SQLiteAsyncConnection I do not have a class map to a table. I'm referring to the following thread. The get the number of row in a table, I am applying the following technique
How to perform raw SQLite query through SQLiteAsyncConnection
SQLiteAsyncConnection conn = new SQLiteAsyncConnection(DATABASE_NAME);
int profileCount = await conn.ExecuteScalarAsync<int>("select count(*) from " + PROFILE_TABLE);

Now, instead of obtaining result as number of row, I would like to retrieve result in multiple row data.
In Java, to obtain multiple row result data, I would perform
Cursor cursor = database.rawQuery(sql, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    // For every cursor, obtain its col data by
    // cursor.getLong(0), cursor.getInt(1), ...
    cursor.moveToNext();
}

Given a same sql statement, how can I achieve using SQLiteAsyncConnection?

A: I added 2 new functions into SQLite.cs. Not elegant, but it works for me.
    // Invented by yccheok :)
    public IEnumerable<IEnumerable<object>> ExecuteScalarEx()
    {
        if (_conn.Trace)
        {
            Debug.WriteLine("Executing Query: " + this);
        }

        List<List<object>> result = new List<List<object>>();
        var stmt = Prepare();

        while (SQLite3.Step(stmt) == SQLite3.Result.Row)
        {
            int columnCount = SQLite3.ColumnCount(stmt);

            List<object> row = new List<object>();
            for (int i = 0; i < columnCount; i++)
            {
                var colType = SQLite3.ColumnType(stmt, i);
                object val = ReadColEx (stmt, i, colType);
                row.Add(val);
            }
            result.Add(row);
        }
        return result;
    }

    // Invented by yccheok :)
    object ReadColEx (Sqlite3Statement stmt, int index, SQLite3.ColType type)
    {
        if (type == SQLite3.ColType.Null) {
            return null;
        } else {
            if (type == SQLite3.ColType.Text) {
                return SQLite3.ColumnString (stmt, index);
            }
            else if (type == SQLite3.ColType.Integer)
            {
                return (int)SQLite3.ColumnInt (stmt, index);
            }
            else if (type == SQLite3.ColType.Float)
            {
                return SQLite3.ColumnDouble(stmt, index);
            }
            else if (type == SQLite3.ColType.Blob)
            {
                return SQLite3.ColumnBlob(stmt, index);
            }
            else
            {
                throw new NotSupportedException("Don't know how to read " + type);
            }
        }
    }


text:
Q: using Regex to match something from left Train from London to Boston - match
Train from Boston to London
Train from Cardif to London
Bus from London to Paris - match

How can I match if London appear before any other cities with regex? I can do it with string matching with loop in JavaScript but I think regex is better.

A: Get lines which includes London to

var str = `Train from London to Boston - match
Train from Boston to London
Train from Cardif to London
Bus from London to Paris - match`,
  city = 'london';

console.log(
  str.match(new RegExp('^.*\\b' + city + '\\sto\\b.*$', 'gmi'))
)

Regex explanation here

A: Try this
\bLondon(?=\s*to\b)

Regex demo
Explanation:
\: Escapes a special character sample
(?=…): Positive lookahead sample
\s: "whitespace character": space, tab, newline, carriage return, vertical tab sample
*: Zero or more times sample
Javascript
var re = /\bLondon(?=\s*to\b)/g;
var str = 'Train from London to Boston - match\nTrain from Boston to London\nTrain from Cardif to London\nBus from London to Paris - match';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    // View your result using the m-variable.
    // eg m[0] etc.
}


text:
Q: After upgrading from Postgres 9.2.4 to Postgres 10.5 query is 170x slower We recently upgraded our Postgres database from 9.2 to 10.5.
We noticed a somewhat odd behavior with a query that under the same circumstances became 170x slower.
The query does a join between 2 tables on 'id' column.
SELECT A.id, A.session
FROM A
JOIN B on A.id = B.f_id
WHERE A.session = 0;

Size of A is ~43K rows.
Size of B is varying from 0 to several thousands.
The execution plan generated by PG 10.5:
Nested Loop (cost=0.54..12.83 rows=1 width=18) (actual time:883.156...883.157 rows=0 loops=1)
  Join Filter: (A.id = B.f_id)
  -> Index Scan using A_session_index on A (cost=0.29..4.55 rows=1 width=18) (actual time=0.032..2.251 rows=1600 loops=1)
    Index Cond: (session > 0)
  -> Index Only Scan using B_f_id_index on B (cost=0.25..8.27 rows=1 width=16) (actual time:0.549..0.549 width=0 loops=1600)
    Heap Fetches: 3074334
Planning time: 0.537 ms
Execution time: 883.189 ms

While the execution plan generated on 9.2 looks like:
Nested Loop (cost=4.28..18.30 rows=1 width=18) (actual time:5.484...5.484 rows=0 loops=1)
  -> Index Scan using A_session_index on A (cost=0.00..4.48 rows=1 width=18) (actual time=0.013..0.918 rows=1600 loops=1)
       Index Cond: (session > 0)
  -> Bitmap Heap Scan on B (cost=4.28..13.78 rows=3 width=16) (actual time:0.002..0.002 width=0 loops=1600)
       Recheck Cond: (f_id = A.id)
       -> Bitmap Index Scan on f_id_index (cost=0.00..4.27 rows=3 width=0) (actual time=0.001..0.001 rows=1 loops=1600)
            Index Cond: (f_id = A.id)
Total runtime: 5.516 ms

We have application flows where this query could execute thousands of times.
Resulting a severe degradation in our application.
At first glance it looks like a simple "Analyze" operation would solve the bad performance by changing plan.
However, this code runs in a context where we can't just execute proactive "Analyze" each time before it happens.
Also we noticed that trying to "time" the Analyze operations is becoming more and more difficult and we have many false negatives.
We didn't change the default auto vacuum/analyze settings.
Although we considered it seriously, we didn't change the auto analyze config.
In order to suit it for this behavior we have to set it to run every ~1000 modification to the table.
Since size of table A could grow to 10 mil, having auto analyze run this much is a bit disturbing.
We didn't change any of the other configurations in postgresql.conf we had in PG 9.2.
I would like to know if this is a known bug and perhaps was fixed in later version.
Or if there is a configuration to tune in order for the planner to behave as it used to be.


text:
Q: Do iterative methods reduce cyclomatic complexity and improve supportability? Do iterative methods such as are commonly found in modern languages such as C#, JavaScript, and (hopefully) in Java 8 reduce cyclomatic complexity's impact on understandability and supportability of code?
For example in C# we might have the following code:
List<String> filteredList = new List<String>();

foreach (String s in originalList){
   if (matches(s)){
      filteredList.add(s);
   }
}

This has a simple cyclomatic complexity of 2.
We could easily re-write this as:
List<String> filteredList = originalList.where(s => matches(s));

Which has a simple cyclomatic complexity of 0.
Does this actually result in more supportable code?  Is there any actual research on this topic?

A: In order to answer the question objectively, we'd need some sort of metric for maintainability. Cyclomatic complexity itself isn't a measure of maintainability, but it is a component of some metrics that purport to measure maintainability. For example, the formula for the Maintainability Index is:
MI = 171 - 5.2 * ln(V) - 0.23 * (G) - 16.2 * ln(LOC)

where G is the cyclomatic complexity of the code in question. Therefore, reducing the cyclomatic complexity of a piece of code does by definition improve the code's Maintainability Index and other metrics which similarly use cyclomatic complexity.
It's hard to say whether the kind of change you propose makes the program seem more maintainable to programmers; that probably depends on how familiar they are with (in your case) the where method.

A: Because it has been shown that cyclomatic complexity (CC) is very strongly correlated with code size, "so much so that CC can be said to have absolutely no explanatory power of its own." what you are really asking is whether "iterative methods such as are commonly found in modern languages such as C#, JavaScript, and (hopefully) in Java 8 reduce code size's impact on understandability and supportability of code."
At that point, one would hope that the answer would be obvious.  It has been known for decades that shorter code is generally easier to understand, maintain, and support.

A: If you're talking about the raw stat of Cyclomatic Complexity, sure.  You just nuked it from 2 to 0.  If you're going by numbers, pure gain, all the way.
From a practical (read: human) perspective though, I would argue you've actually increased the complexity by 2.  One point of that comes from the fact that now some other programmer must bring or get knowledge of fluent-syntax LINQ to understand this code.
Another point of increased difficulty comes from understanding Lambda Expressions; though a Lambda is fairly straightforward in this instance, there are some paradigm shifts that have to be made to fully appreciate them.
This case, using a.where(x => matches(x, arg)) isn't terrible, and in all honesty is a great way to get some coworker to see and work with LINQ and Lambda expressions for the first time (I actually presented a tutorial on LINQ/Lambdas to some former coworkers using this and other sets of code, to great effect.)  However, the usage of these does require some knowledge.
I recommend caution, because I've seen cases where the LINQ refactor is actually significantly worse to read than what that foreach loop becomes.

A: My guess is that you just divided/moved the complexity. It decreased because you doesn't count the implementation of .where() in your CC.
The overall CC hasn't really moved, your own code's CC decreased, only because it's now moved to the framework's code.
I'd say it's more maintainable. When it's a feature of the language, use it. It's no a "ohh, I see, it's a clever trick" that you're using, only a simple inline reduce-like function.

A: All you are doing is highlighting a flaw in cyclomatic complexity as a metric, the complexity of the code really hasn't changed. You have an explicit branch in the first example and need to understand there is an implied branch in the second. The second is clearer and easier to understand provided you understand the syntax, and since it uses less basic syntax that may be an issue.

A: Subjectively, it depends on the developer audience, if they understand lambda expressions, then;
List<String> filteredList = originalList.where(s => matches(s));

is quicker to understand, and perhaps slightly easier.  I would be more concerned about using s, and matches().  Neither is self-descriptive, something like;
List<String> filteredList =
    originalList.where(stringToBeTested => matchesNameTest(stringToBeTested));

Or
List<String> filteredList =
        originalList.where(originalListString => matchesNameTest(originalListString));

gives the developer more meaningful information and is easier to analyze, without having to dive into the matches() function to determine what match is being performed.
Maintainability is not only about the ability to comprehend the code, but mainly about the speed and accuracy with which one can comprehend the code.


text:
Q: Is it correct to use UI and Model for Backbone.Marionette's Layout View? in Backbone.Marionette the Layout View extends the item view and therefor it has the UI elements and can handle a Model. But is it semantically, Philosophically correct to assign a model to a layout view and bind UI elements to it? or a Layout should only have regions and a template?

A: TL;DR I believe the Marionette philosophy is to minimize the semantics. The methods defined in Marionette.View where selected to be inherited by all Marionette views.  While all derivative Marionette views are better at what they're designed for, they are still a Marionette.View.

As of the creation date of this post I've been using Marionette on a daily basis on an enterprise project for over a year. I try to stay active in the community and keep abreast of edge Marionette releases.
From my experience, Marionette imposes an opinion on how to build and manipulate views, but it consciously tries to keep it's views as flexible and general as possible. To wit, see this issue, where @jmeas (a major Marionette contributor and visionary) envisions reducing Marionette to LayoutViews and CollectionViews!
I think the best answer to your question is, if the method is natively available in your view, it's not an accident. The Marionette View inheritance structure has been heavily tested. I've yet to see a method in any derivative View that contradicts the semantics of that View.

UPDATE I think it is worhwhile to point out that there is a potentially major caveat to rendering a model inside a LayoutView template.
Consider this scenario. You have a LayoutView with a model, and at least one region. You also .show() a sub-view in a region of the LayoutView. Now, the data in the LayoutView is updated in a different view, and you want to dynamically update your LayoutView. If you render the LayoutView again, then the whole view gets discarded, including the sub-view that was rendered, demanding a second render of that sub-view.
In some situations this could be a significant performance hit. And there may be other issues depending on how that sub-view was originally handled in the LayoutView.

A: It is definitely correct to use a model in layout view. I could think of various use case cases where it might be useful:

*

*Showing some dynamic attribute which is present in a model.

*Passing the values from one view to another ans so on.

*Listening ans responding to a change in its model attributes.