text:
Q: Dynamically inserting Json data into server-generated HTML table I have a table of server-generated content using MVC HTML helpers, like so:

                @Html.DisplayNameFor(model => model.TimeLogEntries[0].Description)

                @Html.DisplayNameFor(model => model.TimeLogEntries[0].StartTime)

                @Html.DisplayNameFor(model => model.TimeLogEntries[0].EndTime)

                @Html.DisplayNameFor(model => model.TimeLogEntries[0].Location)

                @Html.DisplayNameFor(model => model.TimeLogEntries[0].IsBillable)

                @Html.DisplayNameFor(model => model.TimeLogEntries[0].IsBilled)

                @Html.DisplayNameFor(model => model.TimeLogEntries[0].Phase)

        @foreach (var item in Model.TimeLogEntries)
        {

                    @Html.DisplayFor(model => item.Description)

                    @Html.DisplayFor(model => item.StartTime)

                    @Html.DisplayFor(model => item.EndTime)

                    @Html.DisplayFor(model => item.Location)

                    @Html.DisplayFor(model => item.IsBillable)

                    @Html.DisplayFor(model => item.IsBilled)

                    @Html.DisplayFor(model => item.Phase)

                    @Html.ActionLink("Edit", "Edit", "TimeLog", new { id = item.TimeLogEntryId }, null) |
            @Html.ActionLink("Delete", "Delete", "TimeLog", new { id = item.TimeLogEntryId }, null)

        }

I want to be able to use jQuery to add, change, and delete rows to the server-generated table, but how am I supposed to know the HTML content generated by the HTML helpers? I have already written actions on the controller that return Json, but I need to know how to format it on the client side. It seems pretty bad practice to duplicate the HTML template in my JavaScript code.

A: You can put your table in a partial view.Define an Action that returns the partial view.
and you can call the action that returns partial view by jquery after deleting function.
$.ajax({
         url: '/ActionThatReturnsPartialView',
         cache: false,
         type: 'post'
         success: function (data) {
             $('#tableID').replaceWith(data);
         },
         error: function (e) {
             alert(e.responseText);
         }
});


text:
Q: Getting bits from a packed word I have a 16 bit word that could be anywhere from 1 to 16 data values. They are decoded by knowing the MSB and lsb of the 16 bit word and grabbing those bits.
I'm using VB and I just don't know how to do this.
Example
I have a word that is
    &HA6F2
    1010 0100 1111 0010
I know my data is LSB 3 to MSB 9. Bit ordering is left to right
So the data is 010011
How do I get this in VB code? I want to work in bytes because after I get the packed bits then I have to do type casts on it (signed_fixed, integer, 2's complement, etc)
Thanks

A: You should use mask (bitwise AND, see And keyword). And also probably bitwise-right-shift (see >> operator)
Conceptually:
1010 0100 1111 0010 '= the data
0001 1111 1100 0000 '= 1FC0 the mask
-------------------- And
0000 0100 1100 0000 '= 04C0
-------------------- >> 6
0000 0000 0001 0011 '= 0013 now your value is in the right most

In the code
Dim newData As Integer = (rawData And &H1FC0) >> 6

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter + Firebase Throwing Unhandled Exception: This widget has been unmounted Error Using Navigator to change view I have a firebase driven Flutter app that is working but throwing errors.
What I expected, when the app is open the user has to login using an email and password, if the login succeeds then they are taken the a new view called WelcomeScreen.
What is happening, the users are being taken to a welcome screen after logging in but I get the following errors
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
#0      State.context.<anonymous closure> (package:flutter/src/widgets/framework.dart:1088:9)
#1      State.context (package:flutter/src/widgets/framework.dart:1094:6)
#2      _AuthScreenState.initState.<anonymous closure> (package:autos_latinos/screens/auth_screen.dart:81:35)
#3      _rootRunUnary (dart:async/zone.dart:1362:47)
#4      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
#5      _CustomZone.runUnaryGuarded (dart:async/zone.dart:1170:7)
#6      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
#7      _DelayedData.perform (dart:async/stream_impl.dart:591:14)
#8      _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
#9      _PendingEvents.schedule.<anonymous closur<…>

It seems to be pointing to this part here in my code which I use to track authStateChanges from firebase:
FirebaseAuth.instance.authStateChanges().listen((User user) {
      if (user == null) {
        print('User is currently signed out!');
        if(AuthScreen.id != '/AuthScreen'){
          Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => AuthScreen()));
        }else{
          print("Already on auth screen");
        }

      } else {
        //Send to welcome screen
        print('User is signed in!');
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => WelcomeScreen()));
      }
    });

Any Advice on how to prevent this error is much appreciated.

