text:
Q: Modelica Time Dependent Equations I am new to Modelica, and I am wondering if it is possible to write a kind of dynamic programming equation. Assume time is discretized by an integer i, and in my specific application x is boolean and f is a boolean function of x.
x(t_i) = f(x(t_{i+d}))

Where d can be a positive or negative integer. Of course, I would initialize x accordingly, either true or false.
Any help or references would be greatly appreciated!

A: It is possible. In Modelica the discretization in time is usually carried on by the compiler, you have to take care of the equations (continous dynamics). Otherwise, if you want to generate events at discrete time points, you can do it using when statements.
I suggest you to take a look at Introduction to Object-Oriented Modeling and Simulation with OpenModelica (PDF format, 6.6 MB) - a more recent tutorial (2012) by Peter Fritzson. There is a section that on Discrete Events and Hybrid Systems, that should clarify how to implement your equations in Modelica.
Below you can find an example from that tutorial about the model of a bouncing ball, as you can see discretization in time is not considered when you write your dynamic equations. So the continous model of the ball v=der(s), a=der(v) and than the discrete part inside the when clause that handles the contact with the ground:
model BouncingBall "the bouncing ball model"
  parameter Real g=9.81; //gravitational acc.
  parameter Real c=0.90; //elasticity constant
  Real height(start=10),velocity(start=0);
equation
  der(height) = velocity;
  der(velocity)=-g;
  when height<0 then
    reinit(velocity, -c*velocity);
  end when;
end BouncingBall;

Hope this helps,
Marco

A: If I understand your question, you want to use the last n evaluations of x to determine the next value of x.  If so, this code shows how to do this:
model BooleanHistory
  parameter Integer n=10 "How many points to keep";
  parameter Modelica.SIunits.Time dt=1e-3;
protected
  Boolean x[n];
  function f
    input Integer n;
    input Boolean past[n-1];
    output Boolean next;
  algorithm
    next :=not past[1]; // Example
  end f;
initial equation
  x = {false for i in 1:n};
equation
  when sample(0,dt) then
    x[2:n] =  pre(x[1:(n-1)]);
    x[1] =  f(n, x[2:n]);
  end when;
end BooleanHistory;


text:
Q: Is there a reason to do PCA on disjoint subsets of variables rather than all the variables? Principle component analysis (PCA) is a coordinate transformation of the original data, so that the projection of the data onto the first new coordinate has the greatest variance. I want to know whether there are situations where it is advantageous to split the variables into disjoint subsets, and doing PCA on each subset, instead of doing one PCA on all the data.
In matrix notation, suppose we have a data matrix $M$, of size $n_{\text{obs}} \times p$. That is, the number of rows in $M$ is equal to the number of observations, and the number of columns equal to the number of variables. The new coordinates for each observation is given by $MT$, where $T$ is a $p \times p$ matrix. If the variables are split into subsets, and arranged appropriately, $T$ will be block diagonal.

A: Perhaps you believe that there are two different sets of correlated variables that are independent, i.e. there two sets are uncorrelated with each other. So you run PCA on one of the sets and then on the other and then you can check whether they return a similar projection or a very different one and you could check how far the two projections are from each other.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter dart generic constraint with some special keywords? Hi everyone I'm newbie to dart but I have learn in C# for a while. Is there any generic constraint such as new() factory() in dart ?
(The factory() one is which limit the T has factory constructor)
class SuperDog<T is new(),factory()>

class Snoopy {

  factory Snoopy() {
    return ...
  }

}

A: you use the factory pattern in dart.   Generics are allowed.
Generics follow the pattern
class Cache<T> {
   final T _obj;
   Cache(this._obj);
   get value=> _obj;
}
Cache c=Cache<String>("Hello World")
debugPrint(c.value);

I demonstrate how to create a class factory in dart.
@JsonSerializable()
class EmployeeView {
  final int hrCo;
  final int employee;
  final String lastName;
  final String firstName;

  EmployeeView(
      this.hrCo,
      this.employee,
      this.lastName,
      this.firstName);

  factory EmployeeView.fromJson(Map<String, dynamic> json) =>
      _$EmployeeViewFromJson(json);

  Map<String, dynamic> toJson() => _$EmployeeViewToJson(this);
}

employeeView.g.dart    (builder_runner creates this code)
EmployeeView _$EmployeeViewFromJson(Map<String, dynamic> json) {
      return EmployeeView(
        json['hrCo'] as int,
        json['employee'] as int,
        json['lastName'] as String,
        json['firstName'] as String,
      );
    }

Map<String, dynamic> _$EmployeeViewToJson(EmployeeView instance) =>
    <String, dynamic>{
      'hrCo': instance.hrCo,
      'employee': instance.employee,
      'lastName': instance.lastName,
      'firstName': instance.firstName,
    };

run builder to generate you .g file.  you don't edit the g file
flutter pub run build_runner build


text:
Q: Kafka in distributed system I am new to kafka , i am running kafka in a single machine as of now. I want to run kafka in an distributed environment on multiple machines. There is no proper documentation for this. Any documentation or suggestion on this will be really helpful.

A: Adding on to the previous answer by user2720864
Let us assume that Kafka system with below configuration is needed.
7 Kafka nodes
3 Zoo keepers
To achieve this install 7 Kafka instances, in 7 different server/vm(instances), and in each of these instances set a different broker-id, this will let the zookeeper identify the different kafka nodes for bookkeeping, maintenance.
broker.id=X (/config/server.properties)
To start zookeepers, you can use 3 of the previous kafka instances or can use new servers to start zookeepers. Once the servers on which zookeepers run are decided, change the /config/server.properties to specify zookeepers.
zookeeper.connect=hostname1:port1,hostname2:port2
In a distributed environment its nice to have 3 zoo keepers. While there is only one zookeeper which acts as a true master, other 2 zookeepers act as fail overs. When the master fails one of the two ZKs will take over as master.
I found this link to be very useful, it helped me clarify a lot of things about kafka architecture.
This is a good reference for all the configurations on the property files in kafka.
Hope this helps!

A: Basically you need to do the follwing
1) Set up kafka on all the machines
2) Configure the config/server1.properties properties file to specify an unique id for each machines. You can do that by setting the broker.id properties in the config file. e.g. broker.id=1, broker.id=2. For every brokers this id should be unique. This is how every node is identified in a kafka cluster.
3) Start kafka in all nodes
You can refer Step 6: Setting up a multi broker cluster from their official quick start page.
Also here is a nice article worth taking a look


text:
Q: Extjs and Spring success handler I'm building web application with ExtJs and Spring. With ExtJs I'm uploading excel file and with spring I parse it. Everything works fine, although my success handler in ExtJs code doesn't work. I read many examples about that, but I still can't solve this problem. I hope you guys will help me.
This is ExtJs upload file function:
uploadFile: function(value, fld){
    var me = this;
    var id = this.getTipasCombobox().getValue();
    var record = this.getTipasCombobox().getStore().getById(id);
    var timeId = this.getLaikotarpiaiCombo().getValue();
    var timeRecord = this.getLaikotarpiaiCombo().getStore().getById(timeId);
    var fp = this.getUploadBtn().up('form').getForm();
    if(fp.isValid()){
        fp.submit({
            url: Turtas.Properties.getServicePath()+'/save/' + record.data.resource,
            waitMsg: 'Failas yra įkeliamas, prašome palaukti...',
            success: function(){
                console.log("Upload completed");
                me.storeSelection(record.data.resource, timeRecord.data.open, timeRecord.data.year, true, me.restrictedPage())
            }
        })
    }
},

And this is my controller function which I use to parse Excel:
@RequestMapping(value="turtas/save/gelezinkeliai", method=RequestMethod.POST)
public String saveGelezinkeliaiFromExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file){
    if (file.getSize() != 0){
        ReadExcelFileToList excelFile = new ReadExcelFileToList();
        List<Gelezinkeliai> gelezinkeliai = new ArrayList<Gelezinkeliai>();
        gelezinkeliai = excelFile.readExcelData(/*fileName*/ file);
        gelezinkeliai.remove(0);
        Laikotarpis laikotarpis = new Laikotarpis();
        laikotarpis = laikotarpiaiService.findById(2014);

        for (GelezinkeliaiRest delGelezinkelis : service.getItems(2014, true, false)){
            service.delete(delGelezinkelis);
        }
        List<Gelezinkeliai> finalGelezinkeliai = new ArrayList<Gelezinkeliai>();
        for (Gelezinkeliai gelezinkelis : gelezinkeliai){
            gelezinkelis.setLaikotarpis(laikotarpis);
            finalGelezinkeliai.add(gelezinkelis);
            GelezinkeliaiRest gelezinkeliaiRest = new GelezinkeliaiRest();
            gelezinkeliaiRest.fromGelezinkeliai(gelezinkelis);
            service.save(gelezinkeliaiRest, false);
        }
        response.setContentType("text/html");
        return "{\"success\":true}";
    }
    else {
        return "{\"success\":false}";
    }

}

Response content-type is text/html and response is:
{"success":true}

If I manually reload page or store, data is updated, so functions work properly, but i want to catch event when the request ends, to reload store automatically. I have no idea what's wrong. Thanks for responses in advance!


text:
Q: BlockUI during a function in Angular In a web-app there is a button which call a function. How can I do if I want to insert a blockUI during the operation? Have I do a promise? Where in particular?
$scope.eraseDB = function(){
    database.destroylocalDB();
};

the function:
destroylocalDB: function(){

  localDB.destroy().then(function (response) {
      //Remove cache
      datacache.dr = [];
      database.initDB();
  }).catch(function (err) {
      console.log(err);
  });
}

A: Have you looked the Angular BlockUI?
Take a look at the documentation. After configuration, you will just need to:
destroylocalDB: function(){
  blockUI.start();
  localDB.destroy().then(function (response) {
      blockUI.stop();
      //Remove cache
      datacache.dr = [];
      database.initDB();
  }).catch(function (err) {
      blockUI.stop();
      console.log(err);
  });
}

EDIT:
To do what you want, you would need to change your service to return the promise:
destroylocalDB: function(){

  return localDB.destroy().then(function (response) {
      //Remove cache
      datacache.dr = [];
      database.initDB();
  }).catch(function (err) {
      console.log(err);
  });
}

So you can:
$scope.eraseDB = function(){
    blockUI.start();
    database.destroylocalDB().then(function(){
        blockUI.stop();
    });
};

I didn't test, but it should work.

A: You can also use a spinner to block your UI until your background operation is completed. Something like:
http://ngmodules.org/modules/angular-spinner


text:
Q: Save a PDF file of Sharepoint in a directory in java I am working in a jsp file. I have a lot of files available in my Sharepoint intranet with link like this :

http://myIntranet.eu/my%pdf%1.pdf

I want saved the pdf in a folder in my server. This will help me then to merge all PDF.
I had already merge pdf in java, but I don't know how I can save this PDF on my server.
Can you please help me on how to do that.

