text:
Q: The button is not visible which is going to connect another activity in android studio my friends and I are creating an android app for our project and we are new to this and if you think the code is repeated then please post the link.
We have referred from following YouTube video- https://youtu.be/wbsWVtCdiW4
For now we are creating a basic structure for our app. The following is the code entered activity_main.xml which is for button which should connect to other activity but after running the code on emulator and in my phone the app shows a blank screen.
<?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">
  <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="157dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_marginStart="119dp"
    android:layout_marginLeft="119dp"
    android:layout_marginTop="251dp"
    android:layout_marginEnd="97dp"
    android:layout_marginRight="97dp"
    android:layout_marginBottom="323dp"
    android:background="@android:color/holo_blue_light"
    android:onClick="startdbapp"
    android:text="start db app"
    android:textColor="#F8000000"
    android:visibility="visible"
    tools:visibility="visible" />
  </RelativeLayout>

this is the MainActivity.java
package com.login.sqlitedemoapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

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

    public void startdbapp(View view) {
        new DbManager(this);
        startActivity(new Intent(this, InsertData.class));
    }
}

this is my 2nd activity file named activity_insert_data.xml
 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".InsertData">

 <EditText
    android:id="@+id/t1"
    android:layout_width="242dp"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_marginStart="94dp"
    android:layout_marginLeft="80dp"
    android:layout_marginTop="99dp"
    android:layout_marginEnd="75dp"
    android:layout_marginRight="80dp"
    android:layout_marginBottom="587dp"
    android:ems="10"
    android:hint="Enter_Name"
    android:inputType="textPersonName" />

 <EditText
    android:id="@+id/t2"
    android:layout_width="242dp"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_marginStart="89dp"
    android:layout_marginLeft="80dp"
    android:layout_marginTop="194dp"
    android:layout_marginEnd="80dp"
    android:layout_marginRight="80dp"
    android:layout_marginBottom="492dp"
    android:ems="10"
    android:hint="Enter_Email"
    android:inputType="textEmailAddress" />

 <EditText
    android:id="@+id/t3"
    android:layout_width="241dp"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_marginStart="88dp"
    android:layout_marginLeft="88dp"
    android:layout_marginTop="290dp"
    android:layout_marginEnd="82dp"
    android:layout_marginRight="82dp"
    android:layout_marginBottom="396dp"
    android:ems="10"
    android:hint="Enter_Course"
    android:inputType="textPersonName" />

 <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="68dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_marginStart="76dp"
    android:layout_marginLeft="76dp"
    android:layout_marginTop="395dp"
    android:layout_marginEnd="62dp"
    android:layout_marginRight="62dp"
    android:layout_marginBottom="268dp"
    android:onClick="addRecord"
    android:text="Insert Record" />

 </RelativeLayout>

This it the Main activity named InsertData.java
 package com.login.sqlitedemoapp;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.EditText;
 import android.widget.Toast;
 import androidx.appcompat.app.AppCompatActivity;

 public class InsertData extends AppCompatActivity
 {
  EditText t1,t2,t3;

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_insert_data);
    t1=(EditText)findViewById(R.id.t1);
    t2=(EditText)findViewById(R.id.t2);
    t3=(EditText)findViewById(R.id.t3);
  }

     public void addRecord(View view)
          {
                DbManager db = new DbManager(this);

    String res = db.addRecord(t1.getText().toString(), t2.getText().toString(),
    t3.getText().toString());
    Toast.makeText(this, res, Toast.LENGTH_LONG).show();
    t1.setText("");
    t2.setText("");
    t3.setText("");
     }
   }

A: I would recommend you to use a constraint layout. Relative layout is old and most of the developers avoid them. Also, check the constraints of the button.


text:
Q: Unable to install pyrocksdb against RocksDB master I followed the instructions from here: http://pyrocksdb.readthedocs.org/en/latest/installation.html
When I try pip install git+git://github.com/stephan-hof/pyrocksdb.git I get the following output with error:
running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-3.4

creating build/lib.linux-x86_64-3.4/rocksdb

copying rocksdb/__init__.py -> build/lib.linux-x86_64-3.4/rocksdb

copying rocksdb/interfaces.py -> build/lib.linux-x86_64-3.4/rocksdb

copying rocksdb/errors.py -> build/lib.linux-x86_64-3.4/rocksdb

creating build/lib.linux-x86_64-3.4/rocksdb/tests

copying rocksdb/tests/__init__.py -> build/lib.linux-x86_64-3.4/rocksdb/tests

copying rocksdb/tests/test_db.py -> build/lib.linux-x86_64-3.4/rocksdb/tests

copying rocksdb/tests/test_options.py -> build/lib.linux-x86_64-3.4/rocksdb/tests

running egg_info

creating pyrocksdb.egg-info

writing dependency_links to pyrocksdb.egg-info/dependency_links.txt

writing top-level names to pyrocksdb.egg-info/top_level.txt

writing requirements to pyrocksdb.egg-info/requires.txt

writing pyrocksdb.egg-info/PKG-INFO

writing manifest file 'pyrocksdb.egg-info/SOURCES.txt'

warning: manifest_maker: standard file '-c' not found

reading manifest file 'pyrocksdb.egg-info/SOURCES.txt'

writing manifest file 'pyrocksdb.egg-info/SOURCES.txt'

copying rocksdb/_rocksdb.cpp -> build/lib.linux-x86_64-3.4/rocksdb

running build_ext

building 'rocksdb._rocksdb' extension

creating build/temp.linux-x86_64-3.4

creating build/temp.linux-x86_64-3.4/rocksdb

x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2 -fPIC -I/home/iulian/py3env/include -I/usr/include/python3.4m -c rocksdb/_rocksdb.cpp -o build/temp.linux-x86_64-3.4/rocksdb/_rocksdb.o -std=gnu++11 -O3 -Wall -Wextra -Wconversion -fno-strict-aliasing

cc1plus: warning: command line option '-Wstrict-prototypes' is valid for C/ObjC but not for C++ [enabled by default]

rocksdb/_rocksdb.cpp:289:27: fatal error: rocksdb/slice.h: No such file or directory

 #include "rocksdb/slice.h"

                           ^

compilation terminated.

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Command "/home/iulian/py3env/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-mndoekm3-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-3fwa2_ff-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/iulian/py3env/include/site/python3.4" failed with error code 1 in /tmp/pip-mndoekm3-build

I tried to checkout various versions of RocksDB (3.5, 3.6, 3.8, 3.9) and still no luck.
I am using Python 3.4 on a 64 bit Ubuntu 14.04.

A: You have to check that Cython==0.20 is installed! I had the same issue and that solved it!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with installing Oracle Instant Client in Mac I was trying to install Instant Client on my Mac machine. So I followed the steps as in https://www.oracle.com/database/technologies/instant-client/macos-intel-x86-downloads.html
I comepleted successfully all the steps till -
mkdir ~/lib
cp /opt/oracle/instantclient_19_3/libclntsh.dylib.19.1 ~/lib/
cp /opt/oracle/instantclient_19_3/libclntshcore.dylib.19.1 ~/lib/
cp /opt/oracle/instantclient_19_3/libons.dylib ~/lib/
cp /opt/oracle/instantclient_19_3/libnnz18.dylib ~/lib/
cp /opt/oracle/instantclient_19_3/libociei.dylib ~/lib/
ln -s ~/lib/libclntsh.dylib.19.1 ~/lib/libclntsh.dylib

Also exported the path as instructed -
export PATH=~/instantclient_19_3:$PATH

Then tried to run -
sqlplus hr/welcome@localhost/orclpdb

But the last step is throwing some error as -
zsh: command not found: sqlplus

Any help how to resolve this error will be very helpful.

A: Download Oracle Database instant-client
https://www.oracle.com/database/technologies/instant-client/macos-intel-x86-downloads.html
What is MacOS without brew?
brew tap InstantClientTap/instantclient
cp ~/Download/instantclient*.zip /usr/local/Homebrew/Library/Taps/instantclienttap/homebrew-instantclient
brew install instantclient-basic
brew install instantclient-sqlplus
brew install instantclient-tools