A: You have to dispose the listener in dispose method of stateful widget like this:
class Sample extends StatefulWidget {
  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> {
  StreamSubscription<User> _listener;

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  @override
  void initState() {
    _listener = FirebaseAuth.instance.authStateChanges().listen((User user) {
      if (user == null) {
        print('User is currently signed out!');
        if (AuthScreen.id != '/AuthScreen') {
          Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                  builder: (BuildContext context) => AuthScreen()));
        } else {
          print("Already on auth screen");
        }
      } else {
        //Send to welcome screen
        print('User is signed in!');
        Navigator.pushReplacement(
            context,
            MaterialPageRoute(
                builder: (BuildContext context) => WelcomeScreen()));
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _listener.cancel();
    super.dispose();
  }
}


text:
Q: Correct way to assign Primitive value to a Wrapper class What is a difference between in directly assigning a primitive value to a Wrapper type and using the valueOf API? i.e.
Long val = 91l;

and
Long val = Long.valueOf(91l);

This question arises from a bug that I have been breaking my head on for days now. So far I have not been able to recreate it successfully and would randomly come up. I have some objects which are generated as part of processing some data, these objects have numerous fields of which some are of type Long (Wrapper) I am sure that values are getting assigned to all of the variables, but in some cases they are just coming out NULL, even when there is no reason for that.
The manner in which this question is related is, the Set methods of these Long attributes actually take argument of type long (primitive) and were assigned using the first approach. I am not sure if that could be causing it. I have modified my code with the second approach and am waiting for some good testing to get completed before I be happy about fixing it.
I am keen to know if there is any theoretical difference in the above 2 methods that I have mentioned. (I usually use the first one most of the time.)

A: Those two lines will compile to the same bytecode (at least in all compilers I've seen). It's not clear where your problem is, but it's not there. (It's not guaranteed by the spec how the value is created, but the result is guaranteed to be an object such that the longValue() method will return the original primitive value.)
For example, decompiling this method:
static void foo() {
    Long val1 = 91L;
    Long val2 = Long.valueOf(91L);
}

ends up with:
static void foo();
  Code:
   0:   ldc2_w  #2; //long 91l
   3:   invokestatic    #4; //Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
   6:   astore_0
   7:   ldc2_w  #2; //long 91l
   10:  invokestatic    #4; //Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
   13:  astore_1
   14:  return
}

(As a small point, I'd encourage you to use L rather than l in source code as a suffix - l can look very much like 1 depending on your font.)


text:
Q: Retrieving the non-relativistic Hamiltonian from Relativistic QM I'm trying to follow section 15.5 here, which derives the low-energy limit of the Dirac equation for an electron in a EM-field.
After some manipulations (which I think I follow alright) the author arrives at this result for the non-relativistic Hamiltonian:
$$H_\text{non-rel} = \frac{1}{2m}\left[ \vec\sigma\cdot \left(\vec p -
 \frac{q}{c}\vec A\right) \right]^2 + q\phi$$
The author then says that by the help of the relation for Pauli matrices, $\sigma_i\sigma_j=\delta_{ij} + i\epsilon_{ijk}\sigma_k$ we get the result:
$$H_\text{non-rel} = \frac{1}{2m}\left(\vec p -
 \frac{q}{c}\vec A\right)^2 - \frac{q\hbar}{2mc}\vec\sigma\cdot(\nabla\times\vec A) +q\phi$$
I was trying to follow this derivation, and thought it would be smart to use another identity for Pauli matrices, namely:
$$(\vec \sigma\cdot \vec a)(\vec\sigma\cdot\vec b) = (\vec a\cdot\vec b)\mathbf{I} + i\vec\sigma\cdot(\vec a\times\vec b)$$
My thinking: If I take $\vec a \equiv \vec p - \frac{q}{c}\vec A$, then the squared factor in the first equation is just $(\vec\sigma\cdot\vec a)^2$. But since $\vec a\times\vec a=0$, the above identity should imply that the whole cross term disappears. Since the authors result obviously does not agree we with me, where is the error in my approach?
Update:
Making sure to respect what does and doesn't commute as suggested in comments and answer:
$$(\vec p -\frac{q}{c}\vec A)\times(\vec p -\frac{q}{c}\vec A) = -\frac{q}{c}(\vec p\times\vec A + \vec A\times\vec p)$$
Looking at the first term, letting it act on a test function $f$:
$$(\vec p\times\vec A)f=(-i\hbar\nabla\times\vec A)f = -i\hbar( (\nabla\times \vec A)f +(\nabla f)\times\vec A) = -i\hbar(\nabla\times\vec A - \vec A\times\nabla )f$$
Putting this back in cancels the second term and yields nicely the expected result.

A: I am not sure $\overrightarrow{a}\times\overrightarrow{a}=0$ in your case, you should take into account commutators of $p_i$ and $A_j$.


text:
Q: Calculating Partitioned Matrices from subs Say you have a matrix A which is of size P × P and a number Q < P can be used to
take a partition of said matrix, where:

*

*A1 is the upper-left sub matrix, with dimension Q × Q,

*A2 is the upper-right sub matrix, with dimension Q × (P-Q),

*A3 is the lower-left sub matrix, with dimension (P-Q) × Q,

*A4 is the lower-rightsub matrix, with dimension (P-Q) × (P-Q).

Which looks like this:
      A1 | A2
A =   ---+----
      A3 | A4

How can you calculate the matrix:

Where 0q is a Q × Q matrix with zero elements.
I'm learning from a book called "Discovering Statistics using R" and although it discusses partitioned matrices, it doesn't show how to calculate one like the one given above and unfortunately I'm having no luck on the programming or maths based searches...
Any help, either mathematically and/or example R code would be great. Thanks in advance.

A: R has various ways to grab blocks from matrices.  For instance, you can use a vector of indexes to reference a set of rows or set of columns using the extract function [, as shown in this example.  (The option drop=FALSE is needed if you must handle the case p=1 or q=1 so that R continues to treat the results as matrices and not just vectors.)
#
# Create a symmetric p-d matrix of size p+q.
#
p <- 2; q <- 3 # Both must be 1 or greater
x <- matrix(rnorm((p+q)^2 * 2), ncol=p+q)
a <- cov(x)
#
# Compute b.
#
i <- 1:p; j <- 1:q + p                         # Indexes of the blocks
b <- a[i,i, drop=FALSE] -
     a[i,j, drop=FALSE] %*% solve(a[j,j, drop=FALSE], a[j,i, drop=FALSE])

Matrix inversion is implemented by solve (which is numerically more stable and efficient than computing the inverse of a[j,j] and multiplying that by a[j,i]), the single remaining multiplication is carried out by %*%, and - subtracts one matrix from another component by component.  In this fashion the code closely parallels the mathematical expression in the question.


text:
Q: Ros launch gets stuck on robot in 5G network I am trying to set up a Ros Network between a Robot (Clearpath AGV) and a Multi-access edge computing device (MEC) via 5G. I start roscore on the MEC and launch some nodes there. Everything works fine, but when when starting any launch file on robot side they get stuck as if waiting for the roscore (with and without --wait). This happens also for a simple static_transform_publisher launch. Please find logs of an example launch and the terminal output when I interrupt via keyboard below
The Ros Network seems to be fully established since:

*

*Rostopic list/echo/info works for topics I publish to both ways

*Rosrun works on Robot and MEC

*Various networking tools (Netcat,...) show that all registered ports are open both ways

More details:

*

*Working with docker with kinetic installed.

*Containers run in host network mode

*ROS_MASTER_URI is set to the MECs IP

*ROS_IP on the robot is set to its own IP

*Both IPs are pingable from either machine.

Any help is appreciated!
Logs:
[roslaunch][INFO] 2020-10-05 15:35:44,123: starting in server mode
[roslaunch.parent][INFO] 2020-10-05 15:35:44,123: starting roslaunch parent run
[roslaunch][INFO] 2020-10-05 15:35:44,123: loading roscore config file /opt/ros/kinetic/etc/ros/roscore.xml
[roslaunch] [INFO] 2020-10-05 15:35:44,365: Added core node of type [rosout/rosout] in namespace [/]
[roslaunch.config][INFO] 2020-10-05 15:35:44,365: loading config file /root/catkin_ws/src/realsense-ro
s/realsense2_camera/launch/rs_camera. launch
[roslaunch] [INFO] 2020-10-05 15:35:44,391: Added node of type [nodelet/nodelet] in namespace [/camera/]
[roslaunch] [INFO] 2020-10-05 15:35:44,397: Added node of type [nodelet/nodelet] in namespace [/camera/]
[roslaunch][INFO] 2020-10-05 15:35:44,397: ... selected machine [] for node of type [nodelet/nodelet]
[roslaunch][INFO] 2020-10-05 15:35:44,397: ... selected machine [] for node of type [nodelet/nodelet]
[roslaunch.pmon][INFO] 2020-10-05 15:35:44,400: start_process_ monitor: creating ProcessMonitor
[roslaunch.pmon][INFO] 2020-10-05 15:35:44,400: created process monitor <ProcessMonitor(ProcessMonitor
-1, initial daemon)>
[roslaunch.pmon][INFO] 2020-10-05 15:35:44,400: start_process_ monitor: ProcessMonitor started
[roslaunch.parent][INFO] 2020-10-05 15:35:44,400: starting parent XML-RPC server
[roslaunch.server][INFO] 2020-10-05 15:35:44,400: starting roslaunch XML-RPC server
[roslaunch.server][INFO] 2020-10-05 15:35:44,400: waiting for roslaunch XML-RPC server to initialize
[xmlrpc] [INFO] 2020-10-05 15:35:44,400: XML-RPC server binding to 0.0.0.0:0
[xmlrpc] [INFO] 2020-10-05 15:35:44,401: Started XML-RPC server [http://10.0.91.105:41500/ ]
[xmlrpc] [INFO] 2020-10-05 15:35:44,401: xml rpc node: starting XML-RPC server
[roslaunch.pmon][INFO] 2020-10-05 15:35:50,254: ProcessMonitor.shutdown <ProcessMonitor (ProcessMonitor
-1, started daemon 140017957467904)>
[roslaunch.pmon][INFO] 2020-10-05 15:35:50,308: ProcessMonitor. post_run <ProcessMonitor(ProcessMonito
r-1, started daemon 140017957467904)>
[roslaunch.pmon][INFO] 2020-10-05 15:35:50,308: ProcessMonitor. post_run <ProcessMonitor(ProcessMonito
r-1, started daemon 140017957467904)>: remaining procs are []
[roslaunch.pmon][INFO] 2020-10-05 15:35:50,309: ProcessMonitor exit: cleaning up data structures and signals
[roslaunch.pmon][INFO] 2020-10-05 15:35:50,310: ProcessMonitor exit: pmon has shutdown
[rospy.core][INFO] 2020-10-05 15:35:50,312: signal_shutdown [atexit]

Terminal output:
root@CPR-R100-0067:~/catkin_ws# roslaunch realsense2_camera rs_camera. launch
«.. logging to /root/.ros/log/9cbf306c -0718-11eb-b8a5- fa163ea8af66/roslaunch-CPR-R100- 0067-954. log
Checking log directory for disk usage.
This may take awhile.
Press Ctrl-C to interruptDone checking log file disk usage.
Usage is <1GB.
^CTraceback (most recent call last):
File ""/opt/ros/kinetic/bin/roslaunch", line 35, in <module>roslaunch.main()
File "/opt/ros/kinetic/lib/python2.7/dist-packages/roslaunch/__ init__.py", line 308, in mainp.start()
File ""/opt/ros/kinetic/lib/python2.7/dist-packages/roslaunch/parent.py", line 268, in startself._start_infrastructure()
File "/opt/ros/kinetic/lib/python2.7/dist-packages/roslaunch/parent.py", Line 226, in _start_infrastructureself.start_server()
File "/opt/ros/kinetic/lib/python2.7/dist-packages/roslaunch/parent.py", line 177, in start_serverself.server.start()
File ""/opt/ros/kinetic/lib/python2.7/dist-packages/roslaunch/server.py", line 376, in startcode, msg, val = ServerProxy(self.urt).get_pid()
File "/usc/lib/python2.7/xmlrpclib.py", line 1243, tn _ callreturn self.__send(self.name, args)
File ""/usc/lib/python2.7/xmlrpclib.py", line 1602, in _ requestverbose=self. verbose
File ""/usc/lib/python2.7/xmlrpclib.py", line 1283, in requestreturn self.single_request(host, handler, request_body, verbose)
File ""/usc/lib/python2.7/xmlrpclib.py", line 1311, tn single_requestself.send_content(h, request_body)
File ""/usc/lib/python2.7/xmlrpclib.py", line 1459, tn send_contentconnection.endheaders(request_body)
File ""/usr/lib/python2.7/httplib.py", line 1082, in endheadersself._send_output(message_body)
File ""/usr/lib/python2.7/httplib.py", Line 909, in _send_outputself.send(msg)
File ""/usr/lib/python2.7/httplib.py", line 871, in sendself .connect()
File ""/usr/lib/python2.7/httplib.py", Line 848, in connectself.timeout, self.source_address)
File ""/usr/lib/python2.7/socket.py", line 566, in create_connectionsock.connect(sa)
File ""/usr/lib/python2.7/socket.py", line 228, in methreturn getattr(self._sock,name)(*args)
KeyboardInterrupt


text:
Q: How to get information from a sheet in a mail that will be automatically send I am not a developper but I working on a way to send automatic mails of information coming for a googlesheet.
here is what I want to do :
1/ get the mail adress of the ligne in the sheet 1
2/ on the sheet 2, we looking for the line where we have this adress
3/ from the sheet 2, construct an array which contain all the information for the line where we find the mail adress
4/ automatically send the mail to me which contain all the information that are in the array we created
I think that I only have a problem in getting the data in the array because I did a test by sending a "Hello world" mail, and it works.
The error is : "ReferenceError: infoRandonneur is not defined (line 8)"
I don't know it doesn't find "infoRandonneur" ...
Here is my 3 function :
function MailProduit(){

  var feuille1 = SpreadsheetApp.getActive().getSheetByName('Form Responses 1');
  var data_range1 = feuille1.getDataRange();
  var dernier_rang1 = data_range1.getLastRow();

  for(var ligne=2; ligne<=dernier_rang1;ligne++){
    var isFormulaireOk=feuille1.getRange(ligne,1).getValue();
    if(isFormulaireOk == "Formulaire OK"){

      var mail1 = feuille1.getRange(ligne,13).getValue();
      var nom1 = feuille1.getRange(ligne,4).getValue();
      var prenom1 = feuille1.getRange(ligne,5).getValue();
      envoyerMailProduit(nom1,prenom1,mail1,ligne);
      feuille1.getRange(ligne,1).setValue("Mail produit envoyé");
    }

  }
}

function envoyerMailProduit(nom,prenom,mail,ligne){

  var mailRandonneur = mail;
  var ligneProduit = ligne;

  var info = recupererInfoCommande(mailRandonneur,ligneProduit);

  var modele = HtmlService.createTemplateFromFile('ProduitCommande');
  var message = modele.evaluate().getContent();
  var adressemail = "baptistelautrette@hotmail.fr";

  modele.infoRandonneur = info;

  MailApp.sendEmail({
    to: adressemail,
    subject: "Produits à commander pour un randonneur",
    htmlBody: message
  });

}

function recupererInfoCommande(mailRandonneur,ligneRandonneur)
{
  var mailVerif=mailRandonneur;
  var ligneVerif = ligneRandonneur;
  var feuille2 = SpreadsheetApp.getActive().getSheetByName('Form Responses 2');
  var data_range2 = feuille2.getDataRange();
  var dernier_rang2 = data_range2.getLastRow();
  var valeurs = feuille2.getRange(ligneVerif,6,ligneVerif,26).getValues();

  var enregistrement = valeurs[0];
  var adressemail = "baptistelautrette@hotmail.fr";

  for(var ligne=2; ligne<=dernier_rang2;ligne++){
    var mailRecherche = feuille2.getRange(ligne,2).getValue();
    if (mailVerif == mailRecherche){
      var infoRandonneur =
      {
        sacH:enregistrement[0],
        sockH:enregistrement[1],
        tailleSockH: enregistrement[2],
        pantalonH:enregistrement[3],
        taillePantalonH:enregistrement[4],
        ponchoH:enregistrement[5],
        taillePonchoH:enregistrement[6],
        tshirtH:enregistrement[7],
        tailleTshirtH:enregistrement[8],
        polaireH:enregistrement[9],
        taillePolaireH:enregistrement[10],
        casquetteH:enregistrement[11],
        batonH:enregistrement[12],
        sacF:enregistrement[13],
        sockF:enregistrement[14],
        tailleSockF: enregistrement[15],
        pantalonF:enregistrement[16],
        taillePantalonF:enregistrement[17],
        ponchoF:enregistrement[18],
        taillePonchoF:enregistrement[19],
        tshirtF:enregistrement[20],
        tailleTshirtF:enregistrement[21],
        polaireF:enregistrement[22],
        taillePolaireF:enregistrement[23],
        casquetteF:enregistrement[24],
        batonF:enregistrement[25]
      };

      return infoRandonneur;
    }
  }
}

Here is my mail that I want to send :
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
  <p> Hello World </p>
  <p> <?= infoRandonneur.sacF ?> </p>
  </body>
</html>

For execution, I only launch MailProduit() that has to find if the situation of the hiker ('form OK' for example), then if it's ok, that launch envoyerMailProduit(), that looks on the other sheet to find the ligne where we find the adress of this hiker, get all the data from the line, and send the mail "ProduitCommande".
So, when I don't put infoRandonneur.sacF in the mail, it works, but like that it doesn't ...
If someone could help me, it would be great.
Thanks,
Baptiste L.

A: I see 3 declaration of functions but I don't see the execution order of them. Can you please update the question with it? In order to know in which line you get the error. Or is it in the email?
You say you're not a developer so maybe you don't know this but, declaring a function does not make it run, you have to CALL a function in order to get it executed.
For example:
function hello_world() {
  document.write("Hello world! - I am just plain text");
} // This declares the function

hello_world(); // This calls the function declared previously

EDIT:
So this is not the problem. Try to make some debugging of your code by writing this in a line where the variable should have a value:
document.write("Variable name: " + variable_name); // The text before the actual variable name will help you to not get lost in the output.

// An example with your code:
var info = recupererInfoCommande(mailRandonneur,ligneProduit);
document.write("Info variable: " + info); // This will output the info value at that line.

I suggest you check the variables are arriving to your functions as they are supposed.


text:
Q: How can I get darkent detected object names using qt(QProcess)? I want to call darknet detect command for single image from qt using QProcess class.
This is my code of main window:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QProcess * process = new QProcess();
    QString temp = "./darknet detect cfg/yolov3.cfg yolov3.weights
    iii.jpg";
    connect(process, SIGNAL(finished(int, QProcess::ExitStatus)),
    this, SLOT(ReadOut(int, QProcess::ExitStatus)));
    process->start(temp);
}

void MainWindow::ReadOut(int i, QProcess::ExitStatus statur)
{
  QProcess *p = dynamic_cast<QProcess *>( sender() );
  if (p)
    ui->textBrowser->append( p->readAllStandardOutput() );
  p->close();
  delete p;
}

But because after detection darkent waits for another input I can not get the output of terminal because process is still going.Or there can be another problem.
My question is this:

*

*How can I correct my code for getting detected objects names from process.

*Is there another method to implement this?

A: What you can try to do is use the QProcess::readyReadStandardOutput() signal instead of the process finish signal.

A: The most common mistakes when using QProcess are:

*

*The relative path of the program is with respect to the working Directory which is the executable folder, but often the program is not in the executable folder.

*The program can use resources related to the program so in those cases the working directory must be the directory where the program is.
Considering the above, the solution is:
#include <QtWidgets>

class DarknetWidget: public QWidget{
    Q_OBJECT
public:
    DarknetWidget(QWidget *parent=nullptr): QWidget(parent)
    {
        QGridLayout *lay = new QGridLayout(this);

        lay->addWidget(new QLabel("Darket directory:"), 0, 0);
        directory_le = new QLineEdit;
        lay->addWidget(directory_le, 1, 0);
        QPushButton *directory_button = new QPushButton("Select");
        connect(directory_button, &QPushButton::clicked, this, &DarknetWidget::onSelectDirectory);
        lay->addWidget(directory_button, 1, 1);

        lay->addWidget(new QLabel("Command:"), 2, 0);
        command_le = new QLineEdit;
        command_le->setText("darknet detect cfg/yolov3.cfg");
        lay->addWidget(command_le, 3, 0, 1, 2);

        lay->addWidget(new QLabel("weights:"), 4, 0);
        weight_le = new QLineEdit;
        lay->addWidget(weight_le, 5, 0);
        QPushButton *weight_button = new QPushButton("Select");
        connect(weight_button, &QPushButton::clicked, this, &DarknetWidget::onSelectWeight);
        lay->addWidget(weight_button, 5, 1);

        lay->addWidget(new QLabel("Input image:"), 6, 0);
        image_le = new QLineEdit;
        lay->addWidget(image_le, 7, 0);
        QPushButton *image_button = new QPushButton("Select");
        connect(image_button, &QPushButton::clicked, this, &DarknetWidget::onSelectImage);
        lay->addWidget(image_button, 7, 1);

        run_btn = new QPushButton;
        run_btn->setText("Run");
        connect(run_btn, &QPushButton::clicked, this, &DarknetWidget::runDarket);
        lay->addWidget(run_btn, 8, 0, 1, 2);

        log_te = new QPlainTextEdit;
        log_te->setReadOnly(true);
        lay->addWidget(log_te, 9, 0, 1, 2);

        resize(640, 480);

        process = new QProcess(this);
        process->setProcessChannelMode(QProcess::MergedChannels);
        connect(process, &QProcess::stateChanged, this, &DarknetWidget::onStateChanged);
        connect(process, &QProcess::readyReadStandardOutput, this, &DarknetWidget::onReadyReadStandardOutput);
    }
protected:
    void closeEvent(QCloseEvent *event){
        process->kill();
        QWidget::closeEvent(event);
    }
private Q_SLOTS:
    void onSelectDirectory(){
        QString filename = QFileDialog::getExistingDirectory(this, tr("Open Darket directory"));
        if(!filename.isEmpty()){
            directory_le->setText(filename);
        }
    }
    void onSelectWeight(){
        QString filename = QFileDialog::getOpenFileName(this, tr("Open weights path"));
        if(!filename.isEmpty()){
            weight_le->setText(filename);
        }
    }
    void onSelectImage(){
        QString filename = QFileDialog::getOpenFileName(this,
            tr("Open image path"),
            QDir::currentPath(),
            tr("Image Files (*.jpg)"));
        if(!filename.isEmpty()){
            image_le->setText(filename);
        }
    }

    void runDarket(){
        log_te->clear();
        process->setWorkingDirectory(directory_le->text());
        QString command = QString("%1 %2 %3")
            .arg(command_le->text())
            .arg(weight_le->text())
            .arg(image_le->text());
        process->start(command);
    }
    void onReadyReadStandardOutput(){
        log_te->insertPlainText(process->readAllStandardOutput());
        log_te->verticalScrollBar()->setValue(log_te->verticalScrollBar()->maximum());
    }
    void onStateChanged(QProcess::ProcessState state){
        if(state == QProcess::Running){
            run_btn->setEnabled(false);
        }
        else if(state == QProcess::NotRunning){
            run_btn->setEnabled(true);
        }
    }
private:
    QLineEdit *directory_le;
    QLineEdit *command_le;
    QLineEdit *weight_le;
    QLineEdit *image_le;
    QPushButton *run_btn;
    QPlainTextEdit *log_te;

    QProcess *process;
};

int main(int argc, char* argv[]) {
    QApplication app(argc, argv);
    DarknetWidget w;
    w.show();
    return app.exec();
}

#include "main.moc"


text:
Q: Moving data of DataGridview from left to right by clicking on the ColumnHeader I have encountered a strange problem.
When the program loads, everything is normal and the created rows are displayed correctly.
But when I click on the DataGridView header for ascending and descending sort, the DataGridView data in all rows starts moving from left to right.
I do not know where the reason is.
I made this change in this function but the problem is not solved.
private void dgvWF_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    dgvWF.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
    dgvWF.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
}

This problem did not exist before.

EDIT 1:
dataGridView1.Columns[0].Visible = false;
string myXMLfile = @"C:\Users\PC\Desktop\XMLFile1.xml";

            ds = new DataSet();
            ds.ReadXml(myXMLfile);
            dt = ds.Tables["XMLFile1"];
            if (dt != null)
            {
                dataGridView1.Rows.Clear();
                dataGridView1.Refresh();
                dataGridView1.RowCount = dt.Rows.Count + 1;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dataGridView1.Rows[i].Cells[0].Value = dt.Rows[i][0].ToString();
                    dataGridView1.Rows[i].Cells[1].Value = dt.Rows[i][1].ToString();
                }
                dataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.Automatic;
                dataGridView1.Rows[dt.Rows.Count].DefaultCellStyle.BackColor = Color.Gray;
            }
            else if (dt == null)
            {
                dataGridView1.RowCount = 1;
                dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Gray;
            }

EDIT 2:
My problem was solved.
RichTextBox rtbRootName = new RichTextBox();
string myXMLfile = @"C:\Users\PC\Desktop\XMLFile1.xml";
                DataSet ds = new DataSet();
                ds.ReadXml(myXMLfile);
                DataTable dt = ds.Tables["XMLFile1"];
                if (dt != null)
                {
                    dataGridView1.Rows.Clear();
                    dataGridView1.Refresh();
                    dataGridView1.RowCount = dt.Rows.Count + 1;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        rtbRootName.Clear(); rtbRootName.Text = dt.Rows[i][1].ToString();
                        dataGridView1.Rows[i].Cells[0].Value = rtbRootName.Rtf;
                        dataGridView1.Rows[i].Cells[1].Value = dt.Rows[i][0].ToString();
                    }
                    dataGridView1.Rows[dt.Rows.Count].DefaultCellStyle.BackColor = Color.LightGray;

                }
                else if (dt == null)
                {
                    dataGridView1.RowCount = 1;
                    dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.LightGray;
                }


