text:
Q: Adding items from a listbox into the clipboard in a excel paste friendly format The Aim: using VBA (excel) to populate the clipboard with a table (from a listbox) in an excel friendly format so that I can then paste (ctrl+V) into excel and the values are split into the correct columns and rows as they were in the original listbox.
The Problem: I can't seem to get the formatting right; when I paste the contents of my clipboard into excel each row is contained in one cell (the first column) separated with "," (which is what I have tried to use as a sort of "delimiter" - not sure if this is correct or not?)
I am using the API workaround method to populate the clipboard and I don't want to wall you to death with code but here is the most important bit (I feel anyway - ask me if you need to see more code).
Private Sub btnCopyTable_Click()

Dim I As Long
Dim J As Long
Dim tmp As String
Dim arrItems() As String
Dim clipboard As DataObject

ReDim arrItems(0 To lbIPActions.ColumnCount - 1)
For J = 0 To lbIPActions.ListCount - 1
    For I = 0 To lbIPActions.ColumnCount - 1
        On Error Resume Next ' Handles null values
        arrItems(I) = lbIPActions.Column(I, J)
        On Error GoTo 0
    Next I
    tmp = tmp & Join(arrItems, ",") & vbCrLf
Next J

MsgBox tmp

ClipBoard_SetData tmp

End sub

The Current Output:
1,1,Low,Controls,,LS,Do this,02-Oct-2015,Note 1,Brev
2,1,Low,Controls,,LS,Do that,02-Oct-2015,Note 2,Brev

The Current State: I have had a little look around and found a way to do it in code to a specific sheet, but my end user requires the freedom to copy it into numerous sheets in a very ad hoc fashion. I know there is always the option to right click -> import text wizard, but again ctrl+V is the preferred method if possible.
As always, any help/advice is appreciated, thanks in advance.

A: Separate your string with Tab in each line and it'll work. Like so:
Dim I As Long
Dim J As Long
Dim textItem As String
Dim copyText As String
Dim clipboard As DataObject

For J = 0 To lbIPActions.ListCount - 1
    For I = 0 To lbIPActions.ColumnCount - 1
        textItem = vbNullString
        On Error Resume Next ' Handles null values
        textItem = lbIPActions.Column(I, J)
        On Error GoTo 0
        If I > 0 Then copyText = copyText & vbTab
        copyText = copyText & textItem
    Next I
    If J < lbIPActions.ListCount - 1 Then copyText = copyText & vbNewLine
Next J

ClipBoard_SetData clipboardText


text:
Q: Connecting android client with oracle server I need to connect over the internet with the Android client to Oracle PL/SQL database. (With static ip or with the host name).
But already using java client over the year with oracle. And I don't want to go for another database for implementing (Because I already written most complex procedures.,)
And that java client server connection happening via LAN connections only (But the system has the static ip and not used for this. Because LAN communication works perfectly).
Please tell me the process what I have to take.
Note: I am using Oracle 10g (10.2.0.5.0) and Latest Version of java (1.8).
If Possible: Please Provide a link for ojdbc drivers(Don't know which driver version used for Android).
Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between these two blocks of texts The first function doesn't work. It shows the message "Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'toUpperCase')"
These are the codes:
//this is the one with error
function myReplace(str, before, after){
    var index = str.indexOf(before);
    if (str[index] === str[index].toUpperCase()) {
        after = after.charAt(0).toUpperCase()+ after.slice(1);
    }else{
        after = after.charAt(0).toLowerCase() + after.slice(1);

    }
    str = str.replace(before, after);
    return str;
    }

myReplace("A quick brown fox jump over the lazy dog", "jumped", "leaped");

//This apparently works fine.
function myReplace(str, before, after){
    var index = str.indexOf(before);
    if (str[index] === str[index].toUpperCase()) {
        after = after.charAt(0).toUpperCase()+ after.slice(1);
    }else{
        after = after.charAt(0).toLowerCase() + after.slice(1);

    }
    str = str.replace(before, after);
    return str;
    }
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

A: The code is semantically incorret. In the first example you never use the word "jumped" instead you use "jump". Therefore the result of the indexOf function cant be used. See the following snippet to further understand what's wrong.
If the indexOf function can not find the substring, it will return a -1.
Since you can not access -1 in an array it will return the seen error. You should always handle these edge cases in your code to avoid unwanted behaviour. I added a check of the index before trying to access something.

//this is the one with error
function myReplace(str, before, after){
    var index = str.indexOf(before);
    console.log(index);
    if(index < 0){
      return "error index not found"
    }
    if (str[index] === str[index].toUpperCase()) {
        after = after.charAt(0).toUpperCase()+ after.slice(1);
    }else{
        after = after.charAt(0).toLowerCase() + after.slice(1);

    }
    str = str.replace(before, after);
    return str;
    }

myReplace("A quick brown fox jump over the lazy dog", "jumped", "leaped");

A: In the first case, the index is -1 since the string "jumped" is not part of the str --> so str[index] is basically "undefined" and you can not call toUpperCase() with undefined.
in the seconds case, the index is 18 and str[index] is "j" so you can call toUpperCase() since it's a char

A: You have a typo in your input!
Both functions are the same. But in your first implementation you have "jump" in your phrase and you are searching for "jumped" which will end up as error.
this implementation:
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

will always work


text:
Q: strange garbage data when opening a previously truncated file In my program, I've redirected stdout to print to a file 'console.txt'.  A function writes to that file like this:
void printToConsole(const std::string& text, const TCODColor& fc, const TCODColor& bc)
    {
        // write the string
        cout << text << "@";

        // write the two color values
        cout << static_cast<int>(fc.r) << " "
             << static_cast<int>(fc.g) << " "
             << static_cast<int>(fc.b) << " "
             << static_cast<int>(bc.r) << " "
             << static_cast<int>(bc.g) << " "
             << static_cast<int>(bc.b) << " " << endl;
    }

I have a function that reads from that file that looks like this:
    void Console::readLogFile()
    {
        ifstream log("console.txt", ifstream::in);
        if(!log.is_open())
        {
            cerr << "ERROR: console.txt not found!" << endl;
            return;
        }

        // read new input into Console
        string str;
        while(getline(log, str))
        {
            cerr << "str: " << str << endl;
            /* do stuff with str here */
        }
        cerr << endl;

        log.close();
        clearLogFile();
    }

    void Console::clearLogFile()
    {
        ofstream("console.txt", ios_base::trunc);
    }

The first time through the readLogFile, everything works fine.  Afterwards, however, it starts to have problems.  It will read in the first line of console.txt as a blank string.  I stepped through the program with console.txt open in gvim, and monitored how it changed.  The first time through, when it worked correctly, console.txt looks something like this:
  1 moved UP.@191 191 191 0 0 0
  2 Player moved.@191 191 191 0 0 0
~
~

which is as it should be.  The program then goes to clearLogFile, and afterwards console.txt is empty.  However, the second time through, when I open the ifstream, console.txt looks like this:
  1 ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@
    ^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@moved UP.@191 191 191 0 0 0
  2 Player moved.@191 191 191 0 0 0
~
~

This time, when getline reads the first line into str, str is blank.  Strangely, the cerr << "str: " << str << endl; line still prints str as "moved UP.@191 191 191 0 0 0", even though inspecting str in gdb reveals that it's empty.
Anyone know what's going on here?

A: The routine that is writing is not resetting it's file position before rewriting to the file. As a result it starts off at an offset into the target file.
I believe a cout.seekp(0) after performing the write will reset the write pointer, thus restarting the write at the start of the file.
You're probably going to have a lot of problems with consistency of the content of the logfile with the way you're using it, though.
Comment added here, as I can't get formatting in the comment box...
By resetting the file pointer after every write, there will only ever be one line in the output file. You need to make sure that you read it before you write to it, otherwise the new data will be over-written by the old data, or worse may be partially overwritten.
e.g. write 1:
Player moved 1 2 3 4

e.g. write 2:
Player fell over

Would leave:
Player fell over
3 4

In the written file if the reader didn't get there before the writer made it's second write.
You may be better off using an explicit file, rather than using cout, or you could remember the read position between reads and seek to that before performing your next read, but that leaves you with an ever growing logfile.
HTH


text:
Q: Update multiple tables I have 2 tables namely Profile and Info.
My table looked like this:
PROFILE
| p_Id | FirstName | LastName |

| 1    | Jack      | Cole     |
| 2    | Cynthia   | Cole     |
| 3    | Robert    | Cole     |

INFO
| I_Id | childsID | fathersID | mothersID | Country |

| 1    | 1        | 3         | 2         | USA     |

I'm retrieving values from those tables by displaying them in textboxes, my select query is:
SELECT p.p_Id, p.FirstName, p.LastName, i.*,
(SELECT pp.FirstName+' '+pp.LastName FROM Profile pp WHERE pp.p_Id=i.childsID) AS child,
(SELECT pp.FirstName+' '+pp.LastName FROM Profile pp WHERE pp.p_Id=i.fathersID) AS father,
(SELECT pp.FirstName+' '+pp.LastName FROM Profile pp WHERE pp.p_Id=i.mothersID) AS mother
    FROM Info i
        INNER JOIN Profile p
            ON p.p_Id=i.childsID

no problem with select, I'm able to display values on textboxes, but the problem is, I can't update them, I have tried so far this:
using (SqlCommand cmd = con.CreateCommand())
    {
        con.Open();
        cmd.CommandText = @"UPDATE Profile SET FirstName=@fname, LastName=@lname WHERE p_Id = @pid;
                            UPDATE Info SET childsID=@child, fathersID=@father, mothersID=@mother, Country=@country WHERE I_Id = @iid;";

        cmd.Parameters.Add(new SqlParameter("@fname", txtfname.Text));
        cmd.Parameters.Add(new SqlParameter("@lname", txtlname.Text));
        cmd.Parameters.Add(new SqlParameter("@child", txtchild.Text));
        cmd.Parameters.Add(new SqlParameter("@father", txtfather.Text));
        cmd.Parameters.Add(new SqlParameter("@mother", txtmother.Text));
        cmd.Parameters.Add(new SqlParameter("@country", txtcountry.Text));
        cmd.Parameters.Add(new SqlParameter("@pid", txtpid.Text));
        cmd.Parameters.Add(new SqlParameter("@iid", txtiid.Text));
        cmd.ExecuteNonQuery();
        Response.Write("alert('DATA UPDATED')");
    }

I'm using c# and Asp.net
Thanks in advance :) God Bless

A: Check the MSDN: SqlParameter Constructor (String, Object)