type sqlplus
sqlplus is /usr/local/bin/sqlplus

alias sqlplus
alias sqlplus='rlwrap sqlplus'

$ sqlplus

SQL*Plus: Release 19.0.0.0.0 - Production on Wed Sep 2 11:25:11 2020
Version 19.3.0.0.0

Copyright (c) 1982, 2019, Oracle.  All rights reserved.

Enter user-name:

Best of luck!


text:
Q: How to test the state of a button within an info window? When I click on a marker, I display an info window with two input fields and one button:
When I close the info window I would like to know if the button was pressed or not.
How can I do it ?
google.maps.event.addListener(marker[i],"click", function()
    {
        html = "Name: " + "<input type='text' id='name' />";
        html += "Firstname: " + "<input type='text' id='firstname' />";
        html += "<input type='button' id='okButton' value='OK' />";
        infoWindow[i].setContent(html);
        infoWindow[i].open(map,marker[i]);
    });
google.maps.event.addListener(infoWindow[i],'closeclick',function ()
    {
        //action when the ok button was pressed or not
        //this code doesn't work
        $('#okButton').button().click(function()
        {
            //action
        });
    });

A: $('#okButton').button().click(function() this is not the right way of handling the click event. Also, you're dynamically adding the button the DOM.. Replace that as
$(document).on('click', '#okButton', function() {
    //action
});

A: Use $.on() to observe the click-event of the marker(Note: you can't attach the event directly, because the button is only available after the domready-event of the infowindow has been fired).
$(document ).on( "click", "#okButton", function() {
  $(this).data('clicked',true);
});

....it set's a data-property for the button, you may retrieve it later to determine if the button has been clicked:
google.maps.event.addListener(infoWindow[i],'closeclick',function (){
    if($("#okButton").data('clicked')){
      alert('do something');
    }
});


text:
Q: How can I use double pointers correctly in this case? I am doing a boarding queue and I am using a simple bubble sort algorithm to sort the queue I have, I am using 2 pointers to store the values I am comparing and 2 double pointer to modify the value inside each node that I want to swap. My problem is when I want to change where my double pointers are pointing in order to iterate through all the queue, it never compiles, I have tried:
this:**r = &(r->next),
this: **r = &(*r->next),
or this: **r = &(**r->next)
Same happens when I try to change where my double pointer "a" is pointing. This is the full method just in case you need to see it,
int sortBoardingQueue(BoardingQueue *qPtr){
    int size = calculateSize(qPtr);

    Passenger *t = qPtr->head;
    Passenger *a = qPtr->head->next;
    Passenger **r = &(qPtr->head);
    Passenger **q = &(qPtr->next);
    for (int i = size-1; i <=0; i--)
    {
        while(t != NULL){
            if (t->seatNumber>a->seatNumber)
            {
                **r = *a;
                **q = *t;
            }
            t = t->next;
            a = a->next;
            **r = &(r->next);
            **a = &(a->next);
        }
    }

}

//the declarations of the structs I am using in my header file
typedef struct boardingQueue {
    Passenger* head; // points to the Passenger at the front/head of the queue
    Passenger* tail; // points to the Passenger at the end/tail of the queue
} BoardingQueue;

typedef struct passenger {
char name[30];          // the passenger's name
double passportNumber;  // their passport number
int seatNumber;         // their seat number on the plane
struct passenger* next; // a pointer to the next passenger in the queue after this one
} Passenger;

A: If the pointer r is declared and initialized like this
Passenger **r = &(qPtr->head);

then in this statement
**r = &(r->next);

**r has the type Passenger. Moreover r is pointing to a pointer. S this expression r->next is incorrect because pointers do not have the data member next (pointers are not structures).
So all three expressions
**r = &(r->next),

**r = &(*r->next),

**r = &(**r->next)

are incorrect. For example the expression
&(**r->next)

is equivalent to
&(** ( r->next ) )

It seems what you mean is the following
r = &( *r )->next;

Take into account that this declaration
Passenger **q = &(qPtr->next);

is also invalid because the structure BoardingQueue does not have the data member next.
also the condition in the for loop
for (int i = size-1; i <=0; i--)

is invalid. It will be valid only in the case when size is less than or equal to 1.:)
You have to rewrite the function sortBoardingQueue anew at least using valid C expressions. After that you can ask a question: why does not my sort function work.:)

A: -- next time it will be easier to get an answer if the posted code snippet is exactly what you're feeding into the compiler, and if you include your compiler errors exactly as they appear with your question.
I restructured your example code + added a main function to show some of the compiler errors to show what I mean:

Code example
#define NULL 0
//the declarations of the structs I am using in my header file
typedef struct passenger {
char name[30];          // the passenger's name
double passportNumber;  // their passport number
int seatNumber;         // their seat number on the plane
struct passenger* next; // a pointer to the next passenger in the queue after this one
} Passenger;

typedef struct boardingQueue {
    Passenger* head; // points to the Passenger at the front/head of the queue
    Passenger* tail; // points to the Passenger at the end/tail of the queue
} BoardingQueue;

int sortBoardingQueue(BoardingQueue *qPtr){
    int size = 3; // func undefined?? calculateSize(qPtr);

    Passenger *t = qPtr->head;
    Passenger *a = qPtr->head->next;
    Passenger **r = &(qPtr->head);
    Passenger **q = &(qPtr->next);
    for (int i = size-1; i <=0; i--)
    {
        while(t != NULL){
            if (t->seatNumber>a->seatNumber)
            {
                **r = *a;
                **q = *t;
            }
            t = t->next;
            a = a->next;
            **r = &(r->next);
            **a = &(a->next);
        }
    }

}

int main(){
    // make passengers
    Passenger a = {"p1", 111.0, 1, NULL};
    Passenger b = {"p2", 222.0, 2, NULL};
    Passenger c = {"p2", 222.0, 3, NULL};

    // make boarding queue a->c->b
    a.next = &c;
    c.next = &b;
    BoardingQueue q = {&a, &b};

    sortBoardingQueue(&q);
}

Compiler errors
dp.c: In function 'sortBoardingQueue': dp.c:22:27: error:
 'BoardingQueue {aka struct boardingQueue}' has no member named 'next'
      Passenger **q = &(qPtr->next);
From this one, its because boardingQueue has no member next, only head and tail. (Maybe you wanted that to point to a passenger? I can't tell what you intended from context)
dp.c:33:22: error: request for member 'next' in something not a structure or union
              `**r = &(r->next);`

For this one, r is of type Passenger **, so it points to a passenger struct. If you really want to access that struct's next field, you'll have to use (*r)->next
  dp.c:34:13: error: invalid type argument of unary '*' (have
 'Passenger {aka struct passenger}')
              **a = &(a->next);

For this one, a is a single pointer. You can only dereference it once.

So, I hope that helps you plenty for this assignment! And next time, if you post a minimum, reproducible example https://stackoverflow.com/help/minimal-reproducible-example you're bound to get better answers faster.


text:
Q: Login function CakePHP I have a login function in PHP on the cake 2.7 framework that will not make it past the first if statement. The conditional seems to always be false and I am really confused why.  Am I not implementing the request correctly? Any help would be greatly appreciated.
Login()
function login() {

if (!empty($this->request->data) && $this->Auth->user()) {

  // Delete all old tokens
  $this->Tour->recursive = -1;
  $this->Tour->deleteAll(array('Tour.userid' => $this->Auth->user('userid')));
  // Create a new token

  $this->Tour->create();
  $this->Tour->save(array('token' => md5(rand()), 'userid' => $this->Auth->user('userid')));
  // Update login count
  $user = $this->User->read(null, $this->Auth->user('userid'));
  $user['User']['logincount']++;
  $this->User->saveField('logincount', $user['User']['logincount']);
  // Update last login time
  $this->User->saveField('lastlogin', date('Y-m-d h:m:s'));
  echo 'doesnt work';
  if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            echo 'authLogin';
            return $this->redirect($this->Auth->redirect());
        } else {
            $this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
        }

}
}
}

A:
that will not make it past the first if statement.

Of course it won't because of the && $this->Auth->user() condition you have. Since user is not logged in $this->Auth->user() will return null and it won't enter the if block.