text:
Q: My AES encrypt datas very shortly and doesn't decrypt them I am using AES 128 bit in cbc mode. I want to encrypt the datas and put them into the database, and then read them and decrypt. But while doing encryption due to key and vector I used, sometimes it produces an error and sometimes it doesn't. Also when it does the encryption, it encrypts some data very shortly. For example, let's assume data as "packicon_100006.png". It encrypts it as "68b275" but when I tried to decrypt this encrypted string, the app crashes. I can't find out why this happens. I am using OpenSSL with C++.
Error that I told about: A/libc: invalid address or address of corrupt block 0x9bf33a5c passed to dlfree
It's not writing anything else to logcat.
My encrypt and decrypt functions:
std::string ofxLibcrypto::encrypt(std::string plaintext) {
    unsigned char empty[] = {0};
    unsigned char *ciphertext = empty;
    int lenciphertext = encrypt((unsigned char *) plaintext.c_str(), (int) plaintext.length(), k, v,
                                ciphertext);
    std::string str(reinterpret_cast<char *>(ciphertext));
    clean();
    ofLogVerbose("ofxLibcrypto.cpp") << "encrypted";
    return ofToHex(str.substr(0, lenciphertext));
}

std::string ofxLibcrypto::decrypt(std::string ciphertext) {
    unsigned char empty[] = { 0 };
    unsigned char *plaintext = empty;
    ciphertext = ofHexToString(ciphertext);
    int lenplaintext = decrypt((unsigned char *)ciphertext.c_str(), (int)ciphertext.length(), k, v, plaintext);
    std::string str(reinterpret_cast<char*>(plaintext));
    clean();
    ofLogVerbose("ofxLibcrypto.cpp") << "decrypted";

    return str.substr(0, lenplaintext);
}

OpenSSL's encrypt and decrypt functions:
int ofxLibcrypto::encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext) {
  EVP_CIPHER_CTX *ctx;
  int len;
  int ciphertext_len;

  /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

  /* Initialise the encryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits */
  if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv)) handleErrors();

  /* Provide the message to be encrypted, and obtain the encrypted output.
   * EVP_EncryptUpdate can be called multiple times if necessary
   */
  if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)) handleErrors();
  ciphertext_len = len;

  /* Finalise the encryption. Further ciphertext bytes may be written at
   * this stage.
   */
  if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
  ciphertext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return ciphertext_len;
}

