text:
Q: Flutter Error: Another exception was thrown: Instance of 'DiagnosticsProperty' .It is showing a blank screen when redirected to that page Flutter Error: Another exception was thrown: Instance of 'DiagnosticsProperty' .It is showing a blank screen when redirected to that page.
I have successfully uploaded the text items , one image and one pdf to the firebase database and able to retrieve all of them in cards Widget view and List Tiles View Now I am trying to get individual view when clicked on List Items from List view.
Please check my code , I am seeing a blank screen when tried to redirect to the required Retrievepage.
                                  RetrievePage.dart

import 'dart:async';
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gadjet_inventory/Form/ListTileFeed.dart';
import 'package:gadjet_inventory/Form/ListTiles.dart';
import 'package:gadjet_inventory/main.dart';
import 'package:intl/intl.dart';
import 'package:gadjet_inventory/Form/Data.dart';

import 'package:gadjet_inventory/Form/UploadData.dart';

import 'package:pdf_flutter/pdf_flutter.dart';
// ignore: must_be_immutable
import 'package:url_launcher/url_launcher.dart';

import 'Data.dart';

class RetrievePage extends StatefulWidget {

//  String currentEmail;

  //RetrievePage(this.currentEmail);

  @override
  _RetrievePageState createState() => _RetrievePageState();
}

class _RetrievePageState extends State<RetrievePage> {
  List<Data> dataList = [];
  List<bool> favList = [];
  bool searchState = false;
  FirebaseAuth auth = FirebaseAuth.instance;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    DatabaseReference referenceData = FirebaseDatabase.instance.reference().child("Data");
    referenceData.once().then((DataSnapshot dataSnapShot) {
      dataList.clear();
      favList.clear();

      var keys = dataSnapShot.value.keys;
      var values = dataSnapShot.value;

      for (var key in keys) {

        Data data = new Data(
            values [key]['imgUrl'],

            values [key]['cattegorrytype'],
            values [key]['companyname'],
            values [key]['modelname'],
            values [key]['seriesname'],
            values [key]['serielnumber'],
            values [key]['year'],

            key
          //key is the uploadid
        );
        dataList.add(data);
        auth.currentUser().then((value) {
          DatabaseReference reference = FirebaseDatabase.instance.reference().child("Data").child(key).child("Fav")
              .child(value.uid).child("state");
          reference.once().then((DataSnapshot snapShot){
            if(snapShot.value!=null){
              if(snapShot.value=="true"){
                favList.add(true);
              }else{
                favList.add(false);
              }
            }else{
              favList.add(false);
            }
          });
        });

      }

      Timer(Duration(seconds: 1),(){
        setState(() {
          //
        });
      });

    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "List View",
        ),
        actions: <Widget>[
          // action button

        ],
      ),
      body: Center(

        child: Container(
         child: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
        Column(
            children: <Widget>[
              Image.network(
                dataList[index].imgUrl != null
                    ? dataList[index].imgUrl
                    : '',
                width: 500,
                height: 500,

              ),

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),

                          child: Text(  "Cattegorry Type:- "
                          "$dataList[index].cattegorrytype",

                           style: TextStyle(color: Colors.black),

                      ),

                    ),
                  ),
                ],
              ),

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Theme(
                        data: ThemeData(
                          hintColor: Colors.blue,
                        ),

                        child: Text(  "Company Name:- "
                            "$dataList[index].companyname",

                          style: TextStyle(color: Colors.black),

                            ),
                      ),
                    ),
                  ),

                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Theme(
                        data: ThemeData(
                          hintColor: Colors.blue,
                        ),

                        child: Text(  "Model Name:- "
                            "$dataList[index].modelname",

                             style: TextStyle(color: Colors.black),

                        ),
                      ),
                    ),
                  ),

                ],
              ),

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Theme(
                        data: ThemeData(
                          hintColor: Colors.blue,
                        ),

                        child: Text(  "Series Name:- "
                            "$dataList[index].seriesname",

                             style: TextStyle(color: Colors.black),

                        ),
                    ),
                    ),
                  ),

                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Theme(
                        data: ThemeData(
                          hintColor: Colors.blue,
                        ),

                        child: Text(  "Year Of MFG:- "
                            "$dataList[index].year",

                          style: TextStyle(color: Colors.black),

                        ),
                      ),
                    ),
                  ),

                ],
              ),

            ],
        );
        },
       ),
        ),

      ),

    );
  }

  }

Please fix my issue why I am seeing a blank screen with the error "Another exception was thrown: Instance of 'DiagnosticsProperty'"

A: Try to resolve this view without expanded, make a release version without expanded widget.


text:
Q: localhost redirected you too many times. in codeigniter hooks I;m working on a codeigniter project. I want to create a hook so that, it verify the user login every time when he load the class.
my Hook
$hook['post_controller_constructor'] = array(
        'class'    => 'Auth_login',
        'function' => 'is_logged_in',
        'filename' => 'Auth_login.php',
        'filepath' => 'hooks',
);

and also enabled in the config file.
/**
* Auth_login
*/
class Auth_login
{
    /**
     * loading the CI instance
     * @var [object]
     */
    private $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
        $this->CI->load->library('session');
        $this->CI->load->helper('url');
    }

    /**
     * Check the enduser for login verify, every time when the enduser
     * loads the controller.
     */
    public function is_logged_in()
    {
        /**
        *  if end user is not logged in, redirect to the login page
        */
        if(!$this->CI->session->userdata('is_logged_in'))
        {
            $this->CI->session->set_tempdata('faliure','Please sign in to continue');
            redirect(site_url('login/index'));
        }
    }
}

It checks for the session login verify for the end user. If user not logged in then redirect to the login page.
Here is my Controller where it redirects
class Login extends CI_Controller {
    // class constructor
    //    public function __construct() {
    //     parent::__construct();
    //         // load default
    //     $this->load->model('login_model');
    // }

    /**
     * [display the login page, and verify the login page using "form_validation" for server side validation]
     * @return [redirect] [description]
     */
    public function index()
    {
        $this->load->model('login_model');
        // on form sumbit
        $on_sumbit = $this->input->post('verify');
        if(isset($on_sumbit))
        {
            // server side validation for login
           if ($this->form_validation->run('login/login_verify') == FALSE)
            {
                $this->load->view('login');
            }
            else
            {
                // get the form post value
                $user_name = $this->input->post('user_name');
                $password = $this->input->post('password');
                // verify login
                $verified = $this->login_model->login_verify($user_name,$password);
                if($verified)  // success
                {
                    redirect('dashboard');
                }
                else // failure
                {
                    $this->session->set_flashdata('login_failure','Please check your email and password and try again');
                    redirect('login/index');
                }
            }
        }
        // login page
        $this->load->view('login');
    }

    // delete active session
    public function logout()
    {
        $this->session->sess_destroy();
        redirect('login');
    }
}

When it redirect to the login controller, it show errors like
since it working on the local system
"localhost redirected you too many times"
what is the actual problem with this. Any help would be appreciated.

A: You want to check if you are not on login controller or in other words you want to have hook functionality on every controller except login where you redirect if condition not met. You can exclude that controller in condition this way:
/**
* Auth_login
*/
class Auth_login
{
    /**
     * loading the CI instance
     * @var [object]
     */
    private $CI;

    public function __construct()
    {
        $this->CI =& get_instance();
        $this->CI->load->library('session');//working with sessions - you want sessions
        //to be loaded ASAP so better way would be having it in
        //APPPATH.'config/autoload.php' instead in all classes

        /**
         * @tutorial how to exclude hook interaction with particular class/controller
         */
        if ( strtolower( $this->CI->router->class ) == 'login' )
        {
            return;
        }

        $this->CI->load->helper('url');
    }

    /**
     * Check the enduser for login verify, every time when the enduser
     * loads the controller.
     */
    public function is_logged_in()
    {
        /**
        *  if end user is not logged in, redirect to the login page
        */
        if(!$this->CI->session->userdata('is_logged_in'))
        {
            $this->CI->session->set_tempdata('faliure','Please sign in to continue');
            redirect(site_url('login/index'));
        }
    }
}

A: Delete all sessions from \application\cache\session

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's the difference between these two javascript calls? What does the 'function' do in the following?
$('.event-row').on('mouseover',function(){
  arc.event_handler.event_row_over();
  });

$('.event-row').on('mouseover',arc.event_handler.event_row_over );

A: There's a very important difference.

*

*The first one will call the function with the context its this value as the event_handler object.

*The second one will call the function with the context its this value as the DOM element to which the handler is bound.
So the first one preserves the expected calling context this value, which may be required by the function.

A: In the first case with the anonymous function this inside that function is bound to the DOM element that caused the event. This is a convention that is common in browsers and also done when binding events natively. When calling arc.event_handler.event_row_over(); however, this is re-bound to arc.event_handler inside event_row_over; as it's called as an object method and in such a case this points to the object on which the method was called. The method will be called without any arguments.
In the second case you register the function arc.event_handler.event_row_over for the event. When called jQuery sets this to the related element so inside event_row_over, this points to that element. arc.event_handler is not available in there unless there is some other variable that points to it. jQuery also passes the event object as the first argument so the method is called with that argument.
Usually object methods expect this to be their object, so in almost every case you want to use the anonymous function to wrap the call. In case the element matters, pass this as an argument to the method.
Another way, without an anonymous function, would be using the bind() method every function has:
$('.event-row').on('mouseover', arc.event_handler.event_row_over.bind(arc.event_handler));

However, only modern browsers support this natively.

A: In the first case you are enclosing the function call in an anonymous function.
In the second case you are just assigning the function pointer..

A: First off, it seems like there is an extra dot in there.. arc.event_handler.event_row_over.(); should probably be just arc.event_handler.event_row_over();
And all the anonymous function does is it calls a member function named event_row_over of the arc.event_handler object; and it doesn't return anything.

A: The 'function' keyword will creates a new closure and encapsulate the scope. Good article on closures https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures.

A: The context/scope of the function will not be the same.
Also, with the second one,
$('.event-row').on('mouseover',arc.event_handler.event_row_over );

you're getting the event object as an argument.