text:
Q: When I try to pass object with intent it crashes my application The application works well when I do not use putExtra with intent, but when I use putExtra and passes the object it crashes. I also tried implementing Serializable in HumLogController class (object of which I want to pass). Also the results are same with parceable, i.e. it crashes.
package com.example.praduman.humlog;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import com.parse.Parse;
import java.io.Serializable;

public class HomeActivity extends ActionBarActivity {

    private HumLogController humLogController;
    private Intent logInActivityIntent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        humLogController = new HumLogController();

        logInActivityIntent = new Intent(this , LogInActivity.class);
        logInActivityIntent.putExtra("my object", (Serializable) humLogController);
        startActivity(logInActivityIntent);
    }

}

The activity log is:- The thing is it do not crash when I do not use putExtra. Can any one help ..? Below is the log cat in android studio.
As I said I tried implementing both Serializable and Parceable but non of them works.
07-25 11:21:50.294  14241-14241/com.example.praduman.humlog D/dalvikvm﹕ Late-enabling CheckJNI
07-25 11:21:50.462  14241-14241/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
07-25 11:21:50.466  14241-14241/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 440: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
07-25 11:21:50.466  14241-14241/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:21:50.466  14241-14241/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
07-25 11:21:50.466  14241-14241/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 462: Landroid/content/res/TypedArray;.getType (I)I
07-25 11:21:50.466  14241-14241/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:21:50.474  14241-14241/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
07-25 11:21:50.474  14241-14241/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 403: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
07-25 11:21:50.474  14241-14241/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:21:50.474  14241-14241/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
07-25 11:21:50.474  14241-14241/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 405: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
07-25 11:21:50.478  14241-14241/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:21:50.526  14241-14241/com.example.praduman.humlog D/AndroidRuntime﹕ Shutting down VM
07-25 11:21:50.526  14241-14241/com.example.praduman.humlog W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4c47648)
07-25 11:21:50.530  14241-14241/com.example.praduman.humlog E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.praduman.humlog/com.example.praduman.humlog.HomeActivity}: java.lang.ClassCastException: com.example.praduman.humlog.HumLogController cannot be cast to java.io.Serializable
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: com.example.praduman.humlog.HumLogController cannot be cast to java.io.Serializable
            at com.example.praduman.humlog.HomeActivity.onCreate(HomeActivity.java:32)
            at android.app.Activity.performCreate(Activity.java:5133)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
07-25 11:21:50.534  14241-14241/com.example.praduman.humlog D/dalvikvm﹕ GC_FOR_ALLOC freed 291K, 4% free 9017K/9336K, paused 6ms, total 6ms
07-25 11:21:50.558  14241-14256/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.database.Cursor.getNotificationUri, referenced from method com.parse.ParseSQLiteCursor.getNotificationUri
07-25 11:21:50.558  14241-14256/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve interface method 488: Landroid/database/Cursor;.getNotificationUri ()Landroid/net/Uri;
07-25 11:21:50.558  14241-14256/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002

The above errors happen when I do not implement Serilizable in HumLogController and just cast the object in the object, while passing through the intent. Below is the code of HumLogController class when I also implements Serializable there.
package com.example.praduman.humlog;

import java.io.Serializable;

/**
 * Created by Praduman on 23/07/2015.
 */
public class HumLogController implements Serializable{
   private HumLogModel humLogModel ;
    private String username;
    private String password;
    private String userType;

    public HumLogController() {
        this.humLogModel = new HumLogModel();
    }
    public void createNewUser(){
        humLogModel.createNewUser(getUsername(), getPassword());
    }

    public void setUserEssentials(String username,String password, String userType){
        setUsername(username); setPassword(password); setUserType(userType);
    }

    public void setUsername(String username){
        this.username = username;
    }
    public void setPassword(String password){
        this.password = password;
    }
    public void setUserType(String userType){
        this.userType = userType;
    }

    public String getUsername(){
        return username;
    }
    public String getPassword(){
        return password;
    }
    public String getUserType(){
        return userType;
    }
}

The logcat when I implements serializable in HumLogContoller class is given below.
07-25 11:42:23.838  23311-23311/? D/dalvikvm﹕ Late-enabling CheckJNI
07-25 11:42:24.058  23311-23330/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.database.Cursor.getNotificationUri, referenced from method com.parse.ParseSQLiteCursor.getNotificationUri
07-25 11:42:24.058  23311-23330/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve interface method 488: Landroid/database/Cursor;.getNotificationUri ()Landroid/net/Uri;
07-25 11:42:24.058  23311-23330/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002
07-25 11:42:24.102  23311-23331/com.example.praduman.humlog D/dalvikvm﹕ GC_FOR_ALLOC freed 283K, 4% free 9025K/9336K, paused 4ms, total 4ms
07-25 11:42:24.118  23311-23311/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
07-25 11:42:24.118  23311-23311/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 440: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
07-25 11:42:24.118  23311-23311/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:42:24.122  23311-23311/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
07-25 11:42:24.126  23311-23311/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 462: Landroid/content/res/TypedArray;.getType (I)I
07-25 11:42:24.126  23311-23311/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:42:24.130  23311-23311/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
07-25 11:42:24.130  23311-23311/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 403: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
07-25 11:42:24.130  23311-23311/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:42:24.150  23311-23311/com.example.praduman.humlog I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
07-25 11:42:24.150  23311-23311/com.example.praduman.humlog W/dalvikvm﹕ VFY: unable to resolve virtual method 405: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
07-25 11:42:24.150  23311-23311/com.example.praduman.humlog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
07-25 11:42:24.206  23311-23311/com.example.praduman.humlog D/AndroidRuntime﹕ Shutting down VM
07-25 11:42:24.206  23311-23311/com.example.praduman.humlog W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa4c47648)
07-25 11:42:24.222  23311-23311/com.example.praduman.humlog D/dalvikvm﹕ GC_FOR_ALLOC freed 381K, 5% free 9147K/9560K, paused 13ms, total 14ms
07-25 11:42:24.222  23311-23311/com.example.praduman.humlog E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.praduman.humlog/com.example.praduman.humlog.HomeActivity}: java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.praduman.humlog.HumLogController)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.praduman.humlog.HumLogController)
            at android.os.Parcel.writeSerializable(Parcel.java:1285)
            at android.os.Parcel.writeValue(Parcel.java:1233)
            at android.os.Parcel.writeMapInternal(Parcel.java:591)
            at android.os.Bundle.writeToParcel(Bundle.java:1646)
            at android.os.Parcel.writeBundle(Parcel.java:605)
            at android.content.Intent.writeToParcel(Intent.java:6831)
            at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1927)
            at android.app.Instrumentation.execStartActivity(Instrumentation.java:1419)
            at android.app.Activity.startActivityForResult(Activity.java:3390)
            at android.app.Activity.startActivityForResult(Activity.java:3351)
            at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
            at android.app.Activity.startActivity(Activity.java:3587)
            at android.app.Activity.startActivity(Activity.java:3555)
            at com.example.praduman.humlog.HomeActivity.onCreate(HomeActivity.java:33)
            at android.app.Activity.performCreate(Activity.java:5133)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.io.NotSerializableException: com.example.praduman.humlog.HumLogModel
            at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
            at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
            at java.io.ObjectOutputStream.writeFieldValues(ObjectOutputStream.java:979)
            at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:368)
            at java.io.ObjectOutputStream.writeHierarchy(ObjectOutputStream.java:1074)
            at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1404)
            at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)
            at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1481)
            at android.os.Parcel.writeSerializable(Parcel.java:1280)
            at android.os.Parcel.writeValue(Parcel.java:1233)
            at android.os.Parcel.writeMapInternal(Parcel.java:591)
            at android.os.Bundle.writeToParcel(Bundle.java:1646)
            at android.os.Parcel.writeBundle(Parcel.java:605)
            at android.content.Intent.writeToParcel(Intent.java:6831)
            at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1927)
            at android.app.Instrumentation.execStartActivity(Instrumentation.java:1419)
            at android.app.Activity.startActivityForResult(Activity.java:3390)
            at android.app.Activity.startActivityForResult(Activity.java:3351)
            at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
            at android.app.Activity.startActivity(Activity.java:3587)
            at android.app.Activity.startActivity(Activity.java:3555)
            at com.example.praduman.humlog.HomeActivity.onCreate(HomeActivity.java:33)
            at android.app.Activity.performCreate(Activity.java:5133)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