When you specify an Object in the value parameter, the SqlDbType is inferred from the Microsoft .NET Framework type of the Object.

So when you passing int type parameters you need to convert text value to integer:
cmd.Parameters.Add(new SqlParameter("@pid", int.Parse(txtpid.Text)));

or better:
int tempIntValue;
cmd.Parameters.Add(new SqlParameter("@pid", int.TryParse(txtpid.Text, out tempIntValue)?
  (object)intTempValue: (object)DbNull.Value ));


text:
Q: Can I run the 'min' task twice in Grunt? Is there a way to run a task twice with different configurations in Grunt? Let's say I have two sets of source files in my project and I want to minify them into two separate, minified output files. Like this:
project
    srcA
        fileA1.js
        fileA2.js
    srcB
        fileB1.js
        fileB2.js

As the expected result, I would like to see fileA.min.js and fileB.min.js. How can I achieve that, as min only seems to support one set of src and dest attributes?
min: {
  dist: {
    src: [  'srcA/*.js'],
    dest: 'fileA.min.js'
  }
}

A: Sure
in config object you should configure two min tasks
min: {
  a_file: {
    src : [/* a src */],
    dest : "path_to_a_file"
  },
  b_file: {
    src : [/* b src */],
    dest : "path_to_b_file"
  }
}

After that you can create or rewrite default task or even add it to your custom task:
grunt.registerTask('minify', ['min:a_file', 'min:b_file'])
//or
grunt.registerTask('build', ['concat', 'min:a_file', 'min:b_file'])

And now you can run tasks:
grunt minify
grunt build


text:
Q: Unable To Open Two Cameras Using OpenCV - Multithreading Camera Reads I am trying to use OpenCV to stream video from 2 cameras continuously via separate threads. The following code is displaying  Segmentation fault (core dumped)
What is the reason for this and How do I fix this issue?
main.cpp
#include <iostream>
#include <pthread.h>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp>

using namespace std;

struct thread_data {
  string path;
  int  thread_id;
};

void *capture(void *threadarg)
{
  struct thread_data *data;
  data = (struct thread_data *) threadarg;

  cv::VideoCapture cap(data->path);

  if( !cap.isOpened())
  {
    std::cout<<"Not good, open camera failed"<<std::endl;
  }
  std::cout<< "Opened IP camera successfully!"<<std::endl;
  cv::Mat frame;
  string ext = ".jpg";
  string result;
  while (true) {
    cap >> frame;
    cv::imshow("Frame",frame);
    cv::waitKey(1);
  }
  pthread_exit(NULL);
}

int main(void) {
  pthread_t threads[2];
  struct thread_data td[2];
  int rc=0;
  for( int i = 0; i < 2; i++ ) {
     cout <<"main() : creating thread, " << i << endl;
     td[i].thread_id = i;
     td[0].path = "rtsp://admin:opencv123@192.168.1.23:554/Streaming/Channels/101/";
     td[1].path = "rtsp://admin:opencv123@192.168.1.24:554/Streaming/Channels/101/";
     rc = pthread_create(&threads[i], NULL, capture, (void *)&td[i]);

     if (rc) {
        cout << "Error:unable to create thread," << rc << endl;
        exit(-1);
     }
  }
  pthread_exit(NULL);
  return 0;
}

log:
main() : creating thread, 0    main() : creating thread, 1
Segmentation fault (core dumped)

When I tried running it multiple times, I am able to open only one camera and that too isn't streaming continuously. It starts and stops in a few seconds.
Sometimes I get an error which says
OpenCV Error: Insufficient memory (Failed to allocate 140703464366800 bytes) in OutOfMemoryError

I have gone through various Q&As' on StackOverflow but none helped.

A: The problem here is that the code is facing race conditions. I was able to replicate the issue on my system and identified the following issues:

*

*OpenCV window titles are not unique.

*Spawned threads are not joined.

*Race condition while opening the video stream.

Lets look into these issues in detail.
1.
OpenCV windows are uniquely identified by their title. In the current code, the title is a hardcoded string "Frame". So basically, both threads are creating/updating/destroying the same window in unknown order. That is a race condition which can be fixed by adding a string field to the struct thread_data which will serve as unique window identifier.
2.
In the main thread, the child threads are created asynchronously so the for loop will exit immediately after creating the threads and the program will exit pre-maturely without waiting for the spawned thread to complete execution. This problem can be solved by adding function calls to wait for the threads before the program exits. This process is called joining and can be achieved by calling pthread_join for each spawned thread.
3.
This issue was a bit trickier to track down. Due to some reason the backend library for video stream capture used by OpenCV is not behaving in  a thread-safe manner. Seemingly, the video capture opening process is prone to race-condition and requires a synchronization lock. The lock can be easily implemented by calling the functions pthread_mutex_lock and pthread_mutex_unlock just before and after opening the VideoCapture object.
Here is the modified code demonstrating the solution for all of the above mentioned issues
#include <iostream>
#include <pthread.h>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/videoio.hpp>

using namespace std;

//Mutex for thread synchronization
static pthread_mutex_t foo_mutex = PTHREAD_MUTEX_INITIALIZER;

struct thread_data
{
  string path;
  int  thread_id;
  string window_title; //Unique window title for each thread
};

void *capture(void *threadarg)
{
  struct thread_data *data;
  data = (struct thread_data *) threadarg;

  cv::VideoCapture cap;

  //Safely open video stream
  pthread_mutex_lock(&foo_mutex);
  cap.open(data->path);
  pthread_mutex_unlock(&foo_mutex);

  if( !cap.isOpened())
  {
    std::cout<<"Not good, open camera failed"<<std::endl;
  }
  std::cout<< "Opened IP camera successfully!"<<std::endl;
  cv::Mat frame;
  string ext = ".jpg";
  string result;

  //Create window with unique title
  cv::namedWindow(data->window_title);

  while (true)
  {
    cap >> frame;
    cv::imshow(data->window_title,frame);
    cv::waitKey(10);
  }

  //Release VideoCapture object
  cap.release();
  //Destroy previously created window
  cv::destroyWindow(data->window_title);

  //Exit thread
  pthread_exit(NULL);
}

int main(void)
{
    const int thread_count = 2;

    pthread_t threads[thread_count];
    struct thread_data td[thread_count];

    //Initialize thread data beforehand
    td[0].path = "rtsp://admin:opencv123@192.168.1.23:554/Streaming/Channels/101/";
    td[0].window_title = "First Window";
    td[1].path = "rtsp://admin:opencv123@192.168.1.24:554/Streaming/Channels/101/";
    td[1].window_title = "Second Window";

    int rc=0;
    for( int i = 0; i < thread_count; i++ )
    {
        cout <<"main() : creating thread, " << i << endl;
        td[i].thread_id = i;

        rc = pthread_create(&(threads[i]), NULL, capture, (void *)& (td[i]) );

        if (rc)
        {
            cout << "Error:unable to create thread," << rc << endl;
            exit(-1);
        }
    }

    //Wait for the previously spawned threads to complete execution
    for( int i = 0; i < thread_count; i++ )
        pthread_join(threads[i], NULL);

    pthread_exit(NULL);

    return 0;
}

A:

void writeFrametoDisk(const cv::Mat *frame, std::string path, int frameNum, std::string windowName)
{
  cv::imwrite(path.append(std::to_string(frameNum)).append(".png"), *frame);
  return;
}

void openCameraStream(int deviceId, std::string dirName)
{
  cv::VideoCapture cap;
  cap.open(deviceId);
  if(!cap.isOpened()){std::cerr << "Unable to open the camera " << std::endl;}

  std::cout << cap.get(cv::CAP_PROP_FRAME_WIDTH) << " " << cap.get(cv::CAP_PROP_FRAME_HEIGHT) << std::endl;

  std::string windowName = deviceId == 0 ? "Cam 0" : "Cam 1";
  std::string outputDir = dirName;

  bool frameStFg = false;
  while(!frameStFg)
  {
    cv::Mat frame;
    cap.read(frame);
    if(frame.empty()){std::cerr << "frame buffer empty " << std::endl;}
    else
    {
      frameStFg = true;
    }
  }

  cv::TickMeter timer;
  timer.start();
  int frameCount = 0;

  while(1)
  {
    cv::Mat frame;
    cap.read(frame);

    if(frame.empty()){std::cerr << "frame buffer empty " << std::endl;}
    frameCount++;

    std::thread th(writeFrametoDisk, &frame, outputDir, frameCount, windowName);
    th.join();
    //// a simple wayto exit the loop
    if(frameCount > 500)
    {
      break;
    }
  }
  timer.stop();
  std::cout << "Device id " << deviceId << " Capture ran for " << timer.getTimeSec() << " seconds" << std::endl;
  std::cout << "Device id " << deviceId << " Number of frames to be capture should be " << timer.getTimeSec() * 30 << std::endl;
  std::cout << "Device id " << deviceId << " Number of frames captured " << frameCount << std::endl;
  cap.release();
}

int main(int argc, char * argv[])
{
  std::string outputDir1 = "";
  std::string outputDir2 = "";

  std::thread camera1Thread(openCameraStream, 0, outputDir1);
  std::thread camera2Thread(openCameraStream, 1, outputDir2);
  camera1Thread.join();
  camera2Thread.join();
}

As the comments mention, streaming without any imshow() of the image streams works well with out any problems. My setup includes, running two threads with two USB camera's and also these two threads launch a new thread each to save the image read from the cameras. I didn't observe any frame drops or errors and also was able to capture and write at approximately 30 fps.
A little debugging of the reason, it is recommended to use any imshow() in the main thread only i.e. main() function. Hope this helps anyone.


text:
Q: Ubuntu freeze after upgrade installation interrupt I was upgrading my Ubuntu distro and shut down the laptop in the middle of the installation process. Upon restart, I only get a black screen with these messages:
Starting Hardware RNG entropy gatherer daemon: (Hardware RNG device inode not found)
/etc/rc2.d/S21rng-tools: Cannot find a hardware RNG device to use.
saned disabled: edit /etc/default/saned
* Restoring resolver state... [OK]

And then it waits there forever.
Is there any way to restore Ubuntu or does it need a fresh install?
I would hate to have to reinstall and reconfigure my development environments all over again.

A: You have hosed the installation and you need to do a fresh OS install.
If you've been doing proper backups of your whole system, restore from your latest backup and then redo the upgrade. You should do such a backup before any OS update.
If you don't have such a backup, then wipe the system and do a full OS reinstall.  Even if you can kludge the system into running again, there are too many ways the system could be broken to trust it further.
There are no circumstances under which I would do anything with such a system other than restore from backups and upgrade, or wipe and reinstall from scratch.