A: The first case, you have an additional function wrapper. This is useful when you want to do something else before calling the real event handler 'arc.event_handler.event_row_over()' for example you may do something like below:
$('.event-row').on('mouseover',function(){
  doPreEventHandling();
  arc.event_handler.event_row_over();
  doPostEventHandling();
});

On the other hand you may even extract that annonymous function to be a named function and call as below:
var eventHandler = function(){
      doPreEventHandling();
      arc.event_handler.event_row_over();
      doPostEventHandling();
};

$('.event-row').on('mouseover', eventHandler);

All above will be just similar in behavior, but more wrapper functions you have more abstraction you gain. But it will compromise performance and sometimes readability.


text:
Q: Excel: How to open Data entry form using VBA, when there are 4 tables in the worksheet I have an excel worksheet that has four tables, one for each region of the country (Scot,North,London,South). I need to create a data entry form which will allow user to populate these tables. Ideally, the form will appear on a different worksheet once a button has been pressed. I would like to have four different buttons, each linked to one of the four tables. The tables have identical columns.
What is the best way to do this? I can use Excel's built in data entry form, by clicking on the table and then pressing Form. However, this almost defeats the purpose of the form, sicne the idea is to have a user end.
I have seen tutorials for creating my own form, but I need information on how to populate different tables depending on which button was pressed.
Thanks in advance.

A: Ok now its different code but you should be able to adapt it for your form.
Private Sub CommandButton1_Click()
Dim Inp1 As String
Dim Inp2 As String

Inp1 = TextBox1.Text

Inp2 = TextBox2.Text

Range("B2").Select
Do While ActiveCell.Value <> 0
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Value = Inp1

Range("C2").Select
Do While ActiveCell.Value <> 0
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Value = Inp2

End Sub

A: Having asked the question, I managed to find a solution my self. I will include it as this seems to be a problem without a good answer online. The code is to be used in the example shown in this tutorial:
https://www.youtube.com/watch?v=5oXcct1mOUw
The code for the Submit button is shown below. This is the code for 9 or 10 returns, but can be adjusted easily
Private Sub CommandButton1_Click()

Dim ws As Worksheet
Set ws = Worksheets("Current")

'Add new row
ws.ListObjects("Table1").ListRows.Add (1)

'Populate new row
ws.ListObjects("Table1").DataBodyRange(1, 1).Value = Me.name1.Value
ws.ListObjects("Table1").DataBodyRange(1, 2).Value = Me.namecom.Value
ws.ListObjects("Table1").DataBodyRange(1, 3).Value = Me.cin.Value
ws.ListObjects("Table1").DataBodyRange(1, 4).Value = Me.hold.Value
'DROPDOWN BOX
ws.ListObjects("Table1").DataBodyRange(1, 5).Value = Me.fee.Value
ws.ListObjects("Table1").DataBodyRange(1, 6).Value = Me.unam.Value
ws.ListObjects("Table1").DataBodyRange(1, 7).Value = Me.capfin.Value
ws.ListObjects("Table1").DataBodyRange(1, 8).Value = Me.month.Value
ws.ListObjects("Table1").DataBodyRange(1, 9).Value = Me.comments.Value

MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"

'clear the data

Me.name1.Value = ""
Me.namecom.Value = ""
Me.cin.Value = ""
Me.hold.Value = ""
'DROPDOWN BOX
Me.fee.Value = ""
Me.unam.Value = ""
Me.capfin.Value = ""
Me.month.Value = ""
Me.comments.Value = ""

Me.name1.SetFocus