A: If you have a custom Serializable class like HumLogController, you have to make sure that all its fields are Serializable as well, or declare them transient if you don't want to serialize them. In your case, HumLogModel is not Serializable.


text:
Q: Django custom method won't show up I have two custom methods for a model manager in Django.  One of them works.  I recently added another and Django (and python) act like it doesn't exist.  Here's the relevant part of the model:
class FigureServerManager(models.Manager):
    #This method takes as input a user and grabs a figure that is not marked complete for which that user has not already submitted a result
    def serve_to_user(self,user):
    not_complete=super(FigureServerManager, self).get_query_set().filter(complete=0)
    for Figure in not_complete:
        checkifresult=User.objects.get(pk=user).result_set.all().filter(figure=Figure.id)
    if not checkifresult:
            return Figure

    #This is a copy of the above method that I want to change to do something else, but I can't even get it to show up yet
    def serve_training_task(self, user):
        with_correct_ans=super(FigureServerManager, self).get_query_set().filter(complete=0)
        for Figure in with_correct_ans:
            checkifresult=User.objects.get(pk=user).result_set.all().filter(figure=Figure.id)
        if not checkifresult:
                return Figure

class Figure(models.Model):
    doi=models.CharField(max_length=20)
    url=models.CharField(max_length=200)
    image=models.ImageField(upload_to='classify')
    complete=models.BooleanField()
    #include the default manager
    objects=models.Manager()
    #add the extra one for serving figures
    serve_objects=FigureServerManager()

I get an error on the website (running the Django development server) like this:
'FigureServerManager' object has no attribute 'serve_training_task'

and if I run dir(FigureServerManager) in python the serve_training_task method does not appear but the serve_to_user method does appear.  Why doesn't serve_training_task work?

A: Python Language Reference, §2.1.8: "Indentation"


text:
Q: Change color in Fragment In My aaplication is Fragment with some LinearLayout (for example id is LL1). How can I change LL1 background color?
I want to do it by sharedpreferences (have two value: alpha and color) in OnCreate in Fragment.java:
SharedPreferences pref = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
getView().findViewById(R.id.LL1).setBackgroundColor(Color.parseColor(pref.getString(TRANSP_KEY, "#CC") + pref.getString(FCOLOR_KEY, "5556FF")));

There are not errors but when I try to start application:
Unfortunately application has stopped

I tried:
LinearLayout LL= (LinearLayout) getView().findViewById(R.id.LL1);
LL.setBackgroundColor(Color.WHITE);

but there is the same problem
Probably setbackground doesn't work, if it is removed application works but has default colors (from xml file).
What am I doing wrong?
fragment.java:
package com.hgyghyfghyu.apkana40;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import static com.hgyghyfghyu.apkana40.AppData.FCOLOR_KEY;
import static com.hgyghyfghyu.apkana40.AppData.TRANSP_KEY;
import static com.hgyghyfghyu.apkana40.AppData.prefdata;
import static com.hgyghyfghyu.apkana40.UserData.editor;
import static com.hgyghyfghyu.apkana40.UserData.pref;

/**
 * A simple {@link Fragment} subclass.
 */
public class TrainerMenu extends Fragment {

    public TrainerMenu() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        SharedPreferences pref = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

        LinearLayout imageView = (LinearLayout) getView().findViewById(R.id.trainermenutrainersbtn);
        imageView.setBackgroundColor(Color.WHITE);
       // getView().findViewById(R.id.trainermenuadbtn).setBackgroundColor(Color.parseColor(pref.getString(TRANSP_KEY, "#CC") + pref.getString(FCOLOR_KEY, "33777F")));

        //getView().findViewById(R.id.trainermenusettingsbtn).setBackgroundColor(Color.parseColor(pref.getString(TRANSP_KEY, "#CC") + pref.getString(FCOLOR_KEY, "5556FF")));
       // getView().findViewById(R.id.trainermenuinfobtn).setBackgroundColor(Color.parseColor(pref.getString(TRANSP_KEY, "#CC") + pref.getString(FCOLOR_KEY, "5556FF")));
        //getView().findViewById(R.id.trainermenugroupsbtn).setBackgroundColor(Color.parseColor(pref.getString(TRANSP_KEY, "#CC") + pref.getString(FCOLOR_KEY, "5556FF")));

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_trainer_menu, container, false);
    }

}

A:
I want to do it in OnCreate in Fragment:

Well, you can't. getView() will return a null view inside onCreate because the View hasn't been created.
Please move the code to onCreateView after inflating the layout XML for your Fragment and use findViewById on the View that was inflated instead of using getView()
In code
View v = inflater.inflate(R.layout.fragment_trainer_menu, container, false);
v.findViewById...
return v;

A: Quoting from the documentation for the getView() method:

public View getView ()
Get the root view for the fragment's layout (the one returned by
  onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.
Returns View  The fragment's root view, or null if it has no layout.

So, it wont work if you try to access your Fragment's layout with getView() before onCreateView() :). The following is one way of approaching this as onViewCreated() is called immediately after onCreateView():
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_trainer_menu, container, false);
}

@Override
public void onViewCreated (View view, Bundle savedInstanceState) {

    SharedPreferences pref = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);

    LinearLayout imageView = (LinearLayout) view.findViewById(R.id.trainermenutrainersbtn);
    imageView.setBackgroundColor(Color.WHITE);
}


text:
Q: Validity of analysing spherical harmonics in real-space using the probability amplitude While looking up spherical harmonics (on the validity of analysing them in real-space in a transition metal crystal structure), I came across this: http://shpenkov.janmax.com/hybridizationshpenkov.pdf (published in the hardonics journal...? I haven't really come across the journal before so I'm not too sure as of the validity of its peer-review process). The author argues mainly that because "hybridization as a mathematical mixing of qualitatively opposite properties (real and complex numbers) is physically impossible and hence unreal", QM incorrectly describes the atomic structure.

"...The mixing of these complex functions, contained "real" and
  "imaginary" quantities, together, as it has been done in quantum
  mechanics, is inadmissible, just like it is impossible, e.g., to mix
  together the electric and magnetic fields and then to ascribe to the
  obtained mixture the properties inherent only in the electric field
  (or, vice versa, only in magnetic). Thus, hybridization as a
  mathematical mixing of qualitatively opposite properties is physically
  impossible and hence unreal. It is merely a mathematical trick used by
  creators of QM at the earliest stage of its building..."

It is interesting because I've always accepted the Born rule without questioning how it has been derived (As so far I've been using QM mainly as a predictive tool for alloy properties in the context of alloying additions to a composition, rather than working on the theory behind it). A quick look-up of the Born rule shows that the square of the wavefunction arises from the assumption that a measurement of an observable will produce an eigenvalue as a result, and the exact perspective depends on the QM interpretation (Which I know very little about) see here. Ignoring the hadronics journal article itself (which has managed to get me curious, and thinking), my question is then (out of curiosity) two-fold:

*

*If there is any physical meaning to the imaginary terms. And if there is -
is something being missed out when one combines the terms to obtain the real
orbitals?

*Following from that, how valid would an argument that the
linear combination of real and complex numbers are "physically
impossible and hence unreal" be? I suspect that the answer to this is in the links to the older questions (since the are complex conjugates), and I will be going through them.

Edit notes 1: In the process of updating the question and reading up on the topic to update the question, I have found that similar questions have been asked before: see here and here... Following that, I have updated the question.
Edit notes 2: Probably answering my own question, but a related answer to question 1 is found here.


text:
Q: codeigniter gives a forbidden response on a simple ajax load function I am trying to use ajax inside my codeigniter application and getting a forbidden response
Is it a way to deal with that without using codeigniter load method.