A: I had the same issue as you. My Ubuntu VM would start up but not get to the login prompt. When I booted with verbose on, that "Restoring resolver state" was the last line on my console.
This is how I fixed it:

*

*Boot into the Ubuntu live CD (change the screen resolution if you have to using the displays program).

*Open a terminal. Determine which disk you are using as your "boot" disk:
$ sudo fdisk -l

Mine was /dev/sda1.

*In the same terminal, create a folder in the tmp directory:
$ mkdir -p /tmp/sda1

Mount the boot disk to that folder:
$ sudo mount /dev/sda1 /tmp/sda1

*Mount some of your livecd directories so we can successfully run all our commands:
for i in /dev /dev/pts /proc /sys /run; do sudo mount -B $i /tmp/sda1$i; done

*Chroot into /tmp/sda1:
$ sudo chroot /tmp/sda1 /bin/bash

It's basically as if you booted and logged into your computer. You can now do grub-install to fix the boot issue within that shell:
$ sudo grub-install /dev/sda

*For good measure, also do the following before exiting:
$ sudo apt-get install -f

*Unmount and exit the chroot:
$ sudo umount -a
$ exit

If that doesn't work, try changing your Linux kernel on bootup to a previous one. You can do this with the chroot method too.


text:
Q: what does "s-f" means in spacemacs? Some of the emacs keys are rebound in spacemacs. I saw this in emacs tutorial
** C-s has been rebound, but you can use s-f instead [More] **
what does s-f here means? It can't be character s followed by character f.

A: See EmacsKeyNotation:

S-
  means the Shift key (e.g. S-TAB means Shift Tab)


text:
Q: How to pass this.props.children using hooks in react this is my first time to create a react application.
I wanted to pass buttons from index.js to table component that uses hooks.
Declaration:

  const testButton = () => {
    return (
      <React.Fragment>
        <button>Test1</button>
        <button>Test2</button>
        <button>Test3</button>
        <button>Test4</button>
        <button>Test5</button>
      </React.Fragment>
    );
  };

pass it to Table component
 return (
    <React.Fragment>
      <TestTable
        {...{
          testButton}} />
    </React.Fragment>

Then, table component will use it to render the table, with the buttons included.
export default function TestTable({
testButton,
  ...props
})

return (
{testButton});

Am I doing it correctly?
How can I export this from index.js, import in Table component.js, and render in Table component?
Thank you.

A: The React library promotes component composition. For a good recent writeup of this pattern read Robin Wieruchs article
You can refactor your TestTable component like the following:
Here I have added a codesandbox example: https://codesandbox.io/embed/smoosh-cache-ytfky
import React from 'react'

export default function TestTable(props) {
  return (
    <React.Fragment>
      {props.children}
    </React.Fragment>
  )
}

Your TestButton component can remain mostly the same. You need to add the export keyword to the beginning of the component. Actually, the components are just plain old functions.
To learn more about the different styles of exporting functions see Alex Rauschmayer great description. there are arguments for using either default exports or named exports, I personally prefer named exports which is more declarative and just easier for me to see what is happening.
  export default function TestButton() {
    return (
      <React.Fragment>
        <button>Test1</button>
        <button>Test2</button>
        <button>Test3</button>
        <button>Test4</button>
        <button>Test5</button>
      </React.Fragment>
    );
  };

You can now compose your two components in another function as follows:
export function DisplayTable(props) {
  return (
    <TestTable>
       <TestButton />
    </TestTable>
)
}

NOTE:

*

*This assumes all your functions are in one file, but it is better to
put them in their own file and import / export them.

*The this keyword is only applicable if you are writing a class component, if you write a function component then all you get is props, but you have to explicitly declare it in your function arguments.

*I have converted all your ES6 arrow functions into regular javascript functions, I find it is easier to conceptualise, and learn these are just regular functions, but in React land they are your components.

As for React Hooks, they are a new introduction to React since 16.8 which really solve a specific use case of being able to handle state and side effects without using classes. see the original docs for a great description

A: I think what you want is:
const TestTable = ({ children }) => {
  return (

        Something...
        {children}

  )
}

And then:
const App = () => {
  return (
    <TestTable>
      <button>Test 1</button>
      <button>Test 2</button>
      <button>Test 3</button>
    </TestTable>
  )
}

Hope it helps!

A: In your index.js (where you return the buttons):
const TestButtons = () => (
  <>
    <button>Test1</button>
    <button>Test2</button>
    <button>Test3</button>
    <button>Test4</button>
    <button>Test5</button>
  </>
)

export default TestButtons

Then, in your table.js:
import TestButtons from 'path/to/index.js'

const TestTable = () => (
  <TestButtons />
)

You should use the import statement to import a component from another file.


text:
Q: XAML WebView binding to HTML source not working I have a XAML page layout defined that includes a WebView populated from an HTML string:
<WebView HorizontalOptions="Fill" VerticalOptions="FillAndExpand">
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding Flag.Description}" />

    </WebView.Source>
</WebView>

When I hard code the string into the XAML it displays correctly, but it will not bind to the Flag.Description string. The XAML includes a couple of labels that bind correctly but I can't find any reason why the WebView source isn't binding correctly.

A: I wasn't able to get the binding to work in XAML but there is a code-based solution to the problem. I'm using FreshMvvm so in the page model (not the code-behind for the XAML page) I created a new property that references the HTML string:
public HtmlWebViewSource WebViewSource
{
    get {
        return new HtmlWebViewSource { Html = Flag.Description };
    }
}

And the WebView element in the XAML page becomes:
<WebView
    HorizontalOptions="Fill"
    VerticalOptions="FillAndExpand"
    Source="{Binding WebViewSource}" />

A: The accepted answer worked for me but I will add that it only works when you specify a height and width.
There are a few combinations that worked:
1.
define HeightRequest and WidthRequest
<WebView Source="{Binding HtmlSource}" HeightRequest="300" WidthRequest="250" />

2.
define HorizontalOptions and VerticalOptions
<WebView x:Name="WebViewTermsOfService" Source="{Binding HtmlSource}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />

However, when I specifed CenterAndExpand as a value, the HTML did not render

A: Seems like Binding Html property for HtmlWebViewSource just won't work out of the box. I think a IValueConverter will do the job. Please have a look how it is done in this answer. I think that should be enough

A: Would Flag or Flag.Description ever return null to the WebView? I was having the same problem and it turns out that the default value for my source was null before I initialized it with proper content. The WebView would essentially crashed. When I changed the null to String.Empty, it would work.

A: public HtmlWebViewSource Description { get { var webView = "html content";return
 new HtmlWebViewSource { Html = webView };} }
<WebView
  HorizontalOptions="Fill"
  VerticalOptions="FillAndExpand"
  Source="{Binding Description}" />


text:
Q: inputtype decimal and signed value issue android I have used inputtype
android:inputType="numberDecimal|numberSigned"

I have to make check if the input type is equal to numberdecimal OR  numbersigned then not to execute some set of code.
I found mapping of
//numberDecimal to InputType.TYPE_NUMBER_FLAG_DECIMAL (int 8192)
//numberSigned to     InputType.TYPE_NUMBER_FLAG_SIGNED (int 4096)

Code logic is like this
if (inputType != InputType.TYPE_NUMBER_FLAG_DECIMAL
                        ||  inputType!=InputType.TYPE_NUMBER_FLAG_SIGNED)
{
                  // Some logic here
}

but still this code is getting executed even if inputtype is decimal or signed  numbers.
 So i checked the value of inputType in logs which is coming as 12290.
Now how this value is coming to 12290 if I take OR of (4096|8192) it is coming as 12288 .
 0001000000000000 (4096)
 0010000000000000 (8192)
 0011000000000000 (12288)

Should i do hard coding of 12290 to satisfy this condition ?

A: 12290 = "numberDecimal|numberSigned"
= InputType.TYPE_NUMBER_FLAG_DECIMAL // 8192
+ InputType.TYPE_NUMBER_FLAG_SIGNED // 4096
+ InputType.TYPE_CLASS_NUMBER // 2


text:
Q: ember-cli: how to place CSS in pods I'm using ember-cli's pod structure to group JS and templates by resource, which is a huge improvement. The last vestige of resource-related logic is the CSS (SCSS) files, which are already broken down along pod-like lines, but still stuck over in app/styles.
My idea is to move the CSS files into each pod, under the name style.css. My question is how to instruct SASS (via @import) directives, and/or Broccoli, to look for the SCSS files within the pods (could be several levels deep) and compile them into appname.css.

A: Erik Bryn actually just announced his ember-cli addon at EmberConf that does exactly that. Unfortunately it doesn't support CSS preprocessors yet, so until his addon is further along you'll have to make do with the non-pod way of organizing styles...

A: We create a nice addon ember-cli-sass-pods that uses ember-cli-sass (will install automatically) and lets you to generate and put your style scss files into your pods directories.
for example:
app/login
app/login/route.js
app/login/template.hbs
app/login/style.scss

or a component:
app/components/login-box
app/components/login-box/component.js
app/components/login-box/template.hbs
app/components/login-box/style.scss

Just run
ember g style [path] -p
Enjoy!


text:
Q: How secure SSH dynamic port forwarding? I'm using SSH's dynamic port forwarding to host a socks proxy on localhost. I'm trying to find out if the connection between my computer and the remote server/destination is secured.  Will my ISP or anyone be able to read data sent through the socks connection?

A: The quick answer is No. Data tunneled through your SOCKS proxy will have the same cryptographic strength as much as your SSH session can provide (e.g. RSA-1024, RSA-2048).
Having that said, for the ISP to read your data, in short they'll have to convince you accept a host-key at the beginning of authentication among other things that is not from your remote server, but actually from the ISP. This is why SSH client shows a big fat warning as below to warn you of a possible MITM attack.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
3f:1b:f4:bd:c5:aa:c1:1f:bf:4e:2e:cf:53:fa:d8:59.
Please contact your system administrator.
Add correct host key in /home/peter/.ssh/known_hosts to get rid of this message.
Offending key in /home/peter/.ssh/known_hosts:3
RSA host key for 192.168.0.100 has changed and you have requested strict checking.
Host key verification failed.$

A: If the other side can read the data without decrypting it, then so can any middleman.


text:
Q: jquery or javascript method to add validations to input tags before submitting the page I have the below snippet of input tags which are not server controls so unable to use required field validators. So i want to use validators using jquery or java script.Can anyone help me with this.

             Name

               <input data-bind="value: data.Name" id="inpName" />

             End

               <input data-bind="value: data.end"  />