int ofxLibcrypto::decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) {
  EVP_CIPHER_CTX *ctx;
  int len;
  int plaintext_len;

  /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

  /* Initialise the decryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits */
  if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv)) handleErrors();

  /* Provide the message to be decrypted, and obtain the plaintext output.
   * EVP_DecryptUpdate can be called multiple times if necessary
   */
  if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) handleErrors();
  plaintext_len = len;

  /* Finalise the decryption. Further plaintext bytes may be written at
   * this stage.
   */
  if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
  plaintext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return plaintext_len;
}

Thanks in advance to everyone.


text:
Q: how to use batch field name in Kofax Transformation Script I have created a batch field in Kofax capture as " Invoice_from _Email"
which i need to call in KTM script to assing its value as true.
how can i call the batch field value in KTM script.?

A: There are two different options on how to do this.
Mapping a batch/root folder field:
The first would be to map the field.  In Project Builder open Project Settings and check "Enable folders" on the General tab.  This maps the KC batch to the KTM root folder and does not require you to actually create any additional folders. Then you can create a field, presumably named "Invoice_from_Email",on the root folder which you will be able to map to a KC field in the Synchronization Tool for the batch class.
Because the field is mapped, you have read/write access.
To use from script it would be:
pXRootFolder.Fields.ItemByName("Invoice_from_Email").Text

Read-only access without mapping
pXRootFolder.XValues.ItemByName("AC_FIELD_" & BatchFieldName)

From the documentation:

Note   If you cannot access the field values via script, then you need
  to check whether the "Populate all index fields for read-only access
  in script" option is selected on the Extended Synchronization Settings
  window of the Kofax Transformation Modules - Synchronization Tool.
  This option is cleared by default, and available only if Kofax Capture
  10.0.2 (service pack 2) or a newer version is installed.

If you don't see this setting it means you have an version prior to when it was added and you don't have to worry about it.


text: Q: Xamarin.Forms embed native View in xaml I've got a Xamarin.Forms Page which should display a specific View (in this case, it is a View from Lottie.Forms) but because it does not support UWP, I need to use a different Library for this (LottieUWP) which is a native one. So Iif the platform is UWP, I want to display the View inside LottieUWP. Is there a way to achieve this directly inside my portable project?


text:
Q: Using a custom date formatter on a Telerik MVC AJAX bound property column I am using the latest version of Telerik MVC controls on my ASP.NET MVC3 app with razor.
I have defined my grid structure as follows:
@(Html.Telerik()
     .Grid<GrantApplicationListViewModel>()
     .Name("grdGrantApplications")
     .Columns(column =>
     {
          column.Bound(x => x.FullName)
               .Title("Owner")
               .Width(200);

          column.Bound(x => x.CreatedDate)
               .Title("Created")
               .Width(90);
     })
     .DataBinding(dataBinding => dataBinding.Ajax().Select("AjaxGrantApplicationsBinding", "Home"))
     .Pageable(paging => paging.PageSize(30))
     .TableHtmlAttributes(new { @class = "telerik-grid" })
)

My view model looks like:
public class GrantApplicationListViewModel
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName
     {
          get { return FirstName + " " + LastName; }
     }

     public DateTime CreatedDate { get; set; }
}

I have created a date formatter that I would like to use in my column to format the date:
public static class DateTimeExtensions
{
     public static string FormatDate(this DateTime instance)
     {
          return string.Format("{0:yyyy-MM-dd}", instance);
     }
}

How would I use this format method in my column to format CreatedDate?  I tried the following:
column.Bound(x => x.CreatedDate.FormatDate())
     .Title("Created")
     .Width(90);

..and I get the following error:
Bound columns require a field or property access expression.

A: you have to bind to a property, so what you are doing will not work. What you CAN do is:
public class GrantApplicationListViewModel
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName
     {
          get { return FirstName + " " + LastName; }
     }

     public DateTime CreatedDate { get; set; }
     public DateTime FormattedDate{ get{ return FormatDate(CreatedDate)}; set; }
}

And then
column.Bound(x => x.FormattedDate)
 .Title("Created")
 .Width(90);

(The code is not syntax correct so you have to clean it up :))
you could also do
column.Bound(x => x.FormattedDate)
     .Title("Created")
     .Format("{0:MM/dd/yyyy hh:mm tt}")
     .Width(90);

If I am not mistaken

A: you can format date in GrantApplicationListViewModel class
public DateTime CreatedDate
{
 get
 {
   return string.Format("{0:yyyy-MM-dd}", this);
 }
}

This works for me. Or else you can use in the below way
public DateTime CreatedDate
    {
     get
     {
       return string.Format("{0:yyyy-MM-dd}", DateOfJoining);
     }
    }


text:
Q: CSS to position image a percentage of another image Say I have an image that has width
width: 100vw;

Is it possible to position a title say 50% of the way down from this image? I can't think of how to do it as the height will be changing based on the vw, so can this be done with CSS only, or do I need Javascript? Either way, how would I do this?
Thanks
Edit: I have tried the various suggestions below but it seems that whenever I try to use solely CSS with position:relative it messes up the rest of my code. Is there a javascript function, therefore, that can calculate the height of the image as a % of the page height, and then can I position my title at say 75% of the height of the image?

A: I'm not entirely sure if I've understood you correctly or not, but if you want to vertically centre a piece of text over the top of a responsive image, you could do this:

div {
  position: relative;
}
img {
  width: 100vw;
  height: auto;
}
p {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
}

SOME TEXT

https://jsfiddle.net/fjh6msqL/