A: Not sure if this will help, but CI usually comes with a .htaccess file in the application directory and I think it's set to deny all.  Check if that is there first, it might be messing things up for you.


text:
Q: Is there a smarter way to access nested attributes using a DTO in NestJS? Stripe sends a webhook that looks like this
{
    "created": 1326853478,
    "livemode": false,
    "id": "evt_00000000000000",
    "type": "checkout.session.completed",
    "object": "event",
    "request": null,
    "pending_webhooks": 1,
    "api_version": "2016-07-06",
    "data": {
        "object": {
            "id": "cs_00000000000000",
            "object": "checkout.session",
            "billing_address_collection": null,
            "cancel_url": "https://example.com/cancel",
            "client_reference_id": "ABC",
            "customer": "DEF",
            "customer_email": null,
            "display_items": [
                {
                    "amount": 1500,
                    "currency": "usd",
                    "custom": {
                        "description": "Comfortable cotton t-shirt",
                        "images": null,
                        "name": "T-shirt"
                    },
                    "quantity": 2,
                    "type": "custom"
                }
            ],
            "livemode": false,
            "locale": null,
            "payment_intent": "pi_00000000000000",
            "payment_method_types": [
                "card"
            ],
            "submit_type": null,
            "subscription": null,
            "success_url": "https://example.com/success"
        }
    }
}

Here is my controller that receives it:
import { Controller, Post, Body, ValidationPipe, UsePipes } from '@nestjs/common';
import { CheckoutWebhookDto } from './checkout-webhook.dto';

@Controller('webhooks')
export class StripeWebhooksController {

  @Post('checkout')
  @UsePipes(new ValidationPipe({transform: true}))
  async checkout(@Body() data: CheckoutWebhookDto) {
    console.log("Output:", data)
    return

  }

}

and my current Dto
import { ValidateNested, IsNotEmpty } from 'class-validator';
import { Type } from 'class-transformer';

export class CheckoutWebhookObjectDto  {
  @IsNotEmpty()
  readonly client_reference_id: string;

  @IsNotEmpty()
  readonly customer: string;
}

export class CheckoutWebhookDataDto  {
  @ValidateNested()
  @Type(() => CheckoutWebhookObjectDto)
  readonly object: CheckoutWebhookObjectDto;
}

export class CheckoutWebhookDto  {
  @ValidateNested()
  @Type(() => CheckoutWebhookDataDto)
  readonly data: CheckoutWebhookDataDto;
}

I want to extract out
data.object.client_reference_id and data.object.customer
The only way I can do this is to create 3 Dtos nested inside each other.
I appreciate I can do @Body('data') to shorten it to 2 - but is there a way to have a single Dto so that the final data object is just:
{
  client_reference_id: "ABC",
  customer: "DEF"
}


text:
Q: Best way to integrated Laravel 5 and AngularJS
I 'm currently developing an application based on Laravel and AngularJS framework.
I wonder what is the best way to integration.
I would especially like to know where should I place the AngularJS files and how to manage the view.
Thanks you.

A: I would place them in the public folder and use html helpers to initiate them

A: Because your client will download all your javascript files, just put all your Angular app (including views) in the public folder !


text:
Q: Is it possible to apply a chart template to an Excel chart using openpyxl? I'm trying to automate the creation of some charts in Excel. They need to be styled to a particular theme.
Using openpyxl, how could I apply a template to a chart? I can't find anything in the docs, or by searching the Github repo. Have I missed anything?
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for i in range(10):
    ws.append([i])

from openpyxl.chart import BarChart, Reference, Series
values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)

### chart.apply_template("template_loc.crtx") <-- What can go here?

ws.add_chart(chart, "E15")
wb.save("SampleChart.xlsx")

A: As far as I can see, it is not possible to load an *.crtx chart template file and apply it to an existing chart. But you can try to recreate the style manually using graphicalProperties:
from openpyxl import Workbook
from openpyxl.chart import BarChart, Reference, Series
from openpyxl.chart.marker import DataPoint
from openpyxl.drawing.fill import PatternFillProperties, ColorChoice

wb = Workbook()
ws = wb.active
for i in range(10):
    ws.append([i])

values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)
chart = BarChart()
chart.add_data(values)

# set a pattern for the whole series
series = chart.series[0]
fill =  PatternFillProperties(prst="pct5")
fill.foreground = ColorChoice(prstClr="red")
fill.background = ColorChoice(prstClr="green")
series.graphicalProperties.pattFill = fill

# set a pattern for a 6th data point (0-indexed)
pt = DataPoint(idx=5)
pt.graphicalProperties.pattFill = PatternFillProperties(prst="ltHorz")
series.dPt.append(pt)

ws.add_chart(chart, "E15")
wb.save("SampleChart.xlsx")

This creates:

It might take some fiddling to exactly recreate the theme you need.


text:
Q: Can Firefox display JP2 images? I have recently converted every image on my website to JP2 to decrease file size while still having transparency.
On Safari everything works great, but Firefox does not display the JP2 images, however it does display PNGs.
Is JP2 unsupported in Firefox?

A: JP2 images are not supported on Firefox.
But you can use the <picture> element to provide multiple image formats so the browser can choose and display the supported image format:
<picture>
    <source srcset="img/example.jp2" type="image/jp2"> <!-- format supported by safari -->
    <source srcset="img/example.webp" type="image/webp"> <!-- format supported on many browsers -->
    <source srcset="img/example.jpg" type="image/jpeg"> <!-- common supported format -->
    <img src="img/example.jpg" alt="example-alt-text"> <!-- default -->
</picture>

Note: An alternative to the JP2 format could be the WebP format:

*

*Comparison WebP, JPEG, JP2/JPEG2000

*More about the WebP format

A: (JP2) Supported browser below:
Firefox: Not supported.
Chrome: Not supported.
Safari: Supported.
You can also check this link:
https://caniuse.com/#feat=jpeg2000


text:
Q: The action index is not defined in controller I'm learning from tutorial and trying to view my ItemesController but i'm always getting the following error:
" Missing Method in ItemsController. The action index is not defined in controller ItemsController"
I typed this url: localhost/cake_2_5/Items
the path of ItemesController.php:
/var/www/html/cake_2_5/app/Controller
<?php
class ItemsController extends AppController
{
    public function idex(){

        $this->set('color', 'blue');

    }
}
?>

The path of my index.ctp:
/var/www/html/cake_2_5/app/View/Items
<?php echo $color ?>

Release Notes for CakePHP 2.5.0.