tried using this but didnt work.

A: After trying several option got this working .might help someone.
if ($("#inpName").val() == "" ) {
            alert("Please enter EndBy");
            e.preventDefault();

A: Here is an example for what you are looking
You have to put the things to be validated in a form tag not in a div. Replace the

 with a
<form id="win">

A: You could use HTML5's required attribute, like so:
<input data-bind="value: data.Name" required>
But since it' HTML5 it's not supported by all browsers, you can see the list here. Good luck.
EDIT: Yes, I missed to state that your inputs should be inside a <form> and the validation will be performed on its submit.


text:
Q: How to set same theme color on my entire app? | Flutter I want a same theme color on my entire app
i want output like this

here is my code, i create this statelesswidget in my login file and passing Login (StatefulWidget) where i design my login page.
class MyApp extends StatelessWidget {
  // const MyApp({ Key? key }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(
      primarySwatch: Colors.blue
    ),
    home: Login(),
    );
  }
}

and here is my main file code
void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,

    home: MyApp(),
  ));
}

Anyone please let me know where i am doing wrong.
here is my output

A: Update your main function like :
void main() {
  runApp(new MyApp());
}

You don't have to use MaterialApp several times.
Here a quick example of working code :
import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}
class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Generated App',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
    @override
    Widget build(BuildContext context) {
      return new Scaffold(
        appBar: new AppBar(
          title: new Text('App Name'),
          ),
      );
    }
}

A: the best way to set the theme to make it sperate file of theme and call in main file  theme: ThemeData(), like that you can also set theme of your icon and also you can set theme of your text.
 import 'package:flutter/material.dart';
ThemeData appthemedata(BuildContext context)
{
  return ThemeData(
    primaryColor:appcolor,
    // scaffoldBackgroundColor: Colors.white,
    appBarTheme: AppBarTheme(
        centerTitle: true,
        elevation: 0,
        textTheme: TextTheme(headline1: AppBarTextStyle )
    ),
    textTheme: TextTheme(

      headline1: TitleTextStyle,
      bodyText1:Body1TextStyle,
    ),
    iconTheme: IconThemeData(
      color:Colors.white,
      size: 17,
    ),
  );
}

A: For the entire app, you can set textTheme property in the Material app widget.
MaterialApp(
 theme: ThemeData(
 textTheme: TextTheme(
  bodyText1: TextStyle(),
  bodyText2: TextStyle(),
).apply(
  bodyColor: Colors.orange,
  displayColor: Colors.blue,
),
),
)


text:
Q: Sharing Printers Internal Network My company currently has an internal linux server ( Centos 5.7 ) that runs an internal website ( PHP/Apache ) for internal work.  One thing that has been a bit of a problem is creating print jobs.  We have a wide array of printers anywhere from HP LaserJets to STAR label printers.  What is the best way to manage these shares? I have read somewhere about creating a Printer Server?
Notes

-Not all printers have the ability to be networked
-I found a program in linux ( wkhtmltopdf ) to convert HTML/CSS into a PDF and then use LPR to send these print jobs to printers.
Currently
we currently use two methods.

*

*We use software called Connectship ( On Windows Server 2008 ) to control packages we ship.  It prints label stickers for UPS but we also found it has the ability to send print jobs to any printer that is shared on that server.  Their XML formatting is awful and creating routine print jobs is tough because it is not in HTML/CSS but in some strange format they created.  Also Managing a bunch of printers on this server seems clunky and unreliable at times

*We convert HTML/CSS into PDF and use LPR to print. I tested this out a few weeks ago but only for an HP LaserJet ( Worked Great btw ).  Can Linux print to any printer just like windows? I am not familiar with how Linux handles drivers so I was not sure if there would be any drawbacks to handle printing solely on my linux Server.  I manually added the printers through the GUI but I was not sure if it makes more sense to create a server dedicated to sharing printers ( If that is what people do? )...

A: You don't have to have a dedicated printer server, but you could set up one on the server that is hosting the internal website.1) Add all network printers in CentOS 5.7 cups by ip as shareable2)non-network printers needs to be added as shareable in client computers(assume you have win xp on this ones or linux-it works with a lot of os's)3) add in the CentOS 5.7 the printers throw the client address *for example I have a printer connected throw usb on a xp that has the internal ip of 192.168.0.247 the printer name on this xp is kc2 so the printer address on my server is : smb://192.168.0.247/kc2*I also have some linux clients example ip 192.168.0.99 that has the printer called kc6 set up in cups so the address I add in the server is http://192.168.0.99:631/printers/kc6 (the printer address in on that computer)That 's it. You add each computer with it's driver, normally you shoudan't have issues with any printer driver but exceptions exist. I invite you to read some info about cups and how to set up your printers to handle errors and other things


text:
Q: How can you say you realize something from someone's look? What is a word or phrase that means you understand something from someone's look, e.g. you realize from their look that you should stop talking?

A: I think the word 'apparent' handles this well, unless you mean specifically "apparent from one's body language and mannerisms". In which case I can't think of a word.

A: I like evident (especially since it involves seeing):

easy to see or understand; readily apparent. (TFD)

It is from Latin ēvidēns, to see from.

A: "Perceive" is a transitive you could use.


text:
Q: Magnitude and Amplitude in SAR are different? Are these two terms, amplitude and magnitude of radar signal, the same? If they are different what are each one?
I have been reading some papers and some authors seem to use them interchangeably, while others stick with one along with the whole text.


text:
Q: How to Remove Salt from DB? okay I am trying to make a log in form to my website in C# it has md5 + salt.. the problem is salt. md5 I can make work but salt just won't work. I made a php that gets the user name, user group id's etc. I have removed tons of instances of salt in the db and it either destroyed log in, or just did nothing. I am wondering if there is an easy way to remove salt?

A: What do you think is the purpose of the salt? If you could easily remove it, what would have been the reason to add it? You should really take a few minutes to read a tutorial about password hashing.
MD5 is not an appropriate choice to hash passwords, because it is ways too fast. One can calculate 8 Giga MD5 values per second with common hardware nowadays, that makes brute-forcing too easy. Instead use a slow key derivation function like BCrypt or PBKDF2.
To answer your question, you need the stored salt to verify the user entered password. If the user enters the password for login, you calculate a hash with the same salt you used to calculate the stored password in the database, then you can compare the hashes.


text:
Q: Changing attributes in Zope templates I'm writing a template for an object that contains files. I'm following the theme building blocks instructions.
foo

That makes that the liks downloads the file, as this:
foo

But I want that link points to the view page of the file, showing its title, description and also, allowing to download it. So I want to get the next output:
foo

How can I generate that attribute?

A: Use a string: expression adding the /view part:
foo

Note that you probably want to use the .absolute_url() (for objects) or the .getURL() (for catalog results) methods instead to generate full absolute URLs for your items:
foo


text:
Q: Network request failed in react-native and expo I have a flask server running on docker container. And it runs on port 5000 in container. I've mapped this docker container to my localhost:5000 port. I can display it on my browser so it works.
Now I want to send POST Request to that server endpoint /auth using fetch() in react native.
Here what I've tried so far:
 fetch("https://160.75.195.68:5000/auth",
          {
            method: 'POST',
            body: JSON.stringify({
                phone: phone,
                password: password
            }),
            headers: {
              "Content-Type": "application/json"
            }
          }
          ).then((response) => {
            console.log("RETURNED RESPONSE")
            console.log(response.data);
            deviceStorage.saveKey("id_token", response.data.access_token);
            deviceStorage.loadJWT(response.data.jwt);
            // this.props.newJWT(response.data.jwt);
          }).catch((error) => {
            if (error.response) {
              // There is an error response from the server
              // You can anticipate error.response.data here
              console.log("THERE IS AN ERROR RESPONSE FROM THE SERVER")
              const error = err.response.data;
              dispatch(addError(error.message));
            } else if (error.request) {
                // The request was made but no response was received
                // Error details are stored in error.reqeust
                console.log("THE REQUEST WAS MADE BUT NO RESPONSE WAS RECEIVED");
                console.log(error.request);
            } else {
                // Some other errors
                console.log("SOME OTHER ERRORS");
                console.log('Error', error.message);
            }
          })

But I get Network request failed. Please help!!


text:
Q: How do I prevent a short flickering at dragstart in Vuejs I am trying to make a DIV draggable.
It all works quite well except for a shot flickering at startdrag.
Here is a JSFiddle of the issue
Below is the code so far:
<template>

DRAG

BLA

BLA

BLA

</template>

The desired outcome is a draggable element without the flickering at the start.

A: You solution has different issues in Firefox and Chrome.
In Firefox: you will meet the flicker issue when dragstart due to e.pageX|Y and e.clientX|Y is always zero. Look into firefox Bugzilla #505521 for more details.
The workaround is listen the dragover event on document instead of drag in dragable element.

new Vue({
  el: "#app",
  data: {
    cordY: 200,
    cordX: 200,
    divY: 0,
    divX: 0,
    delay: 20
  },
  mounted () {
    document.addEventListener('dragover', this.dragover, false) // remember to remove the event listener before some-when like Vue.beforeDestroy.
  },
  methods: {
    dragStart: function (e) {
      // https://learnvue.co/2020/01/how-to-add-drag-and-drop-to-your-vuejs-project/
      // HIDE GHOST/DRAG IMAGE BY REPLACING IT WITH A CUSTOM OR NONEXISTING IMAGE
      var img = new Image()
      img.src = 'data:image/jpeg;base64,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'
      e.dataTransfer.setDragImage(img, 10, 10)
      this.divX = e.pageX - e.target.getClientRects()[0].left
      this.divY = e.pageY - e.target.getClientRects()[0].top
      this.cordY = e.pageY - this.divY
      this.cordX = e.pageX - this.divX
    },
    dragover: function (e) {
      this.cordY = e.pageY - this.divY
      this.cordX = e.pageX - this.divX

    },
    dragEnd: function (e) {

    }
  }
})
#mydiv {
  position: absolute;
  width:150px;
  z-index: 9;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  text-align: center;
  resize: both;
  overflow:auto
}

#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}

DRAG

BLA

BLA

BLA

In Chrome: Uses one setTimeout to control the Frame Rate will improve the rendering.
You will find if data property=this.delay is 10 or less, the draggable element will flicker more often. If 20 or more, the flicker happens rarely.
And the flicker is caused by DraggingEvent.pageX/Y return (0, 0) sometimes for last frame before drag ends. I found someone asked similar questions in the Internet, but there is no good answer.