A: Sure, add a parent around the image and set it to inline-block so that it will match the width of the image, add position: relative so that you can absolutely position your title text in relation to the parent, and then either add an element with your title text or use a pseudo element from the parent (that's what I did in this example) and absolutely position that 50% from the top, and use translateY(-50%) to move the image back up 50% of it's own height so it's in the middle of the image vertically. Here is a good article on how to center stuff using CSS https://www.w3.org/Style/Examples/007/center.en.html

div {
  display: inline-block;
  position: relative;
}
div:after {
  content: 'here is your title';
  color: white;
  background: black;
  position: absolute;
  top: 50%;
  width: 100%;
  text-align: center;
}
img {
  width: 100vw;
}

A: You can't really do that with an image without using some Javascript. The best solution I think would be to use a div element and set it's background-image property to the image you want to display, and then position your title vertically inside the div. Something like this:

Vertical positioning can be tricky, but there are ways, for example:
CSS Vertical align middle

A: With CSS margin:auto , max-height:0 with absolute position actually does the magic. this will center your title text perfectly regardless of screen size. Instead of giving title a width and height we can set top, left, right, bottom property to 0 which actually scale the element to its relative parent's size. Hope this helps.

body{
margin:0;
padding:0;
}
.img-placeholder{
  position:relative;
}
.img-placeholder img{
  width:100vw;
  height:auto;
}

.img-placeholder h2{
  position:absolute;
  margin:auto;
  top:0;
  right:0;
  bottom:0;
  left:0;
  max-height:0px;
  text-align:center;
}

Image Title


text:
Q: With memcache, redis throw exception:read error on connection In my project, I want to use redis while using memcached(It's an old system and I donnot want to outright replace memcached).But when I try to push element into a list in redis, I meet exception "read error on connection". I find if connecting memcached before connecting redis, it always throw this exception, but connecting redis firstly can avoid this problem.
ENVIRONMENT:
Nginx + php-fpm + PHP 5.3.3 + Redis 2.8.19
Use connect instead of pconnect can fix this exception. But I perfer to use pconnect.
Here is my code:
$memCache = new Memcached ('client');
$memCache->addServer('127.0.0.1', '8022');

$memCache->set ('mcKey', 1);
echo $memCache->get('mcKey');

$redis = new Redis();
$redis->pconnect('127.0.0.1', '6379', 1000);
$redis->setOption(Redis::OPT_READ_TIMEOUT, -1);

try {
    $redis->lPush('mykey', 1, 2);
    echo 'OK';
} catch (Exception $e) {
    echo $e->getMessage();
}

Any problem of the code here?


text:
Q: early binding late binding is it same as runtime and compile time? When we create object inside a function is that object created at runtime?
What are the things happen? created? at compile time and at runtime?
Is early binding and late binding also means compile time and runtime?
What is dynamic linking static linking? is it right to think compile time when I hear static? damn I so confused?
sorry guys I know my english is bad and also please make your answers and examples beginner friendly as possible.

A: Early binding is like going getting tomatoes from the refridgerator and putting them on the table before you starting cooking the soup.
Late binding is starting cooking the soup, and when you need tomatoes, then you go to get them from the refridgerator.
Cooking the soup is run time.
Getting the knife,spoon and saucepan ready is compile time. (It doesn't involve tomatoes.)

Ok here's a pseudo coded explanation :
late binding :
... get :
if (myvar is null) myvar = new object;
return myvar

early binding
myvar = new object;
... get :
return myvar

A:
When we create object inside a function is that object created at
  runtime?
What are the things happen? created? at compile time and at runtime?

That depends on what you mean by "object." If you mean a class instance, then yes it will be created at runtime on either the stack or the heap. Statically allocated objects, like strings or types explicitly declared as static, will be created at compile-time in the data segment. Static variables live for the life of the program.

Is early binding and late binding also means compile time and runtime?

From Wikipedia:

With early binding the compiler statically verifies that there are one
  or more methods with the appropriate method name and signature. This
  is usually stored in the compiled program as an offset in a virtual
  method table ("v-table") and is very efficient. With late binding the
  compiler does not have enough information to verify the method even
  exists, let alone bind to its particular slot on the v-table. Instead
  the method is looked up by name at runtime.

In a nutshell, in early binding the compiler looks up the method and its offset in the symbol table, so that information must be available, whereas in late binding that can't be done, and the runtime must look it up. Note that late binding is very different from dynamic dispatch, though they are often used synonymously, in that the latter refers to using a dispatch table or "vtable" to store pointers to a method's implementation, which may be overridden.

What is dynamic linking static linking?

Basically this is difference between including referenced files or "libraries" in the final executable (static) and placing them into the program image at runtime. Obviously, the former adds unnecessary size to the executable, but (1) you never have to worry about dependency issues and (2) program start up is more efficient. On the other hand, dynamic linking (1) saves spaces and (2) allows library updates to occur in one place.

A: Nothing in Java is statically linked, but it is statically bound. "Static" means the compiler identifies the exact description of the function to be called: class name, method name, argument types. It does NOT determine its address in memory. That's the difference between static binding and static linking, and this means that it is still not known at compile time what code will be executed when you call a static method. It depends on what's in the .class file that the JVM loads at runtime. Java statically binds all calls to static methods -- hence the keyword. It also applies static binding to private methods, since they cannot be overridden. A similar argument applies to final methods.
Dynamic binding means that the compiler decides everything like in the static case, except for the class which contains that method. The exact class is determined at the last moment before calling the method, relative to the object on which the method is being called. Object.equals is such a dynamically bound method. This means that the same line of code can call a different method each time it is executed.
Early binding == static binding; late binding == dynamic binding. These are synonyms.

A: early binding is a assignment of value to design time where a late binding is a assignment of value to runtime
There is only difference between run time and design time it must show the value of assignment .
For example:
//early binding
myvar =new myvar();
// get
retutn myvar


text:
Q: Using Pandas for Multple Time-Varying Trials I'm just getting into Pandas, and want to figure out a good way of holding time-varying data corresponding to multiple trials.
A concrete example might be:
Trial 1: Salinity = 0.1 (unchanging), pH (at time 1, 2, ...)
Trial 2: Salinity = 0.1 (unchanging), pH (at time 1, 2, ...)
Trial 3: Salinity = 0.2 (unchanging), pH (at time 1, 2, ...)
Trial 4: Salinity = 0.2 (unchanging), pH (at time 1, 2, ...)

Where you'll notice that experiments can be repeated multiple times with the same initial parameters (the salinity), but with different time-varying variables (pH).
A DataFrame is 2-dimensional, so I would have to create a DataFrame for each trial. Is this the best way to go about it, and how would I be able to combine them (ex: get the average pH over time for trials with the same initial setup)?

A: You can aggregate the data across Trials in a single pd.DataFrame. Below is an example.
df = pd.DataFrame({'Trial': [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4],
                   'Date': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4],
                   'Salinity': [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,
                                0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2],
                   'pH': [2, 4, 1, 4, 6, 8, 3, 2, 9, 3, 1, 4, 6, 11, 4, 6]})

df = df.set_index(['Trial', 'Date', 'Salinity'])

#                      pH
# Trial Date Salinity
# 1     1    0.1        2
#       2    0.1        4
#       3    0.1        1
#       4    0.1        4
# 2     1    0.1        6
#       2    0.1        8
#       3    0.1        3
#       4    0.1        2
# 3     1    0.2        9
#       2    0.2        3
#       3    0.2        1
#       4    0.2        4
# 4     1    0.2        6
#       2    0.2       11
#       3    0.2        4
#       4    0.2        6

Explanation

*

*In your dataframe construction, assign an identifier column, in this case Trial with an integer identifier.

*Setting index by ['Trial', 'Date', 'Salinity'] provides a natural index for pandas to use for grouping, indexing and slicing.

*For example, df.loc[(1, 2, 0.1)] will return a pd.Series derived from the dataframe indicating pH = 4.


text:
Q: C++ strange namespace lookup behavior namespace fooo {
  class Fooo {
  public:
    int a;
  };
}

namespace fooo {
  class Test {
  public:
    Test(Fooo::Fooo *i) {
      i->a = 1;
    }
  };
}

This code compiles fine with clang (any version) but fails with gcc.
Can anyone explain why?
EDIT:
Yes, I know the issue here is kinda obvious but why does clang accept it? The person who told me this said that this is a bug in the standard and that there is a Defect Report. Can anyone point to the actual DR?

A: The error message from gcc tells you exactly what the problem is:
t.cpp:11:16: error: 'fooo::Fooo::Fooo' names the constructor, not the type
     Test(const Fooo::Fooo *i) {
                ^

it is suprising that clang doesn't give an error.


text:
Q: PHP Custom Markup Language Parser I am making a website, and I would like to make a custom Markup type language in PHP. I want the tags to be surrounded with [ and ]. Now, I was thinking about this, like anyone would, and I could do something like this:
function formatMarkup($markup = ''){
    $markup = str_replace('[color=blue]', '<span style="color: blue">', $markup);
    return $markup
}

Even though that might work, it would be more progrematically correct if it would do something like explode(), but starting at every [ and ending at every ]. This would be great if I found out. Thank you for your time and effort.
EDIT:
I have decided to use preg_split(). It seems nice, and all, but I cannot get the regex. Here is my code.
EDIT #2:
I have got most of the regex done, but there are uneeded extra keys in the array. How would I fix them? Here is my new code.

A: I have made my Markup language. I used
$split = preg_split("/(\[|\])/", $markup);

to get the individual "tags" and used
foreach($split as $k => $v){
        if(strlen($v) < 1){
            continue;
        }

to illiterate through each of them, and check if the value is empty. Then, after that, I would do all of my checks, and parse the code blocks together, and make line, after line, the re-constructed text.


text:
Q: Протокол поверх TCP, язык C, Windows Возникла потребность организовать определенный протокол поверх TCP, который работает по принципу:
1) Сторона А отправляет данные стороне Б (int, char, double, не суть важно);
2) Сторона А ожидает 1 байт - подтверждение, что данные приняты и обработаны на стороне Б, а не валяются во внутреннем буфере системы на стороне А (или даже на стороне Б).
Проблема в том, что сторона Б может нарушить логическую согласованность действий, например с целью обрушения стороны А.
Сторона Б в ответ на пришедшие данные может отправить не 1 байт с подтверждением, а два, или больше. Или даже отправить один байт сразу, а где-то после получения байта на стороне А, но до отправки следующих данных на стороне А, отправить еще.
Таким образом будет рассогласование, и я не понимаю, как его проконтролировать на стороне А.
В целях упрощения можно считать, что А шлет данные, а Б шлет подтверждения, что это односторонний канал посылки данных.
Например, как эта проблема решается в таких протоколах, как SIP? Как контролируется, что пришел ответ именно "ACK", а не "ACK^53"?
Надеюсь, мне удалось описать суть проблемы достаточно ясно.

A: Строгое решение проблемы:

*

*В заголовок протокола, который Вы накладываете на TCP, добавляете два поля: ID сообщения и CRC32

*Отправляющая сторона, после передачи пакета данных, заносит его ID, CRC32 и время отправки пакета в список отправленных сообщений

*Принимающая сторона, получив пакет с данными, данные оставляет у себя, а заголовок с ID и CRC32 отправляет обратно

*Отправитель, получив подтверждение, вычёркивает этот пакет из списка отправленных.

*Заодно, отправитель проверяет, нет ли в списке отправленных пакетов, на которых не пришло подтверждение по истечению таймаута. Такие пакеты передаются повторно.


text:
Q: Confirming endpoints were deleted in SageMaker notebook I'm just testing out AWS Sagemaker notebook and created an endpoint using a partial script below:
endpoint_name = 'engine' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
endpoint_config_name = 'engine_config' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
model_name = 'engine_model' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())

while status=='Creating':
    time.sleep(60)
    resp = sm_client.describe_endpoint(EndpointName=endpoint_name)
    status = resp['EndpointStatus']
    print("Status: " + status)

I'm trying to remove that endpoint by using:
sm_client.delete_endpoint(EndpointName=endpoint_name)
However, it didn't work because I naively used timestamps for the endpoint_name and I didn't remember them. The original variable values were overriden when I re-run the code. As a result, I can't delete the existing endpoint.
I went to the Sagemaker management dashboard --> inference --> endpoints, but it's empty. I don't even know if I'm currently having any active endpoints or not. Please advise how to delete my endpoint in this case. Thank you in advance.

A: If there are no endpoints active under the "Endpoints" tab in the SageMaker service console, then you will not be incurring any charges for inference or endpoint infrastructure.
If this is the case, your Endpoints tab should look like the following:

Endpoint Configurations, on the other hand, involve the metadata necessary for an endpoint deployment. This is just the metadata, and are stored (without cost) in your account, visible in the console under the "Endpoint Configurations" tab. You do not need to remove these configurations when tearing down an endpoint.
Important note: Double check that you are checking in the console for the region you would have deployed to. For example, if you ran the notebook and deployed an endpoint in us-east-1, but check the SageMaker console for us-west-2, it would not be displaying endpoints from the other region.


text:
Q: Acces 3D Matrix with 2D index and 1D vector I have a 3D matrix A (size m*n*k) where m=latitude, n*longitude and k=time.
I want only specific values from first and second dimension, specified by a logical matrix B (size m*n), and I want only the timesteps specified by vector C (size k).
In the end this should become a 2D matrix D, since the first two dimesions will colapse to one.
What is the most easy approach to do this?
And also is it possible to combine logical with linear indizes here? For example B is logical and C is linear?
Sample code with rand:
A=rand(10,10,10);
B=randi([0 1], 10,10);
C=randi([0 1], 10,1);
D=A(B,C) %This would be my approach which doesnt work. The size of D should be sum(B)*sum(c)

Another example without rand:
A=reshape([1:27],3,3,3);
B=logical([1,0,0;1,0,0;0,0,0]);
C=(1,3); %get data from timestep 1 and 5

D=A(B,C);%What I want to do, but doesnÄt work that way

D=[1,19;2,20];%Result should look like this! First dimension is now all data from dimesion 1 and 2. New dimesion 2 is now the time.

A: A = rand(4,4,4);
B = randi([0 1], 4,4)
B =
     1     1     0     1
     1     0     1     1
     0     0     1     0
     1     0     1     1

>> C = randi([0 1],1,1,4);
>> C(:)
ans =
     0
     1
     1
     0

Then use bsxfun or implicit expansion expansion whith .* if newer Matlab version to generate a matrix of logical for you given coordinates.
>> idx = logical(bsxfun(@times,B,C))

idx(:,:,1) =
     0     0     0     0
     0     0     0     0
     0     0     0     0
     0     0     0     0
idx(:,:,2) =
     1     1     0     1
     1     0     1     1
     0     0     1     0
     1     0     1     1
idx(:,:,3) =
     1     1     0     1
     1     0     1     1
     0     0     1     0
     1     0     1     1
idx(:,:,4) =
     0     0     0     0
     0     0     0     0
     0     0     0     0
     0     0     0     0

Then your output is D = A(idx).  However, note that this D is now an Nx1 array.  Where N is number of true elements is B times number of true elements in C.  10x True in B and 2x True in C:
>> size(D)

ans =

    20     1

A: An easy way to do it is to first reshape A into an m*n-by-k matrix, then do your indexing:
result = reshape(A, [], size(A, 3));
result = result(B, C);

In this case C can be either a logical vector or vector of indices.


text:
Q: Trigger a div on an external button/ click on slick slider I have used a Slick Slider on my page. Now, everything works fine, but I have to make the particular div triggered on a specific button press. It is like if I have div-2, and I have a button named as button-2 somewhere in the section, on click of it, the slick slider should change it to the div 2, making it active with the right active slick dots.
I have researched about it and got to know that sliderGoTo will do my job. But I don't know why it is not working fine. I have tried my level best, but somehow the button doesn't trigger the right div at all.
What I have tried so far (in pseudo form):

$(document).ready(function() {
  $('.box').slick({
    dots: true,
    arrows: false
  });

  $('#trigger-button').click(function() {
      slideIndex = $(this).index();
      $('.slideshow').slickGoTo(parseInt(slideIndex));
    )
  }
});

/*$('#trigger-button').click(function() {
  var slider = $('.box');
  slider[1].slickGoTo(parseInt(actIndex));
})*/

//Alternatively used
Button 2

    Some content

    Some content

I have tried this also, since I want the specific div to be triggered that is div-2, to be triggered when we press the button with the id trigger-button. Can be found as the comment.
But no results. I don't have much experience with usage of SLICK SLIDER, but I have tried. I would be glad to learn more about it. Thanks
EDITS
Thank You guys for helping me out. I have found one solution for me, and that too in an easier way. If you want to go to a specific pos, you have to use this syntax and your work is done :
$('.box').slick('slickGoTo', divNo). Remember divNo = currentPos - 1.
Nowadays, the slickGoTo doesn't work like the previous syntax which is .slickGoTo(parseInt(slideIndex));. It will give you an error which is Undefined slickGoTo method. Proper usage is depicted in my code. Thanks again, and I'm sure this will help people in future references.

A: You have some error in your code.How you can get the index of element is depends upon your elements on HTML
But currently you have to div so you can set index as 1 and increment/reset onclick of button.
Replace
$('#trigger-button').click(function() {
      slideIndex = $(this).index();
      $('.slideshow').slickGoTo(parseInt(slideIndex));
    )
  }

To
var indexVal=1;  $("#trigger-button").click(function(e){
        e.preventDefault();
       // slideIndex = $(this).index();
        $( '.box' ).slickGoTo(indexVal);
        indexVal=indexVal+1;
        if(indexVal>2){
        indexVal=1;
        } });

Here is a working snippet for you:

$(document).ready(function() {
  $(".box").slick({
        dots: true,
    arrows: false
    });

});
var indexVal=1;
 $("#trigger-button").click(function(e){
        e.preventDefault();
       // slideIndex = $(this).index();
        $( '.box' ).slickGoTo(indexVal);
        indexVal=indexVal+1;
        if(indexVal>2){
        indexVal=1;
        }
    });

/*$('#trigger-button').click(function() {
  var slider = $('.box');
  slider[1].slickGoTo(parseInt(actIndex));
})*/

//Alternatively used

    <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/jquery.slick/1.3.6/slick.css"/>

Button 2

    Some content1

    Some content2

A: Try using $('.box').slick('slickGoTo', parseInt(slideIndex), false); instead.
On a side note: I'm not sure using .index() will always work as intended.
Check https://github.com/kenwheeler/slick for more details.


text:
Q: Readline method in Android TCP Server not reading the message sent from my Python Client I am trying to send a message named "ringdoor" from the python client to the android TCP server. However, the readline method in the Server code is not reading the message.
please note:
1) that I am using "sendall" to send the message from the python client
2)I am using the bufferedReader class and readline method to read messages from the client.
3) The codes for the client and the server are below.
Server code in Java
package com.example.mmz_10.test7;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       // startService(new Intent(getBaseContext(), Server.class));

        Thread ServerThread= new Thread(new MyServerThread());
        // starting the thread to do work in the background
        ServerThread.start();

       // Log.d("Server.java", "Starting server...");
    }

    // https://developer.android.com/reference/java/lang/Thread.html
    public  class MyServerThread implements Runnable {
        Socket socket;
        ServerSocket serverSocket;
        InputStreamReader isr;
        BufferedReader br;
        String message;
        @Override
        public void run (){

            try
            {

                int port = 8080;
                serverSocket = new ServerSocket(port);
                // Now the server just started and is listening to  port 4457
                System.out.println ("the server just started and is listening to  port 4457");
                //To make Server  run forever, we use "while(true)" loop as shown below

                while(true)
                {
                    //Reading the message from the client (raspberry pi 3)
                   //   Log.d("Server.java", "Listening on port " + port);
                    socket = serverSocket.accept();
                    System.out.println ("the server just accepted the connection from the client");
                    System.out.println ("preparing to read the message" );
                     isr = new InputStreamReader(socket.getInputStream()); // side note :InputStreamReader is equivalent to DataInputStream
                     br = new BufferedReader(isr);
                     message = br.readLine(); //  message received from the client
                    System.out.println ("preparing to print the message" );
                    if (message!=null){
                        System.out.println ("the messagee is not null");

                    }else {
                        System.out.println ("the message is null");
                    }

                   // System.out.println(br);

                    if (message.equals("ring")){
                        // starting an activity from the service
                        Intent intent = new Intent(MainActivity.this, RingCall.class); // The " Server.this" or in general "ClassName.this" is used  for nested classes when an  inner class need to  use the outer class
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } // end of if

                } // end of the "while(true)" loop
            } // end of the "try block"
            catch (IOException e)
            {
                e.printStackTrace();
            }
            //finally
            //{
              //  try
                //{
                   // socket.close();
                //}
                //catch(Exception e){}
            //}

        }// end of the "run" method
    } // end of "MyServerThread" class

}