`


text:
Q: How to copy one line from long string C I'm looking to copy the FIRST line from a LONG string P into a buffer
I have no idea how to make it.
while (*pros_id != '/n'){
   *pros_id_line=*pros_id;
   pros_id++;
   pros_id_line++;
}

And tried
fgets(pros_id_line, sizeof(pros_id_line), pros_id);

Both are not working. Can I get some help please?

A: Note, as Adriano Repetti pointed out in a comment and an answer, that the newline character is '\n' and not '/n'.
Your initial code can be fixed up to work, provided that the destination buffer is big enough:
while (*pros_id != '\n' && *pros_id != '\0')
   *pros_id_line++ = *pros_id++;
*pros_id_line = '\0';

This code does not include the newline in the copied buffer; it is easy enough to add it if you need it.
One advantage of this code is that it makes a single pass through the data up to the newline (or end of string).  An alternative makes two passes through the data, one to find the newline and another to copy to the newline:
if ((end = strchr(pros_id, '\n')) != 0)
{
    memmove(pros_id_line, pros_id, end - pros_id);
    pros_id_line[end - pros_id] = '\0';
}

This ensures that the string is null-terminated; again, it omits the newline, and assumes there is enough space in the pros_id_line buffer for the data.  You have to decide what is the correct behaviour when there is no newline in the buffer.  It might be sufficient to copy the buffer without the newline into the target area, or you might prefer to report a problem.
You can use strncpy() instead of memmove() but it has a more complex loop condition than memmove() — it has to check for a null byte as well as the count, whereas memmove() only has to check the count.  You can use memcpy() instead of memmove() if you're sure there's no overlap between source and target, but memmove() always works and memcpy() sometimes doesn't (though only when the source and target areas overlap), and I prefer reliability over possible misbehaviour.
Note that setting a buffer to zero before copying a string to it is a waste of energy.  The parts that you're about to overwrite with data didn't need to be zeroed.  The parts that you aren't going to overwrite with data didn't need to be zeroed either.  You should know exactly which byte needs to be zeroed, so why waste the time on zeroing anything except the one byte that needs to be zeroed?
(One exception to this is if you are dealing with sensitive data and are concerned that some function that your code will call may deliberately read beyond the end of the string and come across parts of a password or other sensitive data.  Then it may be appropriate to wipe the memory before writing new data to it.  On the whole, though, most people aren't writing such code.)

A: New line is \n not /n anyway I'd use strchar for this:
char* endOfFirstLine = strchr(inputString, '\n');
if (endOfFirstLine != NULL)
{
    strncpy(yourBuffer, inputString,
        endOfFirstLine - inputString);
}
else // Input is one single line
{
    strcpy(yourBuffer, inputString);
}

With inputString as your char* multiline string and inputBuffer (assuming it's big enough to contain all data from inputString and it has been zeroed) as your required output (first line of inputString).

A: If you're going to be doing a lot of reading from long text buffers, you could try using a memory stream, if you system supports them:  https://www.gnu.org/software/libc/manual/html_node/String-Streams.html
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>

static char buffer[] = "foo\nbar";

int
main()
{
    char arr[100];
    FILE *stream;

    stream = fmemopen(buffer, strlen(buffer), "r");
    fgets(arr, sizeof arr, stream);
    printf("First line: %s\n", arr);
    fgets(arr, sizeof arr, stream);
    printf("Second line: %s\n", arr);
    fclose (stream);

    return 0;
}

A: POSIX 2008 (e.g. most Linux systems) has getline(3) which heap-allocates a buffer for a line.
So you could code
 FILE* fil = fopen("something.txt","r");
 if (!fil) { perror("fopen"); exit(EXIT_FAILURE); };
 char *linebuf=NULL;
 size_t linesiz=0;
 if (getline(&linebuf, &linesiz, fil) {
   do_something_with(linebuf);
 }
 else { perror("getline"; exit(EXIT_FAILURE); }

If you want to read an editable line from stdin in a terminal consider GNU readline.
If you are restricted to pure C99 code you have to do the heap allocation yourself (malloc or calloc  or perhaps -with care- realloc)
If you just want to copy the first line of some existing buffer char*bigbuf;  which is non-NULL, valid, and zero-byte terminated:
char*line = NULL;
char *eol = strchr(bigbuf, '\n');
if (!eol) { // bigbuf is a single line so duplicate it
  line = strdup(bigbuf);
  if (!line) { perror("strdup"); exit(EXIT_FAILURE); }
} else {
    size_t linesize = eol-bugbuf;
    line = malloc(linesize+1);
    if (!line) { perror("malloc"); exit(EXIT_FAILURE);
    memcpy (line, bigbuf, linesize);
    line[linesize] = '\0';
}


text:
Q: how to check function is called or not in react js? I am trying to test my service which have one function saveWithoutSubmit
export const saveWithoutSubmit = async (
  values,
  orderId,
  taskId,
  fseMsisdn,
  updateTaskListAfterFilter
) => {
  var obj = {
    remarks: values.remarks,
    requestedBy: localStorage.getItem("msisdn")
  };
  try {
    const response = await sendPostRequest(`${API_TASK_URL}closeSr`, {
      ...obj,
      saveWithoutSubmit: true
    });

    if (response && response.data && response.data.status.code !== "200") {
      error(response.data.result.message);
    } else {
      console.log(response);
      success(response.data.status.message);
      updateTaskListAfterFilter();
    }
  } catch (e) {
    if (e.response && e.response.data) {
      console.log(e.response.data.message);
      error(e.response.data.status.message);
    }
  }
};

I want to check success or error method is called or not ? or updateTaskListAfterFilter is called or not?
I tried like this
https://codesandbox.io/s/ecstatic-currying-5q1b8
describe("remark service test", () => {
  const fakeAxios = {
    get: jest.fn(() => Promise.resolve({ data: { greeting: "hello there" } }))
  };
  it("save without sumit", () => {
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();
  });
});

can you please suggest how i will test async methods or post request (using mook data)??
so that my test cases will be passed.
I want to check if I got success from promise my success method will be called else error
any update ?..!!
update
https://codesandbox.io/s/ecstatic-currying-5q1b8
it("save without sumit", async () => {
    const sendPostRequest = jest.fn(() =>
      Promise.resolve({ data: { greeting: "hello there" } })
    );
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();
  });

it("save without sumit", async () => {
    const sendPostRequest = jest.fn(() =>
      Promise.resolve({ data: { greeting: "hello there" } })
    );

    const mockUpdateTaskListAfterFilter = jest.fn();
    const updateTaskListAfterFilter = () => {};
    saveWithoutSubmit({}, updateTaskListAfterFilter);

    expect(updateTaskListAfterFilter).toBeCalled();

    await wait(() => {
      expect(mockUpdateTaskListAfterFilter).toBeCalled();
    });
  });

A: You should change it("save without sumit", () => { to it("save without sumit", async () => {.
Then you usually use jest.fn() to create a mock function that you will give to another function or component.
Finally, await the mock function to be called:
await wait(() => {
  expect(mockUpdateTaskListAfterFilter).toBeCalled();
});

Alternatively, you can await some other event that you know will occur before your mock is called, like some other mock getting called or something appearing on the page, and then check that your mock was called.


text:
Q: Embedding bash script into makefile I want to include some conditional statement into a makefile:
SHELL=/bin/bash
all:
        $(g++ -Wall main.cpp othersrc.cpp -o hello)
        @if [[ $? -ne -1 ]]; then \
          echo "Compile failed!"; \
          exit 1; \
        fi

But get an error:

/bin/bash: -c: line 0: conditional binary operator expected /bin/bash:
  -c: line 0: syntax error near -1' /bin/bash: -c: line 0:if [[  -ne -1 ]]; then \' makefile:3: recipe for target 'all' failed make: *** [all] Error 1

How to fix it?

A: Note that each line of a makefile recipe runs in a different shell, so that $? of the previous line is unavailable, unless you use .ONESHELL option.
A fix without .ONESHELL:
all: hello
.PHONY: all

hello: main.cpp othersrc.cpp
    g++ -o $@ -Wall main.cpp othersrc.cpp && echo "Compile succeeded." || (echo "Compile failed!"; false)

With .ONESHELL:
all: hello
.PHONY: all

SHELL:=/bin/bash
.ONESHELL:

hello:
    @echo "g++ -o $@ -Wall main.cpp othersrc.cpp"
    g++ -o $@ -Wall main.cpp othersrc.cpp
    if [[ $$? -eq 0 ]]; then
        echo "Compile succeded!"
    else
        echo "Compile failed!"
        exit 1
    fi

When $ needs to be passed into a shell command it must be quoted as $$ in the makefile (make charges you a dollar for passing one dollar, basically). Hence $$?.


text:
Q: React Native "Invalid Hook" I don't understand how I can put the colorScheme const inside the config const.
I'm getting the error: "Invalid Hook call"
import {extendTheme} from 'native-base'
import { useColorScheme } from 'react-native';

const colorScheme = useColorScheme()
const config = {

    useSystemColorMode: false,
    initialColorMode: colorScheme
}

const colors={
    primary:{
        50: '#EEF2F6',
        100: '#CFD9E7',
        200: '#B1C1D8',
        300: '#92A9C9',
        400: '#7491B9',
        500: '#5578AA',
        600: '#446088',
        700: '#334866',
        800: '#223044',
        900: '#111822'
    }
}
export default extendTheme({config,colors})

A: Your hook can only be used inside a component, like so;
const MyComponent = () => {

    const colorScheme = useColorScheme();

    const config = {
        useSystemColorMode: false,
        initialColorMode: colorScheme
    }

    return (
        <>...</>
    )
}


text:
Q: Bootstrap Modal on clicking a link on UI Grid In my UI Grid here are the Column Defs in my myController.js file:
    { field: 'trans_typ_dsc', headerTooltip: 'Transaction Type Description', displayName: 'Transaction Type Description', cellTemplate: '
{{COL_FIELD}}
' },
    { field: 'trans_stat', displayName: 'Transaction Status' },
    { field: 'sub_trans_actn_typ', displayName: 'Sub Transaction Action Type', cellTemplate: '
{{COL_FIELD}}
' , visible : false },
    { field: 'case_key', displayName: 'Case Key', visible: true, celltemplate: '{{COL_FIELD}}' },
    { field: 'approved_by', displayName: 'Approved By', visible: false }

Here on clicking the case_key link a UI Bootstrap modal should pop up .
How to do that ?
I know in a html file using a button click it is something like :

Search Transaction

<button type="button" class="btn btn-default" data-toggle="modal" data-target="#recentSearchesModal">Recent Searches</button>

                        <button type="button" class="close" data-dismiss="modal">×</button>

Recent Searches

                                         {{obj | placeholderfunc}}

                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

But here the click event is my controller.js file then how to get the modal opened ?

A: You need to modify the field's cellTemplate and then call grid.appScope.openModal().  openModal should live in your main controller under $scope.openModal.  Do it like this:
Your template:
var myTemplate = "{{ row.entity.myFieldName }}";

Use the template in gridOptions.
$scope.gridOptions = {
    columnDefs: [{
        field: 'myFieldName',
        displayName: 'My Field Name',
        cellTemplate: myTemplate;
    }]
};

Function to call modal:
$scope.openModal = function (e, row) {
    //in here, you can access the event object and row object
    var myEvent = e;
    var myRow = row;

    //this is how you open a modal
    var modalInstance = $uibModal.open({
        templateUrl: '/path/to/modalTemplate.html',
        controller: MyModalCtrl,
        backdrop: 'static'
        //disable the keyboard
        //keyboard: false,
        resolve {
            //pass variables to the MyModalCtrl here
            event: function() { return myEvent; },
            row: function() { return myRow; }
        }
    });

    //call the modal to open, then decide what to do with the promise
    modalInstance.result.then(function() {
        //blah blah the user clicked okay
    },function(){
        //blah blah the user clicked cancel
    })
}


text:
Q: Load Balance on Windows 7 Pro Desktop For development and testing purposes, I'd like to install two "web heads" and a database on my Windows 7 Pro desktop, and then round-robin the incoming requests between them.  The basic setup is easy enough, but I have no good solution for distributing the requests between the two web heads.
Is there any load balancing solution that I can run on Windows 7 Pro?
P.S. I can setup Server OS VMs and use Windows Load Balancing, but it would be so much more convenient to have it all contained on my desktop machine.

A: You could try using perlbal as suggested here. Perlbal is pretty well respected, and perl runs well on windows, so it should be more than adequate. F5 also has a virtual appliance if you happen to be using BigIP in production.


text:
Q: Internet and apt-get very slow I am using xubuntu 13.10 right now and I have some Internet problems.
When I use apt-get it takes almost forever to download just a few kBytes.
I get results like these and it pauses there for a long time:
jens@Ultrabuch:~$ sudo apt-get update
[sudo] password for jens:
Ign http://extras.ubuntu.com saucy InRelease
Holen: 1 http://extras.ubuntu.com saucy Release.gpg [72 B]
OK   http://extras.ubuntu.com saucy Release
OK   http://extras.ubuntu.com saucy/main Sources
OK   http://extras.ubuntu.com saucy/main amd64 Packages
OK   http://extras.ubuntu.com saucy/main i386 Packages
Ign http://extras.ubuntu.com saucy/main Translation-de_DE
Ign http://extras.ubuntu.com saucy/main Translation-de
Ign http://extras.ubuntu.com saucy/main Translation-en
Ign http://archive.canonical.com saucy InRelease
OK   http://archive.canonical.com saucy Release.gpg
OK   http://archive.canonical.com saucy Release
OK   http://archive.canonical.com saucy/partner amd64 Packages
OK   http://archive.canonical.com saucy/partner i386 Packages
Ign http://archive.canonical.com saucy/partner Translation-de_DE
Ign http://archive.canonical.com saucy/partner Translation-de
Ign http://archive.canonical.com saucy/partner Translation-en
96% [Verbindung mit archive.ubuntu.com (2001:67c:1360:8c01::18)

It appears to me that these freezes are caused by "Translation" packages, they are always ignored.
I tried to change the server as well, that didn't work either, as can be seen below.
When I reload synaptic I get this message:

Could not download all repository indexes
The repository may no longer be available or could not be contacted because of         network problems. If available, an older version of the failed index will be used. Otherwise, the repository will be ignored. Check your network connection and ensure the repository address is correct in 'Repositories' under 'Settings'.
Failed to fetch http://archive.canonical.com/ubuntu/dists/saucy/InRelease
Some index files failed to download. They have been ignored, or old ones used instead.

I'd be very happy if someone could help me with that!
Best regards,
Jens
Output of ifconfig -a:
eth0      Link encap:Ethernet  Hardware Adresse 50:b7:c3:07:35:1e
          UP BROADCAST MULTICAST  MTU:1500  Metrik:1
          RX-Pakete:0 Fehler:0 Verloren:0 Überläufe:0 Fenster:0
          TX-Pakete:0 Fehler:0 Verloren:0 Überläufe:0 Träger:0
          Kollisionen:0 Sendewarteschlangenlänge:1000
          RX-Bytes:0 (0.0 B)  TX-Bytes:0 (0.0 B)

lo        Link encap:Lokale Schleife
          inet Adresse:127.0.0.1  Maske:255.0.0.0
          inet6-Adresse: ::1/128 Gültigkeitsbereich:Maschine
          UP LOOPBACK RUNNING  MTU:65536  Metrik:1
          RX-Pakete:2440 Fehler:0 Verloren:0 Überläufe:0 Fenster:0
          TX-Pakete:2440 Fehler:0 Verloren:0 Überläufe:0 Träger:0
          Kollisionen:0 Sendewarteschlangenlänge:0
          RX-Bytes:211909 (211.9 KB)  TX-Bytes:211909 (211.9 KB)

wlan0     Link encap:Ethernet  Hardware Adresse c8:f7:33:11:38:70
          inet Adresse:192.168.2.105  Bcast:192.168.2.255  Maske:255.255.255.0
          inet6-Adresse: fe80::caf7:33ff:fe11:3870/64 Gültigkeitsbereich:Verbindung
          inet6-Adresse: 2003:66:8807:c620:456b:7fc9:1041:7cc9/64 Gültigkeitsbereich:Global
          inet6-Adresse: 2003:66:8807:c620:caf7:33ff:fe11:3870/64 Gültigkeitsbereich:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metrik:1
          RX-Pakete:28809 Fehler:0 Verloren:0 Überläufe:0 Fenster:0
          TX-Pakete:18907 Fehler:0 Verloren:0 Überläufe:0 Träger:0
          Kollisionen:0 Sendewarteschlangenlänge:1000
          RX-Bytes:32338097 (32.3 MB)  TX-Bytes:3088377 (3.0 MB)

Partial output of apt-fast:
Hit http://ftp-stud.hs-esslingen.de saucy-security/restricted Translation-en
Hit http://ftp-stud.hs-esslingen.de saucy-security/universe Translation-en
Ign http://ftp-stud.hs-esslingen.de saucy-backports/main Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-backports/main Translation-de
Ign http://ftp-stud.hs-esslingen.de saucy-backports/multiverse Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-backports/multiverse Translation-de
Ign http://ftp-stud.hs-esslingen.de saucy-backports/restricted Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-backports/restricted Translation-de
Ign http://ftp-stud.hs-esslingen.de saucy-backports/universe Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-backports/universe Translation-de
Ign http://ftp-stud.hs-esslingen.de saucy-security/main Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-security/main Translation-de
Ign http://ftp-stud.hs-esslingen.de saucy-security/multiverse Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-security/multiverse Translation-de
Ign http://ftp-stud.hs-esslingen.de saucy-security/restricted Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-security/restricted Translation-de
Ign http://ftp-stud.hs-esslingen.de saucy-security/universe Translation-en_GB
Ign http://ftp-stud.hs-esslingen.de saucy-security/universe Translation-de
98% [Connecting to archive.canonical.com (2001:67c:1360:8c01::16)]>

A: Apt-fast is a script that can "drastically improve APT download speed" by using command line download accelerators such as Axel or Aria2 with multiple connections per package.
Ubuntu users can install the latest stable apt-fast from its official PPA:
sudo add-apt-repository ppa:apt-fast/stable
sudo apt-get update
sudo apt-get install apt-fast

apt-fast configuration:
When installing apt-fast in Ubuntu via its PPA, the package asks you if you want to use aptitude or apt-get, what download manager to use (axel or aria2c). If, later on, you want to change some of the apt-fast options, use the following command:
sudo dpkg-reconfigure apt-fast

aria2c is the download tool recommended by the apt-fast developers, mostly because it supports resuming downloads.
Using apt-fast:
apt-fast works the same as apt-get and all you have to do is use "sudo apt-fast install PACKAGE" instead of "apt-get" and so on for any operation.
Install a package:
sudo apt-fast install PACKAGE

Upgrade packages:
sudo apt-fast upgrade

Install the build dependencies for a package:
sudo apt-fast build-dep PACKAGE

Like I was saying, the commands are identical to apt-get and all you have to do is replace "apt-get" with "apt-fast". There's also a download command ("apt-fast download PACKAGE") which downloads the binary into the current directory.

A: First: Ign is ok - it means that repo has not changed since last check and no indexes need to be downloaded.
It seems you accessing ubuntu repo through ipv6, have you noticed any problems with other ipv6 enabled hosts?
You may use ping6 or traceroute6 for quick check of latency and packets loss (although you should remember that TCP and ICMP traffic may be treated differently by your ISP or intermediate hosts), i.e.
ping6 -c20 -i0.5 archive.canonical.com

Packets loss or high time indicates that you have some network problems.
Try to compare it to ICMP via ipv4:
ping -c20 -i0.5 archive.canonical.com

If problem seems to be network-related, try to get rid of ipv6 and check if it helps. You may just delete ipv6 address from your network interface (with DHCP it will be reassigned after reconnect, so it's safe to do so):
sudo ip addr del 2003:66:8807:c620:456b:7fc9:1041:7cc9/64 dev wlan0
sudo ip addr del 2003:66:8807:c620:caf7:33ff:fe11:3870/64 dev wlan0

Also you may check how repo works in browser or try to download something using curl/wget or similar low-level tool (choose single-threaded tool), for example
wget http://archive.ubuntu.com/ubuntu/dists/saucy-updates/Contents-i386.gz

If you'll get much higher download speed with browser/wget than with apt - it may be some problem related to apt.


text:
Q: How to protect firebase Cloud Function HTTP endpoint using authenticated id token and database rules? admin.auth().verifyIdToken(tokenId)
      .then((decoded) => res.status(200).send(decoded))

I understand verifyIdToken() can verify a user id token from Firebase Authentication clients. However we need to protect our Cloud Function by making sure database queries are limited by the security rules defined for the database for the user identified in the token.  Given that the admin SDK has unlimited access by default, how to I limit its access to just that of the authenticated user?

A: Take a look at the following HTTPS function.  It performs the following tasks:

*

*Verifies a Firebase Authentication ID token using the Admin SDK.  The token comes from the query string (but you should use a better solution to transmit the token).

*Pulls the user's UID out of the decoded token.

*Makes a copy of the default Firebase init configuration object, then adds a property called databaseAuthVariableOverride to it, using the UID, to limit the privileges of the caller.

*Initializes a new non-default instance of an App object (named "user") with the new options.  This App object can now be used to access the database while observing security rules in place for that user.

*The Admin SDK is used along with userApp to make a database query to some protect path.

*If the query was successful, remember the response to send to the cleint.

*If the query failed due to security rues, remember an error response to send to the client.

*Clean up this instance of the Admin SDK.  This code takes all precautions to make sure userApp.delete() is called in all circumstances.  Don't forget to do this, or you will leak memory as more users access this function.

*Actually send the response.  This terminates the function.

Here's a working function:
const admin = require("firebase-admin")
admin.initializeApp()

exports.authorizedFetch = functions.https.onRequest((req, res) => {
    let userApp
    let response
    let isError = false

    const token = req.query['token']

    admin.auth().verifyIdToken(token)
    .then(decoded => {
        // Initialize a new instance of App using the Admin SDK, with limited access by the UID
        const uid = decoded.uid
        const options = Object.assign({}, functions.config().firebase)
        options.databaseAuthVariableOverride = { uid }
        userApp = admin.initializeApp(options, 'user')
        // Query the database with the new userApp configuration
        return admin.database(userApp).ref("/some/protected/path").once('value')
    })
    .then(snapshot => {
        // Database fetch was successful, return the user data
        response = snapshot.val()
        return null
    })
    .catch(error => {
        // Database fetch failed due to security rules, return an error
        console.error('error', error)
        isError = true
        response = error
        return null
    })
    .then(() => {
        // This is important to clean up, returns a promise
        if (userApp) {
            return userApp.delete()
        }
        else {
            return null
        }
    })
    .then(() => {
        // send the final response
        if (isError) {
            res.status(500)
        }
        res.send(response)
    })
    .catch(error => {
        console.error('final error', error)
    })
})

Again, note that userApp.delete() should be called in all circumstances to avoid leaking instances of App.  If you had the idea to instead give each new App a unique name based on the user, that's not a good idea, because you can still run out of memory as new users keep accessing this function.  Clean it up with each call to be safe.
Also note that userApp.delete() should be called before the response is sent, because sending a response terminates the function, and you don't want to have the cleanup interrupted for any reason.


text:
Q: Proper way to hook wp_get_attachment_url I am trying to hook wp_get_attachment_url() with my custom implementation. I am trying to get my post images and any other static data from the Amazon S3 and I was wondering if I can configure the URL with my Amazon bucket URL.
This is what I was trying to do
add_filter('wp_get_attachment_url', 'custom_get_attachment_url', 1, 1);

function clrs_get_attachment_url($post_id = 0) {
// change URL for Amazon bucket
}

but this is not working as expected as I am getting $post_id as 0. How to do it in a proper way?

A: Hook wp_get_attachment_link for this purpose. Here is an example of how to do it -
function attachment_link_filter( $content, $post_id, $size, $permalink ) {

    // Only do this if we're getting the file URL
    if (! $permalink) {
        // This returns an array of (url, width, height)
        $image = wp_get_attachment_image_src( $post_id, 'large' );
        $new_content = preg_replace('/href=\'(.*?)\'/', 'href=\'' . $image[0] . '\'', $content );
        return $new_content;
    } else {
        return $content;
    }
}

add_filter('wp_get_attachment_link', 'attachment_link_filter', 10, 4);


text:
Q: Simple Regex text replace then add suffix Im have a program that vbcan only handle basic regex no C# vb.net etc.
This is my situation.
I have a set of start Urls.
http://www.foo.com?code=234654
I need to remove the ?code= and replace with a / then add the letter t at the end.
Like this:
http://www.foo.com/234654t
I would appreciate any help this this.
Thanks
Sean

A: For the dialect that is used in java.util.regex you can use this regular expression, for example:
String regex = "\\?+[A-Za-z=]+([0-9]+)(?<=[0-9]+)(?=$)";
String replacement = "/$1t";

Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(line);
if (m.find()) {
  System.out.println(m.replaceAll(replacement));
}

Another example, by using replaceAll:
line.replaceAll("\\?+[A-Za-z=]+", "/").replaceAll("(?<=[0-9|/]+)(?=$)", "t");

For the string:
String line = "http://www.foo.com?code=234654";
You'll get:
http://www.foo.com/234654t


text:
Q: How to try reading as int, then if it fails read as string? I'm trying to repeatedly read integers, and for tokens that are not integers, to read and handle them as strings. I thought the following would work:
string s;
int x;

while(1) {
    if (cin >> x)                                     // try reading as int
        cout << "read int: " << x << endl;
    else {                                            // try reading as string
        cin.clear();

        if (cin >> s)
            cout << "read string: " << s << endl;
        else
            break;                                    // eof
    }
}

However, for input (with newline at end)
1 2 a

it gives output
read int: 1
read int: 2

It seems that after clearing the state of the stream is not exactly the same as before, and in fact cin >> s fails. Why is this, and how can I achieve my desired behaviour?
To clarify, I can't parse the string as an int because I have not "learned" that yet.

A: clear does not rewind the stream; it only clears the error flags, as the name suggests. To solve your problem, read the input as a string, then try to parse it as an int. The link explains the details of the string-int conversion better than I could.

A: Why not read it as a string, then try a conversion, so if the conversion fails you can treat it as a string.
In C++11 there is std::stoi.  Which will throw an exception if a conversion cannot be found.
Another way would be read it in as a string, and then parse using a stringstream.
If you cannot use an existing string parsing method, why not write your own?
// Returns false if not an int, otherwise true and outint will hold the correct value.
bool strtoint(const std::string str, int *outint) {
    int val = 0;
    for (int x = str.length() - 1; x >= 0; x--) {
        if (!(str[x] <= '9' && str[x] >= '0') || !(str[x] == '-')) {
            return false;
        } else if (str[x] == '-') {
            val *= -1;
        } else {
            val += (int)((str[x] - '0') * pow(10, (str.length() - 1) - x));
        }
    }

    *outint = val;
    return true;
}

Or something kinda like that, I'm not sure if the logic is completely correct, but I think it's on the right track.


text:
Q: How to wait App.js code to run before mounting components? So I have a problem, where I use a piece of code in App.js to sign the user in, if they have a JWT token stored (to keep them signed in if they leave the page, then return). I am using socket.io to communicate with the server.
The problem is, in a component of mine I make a socket.io call inside componentDidMount(), but that code runs before the App.js code, therefore the socket is not yet stored in my backend. The way the application is now, I am storing the socketIDs and userIDs of users to keep track of open sockets per user.
If the componentDidMount() code runs before storing the newly created socket connection (on opening a new tab, a new socket is created) I can't use the new socket in that call.
I logged the functions to see the order, and this is what I got, that's why I suspect the componentDidMount() code runs first.
userID empty null
usersOfCall null
socketAssign
[
  {
    userID: '5fb483cf93b92d651a281450',
    socketIDs: [ 'hdLMOfFhFXHGyOpDAAAB' ],
    socketPreserved: null
  },
  {
    userID: '5fb47647c93e23622c4e1c10',
    socketIDs: [ 'JAcC2XwLuoZTsgIiAAAC', '7vgKN-sqkqUNS7L_AAAD' ],
    socketPreserved: null
  }
]

From the socketAssign line below, that is where I store the socket for a user.
Above that is the result of the call I make from inside componentDidMount()
The userID empty null line is the result of a function that would get the userID of the user associated with the socket that emitted the signal. It becomes null, since the socket is not yet stored, so it can't find any matches.
App.js piece of code:
if(localStorage.jwtToken){
    const token = localStorage.jwtToken;
    const tokenDecoded = jwt_decode(token);
    const user = tokenDecoded.response;
    store.dispatch(userSocketAssign(user));
    const currentTime = Date.now() / 1000;
    if(tokenDecoded.exp < currentTime){
        console.log('expired');
        store.dispatch(userSocketDeassign());
        window.location.href = './login';
    }
}

function App() {
    return (
        <Provider store = {store}>
            <AppComponent />
        </Provider>
    );
}

The AppComponent just renders the routes for the application, with component properties that specify which component should be rendered when a specific route is taken.
class App extends Component
{
    componentDidMount(){

    }

    render(){
        return (
            <Router>
                <Navbar />
                <Switch className = "container-fluid">
                    <Route exact path = "/" component = {Dashboard} />
                    <Route exact path = "/login" component = {Login} />
                    ...
                </Switch>
                <CallReceived />
            </Router>
        );
    }
}

How could I make the mount process wait until the socket is stored on the backend?

A: I suggest you to read about the state cycle. Based on your situation, you can set a timer for the component to run. Inside the component, try add setInterval for the delay for the app to render first. Here is the documentation about the state cycle https://reactjs.org/docs/state-and-lifecycle.html.


text:
Q: Problem in de-broglie relation! In the starting of quantum mechanics we encounter Plank's relation $E=\hbar \omega$, and from special relativity we have $Ev_p=pc^2$ , where $v_p$ is the velocity of the particle (we are assuming momentum is a particle aspect). Putting the two together, we get
$$\hbar \omega v_p = pc^2 \, .$$
Now we assume that $\omega$ is a wave concept and use $\omega / k =v_w $ where $v_w$ is the wave velocity. For now we assume the wave velocity to be different from that of the particle for we don't know if the wave is the particle itself or an excitement in the probability field of the universe. That's a different topic. Here I just want to say that $v_p$ and $v_w$ might be different, or even the same. We don't know so why take risks?
Plugging the expression, we have $$p = \hbar v_p v_w k /c^2 \, .$$
Then, plugging it into the relativity relation $E^2 = p^2c^2 + m^2 c^4$ and finding out $d \omega /dk$, we get
$$d\omega / dp = v_p^2v_w/c^2 \, .$$
This is the group velocity which has to be equal to the particle velocity if it has to have some meaning! Therefore,
$$v_p = v_p^2v_w/c^2 $$
or
$$ v_p v_w = c^2 $$ or $$ v_w = c^2 / v_p$$
which automatically implies $v_w>c$ (assuming $v_p<c$ , which is the very core of special relativity).
What is going on here? The wave velocity has come out more than the speed of light!

A: What you have found is the difference between the phase velocity and the group velocity by using the de Broglie relation that is quantum mechanical and describing a wave nature.  The phase velocity can be higher than c because it only appears in the mathematical manipulations.

The phase velocity of electromagnetic radiation may – under certain circumstances (for example anomalous dispersion) – exceed the speed of light in a vacuum, but this does not indicate any superluminal information or energy transfer. It was theoretically described by physicists such as Arnold Sommerfeld and Léon Brillouin. See dispersion for a full discussion of wave velocities.

No information can be carried faster than c, the group velocity.
The de Broglie relation as quantum mechanical has to be treated within those rules, where every observable corresponds to an operator. See the answer by Motl here.  Particles can be described by wave packets,  and they will have a group and phase velocity, and the phase velocity can be higher than c because it is not observable.


text:
Q: Docker run syntax Can anyone clarify the syntax in this command:
$ docker run -d -P --name web -v /src/webapp:/webapp training/webapp python app.py

I can see that:
Host directory: /src/webapp
Container: /webapp

but what is training/webapp? Is that the image? If so, why is there a /?
And is everything after that (i.e. python app.py) the command that you want to run in the container?
=====
And to clarify with this command:
$ docker run -d -P --name web -v /webapp training/webapp python app.py

How does it work if you ONLY specify -v /webapp - is that equivalent to /webapp:/webapp?

A: You can find the documentation for docker run here
The basic structure looks like this:
$ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

*

*-d let's you run your docker container in detached mode, so you won't see the console output

*-P publish all exposed ports to the host interfaces

*--name the name of your container

*-v the volume you mount host/path:container/path, where in your case /src/webapp is on your local machine and /webapp is inside your container

*

*training/webapp is the username and image name for the docker image. I have linked the image's location on DockerHub for you

*python app.pyare the command (python) and the argument run when the container starts (app.py)

A: Yes, training/webapp is image name. Dockerhub accept name this way only.
training is username and webapp is image name.
if you  don't use dockerhub(this is image repository from docker pull image by default) and build image locally then you can give any name.
python app.py : command that will execute when docker up
--name web    : this will be name of container
-v /src/webapp:/webapp  : this will create volume webapp and mount on /src/webapp
--publish-all, -P : Publish all exposed ports to random ports

For more help see docker run Documentation.


text:
Q: MongoDB,using java to update three fields of document at the same time,sometimes only two fields is updated //get the collection
DBCollection coll = MongoDBClient.getInstance().getAlarmInfoCollection();

DBObject query = new BasicDBObject();
query.put(aa, "51d2b09f81b8a943f9e825aa");

DBObject update = new BasicDBObject();
DBObject history = new BasicDBObject();
history.put("ishistory", 1);
history.put("acknowledged", 1);
history.put("state", 1);
update.put("$set", history);
coll.updateMulti(query, update);

using the program before to update the document in mongodb,but sometimes it can sucess,sometimes it only update two fields(the field, "state", is not updated), and the propram did not report any error. Is there any mistake in my program?

A: I've written a unit test to show how the code behaves.  This unit test proves that:

*

*you should be able to update more than one field at once (i.e.
multiple fields can be updated with the $set keyword)

*updateMulti will update all matching documents

(Note, like all Java MongoDB tests this uses TestNG not JUnit, but it's pretty similar in this case)
@Test
public void shouldUpdateAllMatchingFieldsUsingMultiUpdate() throws UnknownHostException {
    MongoClient mongoClient = new MongoClient();
    DB db = mongoClient.getDB("myDatabase");
    DBCollection coll = db.getCollection("coll");
    coll.drop();

    //Put some test data in the database
    for (int i = 0; i < 5; i++) {
        DBObject value = new BasicDBObject();
        value.put("fieldToQuery", "a");
        value.put("ishistory", 2+i);
        value.put("acknowledged", 3+i);
        value.put("state", 14+i);
        value.put("someOtherArbitraryField", Math.random() * 1000);
        System.out.println(value);
        coll.insert(value);
    }

    DBObject query = new BasicDBObject("fieldToQuery", "a");

    DBObject history = new BasicDBObject().append("ishistory", 1)
                                          .append("acknowledged", 1)
                                          .append("state", 1);

    DBObject update = new BasicDBObject("$set", history);

    //This syntax for update means that all three fields will be set to the new given value
    Assert.assertEquals(update.toString(), "{ \"$set\" : { \"ishistory\" : 1 , \"acknowledged\" : 1 , \"state\" : 1}}");

    //Do the update, updating every document that matches the query
    coll.updateMulti(query, update);

    //find The new values
    DBCursor updatedDocuments = coll.find(query);
    for (DBObject updatedDocument : updatedDocuments) {
        Assert.assertEquals(updatedDocument.get("ishistory"), 1);
        Assert.assertEquals(updatedDocument.get("acknowledged"), 1);
        Assert.assertEquals(updatedDocument.get("state"), 1);
        System.out.println(updatedDocument);
    }
}

This test passes.  For an example run, the data in the database is:
{ "fieldToQuery" : "a" , "ishistory" : 2 , "acknowledged" : 3 , "state" : 14 , "someOtherArbitraryField" : 700.7831275035031}
{ "fieldToQuery" : "a" , "ishistory" : 3 , "acknowledged" : 4 , "state" : 15 , "someOtherArbitraryField" : 72.65538582882736}
{ "fieldToQuery" : "a" , "ishistory" : 4 , "acknowledged" : 5 , "state" : 16 , "someOtherArbitraryField" : 980.0065367659304}
{ "fieldToQuery" : "a" , "ishistory" : 5 , "acknowledged" : 6 , "state" : 17 , "someOtherArbitraryField" : 91.58266286854722}
{ "fieldToQuery" : "a" , "ishistory" : 6 , "acknowledged" : 7 , "state" : 18 , "someOtherArbitraryField" : 448.19176202797115}

At the end of the test, after updateMulti is called with the $set operator, the documents in the database are:
{ "fieldToQuery" : "a" , "ishistory" : 1 , "acknowledged" : 1 , "state" : 1 , "someOtherArbitraryField" : 700.7831275035031}
{ "fieldToQuery" : "a" , "ishistory" : 1 , "acknowledged" : 1 , "state" : 1 , "someOtherArbitraryField" : 72.65538582882736}
{ "fieldToQuery" : "a" , "ishistory" : 1 , "acknowledged" : 1 , "state" : 1 , "someOtherArbitraryField" : 980.0065367659304}
{ "fieldToQuery" : "a" , "ishistory" : 1 , "acknowledged" : 1 , "state" : 1 , "someOtherArbitraryField" : 91.58266286854722}
{ "fieldToQuery" : "a" , "ishistory" : 1 , "acknowledged" : 1 , "state" : 1 , "someOtherArbitraryField" : 448.19176202797115}

So the update has worked, setting the three fields to 1 for all matching documents, not touching any of the other data on the document.
It might be worth noting that my syntax for setting query, update and history is a little more readable and bit shorter, although it should be doing the same thing as the code in the original question:
DBObject query = new BasicDBObject("fieldToQuery", "a");

DBObject history = new BasicDBObject().append("ishistory", 1)
                                      .append("acknowledged", 1)
                                      .append("state", 1);

DBObject update = new BasicDBObject("$set", history);

Am I correct in assuming that you want all records that match your query to be updated with the given values?  Hence your use of updateMulti?


text:
Q: What can we do for new users who want to ask a question that's already been asked, but hasn't yet got an acceptable answer? I've mentioned this several times, but only in answers to other questions or comments.
What can we do to help new users who come to the site with a problem but find a question already exists, but it doesn't have any answers that solve the problem.
This SU "answer" (deleted, so only available to diamonds and 10K SU users) is a good example.
The way the site is set up at the moment the following things may happen.

*

*They get comments, some polite, others less so telling them not to post questions as answers.

*They get down-votes (which don't actually affect their reputation score, but it's not nice.

*They delete their "question-as-answer".

Now they have another problem. Do they just wait (having bookmarked the question perhaps) in the hope that it gets answered soon or do they post their own question?
If they do the latter then the following will happen:

*

*Comments about not asking duplicate questions will get posted.

*They will get downvotes.

*Their question will get closed and eventually deleted.

Not very welcoming at all.
Now all the above will get the problem some attention - either the original question is bumped or at least re-read by those voting to close, so someone new might see it and post an answer, but is this really the way we want to treat newcomers?
So repeating myself from my previous answer:

... do we need a "I'm having the same problem" button on a question and if it's clicked enough times within a certain period the question gets bumped? There would have to be limits on the number of times a user can click it and perhaps it should only be available to registered users to reduce people bumping their own questions

For reference this is the original SO answer I linked to - as you can see it's been edited to include the information from the comments and so is now a useful answer. Perhaps this is one way we can encourage people - explain that an answer needs to include new information.

A: I don't feel that merely bumping that question is going to necessarily help. If the question has already been answered, especially one with an accepted answer, then the larger percentage of people who are looking at it aren't doing it to answer questions. They're doing it to look at answers. So it is likely that the people who might be able to answer the new user's question may not actually be looking at that question. Combined with the fact that the new user can only properly bring up their plight in comments, there isn't going to be a lot of light shed in their name.
You can think of the original author maybe editing the original question to point out the new user's problem, but then this changes the original question. How is the new user going to accept the answer to her problem?
The problem isn't in the original question, I think the problem we have lies with the treatment of the new question. If a question isn't solved by the answers given in the original question, then I can't really agree that it would be a duplicate. The other question didn't attract the same answers, and if it already has an accepted answer then it's not very likely to get the new answers that the new user will need. Likewise, the new question shouldn't be attracting clone answers of the original because they won't help.
What would help is better identification of these facts. The question asker needs to clearly identify the original question, and identify that those given answers didn't work. It's the same as identifying what technologies cannot be used (such as by executive or business restriction). The new question should be then addressed on those terms.
If people are uncomfortable with having questions that are so similar be kept alive, then when all is said and done, the questions can be merged with the new system.
Of course... if the original one doesn't have an accepted answer and the original question asker is still looking for a better answer... it falls on that person's responsibility to notify people of the unsatisfactory results. If the question is abandoned, then I think there is better worth in someone else basically taking ownership of the question. But that's a separate kind of suggestion altogether.

A: I am not sure if I see the point of @Jeff's answer. The question is more like: How do we avoid that new users are going to post noise in unanswered questions? The real answer is: there is no way. @Jeff's answer suggests that they should have posted it as an answer. Yes, I wholeheartedly agree this, but how would you explain them that? There is no way. Even if you put a big red blinking banner above the Post Your Answer button which is visible to low-rep users only, there are users who are blind to this and will post it as an answer anyway.
The community can at most flag them and/or post a (subtle!) comment or to split the answer out into a new question. I personally however have a slight disagreement in flagging as spam. It's like beating the user with a ruler. There must be another flag option. A Noise flag for example which would push the answer to bottom with a "deleted" background color and messages the user about the what, why and how. Or a This is a Question flag which would split the answer out into a new question (which is actually piece of cake in the DB), if necessary with a link to the original question.
See also:

*

*How should I report answers which are pure noise?

*Function to convert an Answer to a new Question

A: This bugged me too, when I wanted to comment on a question someone asked. With 1 rep, I was out trying to help out because SO is a fun project and probably the coolest resource for programmers out there. The whole reputation, badge stuff really encourages me to work hard to help others, and in doing that, I learn what type of questions to ask, how to ask them, etc. in order to get a good response from people.
So when I tried to comment on someone's question to get more information from them, I couldn't. I had to either answer with a "Is this the problem? If so, you can do this. Is that the problem, if so you can do this other thing." answer, to sort of cover the flanks I couldn't verify through comments.
Personally I think up until the comment threshold, posting a comment should require approval from either the person who posted the question (or answer, if the comment is on an answer), or it should require the approval of someone with say 200+ reputation. If the comment threshold is there to stop people from posting "buy vi@gra, my friend" then perhaps cap the limit on # of comments to 1-2 a day, and disallow links, make it so that you can only post once an hour, etc. And obviously include the nastiest captcha you have for all comments below the threshold. There is one that appears occasionally for me, so I know one exists in the system already.

A: In my opinion, the user in question should attempt to find some new bit of information related to the problem and provide it as a partial answer.
For example in the question you cited:
How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?
A good new partial answer would be:

I have this problem too. I tried the following things:

*

*uninstalling VS2010 Express, and reinstalling it.

*formatting my hard drive and reinstalling Windows.

*bought a new Mac and tried to install it there.

*took a bus to Redmond, WA and asked one of the VS2010 team members in person.

  None of this worked!

Basically, I don't have a problem with answers that at least try to document the ways the tried to solve the problem.
Those kinds of answers help move us toward a solution by documenting what didn't work.


text:
Q: get value of tinyeditor using jquery not working i would like to get the value of tinyeditor textarea using jquery for this i have written:
 var description = new TINY.editor.edit('description', {
    id: 'description',
    width: 330,
    height: 175,
    cssclass: 'tinyeditor',
    controlclass: 'tinyeditor-control',
    rowclass: 'tinyeditor-header',
    dividerclass: 'tinyeditor-divider',
    controls: ['bold', 'italic', 'underline', 'strikethrough', '|',
        'orderedlist', 'unorderedlist', '|', 'undo', 'redo'],
    footer: true,
    fonts: ['Verdana', 'Arial', 'Georgia', 'Trebuchet MS'],
    footerclass: 'tinyeditor-footer',
    resize: {cssclass: 'resize'}
});

for getting value using jquery:
$('#p_description').html($('#description').val()); // does not work

$('#p_description').html(description.post()); // does not work

$('#p_description').html(TINY.editor.description.value); // does not work

and also some other way..
any help or suggestion would be a great help.. thanks in advance

A: well i found the solution.. so i would like to share it with everyone..
description.post();
var p_description = description.t.value;

and then:
 $('#p_description').html(p_description);


text:
Q: Fresh react native app is throwing an error with android emulator
I've made a new React Native project using npx react-native init AwesomeProject.  This is the error I'm getting and I can't find out why.  Any suggestions? Mind you this is a brand new project.  I execute the new command and then tried to start.

A: If you see the error "EONENT: no such file or directory" restart your computer and rebuild your application.  This resolved my issue.  Stupid, yes I know


text:
Q: Compile error using CocoaPods, RestKit with Dynamic Frameworks I am using CocoaPods and RestKit for a long time without any problems.
Since I am using Swift for some time now, I thought it was time to use CocoaPods with dynamic frameworks (available since 0.36.0)
However I run into a the following compile error: Use of undeclared type 'AFHTTPClient'
This is my PodFile (I am using tag 0.25.0 of RestKit since this release is ready for dynamic frameworks):
source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.1'
inhibit_all_warnings!
use_frameworks!

pod 'RestKit', '0.25.0'

link_with ['TestProject', 'TestProjectTests']

I have one class:
import UIKit

import AFNetworking

class AFNetworingService {
    var client: AFHTTPClient?
}

This compiles fine!
Now I add another class:
import UIKit

import RestKit

class RestKitService {

}

Now compile fails with error: Use of undeclared type 'AFHTTPClient' in the AFNetworingService class
When I remove the 'import RestKit' from the RestKitService class, it compiles fine again
Somebody any ideas?


text:
Q: Changing directories while having a file open Say I have a python script that opens a file to write:
The python modules also call C modules that change the directory with
chdir()

Will the python script still have the file open and be able to write?

A: Files are tracked by file handles, and once open for a particular file, stays open to that file until closed.


text:
Q: How to send files instead of just text into JMS queue? I just downloaded and installed WebSphere MQ 8.x (in my Windows 7). Now I want to learn how to send and receive files.
The WebSphere MQ installation comes with some code samples (C:\Program Files\IBM\WebSphere MQ\Tools\jms\sample\JmsProducer.java), but all them (in the /Tools directory) use message(s) as a String (to send and receive).
I would like to send and receive files to/from a JMS queue.
UPDATE:
I started using this :
BytesMessage bytes = session.createBytesMessage();
String codePage = CCSID.getCodepage(((MQDestination) destination)
           .getIntProperty(WMQConstants.WMQ_CCSID));
bytes.writeBytes("In the destination code page".getBytes(codePage));
producer.send(bytes);

but I got this error :
The method getIntProperty(String) is undefined for the type MQDestination

A: Could you show us the code where you inatanciate "destination" ? the casting to "MQDestination" seems to indicate it is not an instance of JMS "Destination" class
It seems you are mixing JMS and MQ proprietary classes/paradigm


text:
Q: React Router Content Not Changing I am a complete React newbie and am creating a simple site to display Tableau visualizations. I am using React Router.
I have a route for each component and a functional component that is adding the necessary shared JavaScript for Tableau to display. In each component I am using a $.getJSON to retrieve the correct visualization for that component.
The URL is changing correctly, but the content in the view is not. It just stays the same. My understanding of React is probably way off and any help is much appreciated.
App.jsx
import React from 'react';
import SiteHeader from './SiteHeader';
import Main from './Main';

class App extends React.Component {

  render() {
    return (

        <SiteHeader />

    )
  }
}

export default App

Main.jsx (router)
import React from 'react'
import { Switch, BrowserRouter, Router, Route } from 'react-router-dom'
import Home from './views/Home'
import ServiceDashboard from './views/ServiceDashboard';
import Feedback from './views/Feedback'

const Main = () => (

        <Route exact path={`${process.env.PUBLIC_URL}/`} component={Home} />
        <Route path={`${process.env.PUBLIC_URL}/viz/service-dashboard`} component={ServiceDashboard} />
        <Route path={`${process.env.PUBLIC_URL}/viz/feedback`} component={Feedback} />

)

export default Main

Tableau.jsx
const loadViz = () => {
  let tabViz,
    testWorkbook,
    testWorksheet,
    placeholderDiv = document.getElementById('root');

  let options = {
    width: '100%',
    height: '850px',
    hideToolbar: false,
    onFirstInteractive: function () {
      testWorkbook = tabViz.getWorkbook();
      testWorksheet = testWorkbook.getActiveSheet();
      worksheetList = testWorksheet.getWorksheets();
    }
  };

  let parseResponse = function (json) {
    if (tabViz) {
      tabViz.dispose();
    }
    tabViz = new window.tableau.Viz(placeholderDiv, json.uri, options);
  };
}

export default loadViz

ServiceDashboard.jsx
import React from 'react';
import $ from 'jquery';
import '../shared/tableau';

class serviceDashboard extends React.Component {

  componentDidMount() {
    $.getJSON("/tableauServer/myVisualization", parseResponse);
  }

  render() {
    return(

    )
  }
}

export default serviceDashboard

I am able to return the visualization if I refresh the page but when going from one page to the next, the visualization does not update with the route. Like going from
<Route path={`${process.env.PUBLIC_URL}/viz/service-dashboard`} component={ServiceDashboard} />

to
<Route path={`${process.env.PUBLIC_URL}/viz/feedback`} component={Feedback} />

A: Try to wrap your routes on a router/switch component:
import { BrowserRouter as Router } from 'react-router-dom';

class App extends React.Component {

  render() {
    return (
      <Router>

          <SiteHeader />

      </Router>
    )
  }
}

import { Route, Switch, withRouter } from 'react-router-dom';

const Main = (history) => (
  // history comes from withRouter
  <Switch location={history.location}>
        <Route exact path={`${process.env.PUBLIC_URL}/`} component={Home} />
        <Route path={`${process.env.PUBLIC_URL}/viz/service-dashboard`} component={ServiceDashboard} />
        <Route path={`${process.env.PUBLIC_URL}/viz/feedback`} component={Feedback} />
  </Switch>
)

export default withRouter(Main);


text:
Q: Destroy tab based component from child frame nativescript-vue
If I exit the Player/1 page with clearHistory, I want to destroy the  Tabs Page component and all rendered pages, and then navigate to the Login Page. But it only destroys Player/1 and Players Page.
Each navigation branch has its own Frame
Login -> Welcome -> Tabs => Main frame
Players -> Player 1 => Players frame
Teams -> Team 1 => Teams frame
Nativescript 8.4.0


text:
Q: Android app work slowly I am using Navigation drawer for my app.
For each fragments I have a big image(I can't use a specify image for each size, because I have more than 100 3d Image for this reason I decide put a large and prefect image in drawable folder and for each size use of those).
I have a trouble, when I run app on the tablets it's work perfectly but when run it on the phones it's slow, I guess it's for images.
Anybody can help me, how can I improve my app?
Note:I know It's not good way, one of the best way is I download image from internet or something like that way. Unfortunately I should make that app as offline.

A: It's slow because your Bitmap is huge. Instead of putting the images directly on ImageView, consider using BitmapFactory.Options to resize image before loading it. Other option would be using a library like Picasso for loading image.


text:
Q: Error in listing data on a javascript/html file I have this javascript that is taking data in from a fusion table and listing on a html document, the error I am getting is located in this line:
" + data[row][4] + "\

I honestly have zero idea as to what is causing the error so I have come to you guys. The data is a web address and I need it to be clickable. If you have any insight in a way to fix this or get around it, it would be greatly appreciated.
:)
I have posted the rest of the section of code it is attached to below.
MapsLib.prototype.displayList = function(json) {
    var self = this;
var data = json['rows'];
var template = '';

var results = $('#results_list');
results.hide().empty(); //hide the existing list and empty it out first

if (data == null) {
  //clear results list
  results.append("
No results found
");
}
else {
  for (var row in data) {
    template = "\

\

\
          " + data[row][0] + "<spacer> --- </spacer><strong2>" + data[row][1] + "</strong2>\

\
          <suburb>" + data[row][2] + "</suburb>\

\
          " + data[row][3] + "\

\
          " + data[row][4] + "\

\
          " + data[row][5] + "\

\
          " + data[row][6] + "\

\
          " + data[row][7] + "\

\

";
    results.append(template);
  }
}
results.fadeIn();
},

A: "href" is to navigate the url...
this is not a correct path= "data[row][4]">" + data[row][4] + "
if you want to call any function use onclick....


text:
Q: Google App Engine Null Pointer Exception when trying to insert It seems as if the method from the endpoint class itself is not being called as none of the print statements I put in to debug gave any output
RELEVANT CODE
accessing the TransLogEndpoint class
        Translogendpoint.Builder builder = new Translogendpoint.Builder(
                 AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
                 null);
        builder = CloudEndpointUtils.updateBuilder(builder);
        Translogendpoint endpoint = builder.build();

I ended up hardcoding the object I wanted to insert
TransLog t=new TransLog();
t.setId(33);
t.setOperation("ins");
t.setTable("hisone");
t.setTransTime((long) 299221212);
t.setAcc("meh");

And tried to insert as such
try {
    endpoint.insertTransLog(t).execute();
} catch (IOException e) {
    System.out.println("could not insert Log");
    // TODO Auto-generated catch block
    e.printStackTrace();
 }

This is how the endpoint method for inserting the TransLog looks I did not change any of its logic
 @ApiMethod(name = "insertTransLog")
 public TransLog insertTransLog(TransLog translog) {
    System.out.println("I am here");
    Key k=KeyFactory.createKey("TransLog",translog.getId());
    translog.setKey(k);
        EntityManager mgr = getEntityManager();
        try {
             if(containsTransLog(translog)) {
             throw new EntityExistsException("Object already exists");
        }
        mgr.persist(translog);
        } finally {
              mgr.close();
        }
        return translog;

}
this is from the App Engine [Web Application Console]
 Jun 21, 2014 2:03:15 PM com.google.api.server.spi.SystemService invokeServiceMethod
 INFO: cause={0}
    java.lang.NullPointerException

    at org.datanucleus.api.jpa.JPAEntityManager.find(JPAEntityManager.java:318)
at org.datanucleus.api.jpa.JPAEntityManager.find(JPAEntityManager.java:256)
at com.example.agriexpensett.TransLogEndpoint.containsTransLog(TransLogEndpoint.java:154)
at com.example.agriexpensett.TransLogEndpoint.insertTransLog(TransLogEndpoint.java:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:359)
at com.google.api.server.spi.SystemServiceServlet.execute(SystemServiceServlet.java:127)
at com.google.api.server.spi.SystemServiceServlet.doPost(SystemServiceServlet.java:85)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:491)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

and
Jun 21, 2014 2:03:15 PM com.google.api.server.spi.SystemService invokeServiceMethod
SEVERE: null
java.lang.NullPointerException

at org.datanucleus.api.jpa.JPAEntityManager.find(JPAEntityManager.java:318)
at org.datanucleus.api.jpa.JPAEntityManager.find(JPAEntityManager.java:256)
at com.example.agriexpensett.TransLogEndpoint.containsTransLog(TransLogEndpoint.java:154)
at com.example.agriexpensett.TransLogEndpoint.insertTransLog(TransLogEndpoint.java:101)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.api.server.spi.SystemService.invokeServiceMethod(SystemService.java:359)
at com.google.api.server.spi.SystemServiceServlet.execute(SystemServiceServlet.java:127)
at com.google.api.server.spi.SystemServiceServlet.doPost(SystemServiceServlet.java:85)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:491)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

A: Your stacktrace says :
...
at com.example.agriexpensett.TransLogEndpoint.containsTransLog(TransLogEndpoint.java:154)

Maybe your issue is because the KeyFactory.createKey return a null value, so when it come to call containsTransLog, the method fire a NPE in containsTransLog.
I was able to fix this kind of issue by changing the default generated "contains..." method.
So, you can try to change your containsTransLog method to take care of the NPE, by adding a check on your Key value :
@ApiMethod(name = "containsTransLog")
public boolean containsTransLog(TransLog translog) {
 if(translog.getKey() ==null)
        return false;
 EntityManager mgr = getEntityManager();

 //...
}

You can also check if the value of "Key k" is null.
Hope this helps !


text:
Q: Como simplificar essa Consulta? Tenha a seguinte quey abaixo e gostaria de saber se há uma forma de simplificar a clausula WHERE
SELECT
 idMembro,
 dataCadastro,
 nome,
 apelido,
 dataNascimento,
 telefone,
 celular,
 bairro,
 endereco,
 email,
 sexo,
 estadoCivil,
 dataBatismo,
 bloqueado,
 batizadoFora,
 usuario,
 senha
FROM membros
WHERE
  idMembro NOT IN (SELECT idMembro FROM pastores) &&
  idMembro NOT IN (SELECT idResponsavel FROM redes) &&
  idMembro NOT IN (SELECT idResponsavel FROM regioes) &&
  idMembro NOT IN (SELECT idResponsavel FROM areas) &&
  idMembro NOT IN (SELECT idResponsavel FROM setores) &&
  idMembro NOT IN (SELECT idLider FROM celulas)
ORDER BY nome

A: Esta consulta já está bem simples, uma outra forma de fazê-la é:
SELECT *
FROM membros
WHERE
   idMembro NOT IN (
        SELECT idMembro FROM pastores
        union SELECT idResponsavel  FROM redes
        union SELECT idResponsavel  FROM regioes
        union SELECT idResponsavel  FROM areas
        union SELECT idResponsavel  FROM setores
        union SELECT idResponsavel  FROM celulas
   )
ORDER BY nome

A: Outra forma de estruturar a consulta (e penso que a mais performante):
SELECT      ME.*
FROM        membros     ME
LEFT JOIN   pastores    PA ON PA.idMembro       = ME.idMembro
LEFT JOIN   redes       RD ON RD.idResponsavel  = ME.idMembro
LEFT JOIN   regioes     RE ON RE.idResponsavel  = ME.idMembro
LEFT JOIN   areas       AR ON AR.idResponsavel  = ME.idMembro
LEFT JOIN   setores     SE ON SE.idResponsavel  = ME.idMembro
LEFT JOIN   celulas     CE ON CE.idResponsavel  = ME.idMembro
WHERE       PA.idMembro         IS NULL
        AND RD.idResponsavel    IS NULL
        AND RE.idResponsavel    IS NULL
        AND AR.idResponsavel    IS NULL
        AND SE.idResponsavel    IS NULL
        AND CE.idResponsavel    IS NULL
ORDER BY    ME.nome

Se quiser ir por tabelas temporárias:
SELECT  DISTINCT X.Id
INTO    #tmpIds
FROM    (
            SELECT  idMembro        AS Id
            FROM    pastores
            UNION
            SELECT  idResponsavel   AS Id
            FROM    redes
            UNION
            SELECT  idResponsavel   AS Id
            FROM    regioes
            UNION
            SELECT  idResponsavel   AS Id
            FROM    areas
            UNION
            SELECT  idResponsavel   AS Id
            FROM    setores
            UNION
            SELECT  idResponsavel   AS Id
            FROM    celulas
        ) X

SELECT      ME.*
FROM        membros ME
LEFT JOIN   #tmpIds TMP ON TMP.Id = ME.idMembro
WHERE       TMP.Id IS NULL
ORDER BY    ME.nome

De certa forma simplifica a query principal.


text:
Q: finding parent in the callback I've two login forms with different ids(#user-login and #user-login-form).
The form elements within them have the same id's. For attaching onlick callback how to get the val() value from whichever called parent?( ie from ("#user-login #edit-name or ("#user-login-form #edit-name)
jQuery('#user-login #edit-submit, #user-login-form #edit-submit').click(

 function(){
 var login = jQuery("#user-login #edit-name").val(); //need #edit-name value from whichever form it is called

Unfortunately I tried Google but nothing useful came up with this query.
Here is the html code:
<form action="/my/node?destination=node" method="post" id="user-login-form" accept-charset="UTF-8">

      Username *
      <input type="text" id="edit-name" name="name" value="" size="15" maxlength="60" class="form-text required">

please full name ending with

      Password *
      <input type="password" id="edit-pass" name="pass" size="15" maxlength="128" class="form-text required">

    <input type="hidden" name="form_build_id" value="form-8-F0WIjwGaSckitaooI93RGSdaM_WVUE65XaMkn6hy4">
    <input type="hidden" name="form_id" value="user_login_block">

      <input type="submit" id="edit-submit" name="op" value="Log in" class="form-submit">

</form>

A: Use $(this).closest('form').find('#edit-name').val(). this refers to the clicked element. .closest('form') will find the closest form ancestor and .find(...) will find every descendant that matches the selector.
Important: IDs should be unique throughout the page. So instead of using IDs for the elements, use classes.

I recommend to read the jQuery tutorial to learn more about event handling basics and DOMtraversal.


text:
Q: Same Tensorflow model giving different results on Android and Python I am trying to run a Tensorflow model on my Android application, but the same trained model gives different results (wrong inference) compared to when it is run on Python on desktop.
The model is a simple sequential CNN to recognize characters, much like this number plate recognition network, minus the windowing, as my model has the characters already cropped into place.
I have:

*

*Model saved in protobuf (.pb) file - modeled and trained in Keras on Python/Linux + GPU

*The inference was tested on a different computer on pure Tensorflow, to make sure Keras was not the culprit. Here, the results were as expected.

*Tensorflow 1.3.0 is being used on Python and Android. Installed from PIP on Python and jcenter on Android.

*The results on Android do not resemble the expected outcome.

*The input is a 129*45 RGB image, so a 129*45*3 array, and the output is a 4*36 array (representing 4 characters from 0-9 and a-z).

I used this code to save the Keras model as a .pb file.
Python code, this works as expected:
test_image = [ndimage.imread("test_image.png", mode="RGB").astype(float)/255]

imTensor = np.asarray(test_image)

def load_graph(model_file):
  graph = tf.Graph()
  graph_def = tf.GraphDef()

  with open(model_file, "rb") as f:
    graph_def.ParseFromString(f.read())
  with graph.as_default():
    tf.import_graph_def(graph_def)

  return graph

graph=load_graph("model.pb")
with tf.Session(graph=graph) as sess:

    input_operation = graph.get_operation_by_name("import/conv2d_1_input")
    output_operation = graph.get_operation_by_name("import/output_node0")

    results = sess.run(output_operation.outputs[0],
                  {input_operation.outputs[0]: imTensor})

Android code, based on this example; this gives seemingly random results:
Bitmap bitmap;
try {
    InputStream stream = getAssets().open("test_image.png");
    bitmap = BitmapFactory.decodeStream(stream);
} catch (IOException e) {
    e.printStackTrace();
}

inferenceInterface = new TensorFlowInferenceInterface(context.getAssets(), "model.pb");
int[] intValues = new int[129*45];
float[] floatValues = new float[129*45*3];
String outputName = "output_node0";
String[] outputNodes = new String[]{outputName};
float[] outputs = new float[4*36];

bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
for (int i = 0; i < intValues.length; ++i) {
    final int val = intValues[i];
    floatValues[i * 3 + 0] = ((val >> 16) & 0xFF) / 255;
    floatValues[i * 3 + 1] = ((val >> 8) & 0xFF) / 255;
    floatValues[i * 3 + 2] = (val & 0xFF) / 255;
}

inferenceInterface.feed("conv2d_1_input", floatValues, 1, 45, 129, 3);
inferenceInterface.run(outputNodes, false);
inferenceInterface.fetch(outputName, outputs);

Any help is greatly appreciated!

A: One Problem is in the lines:
    floatValues[i * 3 + 0] = ((val >> 16) & 0xFF) / 255;
    floatValues[i * 3 + 1] = ((val >> 8) & 0xFF) / 255;
    floatValues[i * 3 + 2] = (val & 0xFF) / 255;

where the RGB values are divided by an integer, thus yielding an integer result (namely 0 every time).
Moreover, the division, even if executed with a 255.0 yielding a float between 0 and 1.0 may pose a problem, as the values aren't distributed in the projection space (0..1) like they were in Natura. To explain this: a value of 255 in the sensor domain (i.e. the R value for example) means that the natural value of the measured signal fell somewhere in the "255" bucket which is a whole range of energies/intensities/etc. Mapping this value to 1.0 will most likely cut half of its range, as subsequent calculations could saturate at a maximum multiplicator of 1.0 which really is only the midpoint of a +- 1/256 bucket. So maybe the transformation would be more correctly a mapping to the midpoints of a 256-bucket division of the 0..1 range:
((val & 0xff) / 256.0) + (0.5/256.0)

but this is just a guess from my side.


text:
Q: JavaScript file doesn't load after page transition with barba.js I have a website with a link. When I click the link I want a smooth page transition to the next page using jQuery. I got the the HTML elements inside the barba DOM to fade out. But when the next page tries to load, all BUT the JavaScript loads.
This is my code:
(index.html)

            Hey There!
            This is my portfolio!
            Click me to continue

I can see the the console logs in the console but JavaScript doesn't load.
This is the page I'm trying to load:
(home.html)

        <canvas></canvas>

I get no errors whatsoever.
Also I have seen a question on here with the same problem as mine, but it was very unclear. (and does not have any answers so far)
Thanks!

A: In Barba, scripts don't evaluated when loading a new container. It can be done easily using Events.
Barba.Dispatcher.on('newPageReady', function (currentStatus, oldStatus, container) {
    $(container).find('script').each(function (i, script) {
        var $script = $(script);
        $.ajax({
            url: $script.attr('src'),
            cache: true,
            dataType: 'script',
            success: function () {
                $script.trigger('load');
            }
        });
    });
});

A: Add this line:
document.getElementsByTagName("head")[0].innerHTML += "<meta http-equiv=\"refresh\" content=\"1\">";

inside below function
fadeInNewcontent: function(nc) {

}