new Vue({
  el: "#app",
  data: {
    cordY: 200,
    cordX: 200,
    divY: 0,
    divX: 0,
    timer: null,
    delay: 20,
    draging: false
  },
  methods: {
    dragStart: function (e) {
      // https://learnvue.co/2020/01/how-to-add-drag-and-drop-to-your-vuejs-project/
      // HIDE GHOST/DRAG IMAGE BY REPLACING IT WITH A CUSTOM OR NONEXISTING IMAGE
      var img = new Image()
      img.src = 'data:image/jpeg;base64,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'
      e.dataTransfer.setDragImage(img, 10, 10)
      this.divX = e.pageX - e.target.getClientRects()[0].left
      this.divY = e.pageY - e.target.getClientRects()[0].top
      this.cordY = e.pageY - this.divY
      this.cordX = e.pageX - this.divX
      this.draging = true
    },
    dragging: function (e) {
        if (this.timer) return;
      this.timer = setTimeout(() => {
        this.timer = null
        if (!this.draging) return
        this.cordY = e.pageY - this.divY
        this.cordX = e.pageX - this.divX
      }, this.delay)
    },
    dragEnd: function (e) {
        this.draging = false
      this.cordY = e.pageY - this.divY
      this.cordX = e.pageX - this.divX
    }
  }
})
#mydiv {
  position: absolute;
  width:150px;
  z-index: 9;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  text-align: center;
  resize: both;
  overflow:auto
}

#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}

DRAG

BLA

BLA

BLA

Below is one gif it shows how the DND works in the Chrome:

As I tried so far, uses dragover solution seems work fine in both
Chrome and Firefox.


text:
Q: Can I Theme, or Change the Title or Appearance, of Mitmweb? I have a setup with two mitmproxy interfaces - one for incoming traffic, and one for outgoing. This is to wrap an applicatiomn server so I can debug what happened post-mortem, for example.
I just had an outage and almost made an incorrect conclusion, because the two interfaces look the same, and the requests coming in and going out are similar - my app server is communicating with the same third-party in most flows. The two are accessed from two different ports, and I can't remember which way round those teo are off the top of my head.
I'd therefore like to change the mitmweb interface to help me differentiate. Apply a theme or colour scheme, or add a clear header or title in the page that helps me see quickly which is incoming and which outgoing. Therefore, if an unexpected outage arises again in the future, it will help me with gathering evidence, when there's a lot of noise going on that I can easily get confused.
I don't see anything in the config options that will let me change the visual appearance of mitmweb. Does anyone know any config items I can change that might help me achieve something like this please?
Thanks
(For info: I am currently using the official container image, on the slightly old 6.0.2 version)

A: There are no theming options for mitmweb at the moment. What you could do is add custom CSS to https://github.com/mitmproxy/mitmproxy/blob/main/mitmproxy/tools/web/templates/index.html. Make sure that you select the base template for the right version. :)


text:
Q: meta-search/ransack for mongoid I was just wondering if anyone has come across anything offering similar search functionality for mongoid as meta-search/ransack? During my searches I came across this mongoid group thread which mentioned sunspot_mongoid. I only had a quick look at it but my impression is that it doesn't quite offer the same view level helpers as meta-search which is really  what I'm looking for

A: There are no project actually to do the same than meta_search on Mongoid gem. But there are a open issue about support Mongoid on meta_search maybe you can follow it.
About sunspot_mongoid it's a gem to wrap your Mongoid to a solr search engine. It's really not related to job do by meta_search
There are no feature request about support Mongoid on ransack.


text:
Q: Run parts of a ipython notebook in a loop / with different input parameter I have written a ipython notebook, which analyses a dataset. Now I want to use this code to loop over different datasets.
The code is split into about 50 cells (including comments, markdown explanations,...). Is there a way to run parts of a notebook in a loop or running a whole notebook with different input parameters?
I don't want to merge all cells into one function or download the code as a python script, as I really like to run (and experimenting with) parts of the analysis by executing only certain cells.
Basically its refactoring parts of a script into a function and calling the function in a loop, just that the "parts of the script" are notebook cells.

A: papermill.execute_notebook was designed (by Netflix) to let us run notebooks as a function (which aids in code reuse, experiments reproducibility and memory efficiency - it runs notebooks in batch mode unlike standard python REPL):
import papermill as pm

pm.execute_notebook(
   'path/to/input.ipynb',
   'path/to/output.ipynb',
   parameters=dict(alpha=0.6, ratio=0.1)
)

More info: docs | example.

A: A cheap, but fast trick is to use "run all cells" in a kind of while loop:
Ipython/Jupyter - can we program a "run all cell above"?
change_parameters
your code
put this in your last cell:
display(Javascript('IPython.notebook.execute_all_cells()'))

A: What I usually do in these scenarios is wrap the important cells as functions (you don't have to merge any of them) and have a certain master cell that iterates over a list of parameters and calls these functions. E.g. this is what a "master cell" looks like in one of my notebooks:
import itertools
# parameters
P_peak_all = [100, 200]
idle_ratio_all = [0., 0.3, 0.6]
# iterate through these parameters and call the notebook's logic
for P_peak, idle_ratio in itertools.product(P_peak_all, idle_ratio_all):
    print(P_peak, idle_ratio, P_peak*idle_ratio)
    print('========================')
    m_synth, m_synth_ns = build_synth_measurement(P_peak, idle_ratio)
    compare_measurements(m_synth, m_synth_ns, "Peak pauser", "No scheduler", file_note="-%d-%d" % (P_peak, int(idle_ratio*100)))

You can still have some data dragging throughout the notebook (i.e. calling each function at the bottom of the cell with your data) to be able to test stuff live for individual cells. For example some cell might state:
def square(x):
    y = x**2
    return y
square(x) # where x is your data running from the prior cells

Which lets you experiment live and still call the generic functionality from the master cell.
I know it's some additional work to refactor your notebook using functions, but I found it actually increases my notebook's readability which is useful when you come back to it after a longer period and it's easier to convert it to a "proper" script or module if necessary.

A: You can use this:
    from IPython.display import Javascript
    Javascript("Jupyter.notebook.execute_cell_range(5,51)") # 51 is not

Note: Do not use the indices shown beside the cells because Jupyter.notebook.execute_cell_range count every single cell including heading and markdown cells. Try to count manually the range of your cells including the markdown cells to give Jupyter.notebook.execute_cell_range the correct range.

A: In case useful... in AWS JupyterLab, i was able to call one notebook from another using the cellmagic %run inside a loop, thus calling it multiple times from a control notebook.
I had a list of dates and needed to call the whole notebook for each date in the list, so was like this:
for x in date_list:
    %run "other_notebook_name.ipynb"

No need to pass parameters as all code is effectively in the same notebook this way.
May help others as I ended up here looking for an answer this week.
Cheers


text:
Q: Creating a loading image while ajax function loads
Possible Duplicate:
Creating a loading image while ajax loads

enter code hereThis is the code i have, im trying to insert a image to show that ajax is loading bt i just cant get this right, tried a lot of possible ways but it just aint working, any suggestions on wat to do?
    ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('main_result');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
        $("#main_result").empty().html('<img src="loading.gif" />');

        var category = document.getElementById('category').value;
        var brand = document.getElementById('brand').value;
        var item = document.getElementById('item').value;
        var queryString = "&category=" + category + "&brand="+ brand +"&item="+ item;
        ajaxRequest.open("GET", "main_search_special.php?section=special" + queryString, true);
        ajaxRequest.send(null);


text:
Q: Creating unconventional charts using Python Pandas I want to create the following chart in python pandas:

in the Tables folder Limits.txt determines the minimum and maximum for every delta_n limit. DUTs.txt contains the values for every delta_n,
you can download it here:
Tables.zip
Please advise

A: matplotlib and bokeh are better options for this. Pandas plot is just matplotlib -- source
In bokeh, you can plot the bars with vbar
And you can plot the lines with line
Bokeh tutorials to get started: http://nbviewer.jupyter.org/github/bokeh/bokeh-notebooks/blob/master/index.ipynb#Tutorial


text:
Q: Phoenix vs Rails - full stack benchmark I'm looking for full stack benchmarks comparisons between Phoenix and Rails.
I found this post (but it doesn't hit the database) http://www.littlelines.com/blog/2014/07/08/elixir-vs-ruby-showdown-phoenix-vs-rails/
A Blog index page would be fine (with variable posts list) - as long as it hits the database.
Thanks!


text:
Q: MUI datatable sorting column I have a column that is basically an object, I display the value I want to display, but the sort does not work for that column.
Attach an example so I can explain myself a little better.
for example:
  const [data, setData] = useState([
    {
      ID: "A001",
      Name: "Joe James",
      Amount: "$300,000",
      Purpose: "$220,000",
      Tib: 12 + "years",
      details: {Score: "620-670" , Name:"Joe James"},
      Score: "620-670",
      Phone: "9292132019",
      Mail: "Nole@temp.io",
      State: "TX",
      Opening: "11.11.2021",
      Pf: "Priority urgent",
      Flags: "In Progress",
      Ls: "DorAff",
      Company: "Dit",
      Ras: "...",
    },
   {
      ID: "A001",
      Name: "Joe James",
      Amount: "$300,000",
      Purpose: "$220,000",
      Tib: 12 + "years",
      details: {Score: "650-720" , Name:"Test James"},
      Score: "620-670",
      Phone: "9292132019",
      Mail: "Noe@temp2t.io",
      State: "TX",
      Opening: "11.11.2021",
      Pf: "Priority urgent",
      Flags: "In Progress",
      Ls: "DavAff",
      Company: "Mit",
      Ras: "...",
    }
)];

 const columns = [
    {
      name: "details",
      label: "Name",
      options: {
        customBodyRender: (value: any, tableMeta: any, updateValue: any) => {
          return value?.Name;
        },
        sort: true,
        filter: true,
        setCellProps: () => ({
          align: "center",
        }),
        setCellHeaderProps: (value: any) => ({
          className: "centeredHeaderCell",
        }),
      },
    },
    {
      name: "details",
      label: "Score",
      options: {
        filter: true,
        sort: true,
        customBodyRender: (value: any, tableMeta: any, updateValue: any) => {
          return value?.Score;
        },
        setCellProps: () => ({
          align: "center",
        }),
        setCellHeaderProps: (value: any) => ({
          className: "centeredHeaderCell",
        }),
      },
    }
]

As you can see in the example I go to the details and display the Name, and in another column displays the Score.
Thanks in advance :-)

A: You can use it in a simple way. You just have to put the name of the column and the direction. Inside the table options
sortOrder: {
   name: 'name',
   direction: 'desc'
}

So your code would be something like this
const [data, setData] = useState([
{
  ID: "A001",
  Name: "Joe James",
  Amount: "$300,000",
  Purpose: "$220,000",
  Tib: 12 + "years",
  details: {Score: "620-670" , Name:"Joe James"},
  Score: "620-670",
  Phone: "9292132019",
  Mail: "Nole@temp.io",
  State: "TX",
  Opening: "11.11.2021",
  Pf: "Priority urgent",
  Flags: "In Progress",
  Ls: "DorAff",
  Company: "Dit",
  Ras: "...",
},
 {
  ID: "A001",
  Name: "Joe James",
  Amount: "$300,000",
  Purpose: "$220,000",
  Tib: 12 + "years",
  details: {Score: "650-720" , Name:"Test James"},
  Score: "620-670",
  Phone: "9292132019",
  Mail: "Noe@temp2t.io",
  State: "TX",
  Opening: "11.11.2021",
  Pf: "Priority urgent",
  Flags: "In Progress",
  Ls: "DavAff",
  Company: "Mit",
  Ras: "...",
}
)];

const columns = [
{
  name: "name",
  label: "Name",
  options: {
    sort: true,
    filter: true,
    setCellProps: () => ({
      align: "center",
    }),
    setCellHeaderProps: (value: any) => ({
      className: "centeredHeaderCell",
    }),
  },
},
{
  name: "score",
  label: "Score",
  options: {
    filter: true,
    sort: true,
    setCellProps: () => ({
      align: "center",
    }),
    setCellHeaderProps: (value: any) => ({
      className: "centeredHeaderCell",
    }),
  },
}
];
const options = {
sortOrder: {
        name: 'name',
        direction: 'desc'
      },
};

A: I was able to solve this, using the sortCompare function from the documentation!
https://www.npmjs.com/package/mui-datatables/v/3.3.1

A: You can add sortOrder in MUI Data Table Options
sortOrder: {
   name: 'name',
   direction: 'desc'
}

Example: https://github.com/gregnb/mui-datatables/blob/master/examples/customize-columns/index.js
sortOrder: Sets the column to sort by and its sort direction. To remove/reset sorting, input in an empty object. The object options are the column name and the direction: name: string, direction: enum('asc', 'desc')


text:
Q: Missing Data Source Tab and Standard Control Tabs when design in VS 2013 I cannot figure out how to recover the Data Source Tab and Standard Control Tab (if I remember the name correctly) when designing a Windows Form in VS 2013.

Do you know where I can get them back?

A: View -> Other Windows -> Data sources
View -> Toolbars -> Standard


text:
Q: Best way to implement a view with multiple widgets in QT? I would like to have a view where I show the user various QLabels, a .jpg image, and a list of items (eg. a QListView). I would like all of them to be vertically scrollable together. The data for filling the various widgets will be set by the function that shows this view. I prefer implementing it in code, without using the GUI Designer.
I thought about creating my custom widget inheriting from QWidget, but I am finding it hard to implement it. Is this the best way to do it?
Could you provide me with an example of how I should proceed?
Thanks in advance

A: //Using QScrollArea

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include <QLabel>
#include <QScrollArea>
#include <QVBoxLayout>

class MyWidget: public QWidget
{
    Q_OBJECT
public:
    explicit MyWidget(QWidget *parent = 0);

private:
    QScrollArea *scrollArea;
    QWidget *widget;
    QLabel *label1;
    QLabel *label2;
    QLabel *label3;
    QVBoxLayout *vLayout;
};

#endif // MYWIDGET_H

#include "mywidget.h"

MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent)
{
    scrollArea=new QScrollArea(this);
    widget=new QWidget;
    label1=new QLabel("Label1");
    label2=new QLabel("Label2");
    label3=new QLabel("Label3");

    label1->setFixedSize(200,100);
    label2->setFixedSize(200,100);
    label3->setFixedSize(200,100);
    vLayout=new QVBoxLayout;

    vLayout->addWidget(label1);
    vLayout->addWidget(label2);
    vLayout->addWidget(label3);
    widget->setLayout(vLayout);

    scrollArea->setWidget(widget);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    scrollArea->resize(200,150);
}