**Client in python**

Import socket
import sys

try:
    s=socket.scoket(socket.AF_INET,socket.SOCK_STREAM)

except socket.error:

    print ('Failed to create socket')

    sysc.exit();

print ('Socket Created')

port=8080

remote_ip="192.168.0.100"

s.connect((remote_ip,port))

message="ring"

try:

  s.sendall(b'ringdoor')

except socket.error

  print ('send failed)

   sys.exit()

print ('message sent successfully to the server')


text:
Q: Error installing Deepface due to dependency conflicts I am trying to install Deepface, but when I run pip3 install deepface I get this error:
from deepface import DeepFace
Requirement already satisfied: deepface in /opt/homebrew/lib/python3.10/site-packages (0.0.75)
Collecting pandas>=0.23.4
  Using cached pandas-1.4.4-cp310-cp310-macosx_11_0_arm64.whl (10.4 MB)
Collecting Flask>=1.1.2
  Using cached Flask-2.2.2-py3-none-any.whl (101 kB)
Requirement already satisfied: numpy>=1.14.0 in /opt/homebrew/lib/python3.10/site-packages (from deepface) (1.23.2)
Requirement already satisfied: mtcnn>=0.1.0 in /opt/homebrew/lib/python3.10/site-packages (from deepface) (0.1.1)
Collecting tqdm>=4.30.0
  Downloading tqdm-4.64.1-py2.py3-none-any.whl (78 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 78.5/78.5 kB 1.3 MB/s eta 0:00:00
Collecting retina-face>=0.0.1
  Using cached retina_face-0.0.12-py3-none-any.whl (15 kB)
Requirement already satisfied: keras>=2.2.0 in /opt/homebrew/lib/python3.10/site-packages (from deepface) (2.10.0)
Requirement already satisfied: Pillow>=5.2.0 in /opt/homebrew/lib/python3.10/site-packages (from deepface) (9.2.0)
Collecting gdown>=3.10.1
  Using cached gdown-4.5.1-py3-none-any.whl
Requirement already satisfied: opencv-python>=4.5.5.64 in /opt/homebrew/lib/python3.10/site-packages (from deepface) (4.6.0.66)
Collecting deepface
  Using cached deepface-0.0.74-py3-none-any.whl (63 kB)
  Using cached deepface-0.0.73-py3-none-any.whl (63 kB)
  Using cached deepface-0.0.72-py3-none-any.whl (62 kB)
  Using cached deepface-0.0.71-py3-none-any.whl (62 kB)
  Using cached deepface-0.0.70-py3-none-any.whl (62 kB)
  Using cached deepface-0.0.69-py3-none-any.whl (62 kB)
  Using cached deepface-0.0.68-py3-none-any.whl (61 kB)
  Using cached deepface-0.0.67-py3-none-any.whl (61 kB)
  Using cached deepface-0.0.66-py3-none-any.whl (61 kB)
  Using cached deepface-0.0.65-py3-none-any.whl (59 kB)
  Using cached deepface-0.0.64-py3-none-any.whl (59 kB)
  Using cached deepface-0.0.63-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.62-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.61-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.60-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.59-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.58-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.57-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.56-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.55-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.54-py3-none-any.whl (60 kB)
  Using cached deepface-0.0.53-py3-none-any.whl (59 kB)
  Using cached deepface-0.0.52-py3-none-any.whl (59 kB)
  Using cached deepface-0.0.51-py3-none-any.whl (57 kB)
  Using cached deepface-0.0.50-py3-none-any.whl (56 kB)
  Using cached deepface-0.0.49-py3-none-any.whl (55 kB)
  Using cached deepface-0.0.48-py3-none-any.whl (54 kB)
  Using cached deepface-0.0.47-py3-none-any.whl (55 kB)
  Using cached deepface-0.0.46-py3-none-any.whl (53 kB)
  Using cached deepface-0.0.45-py3-none-any.whl (52 kB)
  Using cached deepface-0.0.44-py3-none-any.whl (52 kB)
  Using cached deepface-0.0.43-py3-none-any.whl (51 kB)
  Using cached deepface-0.0.41-py3-none-any.whl (50 kB)
  Using cached deepface-0.0.40-py3-none-any.whl (51 kB)
  Using cached deepface-0.0.39-py3-none-any.whl (52 kB)
  Using cached deepface-0.0.38-py3-none-any.whl (52 kB)
  Using cached deepface-0.0.37-py3-none-any.whl (51 kB)
  Using cached deepface-0.0.36-py3-none-any.whl (51 kB)
  Using cached deepface-0.0.35-py3-none-any.whl (51 kB)
  Using cached deepface-0.0.34-py3-none-any.whl (51 kB)
  Using cached deepface-0.0.33-py3-none-any.whl (49 kB)
  Using cached deepface-0.0.32-py3-none-any.whl (50 kB)
  Using cached deepface-0.0.31-py3-none-any.whl (32 kB)
  Using cached deepface-0.0.30-py3-none-any.whl (33 kB)
  Using cached deepface-0.0.26-py3-none-any.whl (32 kB)
  Using cached deepface-0.0.25-py3-none-any.whl (32 kB)
  Using cached deepface-0.0.24-py3-none-any.whl (30 kB)
  Using cached deepface-0.0.23-py3-none-any.whl (29 kB)
  Using cached deepface-0.0.22-py3-none-any.whl (28 kB)
  Using cached deepface-0.0.21-py3-none-any.whl (27 kB)
  Using cached deepface-0.0.20-py3-none-any.whl (27 kB)
  Using cached deepface-0.0.19-py3-none-any.whl (26 kB)
  Using cached deepface-0.0.18-py3-none-any.whl (26 kB)
  Using cached deepface-0.0.16-py3-none-any.whl (26 kB)
  Using cached deepface-0.0.15-py3-none-any.whl (26 kB)
  Using cached deepface-0.0.14-py3-none-any.whl (26 kB)
Requirement already satisfied: matplotlib>=2.2.2 in /opt/homebrew/lib/python3.10/site-packages (from deepface) (3.5.3)
  Using cached deepface-0.0.13-py3-none-any.whl (26 kB)
  Using cached deepface-0.0.12-py3-none-any.whl (26 kB)
  Using cached deepface-0.0.11-py3-none-any.whl (26 kB)
  Using cached deepface-0.0.10-py3-none-any.whl (22 kB)
  Using cached deepface-0.0.9-py3-none-any.whl (20 kB)
  Using cached deepface-0.0.7-py3-none-any.whl (20 kB)
  Using cached deepface-0.0.6-py3-none-any.whl (20 kB)
  Using cached deepface-0.0.5-py3-none-any.whl (19 kB)
  Using cached deepface-0.0.4-py3-none-any.whl (18 kB)
  Using cached deepface-0.0.3-py3-none-any.whl (17 kB)
  Using cached deepface-0.0.2-py3-none-any.whl (17 kB)
  Using cached deepface-0.0.1-py3-none-any.whl (12 kB)
ERROR: Cannot install deepface==0.0.1, deepface==0.0.10, deepface==0.0.11, deepface==0.0.12, deepface==0.0.13, deepface==0.0.14, deepface==0.0.15, deepface==0.0.16, deepface==0.0.18, deepface==0.0.19, deepface==0.0.2, deepface==0.0.20, deepface==0.0.21, deepface==0.0.22, deepface==0.0.23, deepface==0.0.24, deepface==0.0.25, deepface==0.0.26, deepface==0.0.3, deepface==0.0.30, deepface==0.0.31, deepface==0.0.32, deepface==0.0.33, deepface==0.0.34, deepface==0.0.35, deepface==0.0.36, deepface==0.0.37, deepface==0.0.38, deepface==0.0.39, deepface==0.0.4, deepface==0.0.40, deepface==0.0.41, deepface==0.0.43, deepface==0.0.44, deepface==0.0.45, deepface==0.0.46, deepface==0.0.47, deepface==0.0.48, deepface==0.0.49, deepface==0.0.5, deepface==0.0.50, deepface==0.0.51, deepface==0.0.52, deepface==0.0.53, deepface==0.0.54, deepface==0.0.55, deepface==0.0.56, deepface==0.0.57, deepface==0.0.58, deepface==0.0.59, deepface==0.0.6, deepface==0.0.60, deepface==0.0.61, deepface==0.0.62, deepface==0.0.63, deepface==0.0.64, deepface==0.0.65, deepface==0.0.66, deepface==0.0.67, deepface==0.0.68, deepface==0.0.69, deepface==0.0.7, deepface==0.0.70, deepface==0.0.71, deepface==0.0.72, deepface==0.0.73, deepface==0.0.74, deepface==0.0.75 and deepface==0.0.9 because these package versions have conflicting dependencies.

The conflict is caused by:
    deepface 0.0.75 depends on tensorflow>=1.9.0
    deepface 0.0.74 depends on tensorflow>=1.9.0
    deepface 0.0.73 depends on tensorflow>=1.9.0
    deepface 0.0.72 depends on tensorflow>=1.9.0
    deepface 0.0.71 depends on tensorflow>=1.9.0
    deepface 0.0.70 depends on tensorflow>=1.9.0
    deepface 0.0.69 depends on tensorflow>=1.9.0
    deepface 0.0.68 depends on tensorflow>=1.9.0
    deepface 0.0.67 depends on tensorflow>=1.9.0
    deepface 0.0.66 depends on tensorflow>=1.9.0
    deepface 0.0.65 depends on tensorflow>=1.9.0
    deepface 0.0.64 depends on tensorflow>=1.9.0
    deepface 0.0.63 depends on tensorflow>=1.9.0
    deepface 0.0.62 depends on tensorflow>=1.9.0
    deepface 0.0.61 depends on tensorflow>=1.9.0
    deepface 0.0.60 depends on tensorflow>=1.9.0
    deepface 0.0.59 depends on tensorflow>=1.9.0
    deepface 0.0.58 depends on tensorflow>=1.9.0
    deepface 0.0.57 depends on tensorflow>=1.9.0
    deepface 0.0.56 depends on tensorflow>=1.9.0
    deepface 0.0.55 depends on tensorflow>=1.9.0
    deepface 0.0.54 depends on tensorflow>=1.9.0
    deepface 0.0.53 depends on tensorflow>=1.9.0
    deepface 0.0.52 depends on tensorflow>=1.9.0
    deepface 0.0.51 depends on tensorflow>=1.9.0
    deepface 0.0.50 depends on tensorflow>=1.9.0
    deepface 0.0.49 depends on tensorflow>=1.9.0
    deepface 0.0.48 depends on tensorflow>=1.9.0
    deepface 0.0.47 depends on tensorflow>=1.9.0
    deepface 0.0.46 depends on tensorflow>=1.9.0
    deepface 0.0.45 depends on tensorflow>=1.9.0
    deepface 0.0.44 depends on tensorflow>=1.9.0
    deepface 0.0.43 depends on tensorflow>=1.9.0
    deepface 0.0.41 depends on tensorflow>=1.9.0
    deepface 0.0.40 depends on tensorflow>=1.9.0
    deepface 0.0.39 depends on tensorflow>=1.9.0
    deepface 0.0.38 depends on tensorflow>=1.9.0
    deepface 0.0.37 depends on tensorflow>=1.9.0
    deepface 0.0.36 depends on tensorflow>=1.9.0
    deepface 0.0.35 depends on tensorflow>=1.9.0
    deepface 0.0.34 depends on tensorflow>=1.9.0
    deepface 0.0.33 depends on tensorflow>=1.9.0
    deepface 0.0.32 depends on tensorflow>=1.9.0
    deepface 0.0.31 depends on tensorflow>=1.9.0
    deepface 0.0.30 depends on tensorflow>=1.9.0
    deepface 0.0.26 depends on tensorflow>=1.9.0
    deepface 0.0.25 depends on tensorflow>=1.9.0
    deepface 0.0.24 depends on tensorflow>=1.9.0
    deepface 0.0.23 depends on tensorflow>=1.9.0
    deepface 0.0.22 depends on tensorflow>=1.9.0
    deepface 0.0.21 depends on tensorflow>=1.9.0
    deepface 0.0.20 depends on tensorflow>=1.9.0
    deepface 0.0.19 depends on tensorflow>=1.9.0
    deepface 0.0.18 depends on tensorflow>=1.9.0
    deepface 0.0.16 depends on tensorflow>=1.9.0
    deepface 0.0.15 depends on tensorflow>=1.9.0
    deepface 0.0.14 depends on tensorflow>=1.9.0
    deepface 0.0.13 depends on tensorflow>=1.9.0
    deepface 0.0.12 depends on tensorflow>=1.9.0
    deepface 0.0.11 depends on tensorflow>=1.9.0
    deepface 0.0.10 depends on tensorflow>=1.9.0
    deepface 0.0.9 depends on tensorflow>=1.9.0
    deepface 0.0.7 depends on tensorflow>=1.9.0
    deepface 0.0.6 depends on tensorflow>=1.9.0
    deepface 0.0.5 depends on tensorflow>=1.9.0
    deepface 0.0.4 depends on tensorflow>=1.9.0
    deepface 0.0.3 depends on tensorflow>=1.9.0
    deepface 0.0.2 depends on tensorflow>=1.9.0
    deepface 0.0.1 depends on tensorflow>=1.9.0

To fix this you could try to:
1. loosen the range of package versions you've specified
2. remove package versions to allow pip attempt to solve the dependency conflict

ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts

I also tried to follow this:
How to Install Deepface (Python Face Recognition Package) on M1 Mac?
But did not fix the problem.
When this line of code runs for example from deepface import Deepface I then get this error:
ImportError: cannot import name 'Deepface' from partially initialized module 'deepface' (most likely due to a circular import)
How can I install Deepface so it works?


text:
Q: How to create drop down list using Laravel-Excel I tried creating drop down list using laravel excel but after download dropdown list seems not to appear and doesnt even throw errors.
Here is the code below:
$excelsheet->sheet('ClassBoardData', function($sheet1) use($cc, $highrowofclass, $highrowofboard) {
                $variantsSheet = $sheet1->_parent->getSheet(1);
                $range = 'B1:B' . $highrowofclass;
              $sheet1->_parent->addNamedRange(new \PHPExcel_NamedRange('classdata', $variantsSheet, $range));

            $objValidation = $sheet1->getCell('A1')->getDataValidation();
            $objValidation->setType(\PHPExcel_Cell_DataValidation::TYPE_LIST);
            $objValidation->setErrorStyle(\PHPExcel_Cell_DataValidation::STYLE_INFORMATION);
            $objValidation->setAllowBlank(false);
            $objValidation->setShowInputMessage(true);
            $objValidation->setShowErrorMessage(true);
            $objValidation->setShowDropDown(true);
            $objValidation->setErrorTitle('Input error');
            $objValidation->setError('Value is not in the list.');
            $objValidation->setPromptTitle('Pick from the list');
            $objValidation->setPrompt('Please pick a value from the drop-down list.');
            $objValidation->setFormula1('classdata');
        });

A: I've found that when using Maatwebsite's Laravel Excel, addNamedRange doesnt work as expected.
You have to change:
$objValidation->setFormula1('classdata');

To:
$objValidation->setFormula1('ProductList!$A$2:$A$7');

Where ProductList is your sheet name and A2:A7 are the cells


text:
Q: Power App Reset Button - Resets to Default when I want a blank
New to Power Apps . I have a power app linked to a Power BI Record . In this scenario where it brings a rental value from the Power BI Record , initially it should take the value for the customer from the Power BI record . When an user clicks on the RESET button it should blank the text box, but it resets it to the default which is the Power BI Record value . Is there a way to get a value when the form comes up and then when the RESET button is pressed it wipes out the text box instead of going to what is in the DEFAULT property for the text box/ data card in the power app ?

A: Please have a look here http://powerappsguide.com/blog/post/controls-how-to-reset-or-clear-data-entry-controls-and-form-values, this very well explains resetting the values.


text:
Q: Android button place icon on top of it I want to place an image/icon on top of the button how can i reach that same as zindex in css. how can i reach that.
Below is a example of my layout file and xml file of the button.
Layout File.axml
<Button
android:text="RTC Alarm"
android:textColor="#FFFFFF"
android:textSize="30sp"
android:layout_width="270dp"
android:layout_height="80dp"
android:background="@drawable/ButtonInfo"
android:shadowColor="#C4BEBE"
android:layout_gravity="center"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="5"
android:layout_marginTop="10.1dp"
android:layout_marginBottom="10.1dp"
android:id="@+id/btnAlA" />

ButtonInfo.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/inzien"
android:width="40dp"
android:height="40dp"
android:left="0dp"
android:top="20dp"
/>
<item>
<shape>
<corners
android:radius="14dp"
/>
<gradient
android:angle="270"
android:centerX="35%"
android:centerColor="#9C0009"
android:startColor="#C7000B"
android:endColor="#000000"
android:type="linear"
/>
<padding
android:left="0dp"
android:top="0dp"
android:right="0dp"
android:bottom="0dp"
/>
<size
android:width="270dp"
android:height="60dp"
/>
<stroke
android:width="3dp"
android:color="#878787"
/>
</shape>
</item>
</layer-list>

A: Use below code in ButtonInfo.xml
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <shape>
        <corners
            android:radius="14dp"
            />
        <gradient
            android:angle="270"
            android:centerX="35%"
            android:centerColor="#9C0009"
            android:startColor="#C7000B"
            android:endColor="#000000"
            android:type="linear"
            />
        <padding
            android:left="0dp"
            android:top="0dp"
            android:right="0dp"
            android:bottom="0dp"
            />
        <size
            android:width="270dp"
            android:height="60dp"
            />
        <stroke
            android:width="3dp"
            android:color="#878787"
            />
    </shape>
</item>

<item android:drawable="@drawable/icon_leader_board"
    android:gravity="center_horizontal|top"
    />

You need to add upper layer at bottom, because z order maintained from bottom to top


text:
Q: Error in FragmentManager from activity to fragment I am trying to open a fragment upon successful login. I realized that intent cannot be used for fragments and thus used FragmentManager. However, when I try using FragmentManager, my app crashes. I have no errors showing up in the code. The following code shown is in my activity.
 package com.example.ireview;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.ireview.ui.home.HomeFragment;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class LogInPage extends AppCompatActivity {

    private FirebaseAuth mAuth = FirebaseAuth.getInstance();
    private FirebaseUser currentUser = mAuth.getCurrentUser();
    EditText email;
    EditText password;

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

        email = (EditText) findViewById(R.id.editTextEmailLogIn);
        password = (EditText) findViewById(R.id.editTextPasswordLogIn);

    }

    public void clickLogin(View v) {
        String userEmail = email.getText().toString();
        String userPassword = password.getText().toString();

        if (userEmail.length() != 0 && userPassword.length() != 0) {
            mAuth.signInWithEmailAndPassword(userEmail, userPassword)
                    .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            if (task.isSuccessful()) {
                                // Sign up success
                                Toast.makeText(getBaseContext(), "Login Successful.",
                                        Toast.LENGTH_SHORT).show();
                                // Bring user to success activity

                                androidx.fragment.app.Fragment fragment = new Fragment();
                                FragmentManager fragmentManager = getSupportFragmentManager();
                                fragmentManager.beginTransaction().replace(R.id.home_frag, fragment).commit();

                            } else {
                                //
                            }
                        }
                    });
        } else {
            //
        }
    }
}