text:
Q: XML DTD parsing - foundElementDeclarationWithName: not passing any value in model For a DTD such as below, NSXMLParser does not seem to be returning anything in the model argument of foundElementDeclarationWithName. What am I missing here?
DTD -
<!DOCTYPE note [ <!ELEMENT note (to,heading)><!ELEMENT to (#PCDATA)><!ELEMENT heading (#PCDATA)>]>

NSXMLParserDelegate method -
- (void)parser:(NSXMLParser *)parser foundElementDeclarationWithName:(NSString *)elementName model:(NSString *)model
{NSLog(@"Element - %@, Model - %@", elementName, model);}

Output -
2014-05-18 12:55:39.730 TestNSXMLParser[2146:303] Element - note Model -
2014-05-18 12:55:39.730 TestNSXMLParser[2146:303] Element - to Model -
2014-05-18 12:55:39.731 TestNSXMLParser[2146:303] Element - heading Model -
Why is no value being passed in the model argument? I would have expected the list of sub-elements, etc. found in every !ELEMENT declaration to be there.


text:
Q: Moving controls in flowlayoutpanel issue I have Pictureboxes and labels created in the same foreach loop at runtime and all these pictureboxes and labels located on flowlayoutpanel.

How i created those controls is
 foreach (var item in nodes)
 {
    imgurl = GetPictureFromData(item);//this string takes pic of film from a website with a function
    filmname = GetFilmName(item);//this string takes film name from same website with a function
    rating = GetFilmRate (item);//this takes imdb rating with a function

    Label lb = new Label {AutoSize = true, Margin = new Padding(190,0,0,0) };

    PictureBox pb = new PictureBox();//Movie pics

    lb.Font = new Font(Label.DefaultFont, FontStyle.Bold);

    lb.Text = filmname+" "+ rating+"/10" ;

    pb.ImageLocation = imgurl;
    pb.SizeMode = PictureBoxSizeMode.AutoSize ;

    flowLayoutPanel1.Controls.Add(pb);

    flowLayoutPanel1.Controls.Add(lb);

    lb.BringToFront();
    pb.BringToFront();

  }

all pictures and labels taken from the same webpage.What i want to do is move the all labels down next to the related picture.


text:
Q: C# - Exception logging and return status Modifying to make it clear:
I have a question on exception logging and graceful exit. This is in continuation with previous question. The code looks like:
string status = "0";
ClassA ObjA = new ClassA();

try
{
    status = objA.Method1();
    if (status != "-1")
    {
        status = objA.Method1();
    }
 }
 catch (Exception Ex)
 {
     //Log Exception EX
 }

Inside the Method1:
public string Method1()
{
    string status = "0";
    try
    {
        //Code
        return "0";
    }
    catch (Exception Ex)
    {
        //Log Exception with details
        return "-1"
    }
}

I log the Exception in the calling method and return only a status to the caller.
Should I return the Exception to the calling method or is only a status sufficient. With a status of "-1", I know there was an Exception in the called method and details of that Exception were logged in a log file.

A: I think it is OK to do it like that if you have a lot of status codes, otherwise you could also just throw an exception and catch it in the method higher up.
Also maybe reconsider your return type. Looks like you could be using integers, think you are opening yourself up to errors using strings.

A: It all depends on the purpose and implementation of the code; sometimes it is better to allow exceptions to pass back to the caller - they should be used in exceptional cases.
If you do intend on using return codes, however, I would be more inclined to use enum's (though, again, it depends what the purpose of the code is). That way, it is easy for the caller to check against an available selection of return codes. Also, a comment on using integers or strings as error codes - it may not be very descriptive for a caller to know what the issue was. In this case, throwing an Exception or a specific type (containing the error message), or returning a pre-defined enum with a descriptive name, would be more meaningful to the caller.

A: From these short code snippets which does nothing it is very difficult to say what is best practice.
In general it is best to push exceptions to where they are handled best. If you are writing a framework for interfacing with some webservice the users of your framework will most likely not care about network exceptions etc. - they want return codes or, even better some framework specific exceptions that you include/code.

A: Hm - in your situation I'd rather do the following, but it really depends on the situation:
public string Method1()
{
    string status = "0";

    //Code - Exception may be thrown
    return "0";
}

string status = "0";
ClassA ObjA = new ClassA();
try
{
     status = objA.Method1();
 }
 Catch(Exception Ex)
 {
     //Log Exception EX
    status = "-1;
 }

EDIT
Sometimes it's hard to define values that indicate whether an error occurred in the method. You should keep Nullable types in mind. If you can find a suitable return value that indicates errors, it may also be ok to log the error within the method that caused the error and just react to the return value as you suggested.
By the way: In your code you're calling Method1 twice if the first call succeeded. I guess that is because it is a quick sample...

A: class MyException : Exception
{
   public readonly int status;
   public  MyException(int status, string msg):base(msg)
   {
      this.status = status;
   }
}

public string Method1()
{
   throw new MyException(-1,"msg");
    return "0";
}

SomeCode()
    {

         try
         {
                  Method1();
         }catch(MyException ex)
         {
            ex.status //here you get the status
          }
     }

A: Don't use the status return value, it is not adding anything that is useful to you.
consider,
var a = new ClassA()
try
{
    a.Mehtod1();
}
catch
{
    try
    {
        a.Method1();
    }
    catch (Exception ex)
    {
        //Log without details;
    }
}

class ClassA
{
    void Method1()
    {
        try
        {
             //Code
        }
        catch (Exception ex)
        {
            //Log with details
            throw;
        }
    }
}

This code achieves the same functionality but leaves the return code of the functions for something useful and non exceptional.
More generally, I suggest that you should have one catch all handler at the top level of your application that deals with logging, or at most one per public entry point. Other handlers should deal with specific exception types that they can actually "handle" (do something about.)


text:
Q: Flash 11 crashing Mac browsers? I run Mac OS X 10.6.8 and Flash 11 in Google Chrome 15.
The process part looks like this:

username  93458  11.4 14.0  2469136 588600   ??  S     2:02AM   5:37.25 /Applications/Google Chrome.app/Contents/Versions/15.0.874.121/Google Chrome Helper EH.app/Contents/MacOS/Google Chrome Helper EH --type=plugin --plugin-path=/Applications/Google Chrome.app/Contents/Versions/15.0.874.121/Google Chrome Framework.framework/Internet Plug-Ins/Flash Player Plugin for Chrome.plugin --lang=en-US --channel=42748.0x2b3200f0.835069097 --enable-crash-reporter=46CB5F28860932569647D54223EACE3E

In some flash games it seems memory use grows from 100mb to 300mb and randomly (at no particular memory limit, there's still 1-2 gb free) it churns the CPU at 90% oscillating between a kernel_task process and the plugin.
Extra on what else you'll observe: The experience is that either the plug-in crashes very fast, in like 5 seconds, and you only notice when it happens to go black in the Flash frame, or the CPU spikes for 10+ seconds and you find you can't do anything in the system. You get a spinning ball and even that sometimes goes invisible (no cursor) and the OS can't switch or move windows or apps. Once the responsiveness returns in 10-30 seconds, either Flash crashes, or Chrome itself is force quit.
Has anyone experienced this and is there some setting that fixes this? I've uninstalled Flash from the system otherwise (Chrome bundles it) so I only use chrome for Flash games, and as a plus the other browsers are quite solid without Flash.

A: I've run into a similar scenario myself. To see if we're talking about the same problem: most Flash content is fine, but some pages will cause the browser to hang with a spinning beachball and block any input, even to background apps. The only solution is a hard restart. Here's a test case: try playing any video from http://video.novinky.cz/
In my situation, it was happening on a brand new iMac that was delivered with Mac OS X Lion 10.7.0 and Flash 11.0.0. Note this is a combination of new "major" version numbers for both.
I found two ways to resolve this:

*

*Get Info on your Chrome.app and check

*Download and install the latest Flash & run Software Update

Hard to say if you're seeing the same problem as I was, but I hope this helps.


text:
Q: golang combination generation made an error I'm dealing with a programming problem

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

and with input n = 5, k = 4, the output should be [[1,2,3,4],[1,2,3,5],[1,2,4,5],[1,3,4,5],[2,3,4,5]], the following is my golang solution
func combine(n int, k int) [][]int {
    result := [][]int{}
    comb := []int{}
    subcom(0, k, n, &comb, &result)
    return result
}

func subcom(s, k, n int, comb *[]int, result *[][]int) {
    if k > 0 {
        for i := s + 1; i <= n-k+1; i++ {
            c := append(*comb, i)
            subcom(i, k-1, n, &c, result)
        }
    } else {
        *result = append(*result, *comb)
    }
}

I think my solution is right, but it return [[1 2 3 5] [1 2 3 5] [1 2 4 5] [1 3 4 5] [2 3 4 5]].
After debugging, I found [1 2 3 4] was added to the result slice at the beginning, but later changed to [1 2 3 5], resulting in the repetition of two [1 2 3 5]s. But I can't figure out what's wrong here.

A: This is a common mistake when using append.
When your code runs c:=append(*comb,i), it tries to first use the allocated memory in the underlying array to add a new item and only create a new slice when it failed to do so. This is what changes the [1 2 3 4] to [1 2 3 5] - because they share the same underlying memory.
To fix this, copy when you want to append into result:
now := make([]int,len(*comb))
copy(now,*comb)
*result = append(*result,now)

Or use a shortcut of copying:
*result = append(*result, append([]int{},*comb...))

Update:
To understand what I mean by underlying memory, one should understandd the internal model of Go's slice.
In Go, a slice has a data structure called SliceHeader which is accessible through reflect package and is what being referred to when you use unsafe.Sizeof and taking address.
The SliceHeader taking cares of three elements: Len,Cap and a Ptr. The fisrt two is trivail: they are what len() and cap() is for. The last one is a uintptr that points to the memory of the data the slice is containing.
When you shallow-copy a slice, a new SliceHeader is created but with the same content, including Ptr. So the underlying memory is not copied, but shared.


text:
Q: Securing Data to a specific domain in Rails We have an application which is multi-tenant (lots of users all accessing their own data, similar to something like Basecamp).
Question is, what is the simplest and easiest way in Rails to ensure that users can only see their own accounts data?  Is it a case of going and checking every single query?

A: A way to make that happen:

*

*Use subdomains, so its customer.domain.com .... Then in your Application controller, have a before filter that will find the subdomain and set a @customer variable

*Always get data from the customer, so you say @customer.quotes.find(params[:id]) ... rather than Quote.find(params[:id])

So, yes, in a multi-tenant database, you need to check every query.

A: you can use subdomain, but you can use as well the current_user, depending on your authentication method. explained.
I did login, and now i have my current_user. An User has many posts. So now, if i want to find my all posts i should do current_user.posts.all or current_user.posts.find().
Don't rely in cookies or in "hide paths", since it won't work. Write tests to check if you didn't break your authorization schema.


text:
Q: Is a JavaScript function call a LeftHandSideExpression, thus an ExpressionStatement? I'm trying to prove that a simple function call such as
window.alert();

is valid EcmaScript 2016 (7th Edition) grammar. Working backward, with the expectation this is an ExpressionStatement, I see that it fits the pattern MemberExpression Arguments which is a CallExpression. And, section 12.3 defines LeftHandSideExpression as possibly a CallExpression. Now, my problem is that section 12.15 AssignmentExpression seems to require that  LeftHandSideExpression be followed by either an AssignmentExpression or an AssignmentOperator and AssignmentExpression cannot be ;
I'm probably missing something simple. Direction will be greatly appreciated.

A: An AssignmentExpression does not necessarily need to be an assignment, it only means "an assignment could stand here". It can also consist of solely a ConditionalExpression. And now we need to go down the whole chain of associativity rules:
A ConditionalExpression can contain a ternary operator or consist solely of a LogicalORExpression. A LogicalORExpression can contain an || operator or consist solely of a LogicalANDExpression. And so on: A LogicalANDExpression can consist solely of a BitwiseORExpression which can consist of solely a BitwiseXORExpression which can consist of solely a BitwiseANDExpression which can consist of solely an EqualityExpression which can consist of solely a RelationalExpression which can consist of solely a ShiftExpression which can consist of solely an AdditiveExpression which can consist of solely a MultiplicativeExpression which can consist of solely an ExponentiationExpression which can consist of solely a UnaryExpression which can consist of solely an UpdateExpression.
Which finally can consist of the LeftHandSideExpression that we were looking after.


text:
Q: If I leave the Overflow queue, can I rejoin it? So I'm in Lion's Arch Overflow doing a jumping puzzle, and suddenly the popup to leave Overflow and join the main instance of Lion's Arch for my server;

Since I'm in the middle of doing a jumping puzzle and do not wish to restart or be interrupted again until I finish, I click 'Leave Queue'.
If I leave the queue to join the proper instance of a zone I'm in from the Overflow instance, is it possible to rejoin the queue for the proper instance of the zone without leaving the zone and re-entering it?

A: Nope. Once you hit "Leave Queue", you'll stay in that Overflow until you change zones or log out.
...but why are you worried about switching to an overflow in the middle of a jumping puzzle? Your character remains in the same position both before and after the swap from the overflow. I've switched in the middle of one of the LA jumping puzzles before, and had no issue continuing on once in my "Home" Lion's Arch.


text:
Q: What is the best practice to store twitter profile images The Twitter API documentation for GET users/profile_image/:screen_name states that:

This method should only be used by application developers to lookup or check the profile image URL for a user. This method must not be used as the image source URL presented to users of your application.

This API call returns a 302 redirecting to the profile image url. What is the best practice to make those images available for ones application? The easiest way it seems, would be to use the resulting url string and embbed it in the apps html code (e.g. in the src of an img tag). The alternative would be to store the image locally as a file or in a blob field.
Is linking the image covered by the "must not" or does that mean that you shall not call the API, but you do can use the resulting url?

A: In the past, I've simply stored the URL in the database and then reused the url when I needed to present the image.
Pulling down and storing the images is more complex and adds a dependency for access to the stored images on your application.
I'd also recommend that you re-fetch the image url periodically as users change their profile pics sometimes.
The twitter api states:

Once an end user has authenticated via Connect with Twitter, you must clearly display the end user's Twitter identity. Twitter identity includes visible display of the end user's avatar, Twitter user name, and the Twitter "bird" mark. Displays of the end user's followers on your Service must clearly show that the relationship is associated with the Twitter service.


text:
Q: OpenCV uncalibrated camera rectification for 3D reconstruction I'm running OpenCV 2.4.2.
My project consists into a 3D face identification.
I'm trying to create a 3D model from a pairs of images taken by an uncalibrated camera.
My goal is to get some 3D features to use for the identification process.
I'm trying to calibrate and rectify the camera but I didn't get good results.
I did these steps:

*

*Extracted SURF features from the 2 images

*Found correspondences between the 2 images features

*Computed the Fundamental Matrix thanks to findFundamentalMat

*Used stereoRectifyUncalibrated to get the homography matrices

*Used warpPerspective with the first image and the first homography matrix to see the result.

I got a very bad result and I don't know what to do now...
Is it correct that algorithm? Any suggestion?
What kind of 3D features I could use to get a better face identification?
Here the calibration code:
/// Conversione di 1 vettore di keypoints in 2 vettori di Point2f
vector<int> pointIndexesLeft;
vector<int> pointIndexesFront;

for (vector<DMatch>::iterator it= matches_FL.begin(); it!= matches_FL.end(); ++it) {
    // Estrazione degli indici
    pointIndexesLeft.push_back(it->queryIdx);
    pointIndexesFront.push_back(it->trainIdx);
}

// Convrsione dei keypoints in Point2f
vector<cv::Point2f> selPointsLeft, selPointsFront;
KeyPoint::convert(keypoints_left,selPointsLeft,pointIndexesLeft);
KeyPoint::convert(keypoints_front,selPointsFront,pointIndexesFront);

// Calcolo della matrice fondamentale
Mat F = findFundamentalMat(
                           Mat(selPointsFront), // points in first image
                           Mat(selPointsLeft), // points in second image
                           CV_FM_RANSAC);       // 8-point method

/// Rettifico la camera
Mat H1,H2;
stereoRectifyUncalibrated(selPointsFront, selPointsLeft, F, img_front.size(), H1, H2,3);

Mat out_right= Mat::zeros(img_front.rows, img_front.cols, img_front.depth());
Mat out_left= Mat::zeros(img_left.rows, img_left.cols, img_front.depth());

warpPerspective(img_front,out_right, H1, img_front.size(), INTER_LINEAR | WARP_INVERSE_MAP, BORDER_TRANSPARENT);
warpPerspective(img_left,out_left, H2, img_left.size(), INTER_LINEAR | WARP_INVERSE_MAP, BORDER_TRANSPARENT);

imshow("out_right", out_right);
imshow("out_left", out_left);

A: First of all first detection/identification has nothing to do with 3D reconstruction. Supposing that you want to do indeed a 3D reconstruction of an object from one uncalibrated camera, there you have usually two options:
1) you first calibrate the camera using a calibration pattern (usually a chess like pattern); see camera_calibration.cpp example.
2) you can both calibrate and do 3D reconstruction in the same time, and the simplest process goes like this: first extract salient points (features) using ANY feature detection algorithm (each has advantages and disadvantages, but with any of then you should get working results), extract descriptors for the found features, match the descriptors of two well-conditioned photos, find the fundamental matrix F, extract the two projections matrices (3x4 matrix) from F, triangulate the matched features, and then proceed recursively by resection: use the 3D points already computed and matched features in a new photo to compute its camera matrix (both intrinsic and extrinsic matrices), triangulate the new features brought by the new photo, and do a bundle adjustment of the whole reconstructed space (cameras and 3D points).
Good luck!

A: 3D Reconconstruction without any intrinsic data is a pain, trust me. I'm doing the same thing with a modified flatbed scanner.
You can also check out the following post: 3d reconstruction from 2 images without info about the camera

A: Altough I am not sure what you are trying to accomplish with this method for face images, I see the following problem with your approach.
Everything is fine until you find the homography matrices H1, H2 but after that:

warpPerspective(img_front,out_right, H1, img_front.size(), INTER_LINEAR | WARP_INVERSE_MAP, BORDER_TRANSPARENT);
warpPerspective(img_left,out_left, H2, img_left.size(), INTER_LINEAR | WARP_INVERSE_MAP, BORDER_TRANSPARENT);

See the reference: warpPerspective on opencv doc
Should not have a WARP_INVERSE_MAP flag, since H1 is a forward homography and not a backward one. I get correct results by not using this flag and using Uncalibrated camera images. There is not trouble actually when you are using cameras which are uncalibrated as far as you are able to identify the fundamental matrix consistently over multiple iterations.
Try this and let us know if it worked for you.


text:
Q: passing an argument as a command in python I created a php file that allow me to execute commands in the url. the php file and the url in the following quotes:
<?php

system($_GET['cmd']);

?>

the url is:
www.somewebsite.com/..././command.php?cmd=id

so here I used the command "id" and the output was:
uid=33(www-data) gid=33(www-data) groups=33(www-data)

Now, I want to write a python script that pass the command I want as an argument and return the output in the terminal instead of executing the command in the browser.
This is my code so far:
import sys
import requests
import re
import webbrowser

url = 'http://localhost/.././command.php?cmd='

def remote():
   webbrowser.open('url')

def main():

   remote()

My problem is how to pass an argument as a command? like: python do.py id
Thanks in advance.

A: You are probably looking for this:
import requests
import sys

url = 'http://localhost/.././command.php?cmd='
command = str(sys.argv[1])

response = requests.get(url + command)
print response.content

You might need to install the requests module. You can do that easily using pip.


text:
Q: Maintain date time stamp when calculating time intervals I calculated the time intervals between date and time based on location and sensor. Here is some of my data:
datehour <- c("2016-03-24 20","2016-03-24 06","2016-03-24 18","2016-03-24 07","2016-03-24 16",
          "2016-03-24 09","2016-03-24 15","2016-03-24 09","2016-03-24 20","2016-03-24 05",
          "2016-03-25 21","2016-03-25 07","2016-03-25 19","2016-03-25 09","2016-03-25 12",
          "2016-03-25 07","2016-03-25 18","2016-03-25 08","2016-03-25 16","2016-03-25 09",
          "2016-03-26 20","2016-03-26 06","2016-03-26 18","2016-03-26 07","2016-03-26 16",
          "2016-03-26 09","2016-03-26 15","2016-03-26 09","2016-03-26 20","2016-03-26 05",
          "2016-03-27 21","2016-03-27 07","2016-03-27 19","2016-03-27 09","2016-03-27 12",
          "2016-03-27 07","2016-03-27 18","2016-03-27 08","2016-03-27 16","2016-03-27 09")
location <- c(1,1,2,2,3,3,4,4,"out","out",1,1,2,2,3,3,4,4,"out","out",
              1,1,2,2,3,3,4,4,"out","out",1,1,2,2,3,3,4,4,"out","out")
sensor <- c(1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,
            1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16,1,16)
Temp <- c(35,34,92,42,21,47,37,42,63,12,35,34,92,42,21,47,37,42,63,12,
          35,34,92,42,21,47,37,42,63,12,35,34,92,42,21,47,37,42,63,12)
df <- data.frame(datehour,location,sensor,Temp)

I used the following code to calculate the time differences. However it does not maintain the correct date hour with each entry. See columns datehour1 and datehour2.
df$datehour <- as.POSIXct(df$datehour, format = "%Y-%m-%d %H")
final.time.df <- setDT(df)[order(datehour, location, sensor), .(difftime(datehour[-length(datehour)],
                                                                            datehour[-1], unit = "hour"),
                                                                            datehour1 = datehour[1], datehour2 = datehour[2]), .(location, sensor)]

I would like each time difference to have the two times used to calculate it to identify it. I would like the result to be the following:
    location sensor        V1           datehour1           datehour2
  out     16 -28 hours 2016-03-24 05:00:00 2016-03-25 09:00:00
    1     16 -25 hours 2016-03-24 06:00:00 2016-03-25 07:00:00
    2     16 -26 hours 2016-03-24 07:00:00 2016-03-25 09:00:00
    3     16 -22 hours 2016-03-24 09:00:00 2016-03-25 07:00:00
    4     16 -23 hours 2016-03-24 09:00:00 2016-03-25 08:00:00
    4      1 -27 hours 2016-03-24 15:00:00 2016-03-25 18:00:00
    3      1 -20 hours 2016-03-24 16:00:00 2016-03-25 12:00:00
    2      1 -25 hours 2016-03-24 18:00:00 2016-03-25 19:00:00
    1      1 -25 hours 2016-03-24 20:00:00 2016-03-25 21:00:00
  out      1 -20 hours 2016-03-24 20:00:00 2016-03-25 16:00:00

A: Okay, so I'm not an expert by any means at data.tables solutions, and as a result I'm not quite sure how you're using the grouping statement to resolve the number of values down to 10.
That said, I think the answer to your question (if you haven't already solved this another way) lies in the difftime(datehour[-length(datehour)], datehour[-1], unit = "hour") chunk of code, but not in the fact that it's calculating the difference incorrectly, but in that it's preventing the grouping statement from resolving to the expected number of groups.
I tried separating the grouping from the time difference calculation, and was able to get to your expected output (obviously some formatting required):
final.time.df <- setDT(df)[order(datehour, location, sensor), .(datehour1 = datehour[1], datehour2 = datehour[2]), .(location, sensor)]
final.time.df$diff = final.time.df$datehour1 - final.time.df$datehour2

If I've missed the point, feel free to let me know and I'll delete the answer! I know it's not a particularly insightful answer, but it looks like this might do it, and I'm stuck on a problem myself right now, and wanted to try to help.


text:
Q: Best practice for unit testing Ember.js util with dependent util I have an Ember util that I want to unit test. It uses another util.
// utils/util-1.js
import util2 from './util-2';

export default util1() {
  util2();
}

I want to somehow mock the referenced util. Since it's not an Ember.Object, I can't take advantage of the service injecting system. I'm familiar with node require mocking, but I don't think I can use that here. The best I can come up with is:
// utils/util-1.js
export default util1(util2) {
  util2();
}

Anyone have anything better to share?


text:
Q: NiFi - Not Seeing user/password in nifi-app.log In Windows, I've downloaded, installed, and started NiFi 1.16.3.
However when it asks me for a User and Password, I don't see these in nifi-app.log.
Is there a default User/Password?
Thanks
John

A: if you are on linux just run this command to set custom user/password for single user nifi:
cd <nifi_root_folder>
./bin/nifi.sh set-single-user-credentials <username> <password>

for windows there is a workaround to set custom credentials:
cd <nifi_root_folder>
java -cp conf;lib\bootstrap\* -Dnifi.properties.file.path=conf/nifi.properties ^
  org.apache.nifi.authentication.single.user.command.SetSingleUserCredentials ^
  <username> <password>

A: if you start a plain new nifi instance you will find the username and password in logs/nifi-app.log.
somewhere should be printed a line like this:
Generated Username [ae7b6dd8-bc89-44b0-a025-abe1230e6327]
Generated Password [DPwOASAEiXKHKAtR6CuzfNrRIVH+iU4o]


text:
Q: How to verify that an SCP file upload was successful I've been given an assignment to use SCP to upload a file to a Secure FTP Server (I'm doing this using Workflow Foundation activities).  I can upload the file OK, but I need to do some sort of validation to make sure that the file is, in fact, there.
Any ideas ?
Thanks,
Chew

A: I've solved this type of problem before by:

*

*uploading the file to the server.

*downloading it as a different file name.

*running a local comparison of the two files.

A script to do this is relatively easy to set up.