text:
Q: How to structure time specific data so that the most recent point can be found? This is kinda hard to phrase in a single line questions, but I'm looking for some advice/best practices for structuring data and writing a function in Javascript.
I have several items that change status regularly. My data contains an itemID, timestamp, and status. I am currently structuring it as an array of objects (for each item), with a history priority that contains the timestamps and status. (see below).
I'm looking for a function that will allow me to easily get the status of each object at a given time using the most recent past update. I'm not sure if my data structure will allow for this, or if it does, how to write the function. (for this example I'm going to shorten my timestamps to a 4 digit number)
 var items = [
      { id: 1,
        history: {1234: 'open', 1256: 'in-use', 1289: 'reset', 1293: 'open'},
      { id: 2,
        history: {1230: 'open', 1290: 'in-use'},
      { id: 3,
        history: {1238: 'open', 1241: 'in-use', 1251: 'reset'}
 ]

I'd like to be able to have a function like this:
 getStatus(1260);

and get back
 {1: 'in-use', 2: 'open', 3: 'reset'}

Each id, with the status it was in at the time passed in based on the most recent history record prior to the queried time.
I am not at all attached to this data structure. I also tried having the history an array of objects containing the time and the status, but that means I have to loop through the entire array every time. My biggest problem is that my head is pushing me to an SQL method for doing this, but I'm stuck in client-side Javascript...
My questions:  What is the best data structure for this? and How would I go about writing my getStatus() function?
Thanks!

A:
I also tried having the history an array of objects containing the time and the status, but that means I have to loop through the entire array every time.

Not if you had the array sorted, as you then can access the most recent date directly. Also you can use binary search for getting the state at a specific timestamp. With the object you currently have, you always have to enumerate all properties to find the best-matching.
var items = [
  { id: 1,
    history: [
      { timestamp: 1234, status: 'open'},
      { timestamp: 1256, status: 'in-use'},
      { timestamp: 1289, status: 'reset'},
      { timestamp: 1293, status: 'open'}
    ]
  },
  …
];
function index(arr, compare) { // binary search, with custom compare function
    var l = 0,
        r = arr.length - 1;
    while (l <= r) {
        var m = l + ((r - l) >> 1);
        var comp = compare(arr[m]);
        if (comp < 0) // arr[m] comes before the element
            l = m + 1;
        else if (comp > 0) // arr[m] comes after the element
            r = m - 1;
        else // this[m] equals the element
            return m;
    }
    return l-1; // return the index of the next left item
                // usually you would just return -1 in case nothing is found
}
// example:
function insertItem(history, timestamp, status) {
    var i = index(history, function(item) {
        return item.timestamp - timestamp;
    });
    history.splice(i+1, 0, {timestamp: timestamp, status: status});
}

function getStatus(time) {
    var result = {};
    function comparefn (item) {
        return item.timestamp - time;
    }
    for (var i=0; i<items.length; i++) {
        var pos = index(items[i].history, comparefn);
        result[items[i].id] = pos == -1
          ? undefined
          : items[i].history[pos].status;
    }
    return result;
}

A: You could use a loop:
// for each entry:
var n2 = n;
while (typeof items[n2] == "undefined" && n2 >= -1) {
    n2--;
}
if (n != -1) {returnedArray[idBeingProcessed] = items[n2];}
else {alert("Error handling here");}
// repeat for each item (id 1, id 2...)

This will stop if an answer has been found. It may be inefficient, but hey, it works :-)
Also, consider using an array for your history objects if applicable.


text:
Q: Finding vector fields on $S^2$ with equal divergence Let $\mathfrak{X}_{CK}^{\perp}$ be the space of vector fields on $S^2$ that are $L^2$-orthogonal to conformal Killing vector fields. Let $\mathfrak{X}_{CK}$ be the 6-dimensional space of conformal Killing vector fields on $S^2$.
Can we find a vector field $Y \in \mathfrak{X}_{CK}^{\perp}$  and a vector field $W \in \mathfrak{X}_{CK}$ that is not Killing such that
$$\mathrm{div}(Y) = \mathrm{div}(W)$$

A: I think that this is not possible:
Per my comment on Divergence of conformal Killing vector fields on $S^2$ and the spherical harmonics you want to solve
$$
\textrm{div} (Y) = -2a\cdot x
$$
for $Y$ orthogonal to conformal-KVF's and $a \in \mathbb{R}^3$ fixed (nonzero). Suppose you can do this. Then, we find that
$$
Y = a^T + W
$$
for $W$ divergence free. From this question https://math.stackexchange.com/questions/1898371/divergence-free-vector-field-on-a-2-sphere you can see that $W = J \nabla f$ for some function $f \in C^\infty(S^2)$ (for $J$ the complex structure on $S^2$). Now, by assumption, $Y$ is orthogonal to $a^T$:
\begin{align*}
0 & = \int_{S^2} Y\cdot a^T \\
& = \int_{S^2}|a^T|^2 + (J \nabla f) \cdot a^T \\
& = \int_{S^2}|a^T|^2 -   \nabla f \cdot J a^T \\
& = \int_{S^2}|a^T|^2 + f \textrm{div}(J a^T).
\end{align*}
However, note that $Ja^T$ is a KVF and thus divergence free. This implies that $\int_{S^2}|a^T|^2 = 0$. This is a contradiction.


text:
Q: Devise lockable and custom strategy I am developing a custom strategy for LDAP authentication, and I have implemented the valid? and authenticate! methods as per http://kyan.com/blog/2013/10/11/devise-authentication-strategies and this Devise wiki. My custom strategy works by itself.
I also want to use the Lockable module (and other Devise modules), but they seem to work only when Database_Authenticatable is also present. I have been reading the Devise source code, but I do not understand how Lockable is able to find the user (resource) in order to increment the :failed_attempts count. How do I pass the user record or resource to Lockable using my custom strategy?
My custom strategy is below. I am using Devise 3.5 and Rails 4.2
require 'net/ldap'
require 'devise/strategies/authenticatable'

module Devise
  module Strategies
   class LdapAuthenticatable < Authenticatable

  def valid?
    params[:user] && login.present? && password.present?
  end

  def authenticate!

    resource = mapping.to.find_for_authentication(email: params[:user][:email])

    if params[:user]
      begin
        ldap = Net::LDAP.new
        ldap.auth(my_ldap_service, my_ldap_service_password)
        ldap.encryption(:simple_tls)
        ldap.base = "base_here"
        ldap.host = my_ldap_host
        ldap.port = "636"
        result_attrs = ["employeenumber", "givenname", "sn", "mail", "department"]

        result = ldap.bind_as(base: "base_here", filter: "(mail=#{login})", attributes: result_attrs, password: password, time: 3)

        if result
          #valid ldap credentials
          user = get_user_from_database(result)
          if user
            success!(user)
          else
            fail!(:invalid_login)
          end

        else
          fail!(:invalid_login)
        end

      rescue => e
        Rails.logger.error e.message
        fail!(:invalid_login)
      end

    end
  end

  def login
    params[:user][:email]
  end

  def password
    params[:user][:password]
  end

end
end
end

A: Active Directory should take care of a lockable feature. By using LDAP in your custom strategy, you move responsibility for the feature from your application to LDAP/Active Directory. Lockable should prevent a villain from brute-forcing access to your application. If Active Directory had no restrictions on this, he could simply run his attack directly against it and in case of success use the credentials in your application.
You should however enable your application to display error messages returned by the remote server like "Too many retries, try again in 5 minutes".

A: I ended up using devise_custom_authenticatable in combination with the resources posted on the original question. For lockable to work,  database_authenticable must be present. Toni's answer above should work if you have control over LDAP, which I did not when I posed the question.

A: You are missing to call the validate method which is part of Authenticatable class you inherit from. The validate method calls the valid_for_authentication? method from the lockable module which then takes care of incrementing the attempts and lock the account.
In database_authenticatable this is solved here by using valid_password? which returns a boolean. In your case you would need to add a validate(resource) { false } in the case bind_as doesn't return a result.
The fixed full authenticate! method would look like the following
def authenticate!

    resource = mapping.to.find_for_authentication(email: params[:user][:email])

    if params[:user]
      begin
        ldap = Net::LDAP.new
        ldap.auth(my_ldap_service, my_ldap_service_password)
        ldap.encryption(:simple_tls)
        ldap.base = "base_here"
        ldap.host = my_ldap_host
        ldap.port = "636"
        result_attrs = ["employeenumber", "givenname", "sn", "mail", "department"]

        result = ldap.bind_as(base: "base_here", filter: "(mail=#{login})", attributes: result_attrs, password: password, time: 3)

        if result
          #valid ldap credentials
          user = get_user_from_database(result)
          if user
            success!(user)
          else
            fail!(:invalid_login)
          end

        else
          # no result -> wrong password
          validate(resource) { false }
          fail!(:invalid_login)
        end

      rescue => e
        Rails.logger.error e.message
        fail!(:invalid_login)
      end

    end
  end


text:
Q: How can I set the z-index for this select? Hello I would like to set the z-index of the following component :
import React from 'react';
import chroma from 'chroma-js';

import { colourOptions } from './docs/data';
import Select from 'react-select';

const colourStyles = {
  control: styles => ({ ...styles, backgroundColor: 'white' }),
  option: (styles, { data, isDisabled, isFocused, isSelected }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: isDisabled
        ? null
        : isSelected
        ? data.color
        : isFocused
        ? color.alpha(0.1).css()
        : null,
      color: isDisabled
        ? '#ccc'
        : isSelected
        ? chroma.contrast(color, 'white') > 2
          ? 'white'
          : 'black'
        : data.color,
      cursor: isDisabled ? 'not-allowed' : 'default',

      ':active': {
        ...styles[':active'],
        backgroundColor: !isDisabled && (isSelected ? data.color : color.alpha(0.3).css()),
      },
    };
  },
  multiValue: (styles, { data }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: color.alpha(0.1).css(),
    };
  },
  multiValueLabel: (styles, { data }) => ({
    ...styles,
    color: data.color,
  }),
  multiValueRemove: (styles, { data }) => ({
    ...styles,
    color: data.color,
    ':hover': {
      backgroundColor: data.color,
      color: 'white',
    },
  }),
};

export default () => (
  <Select
    closeMenuOnSelect={false}
    defaultValue={[colourOptions[0], colourOptions[1]]}
    isMulti
    options={colourOptions}
    styles={colourStyles}
  />
);

I found this solution :
styles={{menu: provided => ({ ...provided, zIndex: 9999, colourStyles })}}

instead of
styles={colourStyles}

But I lose all the colors...
Could you help me please ?
Here is the code :
https://codesandbox.io/s/condescending-noether-1ee0v?file=/example.js:0-1531
Thank you very much !

A: Note that if you used styles={{colourStyles}} instead of styles={colourStyles}, then the app would also lose the colors. This is because it is not expanded as it should. However, styles={{...colourStyles}} would work. Read more in this post.
So this bit of code should fix your problem:
example.js
export default () => (
  <Select
    [your other props],
    styles={{
      ...colourStyles,
      ...{control: styles => ({ ...styles, zIndex: 9999})},
    }}
  />
);

where the two objects colourStyles and {zIndex: 9999} were merged (in ES6 compatible syntax, see this post for different ways to do this). Alternatively you can just append zIndex: 9999 right behind backgroundColor: 'white' within the colourStyles constant.
Upon inspection you can see it works:


text:
Q: Как убрать лимит в 300 опций на Opencart? После 300 опций ( разные размеры) выводится ошибка при вводе.
Где это ограничение можно снять?

A: Добавьте в .htaccess:
php_value max_input_vars 15000

Или в php.ini, если доступ есть:
max_input_vars = 15000;

Или может в панели настройкой хостинга есть такие пункты, посмотрите.


text:
Q: Fan works hard while `yarn start` I build websites with ReactJs, npm, yarn, etc.
When I do yarn start and check websites in development with localhost, the fan of my Mac works hard, and the noise is annoying.
Does anyone have any solution to smooth this?

A: Obviously your system is experiencing an intensive load or at least your Mac thinks so. Before following any advice I give below please open Activity Monitor while running one of your projects and make sure something doesn't spike. If something is spiking that's why your fans are turning on.
You can download this software which allows you to control your Mac's fans. Be careful not to turn the fans on too high or too low. You can select a fan and choose how fast it should run (RPM).


text:
Q: Referencing field from input in a Logstash filter I have the following input, which is generated by FileBeat
{
  "@timestamp": "2018-12-04T09:21:33.360Z",
  "@metadata": {
    "beat": "filebeat",
    "type": "doc",
    "version": "6.5.0"
  },
  "message": "the message",
  "prospector": {"type": "log"},
  "input": {"type": "log"},
  "beat": {
    "name": "linuxkit-025000000001",
    "hostname": "linuxkit-025000000001",
    "version": "6.5.0"
  },
  "host": {"name": "linuxkit-025000000001"},
  "source": "/opt/foo/logs/bar.log",
  "offset": 9893715,
  "log": {"flags": ["multiline"]}
}

I'd like to use the message field inside my script, so I tried using the following filter
filter {
    mutate {
        add_field => {
            "decoded_base64" => ruby {
                path => "scripts/my_script.rb"
                script_params => { "msg" => "${[message]}" }
            }
        }
    }
}

But I keep getting NoMethodError referencing the method "get".
logstash    | [2018-12-11T14:05:47,765][ERROR][logstash.agent           ] Failed to execute action {:action=>LogStash::PipelineAction::Create/pipeline_id:cep_logs,
:exception=>"NoMethodError",
:message=>"undefined method `get' for #<Java
::OrgLogstashConfigIrImperative::PluginStatement:0x29fc9676>
\nDid you mean?  getClass\n               get_class\n               gem",
:backtrace=>["/usr/share/logstash/logstash-core/lib/logstash/compiler/lscl.rb:210:in `expr'", "org/jruby/RubyArray.java:2486:in `map'", "/usr/share/logstash/logstash-core/lib/logstash/compiler/lscl.rb:202:in `expr'", "/usr/share/logstash/logstash-core/lib/logstash/compiler/lscl.rb:133:in `expr'", "org/jruby/RubyArray.java:2486:in `map'",
"/usr/share/logstash/logstash-core/lib/logstash/compiler/lscl.rb:97:in `expr_attributes'", "/usr/share/logstash/logstash-core/lib/logstash/compiler/lscl.rb:75:in `expr'", "org/jruby/RubyArray.java:2486:in `map'", "/usr/share/logstash/log
stash-core/lib/logstash/compiler/lscl.rb:68:in `expr'", "/usr/share/logstash/logstash-core/lib/logstash/compiler/lscl.rb:47:in `block in compile'", "org/jruby/RubyArray.java:1734:in `each'", "/usr/share/logstash/logstash-core/lib/logstas
h/compiler/lscl.rb:45:in `compile'", "/usr/share/logstash/logstash-core/lib/logstash/compiler.rb:45:in `compile_imperative'", "/usr/share/logstash/logstash-core/lib/logstash/compiler.rb:49:in `compile_graph'", "/usr/share/logstash/logsta
sh-core/lib/logstash/compiler.rb:11:in `block in compile_sources'", "org/jruby/RubyArray.java:2486:in `map'", "/usr/share/logstash/logstash-core/lib/logstash/compiler.rb:10:in `compile_sources'", "org/logstash/execution/AbstractPipelineE
xt.java:149:in `initialize'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:22:in `initialize'", "/usr/share/logstash/logstash-core/lib/logstash/pipeline.rb:90:in `initialize'", "/usr/share/logstash/logstash-core/lib/logsta
sh/pipeline_action/create.rb:38:in `execute'", "/usr/share/logstash/logstash-core/lib/logstash/agent.rb:309:in `block in converge_state'"]}

Can someone please shed some light on why this is happening, please?
I don't think it's relevant, but just in case the script that I'm using is
require "base64"

def register(params)
    @msg = params["msg"]
end

def filter(event)
    if @msg.matches(/<DataB64>(.*)<\/DataB64>/)
        return Base64.decode64($1)
    end
end

A: Unless something has changed that I'm not seeing in the doc, you shouldn't be using mutate->add_field to run your ruby.  Try:
filter {
    ruby {
        ...
    }
}

and have your ruby code add the field with [event.set][1].


text:
Q: Make app icon on task bar have a transparent background (UWA) I am making a Universal Windows App and I want my apps icon on the task bar to have a transparent background so it isn't in a coloured box.
A lot of Microsoft's own stock apps are like this (Mail, Photos, Xbox etc) and I know it can be done because I did it by accident. But the icons I was using were too big and when I used correct sized ones it stopped working. I've tried using the old too large icons again and it still doesn't work.

Setting the tile background in the apps manifest just makes the background the users theme colour rather than actually transparent so I must of done something else, all of my assets for the Square 44x44 Logo of course have transparent backgrounds but I just get the tile background colour where there should be nothing.

A: You need to use the "altform-unplated" qualifier in your icon's filename. For example:
SmallLogo.targetsize-32_altform-unplated.png

If you really want to be thorough... For Square44x44Logo in your manifest, you should have 6 versions of the icon (normal, high contrast black, and high contrast white, x3 for unplated versions) for each of the following target sizes: 16, 20, 24, 30, 32, 36, 40, 48, 60, 64, 80, 96, and 256.
For example, here's 256:
SmallLogo.targetsize-256.png
SmallLogo.targetsize-256_contrast-black.png
SmallLogo.targetsize-256_contrast-white.png
SmallLogo.targetsize-256_altform-unplated.png
SmallLogo.targetsize-256_altform-unplated_contrast-black.png
SmallLogo.targetsize-256_altform-unplated_contrast-white.png

That's a lot of PNGs.


text:
Q: How to read csv file where columns are separated by double quotes and spaces I tried googling and searching stackoverflow already, but most similar answers involve some other character acting as a separator (like comma or |) but in the csv I have, a line of data looks like this:
"2017-02-27 ""2017-02-25"" ""15438"" ""2017-02-27",19,"671"" ""1"" ""14"" ""John Smith"" ""614""
And each value is meant to be a column (so above would be 8 columns). Another problem is the value 2017-02-27",19,"671 is all in one column, which includes single quote marks and commas.
So it seems like the delimiter is this: "" ""
How can I read this in properly?
Also, as a side question, the headers are also listed as the first row of the csv file, but they are separated with just spaces (with the headers themselves using underscores such as: name_1 name_2 name_3). Is there a way to read this in while using read_csv or easier to just copy that row and paste it in to the name parameter as a list?
Thanks!
Edit: I already tried sep='"" ""' which returns everything as one column. Here is everything I tried (taken from other stackoverflow threads):
sep='"" ""'
sep=',\s+',quoting=csv.QUOTE_ALL
sep=" ", quotechar="~"
sep='["]* ["]*', engine='python'

Edit:
I found a solution that worked for my specific case:
df = pd.read_csv('test.csv', header=None, sep='\s""', engine='python', skiprows=1, index_col=False).replace('"','', regex=True)

in case it helps anyone. Basically, I just separated by 2 double quotes since that separated the first two columns (as opposed to 4 double quotes for the rest) and then used the replace bit through RegEx. Thanks everyone for the help!

A: If I take your data as you have it and place in a csv file, and run this
df = pd.read_csv('test.csv', header=None, sep='\s', engine='python').replace('"','', regex=True)
df

I get
            0           1      2                  3  4   5     6      7    8
0  2017-02-27  2017-02-25  15438  2017-02-27,19,671  1  14  John  Smith  614

Then split the column in question:
df[['n1', 'n2', 'n3']] = df.loc[:, 3].str.split(',', expand=True)

            0           1      2                  3  4   5     6      7    8          n1  n2   n3
0  2017-02-27  2017-02-25  15438  2017-02-27,19,671  1  14  John  Smith  614  2017-02-27  19  671

If this isn't the result your looking for, please comment.


text:
Q: How to store key-value pairs in an elasticsearch index using python I want to store the contents of the dict into an elasticsearch index as follows . Is it correct or is there a better way to do it .
    def process(self, inputDict):
       for k, v in inputDict.items():
        # for each key-value pair, store it as a field and string inside the specified index of elastic search.
          key1=k
          value1=v
          doc={
            "key1" : "value" ,
            }
          self.es.index(index='test-index2',doc_type='exdoc', id=1, body=doc)
    pass;

A: First of all: Did you try your code? I tried it and it ran without errors. That means that there must be some documents in the index test-index2. Running it inside idle I got the the following output:
{'_index': 'test-index2', '_type': 'exdoc', '_id': '1', '_version': 1, '_shards': {'failed': 0, 'total': 2, 'successful': 1}, 'created': True}
{'_index': 'test-index2', '_type': 'exdoc', '_id': '1', '_version': 2, '_shards': {'failed': 0, 'total': 2, 'successful': 1}, 'created': False}
{'_index': 'test-index2', '_type': 'exdoc', '_id': '1', '_version': 3, '_shards': {'failed': 0, 'total': 2, 'successful': 1}, 'created': False}

See that _version field in there? That looks suspicious. Querying elasticsearch from sense with
GET test-index2/exdoc/_search
{
  "query": {
    "match_all": {}
  }
}

will give you the following output:
{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "test-index2",
        "_type": "exdoc",
        "_id": "1",
        "_score": 1,
        "_source": {
          "key1": "value"
        }
      }
    ]
  }
}