A: create object of your fragment like
HomeFragment fragment = new HomeFragment();

instead of
androidx.fragment.app.Fragment fragment = new Fragment();


text:
Q: Is it feasible for a general purpose programming language to not have a heap? I'm looking into creating a programming language. What I'm wondering is, in a language that contains a reference-like construct, is it feasible to not have a new/malloc operator? That is, all variables are stored either on the stack somewhere or are statically allocated.
The idea is that you get better type safety, as well as "free garbage collection" without actually having a garbage collector.
I'm not familiar with too many scripting languages, so if one already does this, feel free to point it out.
(Dynamic / unknown size data structures would be handled by a dynamic list structure, which would be handled (obviously) on the heap, behind the user's back.)

A: Fortran was always quite a "general purpose" language, but it had no support for any kind of a dynamic memory allocation out of the box.
A usual practice was to allocate a big array statically and simulate your own memory management on top of it.
If a way to get rid of both GC and a manual memory management is what you're looking for, then region analysis can help, but only in few specific cases.

A: Region-based memory management was one approach for not having a heap managed in the traditional sense.  This manifested in languages like FX and MLKit.

A: There is no requirement at all that you absolutely have to implement a stack, or a heap. C does not specify a stack either, for example. In fact, in many languages you don't even need to care, you just specify that the implementation (a compiler, an interpret, or whatever) to make room for a variable, and perhaps for how long.
Your language's interpreter (assuming one) could do int main(void) { char memory[1048576]; run_script_from_stdin_using(memory); }. You could even call mmap(2) to get an anonymous block of memory and use that to stash your variables in. It just does not matter where objects live, and that stack/heap are terms that have questionable meaning given they are often interchangeable.

A: You can allocate objects on the stack if you know they won't be referenced after the method terminates. This means, the object is used solely withing the method (e.g. a temp object), or use solely in method resulting from nested invocations. This is however a severe restriction. There are some dynamic optimizations that go in this direction though (at least optimization of temp object). You could maybe have a static checking mechanism that enforces this restriction, or possibly distinguish between heap and stack objects with types...


text:
Q: delayed_job waiting for completion How can I poll for completion of a list of jobs with delayed_job?
The scenario is simple: I enqueue some root job, it does something and then enqueues a bunch of other jobs and I need to check if they all have completed.

A: delayed_job has some hooks you can use which are documented here. The after(job ) hook seems the one that fits your needs.
When I had to implement remote api call I tried delayed_job and polling with Faye but I ended up using resque and resque-status, which use redis, it's the nicest way I know at present, but it's not exactly that similar to your situation.


text:
Q: Перебрать все возможные варианты строк по разделителям Есть такая заготовка: (аа) (,|;) (аа|вв) (;|,|) (гв|аб вб)
Надо, сохраняя последовательность, перебрать все возможные варианты, которые образуются с помощью разделителя "|".
Подскажите, как называется такой алгоритм, как его реализовать на c#, или ещё на каком-то языке?
Вот что должно получится из заготовки:
(аа) (,) (аа) (;) (гв)
(аа) (;) (аа) (;) (гв)
(аа) (,) (вв) (;) (гв)
(аа) (,) (аа) (,) (гв)
(аа) (,) (аа) () (гв)
(аа) (,) (аа) (;) (аб вб)
...
и т.д.

A: Такой алгоритм называется "генератор анкоров" (Anchor Generator). Вот пример для рэндомного получения результата (не генерация списка всех вариантов), где разделитель вместо () будет [[...]]  и нет вложенности анкоров
internal class AnchorGenerator
{
    private readonly Random _random = RandomFactory.Create();
    private readonly Regex _regex = new Regex(@"\[\[([^\[\[]*)\]\]");

    public string Generate(string template)
    {
        var matches = _regex.Matches(template);

        if (matches.Count == 0)
            return template;

        foreach (Match match in matches)
        {
            var tpl = match.Groups[1].Value;
            var variants = tpl.Split('|');

            var variant = variants[_random.Next(variants.Length)];

            template = template.ReplaceFirstOccurrence(match.Value, variant);
        }

        return template;
    }
}

где
public static string ReplaceFirstOccurrence(this string s, string oldValue, string newValue)
    {
        int i = s.IndexOf(oldValue, StringComparison.Ordinal);
        if (i == -1) return s;
        return s.Remove(i, oldValue.Length).Insert(i, newValue);
    }

A: Нашел алгоритм на JS, переделал. Если кто-то прокомментирует реализацию (по-моему, достаточно запутано получилось) буду благодарен.
    List<string> resultList = new List<string>();
    List<int> counters1;
    private string strRes;
    private List<List<string>> result;
    public List<string> GetColll(string[] shab)
    {
        foreach (var itemShab in shab)
        {
            counters1 = new List<int>();
            result = new List<List<string>>();

            List<string> pattern = Regex.Split(itemShab, @"\(").ToList();
            List<string> vars = new List<string>();
            List<string> part;

               for (int i = 0; i < pattern.Count; i++)
               {
                //отсеиваем пустую строку
               if (pattern[i].Contains(@")"))
               {
                   part = pattern[i].Split(new char[] {')'},StringSplitOptions.RemoveEmptyEntries).ToList();
                   foreach (var prt in part)
                   {
                        if (prt.Contains(@"|"))
                        {
                            vars = prt.Split(new char[] { '|' }).ToList();
                            result.Add(vars);
                        }
                        else
                        {
                            List<string> partList = new List<string>();
                            partList.Add(prt);
                            result.Add(partList);
                        }

                    }

               }

            }
            CreateCounters();

            OnStep();
        }

        return null;
    }

    void CreateCounters()
    {
        List<int> counters = new List<int>();
        for (int i = 0; i < result.Count; i++)
        {
            counters.Add(0);
        }
        counters1 = counters;
    }

    private bool IsCounters()
    {
        int i = counters1.Count - 1;
        while (i >= 0)
        {
            if (result[i].Count - 1 > counters1[i])
            {
                counters1[i]++;
                return true;
            }
            counters1[i] = 0;
            i -= 1;
        }
        return false;
    }

    private void OnStep()
    {
        int len = counters1.Count;
        int i;
        string part;
        List <string> phrase = new List<string>();

        for (i = 0; i < len; i += 1)
        {
            part = result[i][counters1[i]];
            if (part != null)
            {
                phrase.Add(part);
            }
        }
        strRes = string.Join("", phrase.ToArray());
        resultList.Add(strRes);
        if (IsCounters())
        {
            OnStep();
        }
    }


text:
Q: Is it valid to use top, left, right, and bottom css all at the same time to size an element? I have seen it before and have done it so I know it works pretty consistently, however, I want to know if that is valid and if there are caveats that I have not thought of.
example: http://jsfiddle.net/sfctB/67/ I offered this fix for someone with a FF overflow problem recently, which was caused by a box-sizing property. Adding the simple -moz- prefix fixed it as well but I opted for something that seemed more valid to me. I set the top and bottom on a content div so that it always stretches between a fixed header and fixed footer. Then set margins to avoid the overflow.
I would intuitively think that using top and bottom or right and left at the same time would cause problems, however, what it seems to do is make right act kind of like width when there is a left already stated and make bottom act kind of like height when there is already a top stated.
But is this valid and should I use it when considering long term support?
code
html, body {
    height:100%;
    width:100%;
    overflow:hidden;
}
body {
    padding: 60px 0px;
    height: 100%;
}
.header {
    height:60px;
    background:#000;
    color:#fff;
    width: 100%;
    position: fixed;
    top:0;
}
.body {
    overflow-y: scroll;
    position:fixed;
    bottom:0;
    top:60px;
    margin: 0 0 60px 0;
}
.footer {
    height:60px;
    background:#000;
    position:fixed;
    bottom:0px;
    width:100%;
    color:#fff;
}

<!DOCTYPE html>

This is header

[content here]

This is footer

A: Good question. I've wondered about this for a long time, so I went to the spec ( http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width and http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-height). It looks like it's a fully spelled out and the answer is what you'd expect it to be. For an absolutely positioned element if width is "auto" and left and right are defined then:
5. 'width' is 'auto', 'left' and 'right' are not 'auto', then solve for 'width'

Similarly for height:
5. 'height' is 'auto', 'top' and 'bottom' are not 'auto', then 'auto' values for 'margin-top' and 'margin-bottom' are set to 0 and solve for 'height'

I think tPlummer makes a good point, however. The spec and reality may be two different things; especially when it comes to older browsers.

A: As far as I'm concerned, it's valid mark-up.  I've seen the padding attribute have issues with it in IE, but, that's also IE on most things.


text:
Q: MongoDB - get documents between dates using ObjectID As the title said, I want to get documents between 2 dates using the ObjectID. In mongoose I use _id: { $gte: ObjectID.createFromTime(new Date("2019-01-01")) } but I can't figure it out how to construct this query on mongo shell. There is a post on StackOverflow which lists different queries on mongo shell and mongoose but I can't seem to find that post. Does anyone know how to do the same query on mongo shell? Thanks.
UPDATED
Since I have already found the solution, does anyone know why the method names are different in mongo shell and mongoose? This really causes confusion sometimes.

A: Figured it out, it's _id: { $gte: new ObjectId.fromDate(new Date("2019-01-01")) } on mongo shell