A: If there is no web service or rest service from sharepoint to get the pdf, you can try to use an http client http://hc.apache.org/httpcomponents-client-ga/ to make request to sharpoint on java server to get the pdf file. Maybe you need authentication.


text:
Q: How to include VCS information in setuptools packages I'm (trying) to use setuptools to build a package. I was trying to use a version number major.minor.mercurial_revision but it complains that:
The version specified ('1.0.7ae7970a82c1') is an invalid version, this may
not work as expected with newer versions of setuptools, pip, and PyPI.
Please see PEP 440 for more details.`

Fine. So I look at PEP 440 which says basically says "don't do that":
As hashes cannot be ordered reliably such versions are not permitted in the
public version field. As with semantic versioning, the public  .devN
suffix may be used to uniquely identify such releases for publication,
while the original DVCS based label can be stored in the project metadata.

I understand the logic here. But how can I include the hg revision in the project metadata? I can't find any (up-to-date) documentation for what the arguments to setup.py:setup() can include, but the distutils one I found here doesn't seem to provide a field for this.

A: What about just including it as an attribute in your Python code?
echo '__revision__ = $HG_HASH' > mypackage/revision.py

Once installed, you can:
from mypackage.revision import __revision__
print 'build from', __revision__

Or you could write it to a file, and include that in your source distribution via MANIFEST.in.
You could even include it directly in the arguments to setup(), which seems to simply ignore unknown keyword arguments:
setup(name='Distutils',
      version='1.0',
      description='Python Distribution Utilities',
      author='Greg Ward',
      author_email='gward@python.net',
      url='https://www.python.org/sigs/distutils-sig/',
      packages=['distutils', 'distutils.command'],
      revision='7ae7970a82c1',
     )

This doesn't get recorded anywhere, but it is always available by inspection if someone needs to know it for debugging information or something.  Because this relies on setup() ignoring unknown arguments -- which I'm not sure is explicitly documented behavior -- I don't know that this idea is actually one I would recommend.

A: You can use a local version identifier to accomplish this.

Local version identifiers MUST comply with the following scheme:
<public version identifier>[+<local version label>]

In your case this would be <major>.<minor>+<mercurial_version>, which would result into 1.0+7ae7970a82c1


text:
Q: Error MSB4094: how can archieve my project? I get this error and I can't archieve my project...
MSB4094: "obj\Release\90\testUC.Android.dll;obj\Release\90\testUC.Android.dll" is an invalid value for the "OutputAssembly" parameter of the "Csc" task. Multiple items cannot be passed into a parameter of type "Microsoft.Build.Framework.ITaskItem".
Done building project "testUC.Android.csproj" -- FAILED.
Build FAILED.
it looks like that the first trial worked but then no more...
Any idea?

A: Try those steps:

*

*Close your Visual Studio.

*Remove .vs folder.

*Relaunch and build


text:
Q: how to Convert an ArrayList of Strings to an ArrayList of ArrayList of Strings with the same length strings grouped into a list together I have an array list of strings (each individual element in the array list is just a word with no white space) and i want to group the same length elements in separate ArrayLists.
So say the array list has
element 0 = "abcd"
element 1 = "ansd,"
element 2 = "bac"
element 3 = "abc"
element 4 = "cab"

My result should be ArrayList(ArrayList(String))->{{"abcd","ansd"} , {"bac","abc","cab"}}

A: Never mind, I found the solution.
This problem is somewhat similar to finding the number of repeated characters in a String.
Here is the solution to my problem.
public static void main(String[] args){

ArrayList<String> A= new ArrayList<String>();
A.add("abc");
A.add("bac");
A.add("abcd");
A.add("cabd");

ArrayList(ArrayList(String)) C=new ArrayList(ArrayList(String))();

HashMap(Integer, ArrayList(String)) hm1= new HashMap(Integer, ArrayList(String))();

for (int i=0;i is less than A.size();i++){

    ArrayList<String> B;

    if (!hm1.containsKey(A.get(i).length())){
        B=new ArrayList<String>();
        B.add(A.get(i));
        hm1.put(Integer.valueOf(A.get(i).length()), B);

    }
    else
        hm1.get(A.get(i).length()).add(A.get(i));
}
for (Map.Entry m: hm1.entrySet()){

    C.add((ArrayList<String>) m.getValue());
}

}

If someone has a better solution then please post.


text:
Q: How to stylize table  based on its value from ajax with datatables I have a page showing datatables using php. As the data is increasing day by day, I have considered datatable ajax function to get it processed server side to reduce time taken to load all the data at once.
But the problem is I can't figure out how to style  based on its values. For example:

What I'm using with PHP:

    Date
    Amt
    Status

<?php while ($data = $sql->fetch(PDO::FETCH_OBJ)) {
  echo "

      ".$data->date."
      ".$data->amt."	";

      // Please note this step...
      if ($data->status == "Paid") {
       echo '

          '.$data->status.'
        	';
       }
      elseif ($data->status == "Unpaid"){
       echo '

         '.$data->status.'
        	';
      }
      elseif ($data->status == "Pending"){
       echo '

         '.$data->status.'
        	';
      }
echo '
';
}

How to achieve the same  style on  with data from
  datatables ajax:

    <thead

        Date
        Amt
        Status

$(document).ready(function() {
    //$('#datatable-buttons').DataTable( {
    var table = $('#datatable-ajax').DataTable( {
    "ajax": {
        "url": "scripts/json.php",
        "dataSrc": ""
    },
    "columns": [
        { "data": "date" },
        { "data": "amt" },
        { "data": "status" },
    ]
} );

A: Add following function to $(document).ready(function() { . I have kept 3 seconds delay to take care of ajax. You can adjust the same.
            setTimeout(
            function()
            {
              //do something special
              $('table>tbody>tr>td:nth-child(3)').each(function() {
                //alert($(this).text());
                if($(this).text() === "Paid" ){
                    $(this).addClass('label label-succcess');
                }
                else if($(this).text() === "Unpaid" ) {
                    $(this).addClass('label label-danger');
                }
                else if($(this).text() === "Pending" ) {
                    $(this).addClass('label label-warning');
                }
              });
            }, 3000);


text:
Q: Convert raw javascript object array into structured object tree ready for ng-repeat I am building an app with node.js, mssql (don't ask.. client), socket.io and angularjs.
I have managed to get data from mssql to angular in the following form.
[
    {
        "measure":"value",
        "region":"London",
        "manager":"Jack",
        "supervisor":"James",
        "number1":44,
        "number2":2244.3,
        "number3":1561.6
    },
    {
        "measure":"value",
        "region":"London",
        "manager":"Jack",
        "supervisor":"Jerry",
        "number1":335.4,
        "number2":33.3,
        "number3":11.6
    },
    {
        "measure":"value",
        "region":"London",
        "manager":"John",
        "supervisor":"Joseph",
        "number1":444.3,
        "number2":233,
        "number3":1561.6
    }
]

I am trying to manipulate the data through angular.forEach to achieve the following result:
[
    {
        "region": "London",
        "regionTotals" : {
            "turnover" : {
                "number1" : "TOTAL OF NUMBER 1 WITH REGION LONDON",
                "number2" : "TOTAL OF NUMBER 2 WITH REGION LONDON",
                "number3" : "TOTAL OF NUMBER 3 WITH REGION LONDON"
            }
        },
        "managers" : {
            "jack" : {
                "managerTotals" {
                    "number1": "TOTAL OF NUMBER 1 WITH MANAGER JACK",
                    "number2": "TOTAL OF NUMBER 2 WITH MANAGER JACK",
                    "number3": "TOTAL OF NUMBER 3 WITH MANAGER JACK"
                },
                "supervisors" : {
                    "Jerry": {
                        "supervisorTotals" : {
                            "number1":335.4,
                            "number2":33.3,
                            "number3":11.6
                        }
                    },
                    "James": {
                        "supervisorTotals" : {
                            "number1":44,
                            "number2":2244.3,
                            "number3":1561.6
                        }
                    }
                }
            },
            "john" : {
                "managerTotals" {
                    "number1": "TOTAL OF NUMBER 1 WITH MANAGER JOHN",
                    "number2": "TOTAL OF NUMBER 2 WITH MANAGER JOHN",
                    "number3": "TOTAL OF NUMBER 3 WITH MANAGER JOHN"
                },
                "supervisors" : {
                    "Joseph": {
                        "supervisorTotals" : {
                            "number1":444.3,
                            "number2":233,
                            "number3":1561.6
                        }
                    }
                }
            }
        }
    }
]

Is this the best way to do this? And if you have any advice on how to run it through a javascript loop it would be much appreciated as I'm struggling big time. Especially trying to set the object keys.
The only other way I can think of doing it is running a bunch of queries in node and putting it together server side rather than client side. However considering I'm using mssql I wanted to keep queries to a bare minimum.
Thanks

A: I wont say this is the best solution but rather a solution which achieves your goal
I have flattened the JSON into the corresponding structure by using certain iteration with .reduce and angular.forEach. The $scope.flattenedRecord contains the converted JSON
Working Demo
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
    $scope.records = [{
        "measure": "value",
            "region": "London",
            "manager": "Jack",
            "supervisor": "James",
            "number1": 44,
            "number2": 2244.3,
            "number3": 1561.6
    }, {
        "measure": "value",
            "region": "London",
            "manager": "Jack",
            "supervisor": "Jerry",
            "number1": 335.4,
            "number2": 33.3,
            "number3": 11.6
    }, {
        "measure": "value",
            "region": "London",
            "manager": "John",
            "supervisor": "Joseph",
            "number1": 444.3,
            "number2": 233,
            "number3": 1561.6
    }];

    $scope.flattenedRecord = [];

    $scope.managers = [];
    $scope.region = [];

    $scope.records.reduce(function (result, item) {
        $scope.managers.push(item.manager);
        $scope.region.push(item.region);
    }, 0);

    $scope.managers = _.uniq($scope.managers);
    $scope.region = _.uniq($scope.region);

    var mainRecordobj = {};

    angular.forEach($scope.region, function (regionValue) {
        mainRecordobj.region = regionValue;
        var regionTurnoverObj = {};
        var regionNumberObj = {};
        var regionTotalsObj = {};

        var supervisorTotalsObj = {};
        var supervisorNumberObj = {};
        var supervisorNameObj = {};

        var managerTotalsObj = {};
        var managerNameObj = {};
        var managerNumberObj = {};

        regionNumberObj.number1 = "TOTAL OF NUMBER 1 WITH REGION " + regionValue.toUpperCase();
        regionNumberObj.number2 = "TOTAL OF NUMBER 2 WITH REGION " + regionValue.toUpperCase();
        regionNumberObj.number3 = "TOTAL OF NUMBER 3 WITH REGION " + regionValue.toUpperCase();

        angular.forEach($scope.managers, function (managerName) {

            managerNumberObj = {};
            managerNumberObj.number1 = "TOTAL OF NUMBER 1 WITH MANAGER " + managerName.toUpperCase();
            managerNumberObj.number2 = "TOTAL OF NUMBER 2 WITH MANAGER " + managerName.toUpperCase();
            managerNumberObj.number3 = "TOTAL OF NUMBER 3 WITH MANAGER " + managerName.toUpperCase();
            managerTotalsObj = {};

            managerTotalsObj.managerTotals = managerNumberObj;
            supervisorNameObj = {};

            angular.forEach($scope.records, function (recordArray, recordIndex) {

                if (managerName === recordArray.manager) {
                    angular.forEach(recordArray, function (recordValue, recordKey) {

                        if (recordValue === managerName) {
                            supervisorNumberObj = {};
                            supervisorNumberObj.number1 = recordArray.number1;
                            supervisorNumberObj.number2 = recordArray.number2;
                            supervisorNumberObj.number3 = recordArray.number3;
                            supervisorTotalsObj = {};
                            supervisorTotalsObj.supervisorTotals = supervisorNumberObj;
                            supervisorNameObj[recordArray.supervisor] = supervisorTotalsObj;
                        }

                    });
                }
            });

            managerTotalsObj.supervisors = supervisorNameObj;
            managerNameObj[managerName.toLowerCase()] = managerTotalsObj;
        });
        regionTurnoverObj.turnover = regionNumberObj;
        mainRecordobj.regionTotals = regionTurnoverObj;
        mainRecordobj.managers = managerNameObj;
        $scope.flattenedRecord.push(mainRecordobj);
        console.log(angular.toJson($scope.flattenedRecord));
    });
});

OUTPUT
[
  {
    "region": "London",
    "regionTotals": {
      "turnover": {
        "number1": "TOTAL OF NUMBER 1 WITH REGION LONDON",
        "number2": "TOTAL OF NUMBER 2 WITH REGION LONDON",
        "number3": "TOTAL OF NUMBER 3 WITH REGION LONDON"
      }
    },
    "managers": {
      "jack": {
        "managerTotals": {
          "number1": "TOTAL OF NUMBER 1 WITH MANAGER JACK",
          "number2": "TOTAL OF NUMBER 2 WITH MANAGER JACK",
          "number3": "TOTAL OF NUMBER 3 WITH MANAGER JACK"
        },
        "supervisors": {
          "James": {
            "supervisorTotals": {
              "number1": 44,
              "number2": 2244.3,
              "number3": 1561.6
            }
          },
          "Jerry": {
            "supervisorTotals": {
              "number1": 335.4,
              "number2": 33.3,
              "number3": 11.6
            }
          }
        }
      },
      "john": {
        "managerTotals": {
          "number1": "TOTAL OF NUMBER 1 WITH MANAGER JOHN",
          "number2": "TOTAL OF NUMBER 2 WITH MANAGER JOHN",
          "number3": "TOTAL OF NUMBER 3 WITH MANAGER JOHN"
        },
        "supervisors": {
          "Joseph": {
            "supervisorTotals": {
              "number1": 444.3,
              "number2": 233,
              "number3": 1561.6
            }
          }
        }
      }
    }
  }
]


text:
Q: Extract values along customized circular strips (constant radial distance) from raster I have a large raster object which was imported from a .tif image file. I want to analyze pixels of this raster, at a given radial distance from the center, in order to identify certain axisymmetric phenomenon that I can notice in the image (below). To do this I want to extract the values of pixels that intersect with circular strips of a given radii (and width) from the center of the image (indicated in the figure below).
I have explored several options to do this including the extract function and the imager package. In the imager package, you can easily extract values along rows or columns but I couldn't find functions to extract values with customized shapes like I require.
I might use the extract function with SpatialPolygons argument, however for this I will have to input the locations of all the points in a polygon object, and this would require very high density location of points (since the points, I think, are joined by line elements). Moreover, I want to vary the number density of the strips over which I extract pixel values (and later average) therefore this method would be both tedious and inflexible. I was thus wondering if any of you have any suggestions to tackle this issue.
> str(imRaster)
Formal class 'RasterLayer' [package "raster"] with 12 slots
  ..@ file    :Formal class '.RasterFile' [package "raster"] with 13 slots
  .. .. ..@ name        : chr "C:\\Users\\Nandu\\input_images\\All\\101_1A_1000ms.tif"
  .. .. ..@ datanotation: chr "INT2U"
  .. .. ..@ byteorder   : chr "little"
  .. .. ..@ nodatavalue : num -Inf
  .. .. ..@ NAchanged   : logi FALSE
  .. .. ..@ nbands      : int 1
  .. .. ..@ blockrows   : int 1
  .. .. ..@ blockcols   : int 1392
  .. .. ..@ driver      : chr "gdal"
  .. .. ..@ open        : logi FALSE
  ..@ data    :Formal class '.SingleLayerData' [package "raster"] with 13 slots
       .
       .
       .

Alternately, if there are other methods (other than by importing a .tif image to raster) that would allow such an operation, that might also be useful. Please let me know.
Thanks in advance!
EDIT: In order to make the problem reproducible, I have further added here the link to the image that I want to use. It is a tiff image, and can be downloaded from here
Link to the tiff image that I am trying to process in R
library(tiff)
library(raster)
imRaster = raster(file_path to the image)
plot(imRaster)
xy = cbind(684.4228, 599.0458) # Gives a rough location of the center in the image coordinates

This code can be run in order to obtain the raster described above and visualize it. Hope it helps!

A: Let's start by loading the raster and assigning it a fake coordinate reference system (CRS). We use a metrical one so that 1 pixel in your image refers to one "meter" in the pseudo-geographic raster.
library(raster)

imRaster <- raster("~/Downloads/46-ECN300448-216.tif")
imRaster@crs <-  CRS("+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378137 +b=6378137 +units=m +no_defs")

plot(imRaster, col = grey.colors(255))

Afterwards, as you mentioned we use your center point xy and convert it to a SpatialPoint
xy <- cbind(684.4228, 599.0458)
xySp <- SpatialPoints(coords = xy)
plot(xySp, add = T)

Then we  use the rgeos package to create two radial buffers around the point. In this example we use 200 and 300 px/m.
library(rgeos)

outer <- 300
inner <- 200

bufOut <- gBuffer(xySp, width = outer)
bufIn <- gBuffer(xySp, width = inner)

strip <- bufOut - bufIn
plot(strip, add = T, col = "#FF000050")

Finally, we can use the strip to mask the raster image and calculate statistics (or even use the original values) with getValues().
m <- mask(imRaster, mask = strip)

# plot(m) # plot the mask if you want to see what it looks like

mean(getValues(m), na.rm = T)
# [1] 17004.24

Important Note: Only the cells having their center within the polygon are remain after masking. You might tackle this issue by playing around with the with of the buffers.


text:
Q: placing 64 buttons randomly in a girdlaout java The goal is to create a create a game like rubrics cube where the user has to rearrange the buttons according to the matched color. This is what I did to place the buttons randomly, but it doesn't work when the buttons are presented. The random order is taken as the ordered order if that makes sense. Any ideas on how to fix this?
  while(list1.size()!=501){

     int x=rand.nextInt(8);
     list1.add(x);
  }
  while(list2.size()!=501){

     int x=rand.nextInt(8);
     list2.add(x);
  }
  for(int b=0;b<500;b++){
     int l= list1.get(b);
     //System.out.println(l);
     int j= list2.get(b);
     panel.add(buttons[l][j]);
     //System.out.println(buttons[l][j].getBackground());

  }

A: Consider:

*

*Giving the buttons a value of some sort that represents their true order. There are several ways to do this, including putting them in an array of specified order, or extending JButton and giving your class an int value field, or using a HashMap

*Place these buttons into an ArrayList<JButton>

*Shuffling the ArrayList via Collections.shuffle(...)

*Then adding the buttons to your GUI

*Alternatively, you could use non-shuffled JButtons and instead shuffle AbstractActions which you then set into the buttons.

The details of any solution will depend on the details of your current program, something that we don't yet know enough about. If you need more detailed help, do consider creating and posting a valid MCVE in your question.
For example, compile and run this, and then read the comments:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.*;

public class RandomButtons extends JPanel {
    private static final long serialVersionUID = 1L;
    private static final int ROWS = 8;
    private JButton[][] buttons = new JButton[ROWS][ROWS];
    private List<JButton> buttonList = new ArrayList<>();
    private JPanel buttonsPanel = new JPanel(new GridLayout(ROWS, ROWS));

    public RandomButtons() {
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                // create new JBUtton
                final JButton button = new JButton("Button");
                // put into array
                buttons[i][j] = button;
                // put into ArrayList
                buttonList.add(button);

                // unique value 0 to 63 for each button
                // order it has been created
                final int value = i * ROWS + j;

                // create one of 64 different color hues using value above
                float hue = ((float) value) / (ROWS * ROWS);
                float sat = 0.7f; // reduce sat so we can see text
                float brightness = 1.0f;
                Color color = Color.getHSBColor(hue, sat, brightness);
                button.setBackground(color); // set button's color
                button.addActionListener(e -> {
                    // display the button's order
                    System.out.println("Value: " + value);
                });

            }
        }
        randomizeButtons();

        JButton randomizeButton = new JButton("Randomize");
        randomizeButton.addActionListener(e -> { randomizeButtons(); });
        JButton orderButton = new JButton("Put in Order");
        orderButton.addActionListener(e -> { orderButtons(); });

        JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
        bottomPanel.add(randomizeButton);
        bottomPanel.add(orderButton);

        setLayout(new BorderLayout());
        add(buttonsPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    public void randomizeButtons() {
        buttonsPanel.removeAll(); // remove all buttons
        Collections.shuffle(buttonList); // shuffle the ArrayList

        // re-add the buttons **using the ArrayList**
        for (JButton jButton : buttonList) {
            buttonsPanel.add(jButton);
        }

        // tell JPanel to layout its newly added components
        buttonsPanel.revalidate();
        // and then paint them
        buttonsPanel.repaint();
    }

    public void orderButtons() {
        buttonsPanel.removeAll();  // remove all buttons

        // re-add the buttons **using the 2D array**
        for (JButton[] buttonRow : buttons) {
            for (JButton jButton : buttonRow) {
                buttonsPanel.add(jButton);
            }
        }
        buttonsPanel.revalidate();
        buttonsPanel.repaint();
    }

    private static void createAndShowGui() {
        RandomButtons mainPanel = new RandomButtons();

        JFrame frame = new JFrame("RandomButtons");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}


text:
Q: Converting C# delimiters to javascript I have a silverlight application that i am converting to html5. I have this piece of code in c# that i am having trouble converting to javascript equivalent.
C#:
private const String DELIMITERS = @"(?=[,'\s])|(?<=[,'\s])";
string[] searchList = Regex.Split(MainTextArea.Text, DELIMITERS);

This is what i have tried in javascript but it's not splitting text.
javascript:
var searchList = $input.val().split("(?=[,'\\s])|(?<=[,'\\s])");

Thanks for any help in advance.

A: So the following ended up being the javascript equivalent:
$input.val().split(/([,'\s])+/);

Thanks for the helpful comments


text:
Q: "a chore" vs. "a type of chore" Consider the following two sentences.

*

*Doing laundry is a household chore.

*Doing laundry is a type of household chore.

I guess the first is more natural, but why? One of the possible explanations might be less is more which seems general, are there any other explanations for this use?

A: English is kind of slippery with such concepts.  The difference is whether you want "doing laundry" to be an example of a type, or a sub-type.
Number 1 is indicating that "doing laundry" is an example of a type.
Number 2 is indicating that "doing laundry" is a sub-type.
English is not especially careful about keeping these two things distinct. It is, as in this case, not rare for a sub-type and an example to be expressed in ambiguous form.
Consider a less ambiguous example.
This ostrich is a bird.
An ostrich is a type of bird.
These have been made less ambiguous by adding "this" or "an" at the front. The word "this" is specific while the word "an" is not.
You could do something similar. You could write your examples like so.

*

*Doing this load of laundry is an example of a household chore.

*Doing a load of laundry is a type of household chore.


text:
Q: how to change bridge mode to normal mode I have a dlink router. and my laptop connects to it via wifi but when i type in CMD ipconfig to find the default gateway which must be the router the address looks something like this:
ipv4 address: 192.168.43.249 subnet mask: 255.255.225.0 default gateway: 192.168.43.1
but when i enter the default gateway to my browser i cant access my router admin page? how can i find the right ip of my router if I have a public IP assigned by the ISP?
wireless-networking

A: Your default gateway (as communicated by the router to your computer by DHCP) is normally the ip-adddress of your router that you should use to get at the admin pages. This has nothing to do with whatever real ip-address your ISP assigns to the externally visibile ip-address of the router.
3 things come to mind:

*

*You router doesn't use the default port 80 for it's webpage but another port. Check the manual of the router what link to enter in your browser. (E.g http://192.168.43.1:XX/ where XX is the correct portnumber. Please note that most browsers insist you explicitly add http:// in front of the ip-address if it is any other port than the default port 80.)

*Your router has a setting that only allows the web-interface to be entered by any of it's normal LAN ports, not via Wifi. So try to connect your computer with a network cable to it and see if that helps.

*Your router has actually 2 wifi LAN's. One for personal use and one for guests. You are connecting to the guest Wifi and access to the admin-page is forbidden for guests. Try to connect to the normal wifi or the use a wired port in stead.


text:
Q: HCE - Is there a way to manipulate the ATR? I am making a Host Card Emulation app on Android, everything works fine with my PC/SC reader. I am able to send APDU commands and get the reponses. Now I want to know if it's possible to manipulate the ATR of the card emulated by Android using Android's NFC library (or not)? I have looked into the documentation but there's nothing about the ATR, does Android generate it automatically for each device?

A: Yes, Android generates the answer-to-select (ATS) automatically. There is no Android API to change its contents. The same applies to the anti-collision identifier (UID).
ATS vs. ATR
Note that contactless smartcards (ISO/IEC 14443-4A) do not expose an ATR (answer-to-reset) during the activation sequence. Instead, they provide an ATS (in response to the selection procedure). PC/SC readers for contactless smartcards typically map parts of that ATS into an (emulated) ATR for compatibility.
Rooted devices
Even though Android does not provide an API, you might be able to modify values such as the ATS by modifying the NFC controller configuration files. See Editing Functionality of Host Card Emulation in Android and Host-based Card Emulation with Fixed Card ID


text:
Q: QT5 Switching between Widgets size problem I try to switch between two different Widgets in QT5.
The first problem was that my first window was visible in the background of my second window. I solve this with a check in "autoFillBackground". Now i can switch between them, but if i resize them it only resize the Main content.
Both Widgets have a grid layout.
Resize Problem

Im new at QT5, so is there a better way to make a switching between 2 widgets without this problem?
I try it with wMessages = new Messages(); and hide() but then my program crash after going back.

Code:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include "messages.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_btnMessages_clicked();

private:
    Ui::MainWindow *ui;
    Messages *wMessages;
};
#endif // MAINWINDOW_H

mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_btnMessages_clicked()
{
    wMessages = new Messages(this);
    wMessages->show();
}

messages.h:
#ifndef MESSAGES_H
#define MESSAGES_H

#include <QWidget>

namespace Ui {
class Messages;
}

class Messages : public QWidget
{
    Q_OBJECT

public:
    explicit Messages(QWidget *parent = nullptr);
    ~Messages();

    QString NewsGenerator();
private slots:
    void on_bBack_clicked();

    void on_pushButton_clicked();

private:
    Ui::Messages *ui;
};

#endif // MESSAGES_H

messages.cpp:
#include "messages.h"
#include "ui_messages.h"

Messages::Messages(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Messages)
{
    ui->setupUi(this);
}

Messages::~Messages()
{
    delete ui;
}

void Messages::on_bBack_clicked()
{
    this->close();
    QWidget *parent = this->parentWidget();
    parent->show();
}

Edit 1 - working Main Window Button (from G.M.´s answer):
void MainWindow::on_btnMessages_clicked()
{
    wPlaner = new Planer();
    QMainWindow::setCentralWidget(wPlaner);
}

A: Update (based on the comments):
The best solution was to use the QStackedWidget to navigate between the views.
Docu: https://doc.qt.io/qt-5/qstackedwidget.html#details

Example-Code for Button:
// return back to first view
void MainWindow::on_btnret_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}


text:
Q: Write to Django DB from lists if criteria from database are met? New to Django, so bear with me.  I am working on a simple link aggregator site.  I have a script that pulls links and associated info (titles, date, etc) from xml files and stores them as lists.  This is a file called scraper.py and is under my project app folder news.
scraper.py generates a series of lists from XML files. The scaper.py code is essentially as follows:
def MakeLists():
    ###lots of code to get to this point###
    ###returns the following series of lists###
    return Article_date, Article_link, Article_vote, Article_title, Article_publisher

These outputs correspond to my Django models.py file, which is as follows:
class Article(models.Model):
    title = models.TextField()
    publisher = models.URLField()
    link = models.URLField()
    date = models.DateField()
    pull_date = models.DateTimeField(auto_now=True)
    vote = models.IntegerField(default=1)

And here is the view that makes my home page, with my latest attempt at getting the new scraped data into my db (data is gathered in MakeLists()):
class ArticleList(ListView):
    model = Article
    context_object_name = 'Articles'
    pull_date = Article.objects.aggregate(Max('pull_date'))

    def get_new_db_stuff(self):
        check_time = datetime.datetime.now()-datetime.timedelta(hours=4)
        if pull_date > check_time: #i.e., more than 4 hours ago
            Article_date, Article_link, Article_vote, Article_title, Article_publisher = MakeLists()

            for i in range(0, len(Article_link)):
                if Article.object.filter(link=Article_link[i]).exists()==False:
                    a = Article(link=Article_link[i], date=Article_date[i], vote=Article_vote[i],
                                title=Article_title[i], publisher = Article_publisher[i])
                a.save()

The issue is that it just doesn't seem to be doing anything... nothing is being written to DB.  There aren't an errors popping up when I runserver or when I click on pages.
Questions:
1. How do I check if anything is being done?  i.e., figure out if variables are being created etc.?
2. My thought is that I am botching the query, but how can I troubleshoot that?

A: *

*This is the wrong place to implement this type of solution.  It is better done by putting code all in a separate file and then placing that in a folder structure that is:
app_name>management>commands>file_name.py

*By putting it in this structure, it can either be ran from the manage.py shell or can be set up as a chron job (better).

*For the comparison
if Article.objects.filter(link=Article_link[i]).exists() == False:
works just fine.


text:
Q: How to parse the below mentioned xml in android and store it in the class? I'm having an requirement where i need to parse the below xml and store it in class.
<syncgroupsettings>
        <syncgroupset id = "sgMS" labelid = "lblMS" enabled = "YES" default = "OFF">
            <syncgroup syncgroupname = "VISITS"/>
            <syncgroup syncgroupname = "CUSTOMERS"/>
        </syncgroupset>

        <syncgroupset id = "sgAS" labelid = "lblAS" enabled = "YES" default = "ON">
            <syncgroup syncgroupname = "SALESDOCS"/>
            <syncgroup syncgroupname = "ANALYTICS"/>
        </syncgroupset>
    </syncgroupsettings>

So far what i have done was, i used to get the node value and simply adding it to arraylist of hashmap as shown below for other xml.
public class XmlParser {

    private static final String ns = null;

    /** This is the only function need to be called from outside the class */
    public static List<ArrayList<HashMap>> parse(Reader reader)
            throws XmlPullParserException, IOException {
        try{
            List<ArrayList<HashMap>> list = new ArrayList<ArrayList<HashMap>>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(reader);
            parser.nextTag();
            return readLabels(parser);
        }finally{

        }
    }

    /** This method read each country in the xml data and add it to List */
    private static List<ArrayList<HashMap>> readLabels(XmlPullParser parser)
            throws XmlPullParserException,IOException {

        List<ArrayList<HashMap>> list = new ArrayList<ArrayList<HashMap>>();

        parser.require(XmlPullParser.START_TAG, ns, "xml");

        while(parser.next() != XmlPullParser.END_TAG){
            if(parser.getEventType() != XmlPullParser.START_TAG){
                continue;
            }

            String name = parser.getName();
            if(name.equals("labels")){
                //do nothing
            }
            else if(name.equals("label"))
             {
                 list.add(readLabel(parser));
             }
            else
            {
                skip(parser);
            }
        }
        return list;
    }

    /** This method read a country and returns its corresponding HashMap construct */
    private static ArrayList<HashMap> readLabel(XmlPullParser parser)
            throws XmlPullParserException, IOException {

        parser.require(XmlPullParser.START_TAG, ns, "label");

        String labelid = parser.getAttributeValue(ns, "id");
        String textlan = "";
        String textval="";

        ArrayList<HashMap> al=new ArrayList<HashMap>();
        HashMap<String, String> hm = new HashMap<String, String>();
        while(parser.next() != XmlPullParser.END_TAG){
            if(parser.getEventType() != XmlPullParser.START_TAG){

                continue;
            }

            String name = parser.getName();
             if(name.equals("text")) {
                textlan = parser.getAttributeValue(ns,"language");
                textval = parser.getAttributeValue(ns,"value");
                 String details =   "language : " + textlan  + "value : " + textval;
                 hm.put(labelid,details );
                 al.add(hm);
                 readText(parser);
             }
            else
             {
                skip(parser);
            }
        }
        return al;
    }

    /** Process Capital tag in the xml data */
    private static void readText(XmlPullParser parser)
            throws IOException, XmlPullParserException {
        parser.require(XmlPullParser.START_TAG, ns, "text");
        parser.nextTag();
    }

    private static void skip(XmlPullParser parser)
            throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
            }
        }
     }
}

But for this particular xml, i need to store it in the class. Could you please help me with this regard.


text:
Q: Why am I getting a "Fatal error: Call to a member function fetch_assoc() on a non-object"? I'm working in this project that is an Android login app. It fetches data from an online server.
The registration works and the database gets updated but the login does not work.
We are using JSON to parse data from the server to the app.
Here is my PHP code:
public function getUserByEmailAndPassword($email, $password) {

    $stmt = $this->conn->prepare("SELECT * FROM user_info WHERE email = ?");

    $stmt->bind_param("s", $email);

    if ($stmt->execute()) {
        $user = $stmt->bind_result()->fetch_assoc();
        $stmt->close();
        return $user;
    }
    else {
        return NULL;
    }
}

The error I'm getting is the following:
Fatal error: Call to a member function fetch_assoc() on a non-object.

A: bind_result() is not the method you want here.  That method (which returns a boolean, by the way) lets you assign variables to the columns returned in your query.  Your query uses SELECT *, so you cannot use bind_result().
What you want is to use get_result().  This requires the mysqlnd driver to be installed.
$user = $stmt->get_result()->fetch_assoc();


text:
Q: Android: setOnClickListener for children of RelativeLayout I use RelativeLayout
But children of this layout not work for settext , click and ...
How fixed it ?

Code :

ImageView ImageView01 = (ImageView) findViewById(R.id.ImageView01);
if (ImageView01 != null) {
    ImageView01.setOnClickListener(new OnClickListener() {
       public void onClick(View arg0) {
          Log.i("error", "q" + 108);
       }
   });
}

This code for LinearLayout child of RelativeLayout

XML :

<LinearLayout
android:id="@+id/lnrVideoControl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<ImageView
    android:id="@+id/imgPlayVideo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:focusable="false"
    android:src="@drawable/play" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="5dp"
    android:layout_weight="0.5"
    android:gravity="center" >

    <SeekBar
        android:id="@+id/seekBarVideo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="2dp"
        android:layout_weight="0.5"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:progressDrawable="@drawable/red_scrubber_progress"
        android:thumb="@drawable/red_scrubber_control_thin"
        android:thumbOffset="8dp" />
</LinearLayout>

If i use this code out of RelativeLayout worked full !
How fix this problem ?

A: You have an ImageView with id imgPlayVideo. But you are creating reference to some other ImageView.
ImageView ImageView01 = findViewById(R.id.ImageView01)

This might be a wrong reference. So correct your code and refer to the exact ImageView
ImageView imageView = findViewById(R.id.imgPlayVideo)

This might fix your issue.


text:
Q: Settings API - getting hidden input / submit button's name I'm generating this form using Settings API:
<form action="options.php" method="post">
   <?php settings_fields('XX_theme_settings'); do_settings_sections('my_settings'); ?>
   <input type="hidden" name="foo" value="bar" />
   <input name="SubmitButton" type="submit" class="button-primary" value="<?php _e('Save Changes'); ?>" />
</form>

Validation callbacks $input array returns only 'my_settings' input fields.
How do I access foo (bar) input's value and submit button's name SubmitButton?
This doesn't work for the hidden input:
my_validation($input) {
   $foo = $input['foo'];
}

And when it comes to the submit button I don't even know where to start.

A: Using $_POST is too low level. Simply give it the same name as your other options. When you options are displayed they should have the names of the form: my_settings[a_particular_option]. For instance:
<input name="my_settings[some_input_option]"/>

Then for your hidden input and submit button:
<input type="hiddden" name="my_settings[foo]" value="bar"/>
<input name="my_settings[SubmitButton]" type="submit" class="button-primary" value="<?php _e('Save Changes'); ?>"/>

In your validation array
my_validation($input) {
   $foo = $input['foo'];
   $submit = $input['SubmitButton'];
}


text:
Q: IList - Compiler Error CS0266 - Cannot implicitly convert type I'm doing an automation testing using C# and trying to cancel a request in our portal with specific conditions:

*

*the status of the request should be 'pending for approval' and

*the type of the request should be in 'LNX' to cancel the request.

But I'm troubled on how to fix the error in IList<T>
public void Cancel()
{
    Tile.Click();
    wait = new WebDriverWait(BrowserFactory.Driver, TimeSpan.FromSeconds(10000));
    var reqStatusToSearch = "PENDING FOR APPROVAL";
    var reqTypeToSearch = "LNX";
    int rowNum = BrowserFactory.Driver.FindElements(By.XPath("//*[name()='path' and @stroke-linecap='round']")).Count();
    IList<IWebElement> reqStatus = BrowserFactory.Driver.FindElements(By.XPath("//*[name()='path' and @stroke-linecap='round']"));
    var webElements = BrowserFactory.Driver.FindElements(By.XPath("//*[name()='path' and @stroke-linecap='round']"));

    int currentSelectedRecordCount = 0;
    int recordCoundToSelect = 1;

    while (currentSelectedRecordCount != recordCoundToSelect)
    {

        wait = new WebDriverWait(BrowserFactory.Driver, TimeSpan.FromSeconds(10000));
        var status = ReqNoTableElement.FindElements(By.XPath("//*[name()='path' and @stroke-linecap='round']")).ToString();

        if ((status.Contains(reqStatusToSearch)) && (status.Contains(reqTypeToSearch)))
        {
            var reqNumbers = ReqNoTableElement.FindElements(By.XPath("//*[name()='path' and @stroke-linecap='round']"));
            for (int index = 0; index < reqNumbers.Count; index++)
            {
                var element = reqNumbers[index];

                //Check if current element has a status of PENDING FOR APPROVAL
                var currentStatus = ReqNoTableElement.FindElements(By.XPath("//*[name()='path' and @stroke-linecap='round']"));
                if (currentStatus.Equals(reqStatusToSearch))
                {
                    currentSelectedRecordCount++;
                    element.FindElement(By.ClassName("mat-checkbox")).Click();
                    if (currentSelectedRecordCount == recordCoundToSelect)
                    {

                        CancelModal.Click();
                        wait = new WebDriverWait(BrowserFactory.Driver, TimeSpan.FromSeconds(5000));
                        Cancel.Click();
                        wait = new WebDriverWait(BrowserFactory.Driver, TimeSpan.FromSeconds(5000));
                        Confirm.Click();
                        wait = new WebDriverWait(BrowserFactory.Driver, TimeSpan.FromSeconds(5000));
                        return;
                    }
                }

            }
            if (currentSelectedRecordCount < recordCoundToSelect)
            {
                currentSelectedRecordCount = 0;
            }
            NextPage.Click();
        }
    }
}

A: If you use Visual Studio, the intelisense tells you the expected return type for find_elements:

Instead of using:
IList<IWebElement> reqStatus

try this:
ReadOnlyCollection<IWebElement> reqStatus


text:
Q: Get available time from an array of busy hours PHP I have a php array of booked time as :
print_r($data)
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [start_date] => 2019-09-26
                    [start_time] => 07:00:00
                    [end_date] => 2019-09-26
                    [end_time] => 09:00:00
                )

            [1] => stdClass Object
                (
                    [id] => 4
                    [start_date] => 2019-09-26
                    [start_time] => 12:00:00
                    [end_date] => 2019-09-26
                    [end_time] => 14:00:00
                )

            [2] => stdClass Object
                (
                    [id] => 9
                    [start_date] => 2019-09-26
                    [start_time] => 16:00:00
                    [end_date] => 2019-09-26
                    [end_time] => 17:00:00
                )

            [3] => stdClass Object
                (
                    [id] => 13
                    [start_date] => 2019-09-26
                    [start_time] => 19:00:00
                    [end_date] => 2019-09-26
                    [end_time] => 20:00:00
                )

            [4] => stdClass Object
                (
                    [id] => 2
                    [start_date] => 2019-09-27
                    [start_time] => 07:00:00
                    [end_date] => 2019-09-27
                    [end_time] => 08:00:00
                )

            [5] => stdClass Object
                (
                    [id] => 5
                    [start_date] => 2019-09-27
                    [start_time] => 12:00:00
                    [end_date] => 2019-09-27
                    [end_time] => 14:00:00
                )

            [6] => stdClass Object
                (
                    [id] => 10
                    [start_date] => 2019-09-27
                    [start_time] => 16:00:00
                    [end_date] => 2019-09-27
                    [end_time] => 18:00:00
                )

            [7] => stdClass Object
                (
                    [id] => 14
                    [start_date] => 2019-09-27
                    [start_time] => 19:00:00
                    [end_date] => 2019-09-27
                    [end_time] => 20:00:00
                )

            [8] => stdClass Object
                (
                    [id] => 3
                    [start_date] => 2019-09-28
                    [start_time] => 07:00:00
                    [end_date] => 2019-09-28
                    [end_time] => 10:00:00
                )

            [9] => stdClass Object
                (
                    [id] => 6
                    [start_date] => 2019-09-28
                    [start_time] => 12:00:00
                    [end_date] => 2019-09-28
                    [end_time] => 13:00:00
                )

            [10] => stdClass Object
                (
                    [id] => 11
                    [start_date] => 2019-09-28
                    [start_time] => 16:00:00
                    [end_date] => 2019-09-28
                    [end_time] => 17:00:00
                )

            [11] => stdClass Object
                (
                    [id] => 15
                    [start_date] => 2019-09-28
                    [start_time] => 19:00:00
                    [end_date] => 2019-09-28
                    [end_time] => 20:00:00
                )

        )

)

Now, I want to find the details of available hours for each day.
To check this, let's consider business hours is from 07:00:00 to 20:00:00
Now, I want to find the available time between these hours i.e 07:00:00 to 20:00:00 by filtering all the above booked time.
$available_hour =  => Array(
            [2019-09-26] => Array(
                        [0] => Array(
                            ['start'] => 09:00:00
                            ['end'] => 12:00:00
                        )
                        [1] => Array(
                            ['start'] => 14:00:00
                            ['end'] => 16:00:00
                        )
                        [2] => Array(
                            ['start'] => 17:00:00
                            ['end'] => 19:00:00
                        )
            )
            [2019-09-27] => Array(
                        [0] => Array(
                            ['start'] => 08:00:00
                            ['end'] => 12:00:00
                        )
                        [1] => Array(
                            ['start'] => 14:00:00
                            ['end'] => 16:00:00
                        )
                        [2] => Array(
                            ['start'] => 18:00:00
                            ['end'] => 19:00:00
                        )
            )
            [2019-09-28] => Array(
                        [0] => Array(
                            ['start'] => 10:00:00
                            ['end'] => 12:00:00
                        )
                        [1] => Array(
                            ['start'] => 13:00:00
                            ['end'] => 16:00:00
                        )
                        [2] => Array(
                            ['start'] => 17:00:00
                            ['end'] => 19:00:00
                        )
            )
)

This is the basic idea, I have seen similar problem in stack overflow here, Get available time ranges from an array of busy time ranges, however, I want to deal it in php instead of js.
I have tried my best to represent a sample data array (although this is a full array instead of object), its ok to work with it. Here, is the sandbox link.

A: Try this code..
$res = [];
foreach($x as $value)
{
    if(array_key_exists($value['start_date'],$res))
    {
        end($res[$value['start_date']]);         // move the internal pointer to the end of the array
        $key = key($res[$value['start_date']]);
            if(empty($res[$value['start_date']][$key]['end']))
            {
                if($value['start_time'] >= '07:00:00' && $value['start_time'] <= '20:00:00')
                {
                    $res[$value['start_date']][$key]['end'] = $value['start_time'];
                }
            }
            else
            {
                if($value['end_time'] >= '07:00:00' && $value['end_time'] <= '20:00:00')
                {
                    $res[$value['start_date']][] = ['start' => $value['end_time']];
                }
            }
            if(!empty($res[$value['start_date']][$key]['start']))
            {
                if($value['end_time'] >= '07:00:00' && $value['end_time'] <= '20:00:00')
                {
                    $res[$value['start_date']][] = ['start' => $value['end_time']];
                }
            }
    }

    else
    {
        if($value['start_date'] >= '07:00:00' && $value['start_date'] <= '20:00:00')
        {
             $res[$value['start_date']][] = ['start' => "07:00:00",'end' => $value['start_time']];
             end($res[$value['start_date']]);
             $key = key($res[$value['start_date']]);
             $res[$value['start_date']][++$key] = ['start' =>  $value['end_time']];

        }
    }
}
foreach($res as $key => $result)
{
foreach($result as $k => $v)
{
    if(!array_key_exists('end',$v))
    {
        unset($result[$k]);
    }
}
$new[$key] = $result;
}

The final result will be in $new variable.

A: Here's a nice little trick, assuming the structure of the array/object contains "items".
Working example: https://3v4l.org/Wat8i works with PHP 5.4+.
<?php

$datetimes = [
    "items" => [
        [
            "id" => 1,
            "start_date" => "2019-09-26",
            "start_time" => "07:00:00",
            "end_date" => "2019-09-26",
            "end_time" => "09:00:00"
        ],
        [
            "id" => 4,
            "start_date" => "2019-09-26",
            "start_time" => "12:00:00",
            "end_date" => "2019-09-26",
            "end_time" => "14:00:00"
        ],
        [
            "id" => 9,
            "start_date" => "2019-09-26",
            "start_time" => "16:00:00",
            "end_date" => "2019-09-26",
            "end_time" => "17:00:00"
        ],
        [
            "id" => 13,
            "start_date" => "2019-09-26",
            "start_time" => "19:00:00",
            "end_date" => "2019-09-26",
            "end_time" => "20:00:00"
        ],
        [
            "id" => 2,
            "start_date" => "2019-09-27",
            "start_time" => "07:00:00",
            "end_date" => "2019-09-27",
            "end_time" => "08:00:00"
        ],
        [
            "id" => 5,
            "start_date" => "2019-09-27",
            "start_time" => "12:00:00",
            "end_date" => "2019-09-27",
            "end_time" => "14:00:00"
        ],
        [
            "id" => 10,
            "start_date" => "2019-09-27",
            "start_time" => "16:00:00",
            "end_date" => "2019-09-27",
            "end_time" => "18:00:00"
        ],
        [
            "id" => 14,
            "start_date" => "2019-09-27",
            "start_time" => "19:00:00",
            "end_date" => "2019-09-27",
            "end_time" => "20:00:00"
        ],
        [
            "id" => 3,
            "start_date" => "2019-09-28",
            "start_time" => "07:00:00",
            "end_date" => "2019-09-28",
            "end_time" => "10:00:00"
        ],
        [
            "id" => 6,
            "start_date" => "2019-09-28",
            "start_time" => "12:00:00",
            "end_date" => "2019-09-28",
            "end_time" => "13:00:00"
        ],
        [
            "id" => 11,
            "start_date" => "2019-09-28",
            "start_time" => "16:00:00",
            "end_date" => "2019-09-28",
            "end_time" => "17:00:00"
        ],
        [
            "id" => 15,
            "start_date" => "2019-09-28",
            "start_time" => "19:00:00",
            "end_date" => "2019-09-28",
            "end_time" => "20:00:00"
        ]
    ]
];

$openinghours = [];

function openinghours($times) {

    global $openinghours;

    $openinghours[$times["start_date"]][] = [
        "start" => $times["start_time"],
        "end" => $times["end_time"]
    ];

}

array_map("openinghours", $datetimes["items"]);

var_dump($openinghours);

It basically makes a new array without modifying the old one and no if statements needed.
[EDIT1]
And quick additional foreach() function to show the dates and times: https://3v4l.org/uhUeS
foreach($openinghours as $date => $times) {
    echo "{$date} : {$times[0]["start"]} - " . end($times)["end"] . "\n";
}

[EDIT2]
If you expect people or yourself to change the opening hours so that id 1 can have 07:00:00 to 20:00:00, I suggest you change the output structure to ignore start and end and just pick first and last of the dates: https://3v4l.org/jMvCP
function openinghours($times) {

    global $openinghours;

    $openinghours[$times["start_date"]][] = $times["start_time"];
    $openinghours[$times["start_date"]][] = $times["end_time"];

    sort($openinghours[$times["start_date"]]);

}

array_map("openinghours", $datetimes["items"]);

var_dump($openinghours);

foreach($openinghours as $date => $times) {
    echo "{$date} : {$times[0]} - " . end($times) . "\n";
}


text:
Q: I'm having some issues with previous_post_link() and next_post_link() I've been developing a Wordpress site lately and have come across an issue. I need the user to be able to navigate between posts, I'm using the standard Wordpress functions previous_post_link() and next_post_link() which should in THEORY output the links to the next and previous posts in the database... BUT the only links that appear are in the case of the latest post; the first post that was published and in the case of the first post that was published; the latest post.
There are 5 posts and they all produce the same links, I'm not doing anything silly or outside of the box.
I also had some initial issues with pagination on the main blog feed but that appears to be fixed now....
Here is my code:
single.php
<?php get_header(); the_post();?>

BLOG

            <img class="single__image" src="<?php echo Image::get(wp_get_attachment_url(get_post_thumbnail_id($post->ID))); ?>">

Posted on <?php the_time('jS F Y'); ?> by <?php the_author(); ?>

<?php the_title(); ?>

                <?php the_content(); ?>

<?php previous_post_link(' %link'); ?>

<?php next_post_link('%link '); ?>

<?php get_footer();?>

and here is the main blog feed:
index.php
<?php get_header(); ?>

BLOG

            <?php while(have_posts()) : the_post(); ?>

                    <img class="blog__image" src="<?php echo Image::get(wp_get_attachment_url(get_post_thumbnail_id($post->ID))); ?>">

Posted on <?php the_time('jS F Y'); ?> by <?php the_author(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo get_the_content_excerpt(30); ?>

                        <a class="blog__post__more" href="<?php the_permalink(); ?>">Continue Reading

            <?php endwhile;?>

            <?php if(!have_posts()) : ?>

There are no posts to display at this time.

            <?php endif; ?>

        <?php get_template_part('partials/sidebar', 'landing'); ?>

<?php previous_posts_link(' Newer Posts'); ?>

<?php next_posts_link('Older Posts '); ?>

<?php get_footer(); ?>

I hope that someone is able help me with this issue, if you're able to direct me to potential fixes that would be great! Though I have already searched and searched, tried peoples suggestions etc which is why I've chosen to make this post.
If something isn't clear please let me know :)
Thanks in advance!

A: I've realised what the issue was... some of my posts were generated (for development purposes) using bulk creator which appears to not create a complete post! When I create a post manually using the WP backend my code works fine, thanks for the suggestions anyway guys!


text:
Q: "sitting on the fence" grammar First of all,
I realise that "He's still sitting on the fence about buying the coat" sounds the most natural, but is "He is still sitting on the fence about deciding whether to buy the coat or not" grammatically correct?
Secondly, my main question:
Why is "He is still sitting on the fence to decide whether to buy the coat or not." grammatically incorrect?
Especially in terms of the infinitive (to buy) when used with "sitting on the fence".
And why does it need the preposition (about)?
My first post here so sorry if anything is formatted wrong.
Thank you!

A: It is illogical as well as ungrammatical.
'Sitting on the fence' means a state of indecision, so your suggestion would be like saying "he is undecided about whether to decide".
Your second construction is ungrammatical for the same reason - one is undecided 'on' or 'about' something. Your sentence says they are sitting on the fence (undecided) 'to' decide, which is not an idiomatic preposition aside from anything else.


text:
Q: How to get the projective dimension just by a non-split sequence? In the answer of this question:Question about the category of projective $A$-modules of an Artin algebra $A$
There is a place I don't know:  Here $A$ is an artin algebra, if there is a projective module $P$ non-injective, then there is a monomorphism $i:R \rightarrow S$ and a map $f: R \rightarrow P$, there is no map $g:S \rightarrow P$ suc that $f=gi$, then the answer of this question gets a non-split short exact sequence of $A$-modules of the form : $0 \rightarrow R \rightarrow S \rightarrow S/R \rightarrow 0$, then since it is not split, $Ext^1 _A(S/R,R) \neq0$. Then how to get the projective dimesion of $S/R=1$? (In my mind, $pd M=1$ iff $Ext^1(M,-) \neq0$ and $Ext^2(M,-)=0$)


text:
Q: Backbone - receiving DELETE data in the back end Say you have a model with an id, and you want to delete it in the database. So you call the destroy() method on that model (as below in the code example). That sends an OPTIONS HTTP request, followed by a DELETE HTTP request. My issue is that while I'm catching the DELETE request nicely on the server side, I can't find any information telling me what the model id is - it's not a parameter in the request and it's not in the URL. How do I find this information? I can't see it in the documentation here. Here is a link to the repo where I'm storing the code.
  removeElement: function() {
    // DELETE in DB
    this.model.destroy();
    this.remove();
    this.unbind();
  },

What I would expect is that the HTTP request would have a param like { 'id': 42319 } or some such.

A: You probably need to set the model ID attribute. The id set automatically by Backbone on the client is cid and not id. Note that a common gotcha with DBs that use a different unique key (like MongoDB) is not mapping from that key to ID as described in the docs
For example:
var Model = Backbone.Model.extend({
    idAttribute: "_id"
    //other model setup code
});

A: My problem was that I was defining the url attribute in BOTH the model AND the collection. You should only define url in the collection. Stupid mistake.


text:
Q: Ubuntu 18.04 LTS, securing boot and encrypting data on HDD with TPM 2.0 I want to give for a rent some PC with some software (kiosk software).
I want to not allow people who will rent this PC to read any data on its HDD.
But they will have physical access to this PC.
There will be asus motherboard will asus external TPM 2.0 module.
There will be two users in a system - root and kiosk, both with secret passwords.
The question is what is the best and modern way to secure the data (if someone will try to read data with live cd or with changing shell at boot)?
I studied this problem and have concluded I have to realize the following:

*

*Turn on UEFI and Secure Boot in BIOS settings

*Sign bootable system parts (this point needs clarification - what parts? grub list / or may be use of grub2 / initrd ... etc ....).

*The further actions is to use dm-crypt / crypttab / LUKS to setup fully encrypted HDD based on TPM 2.0

*Somehow install all certs to TPM 2.0

But still I can't figure out what is the best and easiest (for unattended post-setup of all system encryption via sh scripts) way to do it? Should I use all tools mensioned in 3 par. in the list, or a couple of them?
May be there is any step-by-step info with explanation of each command?
Thanks in advance.

A: I made this script to automatically unlock through TPM2: https://github.com/archee565/Bytelocker
BTW, I believe Linux installers should have an option to set this up automatically.


text:
Q: Find all children of user with Searchkick I'm trying to find all records of children account of a given user.
What I have right now:
@parent = @user.id
@children = User.search ("*"),
  page: params[:page], per_page: 20,
    # Discard account that don't have coordinates to avoid distance errors
    where: {
      coordinates: {not: nil},
      role: :organization,
      parent_id: @parent
    },
    order: {_geo_distance: {coordinates: {lat: @coordinates[1], lon: @coordinates[0]}, order: "asc", unit: "mi"} }

This runs the following query:
curl http://localhost:1234/users_development/_search?pretty -d '{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "and": [
          {
            "not": {
              "filter": {
                "missing": {
                  "field": "coordinates",
                  "existence": true,
                  "null_value": true
                }
              }
            }
          },
          {
            "term": {
              "role": "organization"
            }
          },
          {
            "term": {
              "parent_id": {
                "$oid": "44fa9f8962656e0404bd3310"
              }
            }
          }
        ]
      }
    }
  },
  "size": 20,
  "from": 0,
  "sort": {
    "_geo_distance": {
      "coordinates": {
        "lat": -118.3919,
        "lon": 34.1379
      },
      "order": "asc",
      "unit": "mi"
    }
  },
  "fields": []
}'

When I look up one of the children users in the console, I see this for the parent_id: <BSON::ObjectId:0x70205146889309 data=44fa9f8962656e0404bd3310>
The query I run gives Searchkick::InvalidQueryError ([400] {"error":"SearchPhaseExecutionException[Failed to execute phase [query], all shards failed; shardFailures...
I'm pretty sure I'm mistyping the query somehow. What's the correct syntax?
Here's the full error:
Searchkick::InvalidQueryError ([400] {"error":"SearchPhaseExecutionException[Failed to execute phase [query], all shards failed; shardFailures {[MRKTgyLfTGSnADDAIoMdLg][users_development_20151220094401447][0]: SearchParseException[[users_development_20151220094401447][0]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\"query\":{\"filtered\":{\"query\":{\"match_all\":{}},\"filter\":{\"and\":[{\"not\":{\"filter\":{\"missing\":{\"field\":\"coordinates\",\"existence\":true,\"null_value\":true}}}},{\"term\":{\"role\":\"organization\"}},{\"term\":{\"parent_id\":{\"$oid\":\"44fa9f8962656e0404bd3310\"}}}]}}},\"size\":20,\"from\":0,\"sort\":{\"_geo_distance\":{\"coordinates\":{\"lat\":-118.3919,\"lon\":34.1379},\"order\":\"asc\",\"unit\":\"mi\"}},\"fields\":[]}]]]; nested: QueryParsingException[[users_development_20151220094401447] [term] filter does not support [$oid]]; }{[MRKTgyLfTGSnADDAIoMdLg][users_development_20151220094401447][1]: SearchParseException[[users_development_20151220094401447][1]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\"query\":{\"filtered\":{\"query\":{\"match_all\":{}},\"filter\":{\"and\":[{\"not\":{\"filter\":{\"missing\":{\"field\":\"coordinates\",\"existence\":true,\"null_value\":true}}}},{\"term\":{\"role\":\"organization\"}},{\"term\":{\"parent_id\":{\"$oid\":\"44fa9f8962656e0404bd3310\"}}}]}}},\"size\":20,\"from\":0,\"sort\":{\"_geo_distance\":{\"coordinates\":{\"lat\":-118.3919,\"lon\":34.1379},\"order\":\"asc\",\"unit\":\"mi\"}},\"fields\":[]}]]]; nested: QueryParsingException[[users_development_20151220094401447] [term] filter does not support [$oid]]; }{[MRKTgyLfTGSnADDAIoMdLg][users_development_20151220094401447][2]: SearchParseException[[users_development_20151220094401447][2]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\"query\":{\"filtered\":{\"query\":{\"match_all\":{}},\"filter\":{\"and\":[{\"not\":{\"filter\":{\"missing\":{\"field\":\"coordinates\",\"existence\":true,\"null_value\":true}}}},{\"term\":{\"role\":\"organization\"}},{\"term\":{\"parent_id\":{\"$oid\":\"44fa9f8962656e0404bd3310\"}}}]}}},\"size\":20,\"from\":0,\"sort\":{\"_geo_distance\":{\"coordinates\":{\"lat\":-118.3919,\"lon\":34.1379},\"order\":\"asc\",\"unit\":\"mi\"}},\"fields\":[]}]]]; nested: QueryParsingException[[users_development_20151220094401447] [term] filter does not support [$oid]]; }{[MRKTgyLfTGSnADDAIoMdLg][users_development_20151220094401447][3]: SearchParseException[[users_development_20151220094401447][3]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\"query\":{\"filtered\":{\"query\":{\"match_all\":{}},\"filter\":{\"and\":[{\"not\":{\"filter\":{\"missing\":{\"field\":\"coordinates\",\"existence\":true,\"null_value\":true}}}},{\"term\":{\"role\":\"organization\"}},{\"term\":{\"parent_id\":{\"$oid\":\"44fa9f8962656e0404bd3310\"}}}]}}},\"size\":20,\"from\":0,\"sort\":{\"_geo_distance\":{\"coordinates\":{\"lat\":-118.3919,\"lon\":34.1379},\"order\":\"asc\",\"unit\":\"mi\"}},\"fields\":[]}]]]; nested: QueryParsingException[[users_development_20151220094401447] [term] filter does not support [$oid]]; }{[MRKTgyLfTGSnADDAIoMdLg][users_development_20151220094401447][4]: SearchParseException[[users_development_20151220094401447][4]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\"query\":{\"filtered\":{\"query\":{\"match_all\":{}},\"filter\":{\"and\":[{\"not\":{\"filter\":{\"missing\":{\"field\":\"coordinates\",\"existence\":true,\"null_value\":true}}}},{\"term\":{\"role\":\"organization\"}},{\"term\":{\"parent_id\":{\"$oid\":\"44fa9f8962656e0404bd3310\"}}}]}}},\"size\":20,\"from\":0,\"sort\":{\"_geo_distance\":{\"coordinates\":{\"lat\":-118.3919,\"lon\":34.1379},\"order\":\"asc\",\"unit\":\"mi\"}},\"fields\":[]}]]]; nested: QueryParsingException[[users_development_20151220094401447] [term] filter does not support [$oid]]; }]","status":400}):

A: According to the error
[term] filter does not support [$oid]]

The issue lies in the following part
      {
        "term": {
          "parent_id": {
            "$oid": "44fa9f8962656e0404bd3310"
          }
        }
      }

You simply need to write it like this:
      {
        "term": {
          "parent_id": "44fa9f8962656e0404bd3310"
        }
      }


text:
Q: Arbitrary number of entries in a column in SQLITE It's been a while since I used SQL, and I'm having trouble coming up with the best schema for the table(s) in my database.
Ultimately, I have a bunch users (primary key) which each have a number of attributes that I'm keeping track of. One of these attributes is a set of groups to which they belong (think of the way blog posts have tags - multiple posts can share the same tag, and the same tag can have multiple posts).
What is the best way to construct the table(s) for this database so that I can easily check the groups associated with a user, and also the users who belong to a given group?

A: As a rule, there's only 0 or 1 entry per column, no more. (Arguably, Null is an entry, so in that sense there really is always 1 entry per column). When you're thinking of having several entries in a column, it's time to break down the model.
Start with your basic data elements, forget about how they relate with each other:

User
-----
ID
Name

Group
----------
ID
Description

Then link the two:

UserGroup
----------
UserID
GroupID

The other "single" attributes that the user could have (e-mail address, url, age, whatever) would go in the User table.
Example:

User: ID = 1, Name = John
User: ID = 2, Name = Mary
Group: ID = 1, Description = Boys
Group: ID = 2, Description = Students
Group: ID = 3, Description = Programmers
UserGroup: UserID = 1, GroupID = 1  -> John is a member of "Boys"
UserGroup: UserID = 1, GroupID = 2  -> John is also a member of "Students"
UserGroup: UserID = 2, GroupID = 2  -> Mary is another member of "Students"


text:
Q: How do I recieve and pass "v-" props to children? I want to have some set of wrapper components, which mainly purpose, as you might guess, is just to be styled some way and contain passed children/have passed props.
I have wrapper component:
// components/FancyButton.vue

<template>
  <button class="fancy-button">
    <slot />
  </button>
</template>

How do I pass "v-" props to that <button> so it handle click ?
// components/App.vue

<template>
  <FancyButton v-on:click="doSomething()"> <!-- props go to nowhere -->
    Some children
  </FancyButton>
</template>

<script>
import FancyButton from './FancyButton'

export default {
  components: {
    FancyButton
  }
}
</script>

A: To pass a property to a component, you must declare it as such in the component and then use the v-bind syntax when using the component.
For example, if this is your component:
<template>
    <button class="fancy-button">
    <slot />
</button>
</template>

In the script part of the template:
<script>
   module.exports = {

      /...
      props: {
         yourData {
           type: DATA_TYPE
         }
      }
  }
  </script>

In the wrapper component, you do the following:
<template>
   <FancyButton v-on:click="doSomething()" v-bind:yourData="">
        Some children
   </FancyButton>
</template>

To pass a function as a props, do this:
<script>
   module.exports = {

      /...
      props: {
         yourData {
           type: Function
         }
      }
  }
  </script>

This is often times discouraged and you can use events to achieve the same logic that you want.
I recommend reading the following articles:
How to Pass a Function as a Prop in Vue
Passing functions as props an anti-pattern in Vue.js


text:
Q: Listening to window events within Android WebView I'm loading a webpage within a WebView and trying to subscribe to JS events. As an example, let's say I'm looking for the window 'load' event.
I configure the webview in its onFinishInflate:
webView.setJavaScriptEnabled(true);
webView.loadUrl("javascript:window.addEventListener('load', function(){alert('loaded');})");

I assume this registration persists across page navigations and that it can be made before any page is actually loaded (due to being done on window).
When loading any url following that, such as webView.loadUrl("https://www.google.com"), no alert shows up.
I have also tried loading that javascript string as a url in the web view client's onPageStarted & onPageFinished. No difference.
Is it possible to subscribe to a web view's window events? Eventually, I plan on using the @JavascriptInterface pattern to call back into the native code when the JS event occurs. I would like to avoid having the web page itself know about the injected Java/JS object (having to verify the existence of this bridge object before calling a method on it seems sloppy– I find the event bus pattern cleaner here).


text:
Q: Nested sql transaction in .Net I have two methods which start sql transaction and commit (or rollback) the connection inside the method.
public void Method1(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do some work
    trans.Commit(); // or trans.Rollback();
}

public void Method2(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do some work
    trans.Commit(); // or trans.Rollback();
}

I have to create another method which executes logic of Method 1 and 2 but in a single transaction.
public void Method1And2(SqlConnection connection)
{
    var trans = connection.BeginTransaction();
    // do work of method 1
    // do work of method 2
    trans.Commit(); // or trans.Rollback();
}

Instead of duplicating code of method 1 and 2 inside Method1And2, I would like to call Method1 and Method2 from Method1And2 but still keeping a single db transaction. Method1 and Method2 will also require their own transaction if they are invoked directly.
What is the best approach to implement this in .Net?
Thanks.


text:
Q: Kubernetes Pod will restart after deleting I created a pod that I want to delete but it does not seem te work.
I did all ready tried a lot of different things.
I do not have deployments or replica sets, as a lot of people suggest to delete those.
When i type:
kubectl get all
Only the pod and the service is visible, both of which will return upon deleting them.
When i type:
kubectl delete pods <pod-name> --grace-period=0 --force
The pod will come back again.
Is there something else I can do?

A: If pod not part of the deployment, rs, sts, ds, then it must be part of the static pod. Static pod name combines with node (i.e staticpod-node01). By default location of the static path is /etc/Kubernetes/manifest/.
Doc: https://kubernetes.io/docs/tasks/configure-pod-container/static-pod/

A: Apparently, it was some sort of invisible job that started the pod.
It was not showing when entering kubectl get jobs
So when finding this job and deleting it the pod disappeared!


text:
Q: Access Remote machine files in host machine I have my machine (windows 7) and i got a remote machine (windows server 2012) and i can map the host machine drive in the remote connection, but i would like the opposite navigate the drive in the host machines, how can i achieve that?
My main goal is to use my IDE in the host machine to alter some code on my virtual machine and not have to install anything on the server
I tried

\\servermachine\c$ or just \\servermachinename\

i get actually some authentication requests but inserrting the right domain user and password i dont seem to be able to open the connection

A: After all the right command was
\\servermachinename\
but the autentication domain was not the same as the domain the machine was cointained. After that it opened a empty folder, and i had to share the folder i wanted inside the remote machine


text:
Q: Cant do proper forest plot on R studio with actual OR? I am trying to do a forest with the predict function for the actual OR but I am having difficulties with the metafor package on R, any advice please?
I did it without predict, and the odds ratios are not correct this way


text:
Q: How to reset the ilo5 factory generated password using API ? or ilorest Tool from remote machine? I have multiple HPE Gen10 servers which have ILO5 license.
Now I want to manage the server from remote system using API or HP ilorest Tool, but to authenticate, it requires a password of user administrator & it comes as tag on the server. It's a very tedious task to note down the password & reset if you have 100 to 200 servers.
Does anyone know how I can reset the password from a remote system without having old one .

A: iLO_host = "https://{iLO}"
login_account = "admin"
login_password = "password"
But you use the PATCH to "Password" Action in the account (ManagerAccount) to change it.
HEre is a sample code to do it on the tool remotely
https://github.com/HewlettPackard/python-redfish-utility/blob/master/examples/Linux/Change_Password.sh


text:
Q: Java equivalent of CryptoJS.enc.Base64 for encryption 've been trying to port some NodeJS code to Java in order to make HMAC signed requests to an API. I've been able to simplify the code to a point were encoding is clearly affecting the output.
Here's my code in JavaScript:
var APIKey = "secret";
var secretByteArray = CryptoJS.enc.Base64.parse(APIKey);
var hash = CryptoJS.HmacSHA256("Message", secretByteArray);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
//alert(hashInBase64);
document.write(hashInBase64);

Here's the Java Code:
try {
        String secret = "secret";
        String message = "Message";

        byte[] secretByteArray = Base64.getEncoder().encode(secret.getBytes());

        //byte[] secretByteArray = Base64.encodeBase64(secret.getBytes("utf-8"), true);

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secretByteArray, "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String hash = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(message.getBytes()));
        System.out.println(hash);
    }
    catch (Exception e){
        System.out.println("Error");
    }

**What to use instead of Base64.getEncoder().encode? **


text:
Q: Rtools 3.5 not recognized? I just installed R3.5 (and RStudio) on a new computer that has not previously had R on it.  I then installed the devtools package, and when I went to install a package off of github, I realized (when prompted!) I had forgotten to install Rtools, so I followed the prompts to do so. Interestingly, this R tools installed to the directory of C:\RBuildTools by default and with no prompts for setting path variables as I had recalled in previous versions.
When I reloaded R, I was prompted to install Rtools again. My path contained no reference to Rtools (or the Rbuildtools directory), and remembering that my past installations had used the dir C:\Rtools, I decided to uninstall C:\RBuildTools and installed a fresh version off http://cran.r-project.org/bin/windows/Rtools/ ( installed version 3.5) into C:\Rtools.  In installation I had the path variable option checked.
I reloaded RStudio and checked to make sure Rtools was found:
> devtools::find_rtools()
Error in system(full, intern = TRUE, ignore.stderr = quiet, ...) : running command '"C:/PROGRA~1/R/R-35~1.0/bin/x64/R" --no-site-file --no-environ --no-save --no-restore --quiet CMD config CC' had status 2

However, rtools appears in my PATH:
> Sys.getenv("PATH")
[1] "C:\\Program Files\\R\\R-3.5.0\\bin\\x64;C:\\Rtools\\bin;..."

So this doesn't appear to be an issue with Rtools not being added properly to my Path variable.  Google searches have turned up seemingly related errors but nothing so far that solves my issue. I have tried both suggestions here and neither have worked.  I wonder if this could be related to RStudio.

A: I had a similar problem with RTools 3.5.
The installer did add C:\RTools\bin to the PATH, but it did not add
C:\RTools\mingw_64\bin which apparently did cause some confusion.
After adding C:\RTools\mingw_64\bin to the PATH, everything was fine.
My symptoms were a bit different though: RStudio reported an error when trying to "Install and Restart" my package that RTools were not found, while devtools::find_rtools() reported them to be present.

A: I have a comprehensive answer here for rtools not being recognized thru use of pkgbuild
`devtools::install_github(repo)` keeps installing rtools35.exe
The code snippet acknowledges the github comment this is posted (helped by r-sig-finance citizens)
However, (I can't comment) the error of find_tools() has disappeared but remains in devtools::install_bitbucket() for the new code that was the ultimate target and is in a src/master on BB cloud.
I unloaded the devtools and installed with remotes
unloadNamespace("devtools")
library(remotes)
install_bitbucket(author/repo)

As I said the problem with find_tools is taken care of by pkgbuild loading all items

A: Try updating RStudio to the latest version.
I had this problem after updating Rtools to 3.5 and found that updating RStudio to 1.1.447 fixed it.
If that doesn't work, Can you run rstudioapi::versionInfo()$version from inside RStudio and share the output?
If this isn't your problem I found that RStudio keeps a log - and it helped me isolate this issue. In my case the file was located in, "C:\Users\my_windows_username\AppData\Local\RStudio-Desktop\log\rsession-my_windows_username.log"
I found this warning in the log time that corresponed to the error in RStudio

WARNING Unknown Rtools version: 3.5; LOGGED FROM: rstudio::core::Error rstudio::core::r_util::scanRegistryForRTools(HKEY, bool, std::vector*) C:\Users\Administrator\rstudio\src\cpp\core\r_util\RToolsInfo.cpp:269

This indicated that RStudio didn't recognize 3.5, which led me to check for an updated version of RStudio.


text:
Q: How to create the graph only once in Tikz/pgf/pgfplots I saw Why is tikz so much slower when plotting a huge amount of data than WYSIWYG plotting tools? that pgfplots can be configured to do the plotting only once. How to do this? I have a document with many graphs and repeated runs takes so much time.

A: The details of this are described in Section 32 Externalization Library of the tikz/pgf manual.
Basically adding the following to your preamble should be all that is needed:
\usetikzlibrary{external}
\tikzexternalize


text:
Q: Defines a function that lets you see if the integer m is a multiple of n I cannot have a correct use of if-sentences and I get the error "parse error (possibly incorrect indentation or mismatched brackets)".
I've tried to use different if-sentences, but my experience is in Imperative Language, so I really don't know how to use properly the if-sentences in Haskell

multiple m n = mod m n
if mod m n /= 0 then "not multiple"

OR

multiple m n = mod m n
if mod m n = 0
then putStrLn "multiple"

OR

if multiple m n = 0 then "multiple m n" = "multiple"

And another amount of things
I expected to get an answer like "Multiple" or "Not Multiple".

A: You are quite close. You can see an if … then … else … as a ternary operator in imperative languages. There is nothing special about if … then … else …, it can be seen as syntactical sugar for an expression if' … … …, and it has the same laziness rules as any other function. So it is similar to … ? … : … in Java, C#, etc.
You thus can define this as:
multiple :: Integral a => a -> a -> String
multiple m n = if mod m n /= 0 then "not multiple" else "multiple"


text:
Q: Three span inside mat-option I have a requirement to show mat-options like below

I have added three spans to cover them but they seems attached together.Here is the resulted image.
Kindly help.
<mat-option *ngFor="let acc of fromAccounts.deposit" [value]="acc" >
                {{acc.accountProductDesc}}
                {{acc.maskedAccountNumber}}
                {{acc.balance}}
              </mat-option>

A: If you just want to change the display of the <mat-option> content then fiddling with the scss should be all you need.
Of course CSS solutions are pretty much endless and there are a lot of ways to achieve what you want , you just have to pick what you think:

*

*is scalable (if needed)

*achieves what you want correctly

*is easy to understand/read/debug

Here's a simple approach I'd suggest:
Template:
<mat-option *ngFor="let acc of fromAccounts.deposit" [value]="acc" >

    {{acc?.accountProductDesc}}
    {{acc?.maskedAccountNumber}}
    {{acc?.balance | currency}}

</mat-option>

SCSS:
.account-details{
  display: flex;
  *{
    padding: 0 3px;
  }
}
.description{
  font-weight: bold;
}
.number{
  font-size: small
}
.balance{
  margin-left: auto;
}