There is only one document there: {"key1": "value"}. So you are always sending the same document - ignoring the keys and values from inputDict -  for the same id (id=1) to elasticsearch. I think you wanted something like this instead:
def process(self, inputDict):
       i = 1
       for k, v in inputDict.items():
        # for each key-value pair, store it as a field and string inside the specified index of elastic search.
          doc={
            k: v
            }
          self.es.index(index='test-index2',doc_type='exdoc', id=i, body=doc)
          i += 1


text:
Q: How to see errors in MySQL Workbench 6.1? I recently upgraded my development machine to use MySQL Workbench 6.1.  I am trying to enter some data into a table using the workbench and "Select rows..."  When I click the "Apply" button to insert the data, the workbench reports that an error occurred (see the image below), but it doesn't tell me what the error is.  Workbench 5.* used to show the errors.  I cannot find any way to get Workbench 6.1 to show me the errors.  How can I see the error messages?

A: If you are on linux machine this solution will work.
It is already there you have to move your mouse and expand it:
At first it will look like this:

you have to hover the mouse until the cursor icon change to resize icon.upward

then click it and pull

and then you can hover on cross sign scroll right to see the error message completely.

A: If you are not seeing any sql errors or exceptions this could be one off your problems.
Toggle the button in the picture
button panel of mysqlworkbench

A: I eventually worked out that the panel could be opened by hovering my mouse at just the top of the status bar (at the bottom of the UI).
The hit area is tiny so you really have to 'feel' around for the drag point.

A: To cause MySQL Workbench to show error messages, I had to change a preference.  From the Workbench menu, click "Edit" -> "Preferences..."  Open the "SQL Queries" tab.  Check "Confirm Data Changes".


text:
Q: Jquery callback with synchronous animations In my jQuery plugins I often expect to have some callbacks defined by the user like in the simple example below
(function($) {
    $.fn.myplugin = function(options) {
        var s = $.extend({}, options),
            $this = $(this);

        if (typeof s['initCallback'] === 'function') {
            s['initCallback']($this);
        }
        $this.animate({width: '+=300'}, 3000);   /* animation in plugin */
    }
})(jQuery);

Sometimes the defined callback contains synchronous code like this, and this code works as I'm expecting
$('#mydiv').myplugin({
    initCallback : function(mydiv) {
       $('
This is synchronous, so it will entirely executed before animation
')
           .insertBefore(mydiv);
    }
});

but in some other case the callback could defines an asynchronous animation like this
$('#mydiv').myplugin({
    initCallback : function(mydiv) {
       $('
animations are not synchronous here
')
           .insertBefore(mydiv)
           .hide()
           .fadeIn(4000); /* animation in callback */
    }
});

in this last case we have  two animations that clearly overlap, because after execution of my initCallback() the remaining plugin code is not properly executed on fadeIn() callback.
So I'm asking: does it exists a common jQuery pattern to deal with both kind of code (async/sync) to be sure that the initCallback() will ever terminate the execution, no matter of which code it defines? Or am I require to code both the case in two different ways?
Code of this example is available on http://jsfiddle.net/fcalderan/LKttT/
Thanks in advance.

A: http://api.jquery.com/animate/

.animate( properties, options )
propertiesA map of CSS properties that
  the animation will move toward.
optionsA map of additional options to
  pass to the method. Supported keys:

*

*duration: A string or number determining how long the animation
  will run.

*easing: A string indicating which easing function to use for the
  transition.

*complete: A function to call once the animation is complete.

*step: A function to be called after each step of the animation.

*queue: A Boolean indicating whether to place the animation in the
  effects queue. If false, the animation
  will begin immediately.

*specialEasing: A map of one or more of the CSS properties defined by
  the properties argument and their
  corresponding easing functions (added
  1.4).

You should set queue to false.


text:
Q: How to loop through a range of week status variables in SAS and pull status according to specific week given by other variable I have a range of weekly variables describing a person's "status" (from week 1, 2010 to 2012 week 17).
The variables are given by:
y_1001, y_1002,...y1052, y1101, y1102,......y_1217

I define the period of variables like this:
%let period = y_1001-1052 y_1101-y1148;

I also have a treatment period given as a start date and an end date. My challenge is to find the status given by the y_ variables in the week after the person stops the treatment.
I am not too familiar with SAS, but my idea was to "pick" the correct y_ variable based on a week counter, say by counting the number of weeks since the beginning of the period  (week 1 in 2010) and until the date where the treatment ends.
I get the weeks until end of treatment like this
week_count = 1 + intck( 'week.2', '1JAN2010'd, end_treatment_date, 'd');

But how can I retrieve the corresponding y_ variable based on this count?
After fruitless search on how to loop over the period variables and pick the number corresponding to the week_count variable for each person, I thought about going a different way... say something like this.
array weeks(*) .
do i = 1 to dim(weeks) by 1;
  if week_count = i then end_status = y_10&i;
end

...but with modifications to take into account that there is a mismatch between the dimension of the array and the number of weeks and years.
But then my challenge is to make the following part work...
if week_count = i then end_status = y_10&i;

How can I make SAS pick the right y_ variable based on the loop index? This seems like a really simple problem, but somehow I have not managed to find a solution. Is there no way to use the variable "i" as input in defining the correct y_ variable?
Would really appreciate if somebody could throw some hints.

A: I think you want:
if week_count = i then end_status = weeks{i};

A: VVALUEX is a little known function in SAS which can help you to extract a value from a SAS variable name. Here your problem is to construct the SAS variable name given the number of weeks from the 1st Jan to the end of treatment. You can avoid using a DO LOOP for every observation by using the ideas in the example below -
data _null_;
    end_treatment_date = "09FEB2010"d;
    y_1007 = 'D';
    status = vvaluex(compress("y_" || substr(strip(year(end_treatment_date)), 3, 2) || put(1 + intck("week.2", "01JAN2010"d, end_treatment_date), z2.)));
    put status;
run;

The variable name is constructed as follows - initally you take the string "y_" and then append the last two digits of the year followed by the week using similar logic to your variable week_count as before. You get the variable you want, and then apply VVALUEX to get the value. Running the DO LOOP for every observation can be inefficient if you have millions of them.