text:
Q: MPI_Scatterv (c) will give segmentation fault I've built a fairly simple c code that reads a pgm image, splits it in different sections and sends it to various cores to elaborate it.
In order to account for some elaboration margins (each core has to access a larger area of the image than the it needs to write on), I can't simply split the image but I first have to create an array where I add the before mentioned margins.
As a quick example: an image is 1600x1200 (width x height), I have 2 cores, I want to access an area of 3x3 centered on the pixel and I'm splitting this image horizontal line by horizontal line then the subdivision would be -> the first core gets the pixels from 0 to 6011600, the second core gets the pixels from 5091600 to 1200*1600.
Now, I believe there is nothing wrong in how I implemented this in my program, still I get this error:
[ct1pt-tnode003:22389:0:22389] Caught signal 11 (Segmentation fault: address not mapped to object at address 0x7ffe7f60ead8)
==== backtrace (tid:  22389) ====
 0 0x000000000004ee05 ucs_debug_print_backtrace()  ???:0
 1 0x0000000000402624 main()  ???:0
 2 0x0000000000022505 __libc_start_main()  ???:0
 3 0x0000000000400d99 _start()  ???:0

This is my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <math.h>
#include <time.h>
#include "testlibscatter.h"
#include <mpi.h>

#define MSGLEN 2048

int main(int argc, char *argv[]){

MPI_Init(&argc, &argv);

int m = atoi(argv[1]), n = atoi(argv[2]), kern_type = atoi(argv[3]);
double kernel[m*n];
int i_rank, ranks;
int param, symm;

MPI_Comm_rank( MPI_COMM_WORLD, &i_rank);
MPI_Comm_size( MPI_COMM_WORLD, &ranks);

int xsize, ysize, maxval;
xsize = 0;
ysize = 0;
maxval = 0;

void * ptr;

switch (kern_type){
    case 1:
    meankernel(m, n, kernel);
    break;
    case 2:
    weightkernel(m, n, param, kernel);
    break;
    case 3:
    gaussiankernel(m, n, param, symm, kernel);
    break;
}

if (i_rank == 0){
    read_pgm_image(&ptr, &maxval, &xsize, &ysize, "check_me2.pgm");
}

MPI_Bcast(&xsize, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&ysize, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&maxval, 1, MPI_INT, 0, MPI_COMM_WORLD);

int flo, start, end, i;
flo = floor(ysize/ranks);

int first, last;

first = start - (m - 1)/2;
last = end + (m - 1)/2;

if (start == 0){
    first = 0;
}
if (end == ysize){
    last = ysize;
}

int sendcounts[ranks];
int displs[ranks];

int first2[ranks];
int last2[ranks];
int c_start2[ranks];
int c_end2[ranks];

int num;
num = (ranks - 1) * (m-1);
printf("num is %d\n", num);

unsigned short int bigpic[xsize*(ysize + num)];

if (i_rank == 0){
    for(i = 0; i < ranks; i++){
        c_start2[i] = i * flo;
        c_end2[i] = (i + 1) * flo;
        if ( i == ranks - 1){
            c_end2[i] = ysize;
        }
        first2[i] = c_start2[i] - (m - 1)/2;
        last2[i] = c_end2[i] + (m - 1)/2;
        if (c_start2[i] == 0){
            first2[i] = 0;
        }
        if (c_end2[i] == ysize){
            last2[i] = ysize;
        }
        sendcounts[i] = (last2[i] - first2[i]) * xsize;
    }

    int i, j, k, index, index_disp = 0;
    index = 0;
    displs[0] = 0;

    for (k = 0; k < ranks; k++){
        for (i = first2[k]*xsize; i < last2[k]*xsize; i++){
            bigpic[index] = ((unsigned short int *)ptr)[i];
            index++;
        }
        printf("%d\n", displs[index_disp]);
        index_disp++;
        displs[index_disp] = index;
    }

}

MPI_Bcast(displs, ranks, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(sendcounts, ranks, MPI_INT, 0, MPI_COMM_WORLD);

unsigned short int minipic[xsize*(last-first)];
MPI_Barrier(MPI_COMM_WORLD);
MPI_Scatterv(&bigpic[0], sendcounts, displs, MPI_UNSIGNED_SHORT, minipic, (last-first)*xsize, MPI_UNSIGNED_SHORT, 0, MPI_COMM_WORLD);

MPI_Finalize();
}

the function kernel simply returns an array of m*n doubles to edit the image, while the read_pgm_image returns a void pointer with the values of the image read.
I've tried printing the values of bigpic and they show no problem.

A: In the code shown here, start and end are used uninitialised in the computations of first and last:
int flo, start, end, i;
         ~~~~~~~~~~
flo = floor(ysize/ranks);

int first, last;

first = start - (m - 1)/2; // <---- start has a random value here
last = end + (m - 1)/2;    // <---- end has a random value here

If the values are very large, the size of minipic may become larger than the stack size:
unsigned short int minipic[xsize*(last-first)];
                                  ^^^^^^^^^^ random (possibly large) value

A strong indication that this is indeed the cause is the fact that the address of the fault 0x7ffe7f60ead8 is very close to the end of the positive part of the virtual address space, which is where most 64-bit OSes allocate the stack area of the main thread.
Always compile with -Wall in order to get back as many diagnostic messages from the compiler as possible.


text:
Q: Error in CardView I want to create CardView layout but I getting this type of error.....
also give me suggestion  if any library or any jar file add in to project ..
code or error is here....
error
03-08 00:10:05.836: E/AndroidRuntime(3916): FATAL EXCEPTION: main
03-08 00:10:05.836: E/AndroidRuntime(3916): Process: com.test.cardview, PID: 3916
03-08 00:10:05.836: E/AndroidRuntime(3916): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.cardview/com.test.cardview.MainActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.CardView

xml file..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:gravity="center_horizontal"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_marginTop="20dp"
        android:layout_width="200dp"
        android:layout_height="100dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardBackgroundColor="#C92A2A">

        <TextView
            android:id="@+id/info_text_header"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/sample_text_header" />

        <ImageView
            android:id="@+id/info_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/sample_text_image"
            android:layout_gravity="center"
            android:layout_marginTop="2dp"
            android:src="@drawable/ic_launcher" />

        <TextView
            android:id="@+id/info_text_footer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="80dp"
            android:text="@string/sample_text_footer" />
    </android.support.v7.widget.CardView>

</LinearLayout>

A: Remove the below in your CardView as its already declared.
xmlns:card_view="http://schemas.android.com/apk/res-auto"

It should just be:
.............................
<android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_marginTop="20dp"
        android:layout_width="200dp"
        android:layout_height="100dp"
        card_view:cardCornerRadius="8dp"
        card_view:cardBackgroundColor="#C92A2A">
.................

A: Make sure you have added the appcompact library for cardview

redpajama_set_name: RedPajamaStackExchange


text:
Q: \n newline character is ignored by java I'm writing to a txt file and I'm appending \n (newline character). the character is shown clearly in System.out.println. but this character is not shown in the textfile. therefore, the textfile is composed by only one long line

A: What operating system are you using? If you're using Windows, try "\r\n" - or (more universally), System.getProperty("line.separator")


text:
Q: Display the sub-subcategories of the current subcategories in Woocommerce I'm trying to Show sub-subcategories under current subcategory in Woocommerce like this Website.
I've 2 parents categories "Products" and "Sectors". Then I've a menu link that go to both.
When I'm in "Products" I want to see the picture of the subcategory, the title of category and then all the sub-subcategories with the title and link to them.
For Example, the parent category is "Products", Construction is the subcategory, and Sealants & adhesives, waterproofing, plyurethane foams… are sub-subcategories.
Sealants & Mastics is the subcategory, and ACETIC SILICONE SEALANT, NEUTRAL SILICONE SEALANT, ACRYLIC SEALANT… are sub-subcategories…
Here is a screenshot that explains it better:

A: The code to be used in here is very similar to your previous question thread. But we use a specific action hook with some few changes to get the sub-subcategories of the subcategories:
// Displaying the sub-subcategories of the current subategories
add_action('woocommerce_after_subcategory', 'display_subsubcategories_list', 20, 1 );
function display_subsubcategories_list( $category ) {
    $taxonomy = 'product_cat';

    // Get sub-subcategories of the current subcategory
    $terms    = get_terms([
        'taxonomy'    => $taxonomy,
        'hide_empty'  => true,
        'parent'      => $category->term_id
    ]);

    if( count($terms) > 0 ) :

    echo '
';

    // Loop through product sub-subcategories WP_Term Objects
    foreach ( $terms as $term ) {
        $term_link = get_term_link( $term, $taxonomy );

        echo '
slug .'" style="border-bottom: solid 1px #ddd;">'. $term->name .'
';
    }

    echo '
';

    endif;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Notes: The woocommerce_after_subcategory action hook is located on content-product_cat.php template file, which handle subcategories to be displayed as products are (with an image and a linked term name).
  For that your main categories needs to have the option "Display type" set on "Subcategory".


text:
Q: Unable to import self-made classes into IntelliJ GUI designer form's corresponding class I am currently unable to use any classes that I have written into the IntelliJ GUI Designer form's corresponding class unless they are within the same package. I already invalidated IntelliJ's caches with no change. Anyone know what's going on here?

EDIT: Crud. Anything within the maingui package cannot view any self-made classes outside of it now.

A: Changing the source folder to a generic package and back to the source folder fixed it. Don't ask me why. I don't know.


text:
Q: How to print part of value in json data by using dart right now I am working in dart. I have json data like this:
{
  "name":"firstName lastName",
  "address": "myAddress"
}

I wanna ask...is there a possibility to print only firstName without lastName?

A: var name = data['name'];
var firstName = name.split(' ')[0];


text:
Q: Convert Timestamp to_datetime() and aggregate by year and month, Pandas, Python I have a DF, with timestamps that I converted to datetime(), and I want to create a Python table to aggreagate by month and year, but I get the following error:
ValueError: Duplicated level name: "TimeStamp", assigned to level 1, is already used for level 0

flowData =pd.read_csv('...')

flowData["TimeStamp"] = pd.to_datetime(flowData["TimeStamp"])

pv = flowData.pivot_table(index=flowData['TimeStamp'].dt.month,columns=flowData['TimeStamp'].dt.year, values='Value', aggfunc=np.mean)
pv.head()

Could you please help me?

A: Try renaming the indices:
pv = (flowData.pivot_table(index=flowData['TimeStamp'].dt.month.rename('month'),
                           columns=flowData['TimeStamp'].dt.year.rename('year'),
                           values='Value', aggfunc=np.mean))


text:
Q: RSA (client side encryption/ server decryption) This is a continuation of the project in this question, but without the Bouncy Castle.
So I decided to scrap Bouncy Castle (pity, I loved the name)
ANYWAY
I have a server and a client. the client needs to send a serialized object to the server, the server will then process this object.
It does this, however I'd like to add encryption to the process. But without storing a file or anything like that. the process needs to be session based(in a sense)
So, the client will request a key from the server, the server will generate a key pair and send a key to the client.
Client then uses this key to encrypt the object
string key = ASCIIEncoding.ASCII.GetString(RequestKey(tcpclnt));
var RsaClient =new RSACryptoServiceProvider(2048);
while (key.Length > 0) {
     RsaClient.FromXmlString(key);
     var transmit = ASCIIEncoding.ASCII.GetBytes(stringtosend);
                  var encrypted = RsaClient.Encrypt(transmit,false);

the server then receives these encrypted bytes and tries to decrypt them
 raw = Receive(clientSocket);
 byte[] r = TrimBytes(ASCIIEncoding.ASCII.GetBytes(raw),256);
 var sdecrypted = ASCIIEncoding.ASCII.GetString(RsaServer.Decrypt(r, false));

But alas, the server can't do this. On Decryption it throws an error
Key does not exist.

So, my question is, what am I doing wrong?
Many thanks in advance for any help you can offer.

UPDATE

Altered the code in the server
var RSAKeyInfo = new RSACryptoServiceProvider(2048, new CspParameters(1)).ExportParameters(true);

New error
The parameter is incorrect

A: Whilst fine as an exercise in the use of cryptography, the use of basic cryptographic algorithms to build your own system for secure communication is a recipe for insecurity. For every weakness you address in your own system, there are likely 10 (or more!) that you won't even have thought of.
My strong suggestion therefore is to use SSL/TLS to secure your communications. This should provide all the security you need whilst also being straightforward to integrate as the .NET Framework's SslStream has the necessary functionality to operate as either the server or client side of the connection.
Doing this will also allow you to optionally use additional security mechanisms in the future, e.g. certificate based client authentication, with minimal additional effort.


text:
Q: Call method on form when I click on my UserControl I created my own button. Not standard, it's a PictureBox with two pictures inside. I need to a call method in form which will turn my picture left (the method is complete and this picture is in a pictureBox on form). I tried userControl1.Click, but nothing happened.
I think it must be an event on pictureBox inside my own UserControl, but I don't know how to call method which is in my form.

A: You have to subscribe to the event. Take a look at this doc; http://msdn.microsoft.com/en-us/library/ms366768(v=vs.80).aspx
If you make it so your method to rotate the picture subscribes to the Click event on the picture element then that code will get invoked anytime the picture is clicked.

A: open the designer, click on your button.  Look over at the properties window, that describes your button.  At the top, there should be a lightning bolt looking icon.  click that, and you can see events for the button.  you need a method in there, that links the button to the event.  To see the code that's involved, open up the designer code and locate your picture box after adding it.
To see if it worked, try adding MessageBox.Show("Test") inside the click function.
---Oops this doesn't apply to you, but may be useful information--
Or, if you want the short way that doesn't explain much, double click your button in the designer  and it should create the Click() event for you.

A: Try this:
public class YourUserControl : UserControl {
     public YourUserControl(){
        InitializeComponent();
     }
     private void pictureBox_Click(object sender, EventArgs e){
        //your code for pictureBox_Click
        OnClick(e);//This is needed if you want to register some Click event handler from ouside your UserControl.
     }
}

I think you don't need to use a UserControl here, just use a PictureBox like this:
public class MyButton : PictureBox {
    public MyButton(){

    }
    //
    protected override void OnClick(EventArgs e){
        //Your code here
        //base.OnClick(e);
    }
}


text:
Q: How to capture live traffic on a remote Linux server and how to view it in Wireshark on the local Windows machine? This is related to this question: How to Capture Remote System network traffic?
I would like to be able to export live traffic captured on a Linux server and to view that in real time on my Windows machine.
Please do not suggest SPAN or RSPAN because it does not apply to my needs. This is about internal traffic (VM traffic) that tshark can see without any problems, I would just like to watch the traffic on my desk (Windows machine) with Wireshark

A: You should use the tool rpcapd in the machine (A) that you want to capture the traffic:
rpcapd -n -p <port>

With -n is launched without authentication
Finally, in the other machine (B) go to Wireshark > Capture > Interfaces > Options > Manage Interfaces > Remote Interfaces
And you should see the traffic of Machine (A)

A: I think that the only viable way to do it is to use Wireshark with X11 remote desktop. VNC may also work but you don't really use the Windows System resources to display the results, everything is still processed on the Linux server.


text:
Q: Definition query that returns based on date in arcgis I was wondering if anyone knew how to build a definition query in Arcmap 10.0  that returns only features that are f.e. only 7 days old.
I have a SDE geodatabase with polygons, each with a "date"-field (format yyy-mm-dd). I would like to select these features based on their age:

Output 1 ;  Last 7 days
Output 2 ;  Last 14 days
Output 3 ;  Last 30 days
Output 4 ;  Last year
....

Thanks in advance

A: This works on an SDE/Oracle database - select the dates within the last year you can do something like this:
ACQUIREDATE > ADD_MONTHS(SYSDATE, -12)

or last 7 days
ACQUIREDATE > SYSDATE - 7


text:
Q: Set backcolor for specific cell in gridview in VB.net Visual Studio I have a fixed size grid and would like to specify the backcolor of specific cells within the grid, so not whole rows and not whole columns just a single cell or maybe a range of cells. Please see the screenshot below for and example of what I mean.
Ideally I would like to do this via vb as I would ultimately like to alter the backcolor based on values selected from a dropdown list.

Edit:
Based on the answer below I modified it until I got the below which worked.
GridView.Rows(n).Cells(n).BackColor = Drawing.Color.FromArgb(n, n, n)

A: Assuming you are creating a windows forms application, you can use the DataGridView.  It allows individual cells to be styled using the following property:
dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Red


text:
Q: How do I see all foreign keys and primary keys in SQL Server Management System In SQL Server Management System, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as this Oracle question, but for SQL Server Management System.
Also How do I see all primary keys of all tables.

A: You can use following
EXEC sp_fkeys 'yourTableName'

A: You can select the tablename in the query in management studio and press ALT+F1 then it display all keys and index on that table


text:
Q: Laravel: Get model attributes by key array I'm attempting to access a models attributes by an array of keys. The desired functionality would work something like $model->getAttribute('name'), but accept an array instead of a string.
Let's say we had a model with attributes name of 'A', age of 2 and blood_type of 'B'.
$attributesToPull = ['name', 'age'];
$model->getAttributes($attributesToPull);

// returns ['A', 2]

I've checked through the Laravel docs and cant find anything that quite fits.
The results dont need to come straight from the model, they can be pulled into their own associative array using $model->getAttributes() and then have a native PHP array function such as array_intersect to filter the results, but even then I can't seem to find a function that will allow me to filter an associative array with an indexed array.
Does anyone know how I could go about this, ideally without using a loop or a callback? The answer can be pretty open, it can return a collection or an array and use either the associative array of the model attributes or call a function on the model itself.

A: The Model has a only method:
$model->only($attributesToPull);


text:
Q: Filter out results and answers that involve jQuery Is there any easy way in Stack Overflow to filter out all solutions that involve jQuery. Due to licensing restrictions I only want to view solutions that use pure JavaScript.

A: Yes, you can search text and filter by tags and try to find the answer you need.

*

*To look for a tag use: [tagName]

*Too exclude a tag use the minus before it: -[tagName]
If you don't find the answer you are looking for, post a new question and specify you want Vanilla JS  in the solution.
In the right upper corner you can find a search field, if you use [javascript] you will get postes tagged javascript. You can also combine like [javascript] for loop.
Another way is to click the tags on the right column of Stackoverflow.

*

*About the MIT license you can read more here

*You can find more info about Advanced Search here


text:
Q: Response.Redirect doesn't work in .net 4 where used on http://localhost:8692/Contacts/Default.aspx
Response.Redirect("http://www.google.com") redirects to http://localhost:8692/Contacts/http%3a%2f%2fwww.google.com
The problem just appeared once I upgraded to .Net 4
Edit: Response.Redirect("~/Contacts/MemberDetails.aspx?Id=3") goes to http://localhost:8692/Contacts/%2fContacts%2fMemberDetails.aspx%3fId%3d1
I found one mention of this on the web but no solution and it was for the release candidate http://forums.asp.net/t/1527814.aspx

A: Are you using the Ajax Control toolkit at all?  Same issue was happening to me and the fix was to download the toolkit for the .net 4.0 version.  I was using the ToolkitScriptManager which might have been the ultimate problem, but the new Ajax Toolkit for .net 4.0 seems to have solved it!

A: I was getting this same issue in the form of an extra encoded forward slash as a suffix for table.ListActionPath.
Very annoying but it had to do with the Ajax toolkit 3.5 -4 upgrade requirement mentioned above.


text:
Q: React Native : Access to component ref child in FlatList I'm not able to access to component ref child in FlatList. On componentDidMount method, I've only one ref for the FlatList.
Here is my code in case you want to reproduce it:
import React, { Component } from "react";
import {
  AppRegistry,
  FlatList,
  StyleSheet,
  Text,
  View
} from "react-native";

export default class touchable extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          ref="REF-FLATLIST"
          data={[{ key: "a" }, { key: "b" }]}
          renderItem={({ item }) =>
            <Text ref={`REF-FLATLIST${item.key}`}>
              {item.key}
            </Text>}
        />
      </View>
    );
  }
  componentDidMount() {
    console.log(this.refs);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  }
});

AppRegistry.registerComponent("touchable", () => touchable);

I'm using React Native v0.45.1.

A: you can set it the ref using the ref callback this way:

import React, { Component } from "react";
import {
  AppRegistry,
  FlatList,
  StyleSheet,
  Text,
  View
} from "react-native";

export default class touchable extends Component {
  render() {
    return (
      <View style={styles.container}>
        <FlatList
          ref="REF-FLATLIST"
          data={[{ key: "a" }, { key: "b" }]}
          renderItem={({ item }) =>
              <Text ref={(ref) => this.textRef = {...this.textRef, [`REF-FLATLIST${item.key}`]: ref}}>
                {item.key}
              </Text>}
            />
          </View>
    );
  }
  componentDidMount() {
    console.log(this.refs, this.textRef);
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF"
  }
});


text:
Q: How to keep two master lines? My situation:
I'm coding on a project, called project, now it's half-done.
But at this moment, I'm asked for another project, called project-cn, 80% same as project, but there are still different features to be develop.
My solution for now:

*

*new branch master-cn from master branch of project;

*develop the unique features of project-cn under master-cn;

*checkout back to  master branch, develop new common feature of both;

*Manual copy the new feature modify to the master-cn.

My expectations:
           project-hk
             /   \
            /     \
       master   master-cn
         /           \
        /             \
add feature-hk-1     add feature-cn-1
     |                    |
     |                    |
add feature-hk-2     add feature-cn-2
     |                    |
     |                    |
     |    feature-both    |
     |      /      \      |
     |merge/        \merge|
     |    /          \    |
     |   /            \   |
     |  /              \  |
     | /                \ |
   master              master-cn

My Question:
What should I do ? And where is the feature-both from ? A new branch ? Base on where?

A: I think it's a good idea to maintain both a master branch and a master-cn branch.
Only make commits on master that can live on both branches. After you add a feature on master merge it into the master-cn branch.
Eventually, when master-cn is finished, merge it back into master so master effectively becomes feature-both.
For this step:

Manual copy the new feature modify to the master-cn.

I would do this:
git checkout master-cn
git merge master

BUT, if there are commits on master that simply cannot go to master-cn yet you may want to cherry-pick individual commits over:
git checkout master-cn
git cherry-pick a2j233 # sha
git cherry-pick vsdd3f # sha


text:
Q: What is the longest coherence length stimulated-emission beam demonstrated? Originally I was going to put "laser" in the title, but didn't want to restrict wavelength (e.g. masers). I did put "beam" in the title, since there may be highly stable oscillators that are also quite isolated, and I'd like to exclude those for this question.
In this Wikipedia article on Coherence Length it mentions a fiber laser with a coherence length of the order of 100km (yes 100,000 meters, not a typo). The article mentions a bandwidth of a few kHz and that number does get you to that length, and fiber lasers certainly can be collimated to form beautiful beams.
But there is no citation for this measurement in the article as of this moment, and I'm surprised because most laser-related articles used to be curated fairly carefully.
My question "What is the longest coherence length beam demonstrated?" also has the word "demonstrated". Of course it could be a coherence time, or a frequency spread converted to length. They are all roughly the same thing. No not exactly, and please don't open up a long discussion here. If the spread in frequencies has some characteristic width that can be defined in some way, then so will the wavelengths, in this context.
I added "stimulated emission" to the title to be sure to exclude something like a radio transmitter with directional antenna, or it's (in the not so distant future) optical nanoantenna equivalent. I'm looking for beams based on quantum transitions within naturally occurring systems. Thanks!
I thought I remembered seeing HeNe coherence lengths of 1km in catalogues, but now all I see are the 100m values as mentioned in the article. What got me thinking about this is the mention of coherence in this answer to Taking detailed photos of satellites using laser illumination.

A: "Coherence length" is not necessarily a clearly defined term. A laser source can have phase jitter but still have a very large coherence length, as long as the phase jitter is periodic or very small. A laser whose cavity has a fixed given length may emit multiple wavelengths corresponding to different longitudinal modes, resulting in what appears to be a relatively short coherence length of a few centimeters.  However, in a two-path interferometer such as a Mach-Zehnder interferometer, it is easily seen that the fringe contrast (a measure of coherence) is a slowly decaying periodic function of twice the laser's cavity length.
A bit of thought reveals that the absolute coherence length of the laser (the path length difference at which fringe contrast drops to 50%) really depends on the Q of the cavity: the average number of times a photon bounces between the two mirrors of the cavity before it makes its way through one of the mirrors.  The longer a typical photon stays in the cavity, the longer the laser's absolute coherence length.
A laser's coherence length can be increased at least two ways: by increasing the reflectivity of the cavity mirrors (to increase the Q), and by increasing the length of the cavity.  In graduate school I was involved in a project in which a laser was constructed with a kilometer-length cavity. (It was used to monitor stretching of the Earth's surface.)  We never measured its coherence length, but its Q was probably around 100, which would have given it a coherence length on the order of tens of kilometers.
But if coherence length is defined in terms of fringe contrast in an interferometer with unequal path lengths, there is another way to increase coherence length: by phase locking.  Two separate lasers can be made mutually coherent by interfering their beams and continuously adjusting the cavity length of one of the lasers to maintain a nearly-zero phase difference between the two beams.  The frequency of the pair of lasers may drift, but the difference between their frequencies - and their phases - will be nearly zero.
If the two beams come from the same laser, but in the interferometer one beam traverses a very long path before being combined with the other beam, it is possible to continuously adjust the laser cavity to maintain a zero phase difference, even if there is a slow or periodic drift in the laser's emission frequency.  But the combined beam will always produce high contrast fringes in a downstream interferometer, as long as the path length difference in the second interferometer matches that in the first interferometer.
The combined beam from such a laser will behave as if it is emitted by a laser whose cavity length is equal to the difference D between the two paths in the first interferometer: the coherence will be a slowly decaying periodic function of D which can stretch out to many times D.  The decay rate of the periodic function depends on how close to zero the phase difference between the two paths can be maintained (in practice, better than 0.00001 radians).
This means that it is possible (in principle) to make a laser whose coherence length is light-years long, in that the phase difference between the light emitted now and the light emitted years ago from the same laser is maintained at zero.  In practice, the long path in the first interferometer can be down a coiled length of optical fiber, as long as the attenuation coefficient is small enough that a reliable signal can be received at the other end of the fiber.  The lowest attenuation coefficient of an optical fiber is around 0.22 dB/km, which means that a fiber can be as long as 100 km and still conduct a reliable signal.  So, a coherence length (per this definition) of around 1000 km is readily achievable.

A: I think the coherence length depend on the power that you want from that laser, the frequency profile of it and the loss in your optical fiber. Also you can use repeaters to increase the coherence length. Usually in laser industry to increase the coherence length people using the brag grating. It could help us having single frequency with long coherence length in vacuum but as it decrease the power significantly it's not always welcome by laser industry for the optical fibers.
For long distance quantum communication it is better to use entangled photons sources.
If you want to know more about the quantum coherency take a look at this article and some of it's references:
https://arxiv.org/abs/0710.1143

A: An atomic clock consists of a source such as a laser or a microwave source (called a local oscillator) and an atom-based measuring technique. For example, the laser or microwave source is used to stimulate a transition in the atom, or in a cloud of atoms. Depending on the atomic response, the laser or microwave source is then adjusted, so as to keep it in step with the atoms.
The result of all this is that the laser or microwave source becomes frequency-stable on long timescales---that is, timescales larger than those required to probe the atoms. But frequency stability is the same thing as coherence time which in turn gives rise to coherence length. Suppose, for example, that the clock drifts by one second in one hour. This means that its relative frequency stability is approx $3 \times 10^{-4}$ and if its frequency is $12$ GHz then its linewidth will be $3$ MHz and coherence length 90 metres.
The best atomic clocks currently attain a relative precision of order $10^{-18}$, using an optical transition of frequency around $10^{15}$ Hz. That translates to a linewidth of 1 millihertz and a coherence length of $3 \times 10^{11}$ metres. The linewidth of a microwave-based clock can be lower still (even if its relative precision is not quite so good).
It might be objected that these very long coherence lengths are not quite what the question was about. But I think they do represent a legitimate example of the concept of coherence length. One can send out a signal from a frequency-standard laboratory, a signal such as a laser beam or other oscillation, in such a way that two people separated by $10^{11}$ metres will receive oscillations with a non-random phase relationship. They could, for example, recombine their two signals by sending them on to a third party, and the third party could observe interference between the signals. But since that is the definition of coherence, it means that this is indeed a form of temporal coherence and thus a coherence length.
Having said all this, I remain a little uneasy about whether the concept of coherence length is really the most helpful one in such cases. Orbiting bodies in astronomy remain regular over millions of years. This implies that they emit gravitational waves with coherence length of the order of millions of light years (I think---happy to be corrected!)


text:
Q: After upgrade MongoDB it does not start and log is empty Can you help me with this problem please? I have updated (apt-get upgrade) my system Debian GNU/Linux 7.6 (wheezy) but for problem with disk space operation failed. After I have released disk space, but MongoDB does not start. I have tried several procedures.
First apt-get --purge remove mongodb-org:
invoke-rc.d: unknown initscript, /etc/init.d/mongod not found.
dpkg: error processing mongodb-org-server (--configure):
 subprocess installed post-installation script returned error exit status 100
Errors were encountered while processing:
 mongodb-org-server
E: Sub-process /usr/bin/dpkg returned an error code (1)

In /etc/init.d/ was:
mongod -> /lib/init/upstart-job

I removed this and replace it with mongod from other mongoDB installation from other system. Then uninstallation was correct.
After I run apt-get install -y mongodb-org but it failed with:
invoke-rc.d: unknown initscript, /etc/init.d/mongod not found.
dpkg: error processing mongodb-org-server (--configure):
 subprocess installed post-installation script returned error exit status 100
Setting up MongoDB package-org-Mongos (2.6.4) ...
Setting up MongoDB package-org-tools (2.6.4) ...
dpkg: unmet dependencies prevent configuration package MongoDB-org:
  MongoDB-org depends on MongoDB-org-server; but:
   MongoDB package-org-server is not configured yet.

In /etc/init.d/ was:
mongod -> /lib/init/upstart-job
mongod.dpkg-bak

I removed mongod and renamed mongod.dpkg-bak to mongod. Then installation was correct. But MongoDB does not start.
Reading package lists ... Done
It creates a dependency tree
Reading state information ... Done
MongoDB-org is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
2 not fully installed or removed.
After this operation will be used to drive other 0 B.
Setting up MongoDB package-org-server (2.6.4) ...
[FAIL] Starting database: mongodb failed!
invoke-rc.d: initscript mongod, action "start" failed.
dpkg: error processing MongoDB-org-server (--configure):
subprocess installed post-installation script returned error exit status 1
dpkg: unmet dependencies prevent configuration package MongoDB-org:
MongoDB-org depends on MongoDB-org-server; but:
MongoDB package-org-server is not configured yet.

dpkg: error processing MongoDB-org (--configure):
   dependency problem - leave it unconfigured
Errors were encountered while processing:

MongoDB-org-server
  MongoDB-org
  E: Sub-process /usr/bin/dpkg returned an error code (1)
If I run service mongod start:
[FAIL] Starting database: mongodb failed!

But /var/log/mongod/mongod.log does not contain any entries from this time.
Thank you very much for help.
dpkg-query -l "MongoDB-org *" output:
+++-=================================-=====================-=====================-=======================================================================
    iU  mongodb-org                       2.6.4                 i386                  MongoDB open source document-oriented database system (metapackage)
    ii  mongodb-org-mongos                2.6.4                 i386                  MongoDB sharded cluster query router
    iF  mongodb-org-server                2.6.4                 i386                  MongoDB database server
    ii  mongodb-org-shell                 2.6.4                 i386                  MongoDB shell client
    ii  mongodb-org-tools                 2.6.4                 i386                  MongoDB tools
    un  mongodb-org-unstable              <none>                                  (no description available)
    un  mongodb-org-unstable-mongos       <none>                                  (no description available)
    un  mongodb-org-unstable-server       <none>                                 (no description available)
    un  mongodb-org-unstable-shell        <none>                                  (no description available)
    un  mongodb-org-unstable-tools        <none>                                  (no description available)

dpkg --configure mongodb-org-server mongodb-org:
Setting up mongodb-org-server (2.6.4) …
[FAIL] Starting database: mongodb failed!
invoke-rc.d: initscript mongod, action "start" failed.
dpkg: error processing mongodb-org-server (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: unmet dependencies prevent configuration package MongoDB-org:
MongoDB-org depends on MongoDB-org-server; but:
MongoDB package-org-server is not configured yet.

dpkg: error processing MongoDB-org (--configure):
dependency problem - leave it unconfigured
Errors were encountered while processing:
MongoDB-org-server
MongoDB-org

dpkg --configure --force-depends mongodb-org-server mongodb-org:
Setting up mongodb-org-server (2.6.4) …
[FAIL] Starting database: mongodb failed!
invoke-rc.d: initscript mongod, action "start" failed.
dpkg: error processing mongodb-org-server (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems, but configuring as per your requirement:
 mongodb-org depends on mongodb-org-server; however:
  MongoDB package-org-server is not configured yet.

Setting org-package MongoDB (2.6.4) ...
Errors were encountered while processing:
 mongodb-org-server

A: Option 1:
As you seem to have half-configured mongodb-org-server and unpacked but (not configured) mongodb-org, please try the following command:
dpkg --configure mongodb-org-server mongodb-org

If also that fails for dependency issues, try this:
dpkg --configure --force-depends mongodb-org-server mongodb-org

Option 2:
As package configuration doesn't seem to get done ok in your case, I'd suggest next to try to clean up the system of the previous installation and then do a fresh install. However, the following is pretty rough way of doing it and I suggest you to first read it through and keep in mind that I haven't actually tested it.
First, obtain the list of files installed by the mongodb-org packages:
dpkg-query -L mongodb-org mongodb-org-server mongodb-org-mongos mongodb-org-shell mongodb-org-tools | grep "^\/[^\.]" > mongo.files

Then, do validate the contents of mongo.files (to make sure it only contains paths that are ok to be deleted) by doing:
less mongo.files

Then, remove those files from the system by issuing:
 rm `cat mongo.files`

Next it is time to tell the package manager that those packages are not currently installed in the system by modifying manually /var/lib/dpkg/status. Before doing anything to that file, back it up in case something goes wrong (remember, we're doing surgery on the package manager internal data...). The file is formatted in sections of sequential lines of text with the sections separated by an empty line. Find out all sections in the file that begin by Package: mongodb-org and remove those up (delete all lines from the line starting with 'Package' up to the empty line). When done, save the file and run apt-get update followed by apt-get install mongodb-org.
I certainly hope that doesn't break anything and in the end you get a functioning copy of MongoDB.


text:
Q: how we can pass multiply id in laravel My view.blade.php code here
 sub_id}}">

My route code here
Route::resource('p_grid', 'BasicController@p_grid');

And my BasicController code here
public function p_grid(Request $request, $id)
{
    echo "success";
    if ($id == 1) {
        $r = DB::table('sub_category')
        ->select('*')
        ->where('cat_id', $id)
        ->where('sub_status', '1')
        ->orderBy('sub_id', 'asc')
        ->get();

        $cat_name = DB::table('category')
        ->where('cat_id', $id)
        ->get();

        $count = DB::table('products')
        ->where('sub_id', $id)
        ->count();
       return view('buy-and-sell/p_grid', compact('r','cat_name','count','id'));
    }

click on anchor tag to show this error

A: The extra parameter in your URL is causing the 404. Laravel doesn't expect the URL to have multiple id's, because you are using resourceful routing. You will need to append your routes.php file to account for this:
Route::resource('p_grid', 'BasicController@p_grid');
Route::get('p_grid/{category}/{subcategory}', [
    'as'   => 'category-with-subcategory',
    'uses' => 'BasicController@gridWithSubcategory',
]);

And make sure you have a gridWithSubcategory method in your BasicController.php file.
That said, I'd advise you to understand better what Laravel is doing when you declare Route::resource(), because I would question how much of it you really need. It's really just a shorthand for registering ordinary routes (see here for the full list and specifications) like index, create, show, destroy, etc. If you want to see the routes your app actually has, after being parsed by Laravel (including routes not in your routes.php, which could have been registered by third-party packages) type php artisan route:list on a CLI.
Finally, I'd strongly suggest using route names throughout your app for better clarity and portability. The artisan command above will give you route names, so you can use something like this in your views:
 $cat_id, 'subcategory' => $row->sub_id]) }}">

That way, if you ever want to change your route's footprint, the view won't break (as long as you maintain the parameter requirements).

A: My view.blade.php code here
 $cat_id, 'subcategory' => $row->sub_id]) }}">

My route code here
Route::get('p_grid/{category}/{subcategory}', [
    'as'   => 'category-with-subcategory',
    'uses' => 'BasicController@p_grid'
]);

And my BasicController code here
public function p_grid(Request $request, $id)
{
 echo "success";
}

success image upload and work done
enter image description here


text:
Q: init method in jersey jax-rs web service I'm new with jax-rs and have build a web service with jersey and glassfish.
What I need is a method, which is called once the service is started. In this method I want to load a custom config file, set some properties, write a log, and so on ...
I tried to use the constructor of the servlet but the constructor is called every time a GET or POST method is called.
what options I have to realize that?
Please tell, if some dependencies are needed, give me an idea how to add it to the pom.xml (or else)

A: There are multiple ways to achieve it, depending on what you have available in your application:
Using ServletContextListener from the Servlet API
Once JAX-RS is built on the top of the Servlet API, the following piece of code will do the trick:
@WebListener
public class StartupListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Perform action during application's startup
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // Perform action during application's shutdown
    }
}

Using @ApplicationScoped and @Observes from CDI
When using JAX-RS with CDI, you can have the following:
@ApplicationScoped
public class StartupListener {

    public void init(@Observes
                     @Initialized(ApplicationScoped.class) ServletContext context) {
        // Perform action during application's startup
    }

    public void destroy(@Observes
                        @Destroyed(ApplicationScoped.class) ServletContext context) {
        // Perform action during application's shutdown
    }
}

In this approach, you must use @ApplicationScoped from the javax.enterprise.context package and not @ApplicationScoped from the javax.faces.bean package.
Using @Startup and @Singleton from EJB
When using JAX-RS with EJB, you can try:
@Startup
@Singleton
public class StartupListener {

    @PostConstruct
    public void init() {
        // Perform action during application's startup
    }

    @PreDestroy
    public void destroy() {
        // Perform action during application's shutdown
    }
}

If you are interested in reading a properties file, check this question. If you are using CDI and you are open to add Apache DeltaSpike dependencies to your project, considering having a look at this answer.


text:
Q: Is is possible to add member variables to objects at runtime in Actionscript 3? I have an object of type sprite. I would like to add a new field in the sprite object without deriving the class. I'm not sure is possible.
I tried to do
 object.newField = 'value';

but it's not working.
I need it because the Api expect that field in the sprite class.

A: It is possible for objects of dynamic classes.
For example, Sprite is not a dynamic class, but MovieClip is. This will fail with "1119: Access of possibly undefined property newField through a reference with static type flash.display:Sprite":
var s:Sprite = new Sprite();
s.newField = 'value';

But this will work:
var m:MovieClip = new MovieClip();
m.newField = 'value';


text:
Q: Ajax with polymorphic association (destroy) I have a polymorphic association with Resources & Flags in my rails app. Each Resource can be Flagged by a user.
I am trying to delete resource Flags through its Edit Page. This way a user can edit a Resource, and eliminate/destroy its Flags via ajax.
Everything works fine in the database, but when I try to delete a Flag using ajax, it doesn't work unless unless I refresh the page. I am using this tutorial.
This is my code...
Models
class Resource
  belongs_to :district
  has_many :flags, as: :flaggable, :dependent => :destroy
end

class Flag
    belongs_to :flaggable, polymorphic: true
end

Controllers
Resource Controller

  #edit page
  def edit
    @district = District.find_by_abbreviation(params[:district_id])
    @resource = @district.resources.find(params[:id])
    @flaggable = @resource
    @flags = @resource.flags.all
  end

end

Flags Controller

  def destroy
    @flag = Flag.find(params[:id])
    @flaggable = @flag.flaggable
    if @flag.destroy
      respond_to do |format|
        format.html { redirect_to @flaggable }
        format.js
      end
    end
  end

end

Views
edit.html.erb - Resource Edit Page
#renders all flags associated with this resource

  <%= render @flags %>

   #Code that holds edit form

_flag.html.erb
###delete action to destroy a flag

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <%= link_to '×'.html_safe, [@flaggable, flag], method: :delete, data: { confirm: "Are you sure you want to delete this flag?" }, remote: true  %>
  </button>

  <%= flag.message %>

destroy.js.erb
###I am not sure if this is correct...
$('#flags #<%= dom_id(@flag) %>').remove();

A: I believe the problem is in your partial _flag.html.erb
It should be <div id="<%= dom_id(flag) %>"> instead of


text:
Q: react native MaterialTopTabNavigator I am trying to implement this code to my TopTabNavigator:
    const tabNavigator = createMaterialTopTabNavigator({ /* */ });
tabNavigator.navigationOptions = ({ navigation }) => {
  let activeRoute = navigation.state.routes[navigation.state.index];
  if (activeRoute.routeName === 'Offers') { // or whatever the name is
    return {
      headerRight: <SomeThingHere />
    };
  } else {
    return {};
  }
};

This is the code I have so far:
    const TopTab = createMaterialTopTabNavigator();

function MyOffersTabNavigation() {
  const {theme} = useTheme();
  return (
    <TopTab.Navigator
      tabBarOptions={{
        labelStyle: {
          fontFamily: boldFont,
          fontSize: 15,
          textTransform: 'none',
          paddingVertical: 6,
        },
        activeTintColor: theme.topTab.topTabActiveColor,
        inactiveTintColor: theme.topTab.topTabInactiveColor,
        indicatorStyle: {
          backgroundColor: theme.topTab.topTabIndicatorColor,
          height: 2,
          bottom: -1,
        },
        style: {
          borderBottomWidth: 1,
          borderBottomColor: theme.borderColor,
          backgroundColor: theme.topTab.topTabBgColor,
          borderTopLeftRadius: 30,
          borderTopRightRadius: 30,
        },
      }}
      style={{
        // backgroundColor: colorScheme === 'dark' ? '#1D2633' : mainBackgroundColor,
        backgroundColor: theme.header.backgroundColor,
        paddingTop: 10,
      }}
      screenOptions={({navigation, route}) => {
        if (route.name === 'Offers' && navigation.isFocused()) {
          isActive = true;
          if(Platform.OS === 'ios') {
            isActive = false;
          }
        } else if (route.name !== 'Offers' && navigation.isFocused()) {
          isActive = false;
          if(Platform.OS === 'ios') {
            isActive = true;
          }
        }
      }}
      barStyle={{backgroundColor: mainBackgroundColor, paddingTop: 20}}>
      <TopTab.Screen name="Offers" component={MyOffersView}  />
      <TopTab.Screen name="Offer Lists" component={MyOffersListView} />
    </TopTab.Navigator>
  );
}

Any ideas how to do this? I want to use navigationOptions in hope I can get active route of one specific tab, so I can show an Icon in header. Basically, the idea is to show icon in header only when the first (Offers) tab is active, so I figured I could create custom header for my top tabs and if first tab is active, show custom header with that icon. Thank you!

A: just add options prop to Tab's Screen where you need Icon when tab is active
<TopTab.Screen
    name="Offers"
    component={MyOffersView}
    options={{
        headerRight: () => (
            <SomeComponentHere />
        )
    }}
/>


text:
Q: Split  with a delimeter and set predetermined tags with class names using BeautifulSoup Here's my input data/file which I got by converting from docx to html. For this reason the file is "not prettyfied" html.

TABLE 1  EUR A++ AT JON DOE'S PLACE 27-06-2020

   13.30   1   Jennifer Shea (R)       27-06   29.99   Tea 1/1 Fish and chips or Salad and rice

 15.00   2   Micheal Beltran (R)     27-06   30.99   Wine    2/2 Vegan super silky puff pastry

    16.00   3   DARIUS GALLAGHER (IP)      27-06   29.99   Wine Premium    4/4 Pear pecan and blue cheese salad

 18.00   4   Ashanti Fields (R)      27-06   N/A Wine    2/0

Reading the file/data into Python (with bs4), in line 2 we see:
'\t13.30\t1\tJennifer Shea (R)\t\t27-06\t29.99\tTea\t1/1\tFish and chips or Salad and rice'

The text inside the

 tags are seperated with tabs ('\t').
I want to split each

 line content into smaller pieces (i) using '\t' as a seperator, (ii) change the element tags to table rows and (iii) set (predefined) tags with class names for each item. For example I want above paragraph line converted to:

            TABLE 1
            EUR
            A++
            AT JON DOE'S PLACE 27-06-2020

            13.30
            1
            Jennifer Shea (R)
            27-06
            29.99
            Tea
            1/1
            Fish and chips or Salad and rice

There are about 3000 more tables to loop over and the data is consistent.
So far I've managed to split every line and add into a list:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open("simplesample.html"), features="lxml")
paragraphs = soup.find_all("p")
delimeter ='\t'
total_list=[]

for i in range(len(paragraphs)):
     plist = (paragraphs[i].get_text()).split(delimeter)
     total_list.append(plist)

for i in total_list:
     print(i)
# Output
['TABLE 1', 'EUR', 'A++', "AT JON DOE'S PLACE 27-06-2020"]
['', '13.30', '1', 'Jennifer Shea (R)', '', '27-06', '29.99', 'Tea', '1/1', 'Fish and chips or Salad and rice']
['', '15.00', '2', 'Micheal Beltran (R)', '', '27-06', '30.99', 'Wine', '2/2', 'Vegan super silky puff pastry']
['', '16.00', '3', 'DARIUS GALLAGHER (IP)', '', '27-06', '29.99', 'Wine Premium', '4/4', 'Pear pecan and blue cheese salad']
['', '18.00', '4', 'Ashanti Fields (R)', '', '27-06', 'N/A', 'Wine', '2/0', '']

EDIT: Problem here is that when I use str.split() method on data I got from get_text(), I lose some format information. E.g: In the original data, on line 3 'DARIUS GALLAGHER (IP)' is actually inside  tag. But using get_text() naturally, returns only the string value. So the output becomes non-bold.
UPDATE: To clarify, I would like to keep  as they are. Except for the headers,  tags appear randomly in the data.
Questions are:

*

*Is there any bs4 method to solve this by keeping current formats, instead of splitting tags as strings and adding to list?

*From here, how can I tag list elements with predetermined tags and class names using BeautifulSoup ?

A: Without the real data it's hard to come-up with 100% correct solution, but this example can get you started (it uses only beautifulsoup module and itertools.zip_longest for filling up missing cooktable-menu entries):
from bs4 import BeautifulSoup
from itertools import zip_longest

txt = '''
TABLE 1\tEUR\tA++\tAT JON DOE'S PLACE 27-06-2020

\t13.30\t1\tJennifer Shea (R)\t\t27-06\t29.99\tTea\t1/1\tFish and chips or Salad and rice

\t15.00\t2\tMicheal Beltran (R)\t\t27-06\t30.99\tWine\t2/2\tVegan super silky puff pastry

\t16.00\t3\tDARIUS GALLAGHER (IP)\t\t27-06\t29.99\tWine Premium\t4/4\tPear pecan and blue cheese salad

\t18.00\t4\tAshanti Fields (R)\t\t27-06\tN/A\tWine\t2/0\t
'''

template_header = '''

            {table_no}
            {currency}
            {class_}
            {place_date}

'''

template_row = '''

            {time}
            {no}
            {name}
            {date}
            {price}
            {drink}
            {ppfood}
            {menu}

'''

template = '''

{header}
{rows}

'''

soup = BeautifulSoup(txt, 'html.parser')

# remove strong tags:
for strong in soup.select('strong'):
    p = strong.parent
    strong.unwrap()
    p.smooth()

all_p = soup.select('p')

table_no, currency, class_, place_date = all_p[0].get_text(strip=True).split('\t')
h = template_header.format(table_no=table_no, currency=currency, class_=class_, place_date=place_date)

all_data = []
for p in all_p[1:]:
    all_data.append(p.get_text(strip=True).split('\t'))

r = []
for time, no, name, _, date, price, drink, ppfood, menu in zip(*zip_longest(*all_data, fillvalue='')):
    r.append(template_row.format(time=time, no=no, name=name, date=date, price=price, drink=drink, ppfood=ppfood, menu=menu))

print(template.format(header=h, rows='\n'.join(r)))

Prints:

            TABLE 1
            EUR
            A++
            AT JON DOE'S PLACE 27-06-2020

            13.30
            1
            Jennifer Shea (R)
            27-06
            29.99
            Tea
            1/1
            Fish and chips or Salad and rice

            15.00
            2
            Micheal Beltran (R)
            27-06
            30.99
            Wine
            2/2
            Vegan super silky puff pastry

            16.00
            3
            DARIUS GALLAGHER (IP)
            27-06
            29.99
            Wine Premium
            4/4
            Pear pecan and blue cheese salad

            18.00
            4
            Ashanti Fields (R)
            27-06
            N/A
            Wine
            2/0

EDIT: Version without extracting  tags:
from bs4 import BeautifulSoup
from itertools import zip_longest, chain

txt = '''
TABLE 1\tEUR\tA++\tAT JON DOE'S PLACE 27-06-2020

\t13.30\t1\tJennifer Shea (R)\t\t27-06\t29.99\tTea\t1/1\tFish and chips or Salad and rice

\t15.00\t2\tMicheal Beltran (R)\t\t27-06\t30.99\tWine\t2/2\tVegan super silky puff pastry

\t16.00\t3\tDARIUS GALLAGHER (IP)\t\t27-06\t29.99\tWine Premium\t4/4\tPear pecan and blue cheese salad

\t18.00\t4\tAshanti Fields (R)\t\t27-06\tN/A\tWine\t2/0\t
'''

template_header = '''

            {table_no}
            {currency}
            {class_}
            {place_date}

'''

template_row = '''

            {time}
            {no}
            {name}
            {date}
            {price}
            {drink}
            {ppfood}
            {menu}

'''

template = '''

{header}
{rows}

'''

soup = BeautifulSoup(txt, 'html.parser')

all_p = soup.select('p')
table_no, currency, class_, place_date = all_p[0].get_text(strip=True).split('\t')
h = template_header.format(table_no=table_no, currency=currency, class_=class_, place_date=place_date)

all_data = []
for p in all_p[1:]:
    all_data.append([t.strip() for t in chain.from_iterable(t.split('\t') for t in p.find_all(text=True)) if t.strip()])

r = []
for time, no, name, date, price, drink, ppfood, menu in zip(*zip_longest(*all_data, fillvalue='')):
    r.append(template_row.format(time=time, no=no, name=name, date=date, price=price, drink=drink, ppfood=ppfood, menu=menu))

print(template.format(header=h, rows='\n'.join(r)))


text:
Q: Updating a key in a OData services I wrote the following statement to update a entry in my OData service:
PUT /HOData/library.xsodata/books('HAPI%20Hana%20Integration%20Test%20Volume%201') HTTP/1.1
Host: xxxxx
DataServiceVersion: 1.0
MaxDataServiceVersion: 2.0
accept: application/atom+xml
Content-Type: application/atom+xml

<?xml version="1.0" encoding="utf-8" ?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:g="http://www.opengis.net/gml" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
    <id>http://odata.host/unknown:</id>
    <title/>
    <updated>2014-07-17T08:26:23.939Z</updated>
    <category scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" term="HOData.library.booksType"/>
    <content type="application/xml">
        <m:properties>
            <d:title>HAPI Hana Integration Test Volume 1</d:title>
            <d:ISBN>ISBN-13: 978-0-321-71838-9</d:ISBN>
            <d:editions m:type="Edm.Int32">2</d:editions>
        </m:properties>
    </content>
</entry>

it works fine when I try update a property that is not a key of the entity. For this case the key of the entity is title. So, anybody knows if for update a key in an OData service should I do something different or this is a problem with OData V2 or still this is a problem with my service?
Thank you
Pablo

A: According to the OData spec, keys are non-updatable properties. In order to work this scenario around, you can delete the entity whose key you want to update and post a new entity with the key you wanted and other properties being identical to the other properties of the deleted entity.


text:
Q: React `value` prop on `input` should not be null I'm new to react and I got this input in my component:
<input
        type="text"
        placeholder="..."
        className="form-control"
        value={this.state.value}
        disabled={this.props.edit}
        readOnly={this.props.readOnly}
        onChange={(e) => this.state.value = e}
    />

Now if this.state.value is empty I get this warning:
Warning: `value` prop on `input` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.

But if I change my input to:
<input
        type="text"
        placeholder="..."
        className="form-control"
        value={this.state.value || ""}
        disabled={this.props.edit}
        readOnly={this.props.readOnly}
        onChange={(e) => this.state.value = e}
    />

I can't edit it anymore.

A: It should be like -
onChange={(e) => this.setState({value:e}) }


text:
Q: Getting Exit Code 127 (Command not Found) from php exec() EDIT - Adding new info at the top for visibility. The www-data user can't use the exec() command. All attempts return a 127 error.
I setup a simple script that is just this
<?php
$res = exec("echo EXEC", $res1, $res2);
var_dump($res);
var_dump($res1);
var_dump($res2);
?>

When executed via the application (which of course runs as www-data) this returns the 127 error code.
When executed via this command it runs flawlessly sudo -u root php testExec.php
When executed via this command it again returns the 127 error code sudo -u www-data php testExec.php

Original Question

I can only seem to get the error code 127 back when trying to use the exec command in php. I'm trying to use the https://github.com/rialto-php/puphpeteer package to generate pdfs and it was working flawlessly but I can't find what changed that is causing it to fail now.
I've been using /usr/local/.nvm/versions/node/v14.2.0/bin/node as the path to node but I also tried copying it here /node/v16.14.2/bin so I could give the entire directory structure execute permissions. In either/both places node is owned by www-data (the user that php runs as) and has execute permissions (755).
Running '/node/v16.14.2/bin/node' '/var/www/html/vendor/nesk/puphpeteer/src/get-puppeteer-version.js' (the initial command that puphpeteer generates) from the command line works just fine and returns the expected result "5.5.0" so node is there and executable and the get-puppeteer-version script exists.
After troubleshooting that I decided to just test exec and discovered that that doesn't work for any commands. I've tried just running exec("date"); and exec("echo EXEC") and these also return the same exit code 127.
The disable_functions ini setting is empty (confirmed via empty result from ini_get('disable_functions')). Safe mode is not enabled (confirmed via false result from ini_get('safe_mode')).
If anyone has any insight into why exec won't work at all would be great!
Environment:
Ubuntu 18.04.4
PHP 8.1

A: So after further investigation.. I found that this was indeed a permissions issue. I had double checked that node and everything in the /bin folder had appropriate execute permissions..
What I had missed (and am not sure how it got changed) was that the /bin folder itself didn't have the appropriate execute permissions. Adding those immediately fixed my issue.


text:
Q: How do to block comments in Liberty Basic? Each day has its own data, and I need to run some science stuff without using the recent data.
Basically I need to block comment it out. How is that done in Liberty Basic?

A: Liberty Basic does not support multi-line comments. it only supports these two single line formats:
'This is a comment
REM This is a comment

so the best alternative is it repeatedly type: ' + down arrow + left arrow
Some BASIC programming languages support multi-line comments like so:
/' This is
a multi-line
comment '/


text:
Q: Merging boolean results from different rows into single row I have a join query which returns multiple rows
ID    SearchID   Bool1      Bool2    Bool2
1     1          1          1        0
1     1          0          0        0
5     1          1          0        0
6     1          0          0        0
9     1          0          0        0

The first column ID can be omitted, which leaves us with
SearchID   Bool1      Bool2    Bool2
1          1          1        0
1          0          0        0
1          1          0        0
1          0          0        0
1          0          0        0

Since all the data returned applies to SearchID 1, I would like to end up with a row that will merge the results of all the boolean fields i.e.
SearchID   Bool1      Bool2    Bool2
1          1          1        0

IsButton should be 1 as there was one or more row with 1
AutoRun should be 1 as there was one or more row with 1
IsOnMain should be 0 as there was no rows with 1
but I want handle this for multiple rows that may have been returned and I want to end up with a unique row for each searchid
ID    SearchID   Bool1      Bool2    Bool2
1     1          1          1        0
1     1          0          0        0
5     1          1          0        0
6     1          0          0        0
9     1          0          0        0
3     2          0          0        0
5     2          0          0        0
3     3          0          0        0
9     3          0          0        1
etc...

SearchID   Bool1      Bool2    Bool2
1          1          1        0
2          0          0        0
3          0          0        1
etc...

Am I making sense?

A: SELECT SearchID,
       CAST(CASE WHEN SUM(CAST(Bool1 AS INT)) > 0 THEN 1 ELSE 0 END AS BIT) AS Bool1,
       CAST(CASE WHEN SUM(CAST(Bool2 AS INT)) > 0 THEN 1 ELSE 0 END AS BIT) AS Bool2,
       CAST(CASE WHEN SUM(CAST(Bool3 AS INT)) > 0 THEN 1 ELSE 0 END AS BIT) AS Bool3
FROM Table
GROUP BY SearchID

A: SELECT SearchId
     , MAX(CAST(Bool1 AS INT)) AS Bool1
     , MAX(CAST(Bool2 AS INT)) AS Bool2
     , MAX(CAST(Bool3 AS INT)) AS Bool3
FROM TableX
GROUP BY SearchId

A: If you are using a BIT data type then you can't make use of SUM or MAX function on it directly. You have to convert it first.
--Sample table
CREATE TABLE #test
(
    SearchID INT,
    Bool1 BIT,
    Bool2 BIT,
    Bool3 BIT
)
GO

INSERT #test VALUES (1,1,1,0)
INSERT #test VALUES (1,0,0,0)
INSERT #test VALUES (1,1,0,0)
INSERT #test VALUES (1,0,0,0)
INSERT #test VALUES (1,0,0,0)
Go

 SELECT
    SearchId
    ,MAX(CONVERT(INT,Bool1)) AS Bool1
    ,MAX(CONVERT(INT,Bool2)) AS Bool2
    ,MAX(CONVERT(INT,Bool3)) AS Bool3
FROM #test
GROUP BY SearchId


text:
Q: Which version of openssl should I use? Three different versions of openssl are being concurrently updated on openssl.org: 0.98, 1.0.0, 1.0.1?  What's the difference between them, and how do I go about choosing which version to use?

A: https://en.wikipedia.org/wiki/OpenSSL
Has an easy readable table in timeline order.

A: To know the difference between versions, you can look at change log of OpenSSL here.
To know how 1.0.0 is different, just see the entries below "Changes between 0.9.8n and 1.0.0  [29 Mar 2010]".
Some of the difference for example support for name constraints certificate extension.
To know the difference between 1.0.0h and 1.0.1 see Changes between 1.0.0h and 1.0.1  [14 Mar 2012].
Criteria for choosing OpenSSL version: It depends all on your use. For example, if you want to use GCM for TSL, then you need to use 1.0.0.
This change log will be helpful for you in identifying which version to use.


text:
Q: Recommended way for access webservices on domain A from domain B if A is SSO'ing into B? frontend dev here with no experience with SSO so bear with me. Keen for a high-level recommendation on the following as I can appreciate it may vary.
We've got a client setting up SSO to login to our site, and Im trying to understanding how I can safely call their webservices for user info from our domain via AJAX. Looking at their services they're asking for a User ID and Password which I dont think is usable/feasible as I assume our system would need to expose the password to the frontend which doesnt seem secure... They mentioned they could pass these via http but that doesnt seem secure either!
Is there some sort of way we can validate the webservice all via SSO or is there some other way?
Thanks

A: Further my comment, we're pushing ahead with using the shared encryption method used for our SSO (TripleDES in ECB mode) to encrypt the token in the webservice request


text:
Q: Offline encyclopedia for Ubuntu My question is concerning the latest LTS version of Ubuntu, not any of its offspring, e.g. Edubuntu, Lubuntu. I'm wondering if there is ANY way to get an offline Wikipedia on it. I work at the library in an offline situation and must have it downloaded onto the system.
I am familiar with both Kiwix and Xowa, and have ran them both offline on mac and windows, respectively.
- I have seen that Sugar linux and Archlinux offer packages for Kiwix. But has anybody been able to successfully put Kiwix onto Ubuntu?
- I had tried to install Xowa on an older version of Ubuntu (real old... 10.4 on a Power PC mac), but couldn't get Xowa on it. I am debating installing the most recent version of Ubuntu on a newer computer, but don't want to bother if I won't be able to get some version of offline wikipedia on it.
Thanks for any helpful pointers,
Kara

A: First of all you should have java installed on your system.If you don't have it, download it using this command line:  sudo apt-get install openjdk-7-jre
Now download the approprite XOWA version from here.
Then unzip it using the command(assuming that you have downloaded the 64bit version):unzip xowa_linux_64.jar
And then run it with command(assuming that you have downloaded the 64bit version):sh xowa_linux_64.sh
I think this should work.

A: This is not an application solution, but www.archive.org has plenty of EPUB, and PDF encyclopedias. It may be worth your while to download and own some of them, if you were looking for something. Although it may not contain media, and quick links as Encyclopedia Britannica and other alternatives.


text:
Q: cqlsh command not working in cassandra 2.0.8 I downloaded cassandra 2.0.8 and installed python 2.7.6 and set path of python.(also tried with 2.7.3 but)
now after starting cassandra server executing
cqlsh or python cqlsh localhost 9160
it is giving me error of
Unsupported CQL version: Provided version 3.1.1 is not supported by this server

(supported: 2.0.0, 3.0.1)
so am i doing something wrong over here?
i am using jdk7

A: Try the following command:
cqlsh --cqlversion=3.0.1 localhost 9160

A: That symptom looks like the case where an older 1.x Cassandra server is actually starting, rather than the 2.0.8 you downloaded. See [CASSANDRA-6049] Cassandra 2.0.0 distribution - CQL supported versions issue - ASF JIRA for an example.


text:
Q: I have deleted my .android keystore but I didn't use it, how do I generate a new one? I used keystore for the first time in a random app I made to as my first ever flutter app but now I am making an actual app and I would like to sign it with the keystone. I could not remember the password and so I just deleted the file hoping I could make a new one but now I cannot find instructions on how to generate an android flutter keystore.
Does anyone know how I could make one?

A: Use this command
keytool -genkey -v -keystore C:\upload-keystore.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias upload
You can find your keystore in C directory. Or change the location as your wish.
Refer Here


text:
Q: Came across weird javascript operation I am working on a project, designed by someone else. I came across the following operation. I have no idea what it is doing. It seems to be returning 1.
Anyone care to elaborate?
Thank you!
   ( 7  > 8?2:1)

A: You're looking at the Ternary Operator.
It consists of (condition) ? (expression1) : (expression2). The entire expression will evaluate to (expression1) if (condition) is true, and (expression2) if (condition) is false.
var i = (7 > 8 ? 2 : 1);

translates into
if (7 > 8)
{
  i = 2;
}
else
{
  i = 1;
}

A: See: http://en.wikipedia.org/wiki/%3F:
Your example would return 2 if 7 > 8, or 1 otherwise.

A: ? : is a ternary operator.  This is equivalent to
var x = 0;
if (7 > 8){
  x = 2;
} else {
  x = 1;
}

It is a terse way of expressing simple conditional statements.  It is a great way to conditionally assign values to a variable without the verbose semantics used above.


text:
Q: VBScript receives syntax error when trying to run SQL I have a vbscript that runs a SQL Server script against a database. The script creates a bunch of foreign keys. It works fine if you log into SQL Server Management Studio, choose the correct database from the dropdown menu, copy and paste in the query, and click run.
However, using this VBScript, I receive a syntax error every time:
Function runSQL()
  Set objSQLConnection = CreateObject( "ADODB.Connection" )
  Set objSQLData = CreateObject( "ADODB.Recordset" )

  SQLConnectionString = "driver={SQL Server};server=.;Trusted_Connection=yes;database=MyDB"

  objSQLConnection.Open SQLConnectionString

  query = objFSO.openTextFile("MyScript.sql", 1, 0, -2).readAll()

  objSQLData.Open query, objSQLConnection

  objSQLConnection.Close
End Function

The exact error is Microsoft OLE DB Provider for ODBC Drivers: [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'GO'. It's not particularly helpful because there are a jillion GOs in the file.
There's nothing special about the SQL file. It just creates a jillion foreign key constraints. What is going on? I am at wit's end. Potentially relevant is that I had a difficult time reading the file (hence the openTextFile("MyScript.sql", 1, 0, -2)).

A: GO si not a T-SQL statement, it's what is called a batch separator. It is understood by tools such as SQL Server Management Studio or command line tool sqlcmd.exe.
 It's used to separated statements to be sent to the database engine. In SSMS, for instance, you can use it to show some feedback with PRINT in between batches, useful for long running scripts with multiple batches.


text:
Q: Unable to install package Sleuth in R I've been trying to install the Sleuth package in R all morning and it keeps giving me errors. This is how I tried to install it:
if(!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("DESeq2")

BiocManager::install ("rhdf5")
install.packages("devtools")
devtools:: install_github("pachterlab/sleuth")

I did use the library() command.
I get the following error messages:
Error: object 'h5write.default' is not exported by 'namespace:rhdf5'
Execution halted
ERROR: lazy loading failed for package 'sleuth'

*

*removing 'C:/Users/31625/OneDrive/Documents/R/win-library/4.1/sleuth'

A: I was having the same issue and found that there's current an open issue on Github discussing this problem.
Currently there is a workaround which was shared in the same issue on Github:

*

*Run git clone https://github.com/pachterlab/sleuth

*Remove the last line in ./sleuth/NAMESPACE which is the h5write.default that raises the error during installation - ignore the warning in the first line

*Then in R: devtools::install('./sleuth/')
It worked for me while using Linux - ZorinOS and R 4.1.2 but it should work on Windows as well.
Someone also opened a PR to fix the whole issue but it seems they are not updating the package anymore (unfortunately).


text:
Q: How to validate class parameters in __init__? I've been searching a lot for this type of problem, haven't found a single similar question on SO yet.
I have tried using a for loop to put some validation in the train's init that would disregard those passengers although with no success.
tl;dr - How do I validate which passengers will be in the passengers list when I know that some of the passengers in the passengers list are ineligble to be in the train, due to seat_nr out of range or the carriage_nr out of range.
"""Train."""

class Train:
    def __init__(self, passengers: list, carriages: int, seats_in_carriage: int):

        #--Insert validation for passengers allowed on train--#

        self._passengers = passengers
        self._carriages = carriages
        self._seats_in_carriage = seats_in_carriage

    @property
    def passengers(self) -> list:
        return self._passengers

    @property
    def carriages(self) -> int:
        return self._carriages

    @property
    def seats_in_carriage(self) -> int:
        return self._seats_in_carriage

    def get_seats_in_train(self) -> int:
        return self._seats_in_carriage * self._carriages

    def get_number_of_passengers(self) -> int:
        return len(self._passengers)

    def get_passengers_in_carriages(self) -> dict:
        return {}

    @passengers.setter
    def passengers(self, value_list: list):
        self._passengers = value_list

    @carriages.setter
    def carriages(self, value: int):
        self._carriages = value

    @seats_in_carriage.setter
    def seats_in_carriage(self, value: int):
        self._seats_in_carriage = value

class Passenger:
    def __init__(self, passenger_id: str, seat: str):
        self.carriage_number = seat.split("-")[0]
        self.seat_number = seat.split("-")[1]
        self._seat = seat
        self._passenger_id = passenger_id

    def __dict__(self):
        if str(2) >= self.seat_number > str(0) and self.carriage_number <= str(3):
            passenger_dct = {'id': str(self._passenger_id), 'seat': str(self._seat)}
            return passenger_dct

if __name__ == '__main__':
    passengers = [
        Passenger('test', '1-2'),   #--"test"= passenger_id, "x-y" : x= carriage_nr, y= seat_nr// valid
        Passenger('test2', '2-3'),  #-- invalid, seat_nr=3, train carriage has only 2 seats.
        Passenger('test3', '4-2'),  #-- invalid, carriage_nr = 4, train only has 3 carriages.
        Passenger('test4', '3-2'),  #-- valid
        Passenger('test5', '1-1'),  #-- valid
        Passenger('test6', '1-0'),  #-- invalid, no seat_nr 0 on train carriage
    ]
    assert passengers[0].__dict__() == {'id': 'test', 'seat': '1-2'}

    t = Train(passengers, 3, 2)  #--passengers list, number of carriages, number of seats in carriage.

    print(t.get_number_of_passengers()) # -- Should print 3, instead prints all 6.

Any info regarding to the topic is much appreciated, thanks in advance!

A: I think the solution is pretty straightforward and I'm not sure why this wouldn't work: "I have tried using a for loop to put some validation in the train's init that would disregard those passengers although with no success." Essentially you can just loop through the passenger list and filter out invalid passenger objects as such:
self._passengers = list(filter(lambda p: p.seat_number is valid, passengers))

This uses a lambda function to check certain criteria for including them in the final list. Also your getters and setters don't currently do anything so they are kind of pointless.


text:
Q: What kind of data is stored in the ext4 file system's journal? The ext4 file system has a feature called has_journal. In the dumpe2fs output, we can see something like this:
# dumpe2fs /dev/sda2 | grep -i journal
Journal inode:            8
Journal backup:           inode blocks
Journal features:         journal_incompat_revoke
Journal size:             32M
Journal length:           8192
Journal sequence:         0x00000662
Journal start:            1

So the journal is 32M in size, and it starts at the beginning of the file system. I know that the size of the journal depends on the size of the partition. I don't remember the limits right now, but it's not that big value. So what kind of data is stored in the journal?
I've read once that if you want to secure remove a file from your disk (via shred), you have to take into account the file system's journal because it can store some information about the removed file. Is there a way to check what is in the journal? Are there any tools that can show the information?

A: The exact contents of the journal depend on how you have configured your ext4 file system. The official ext4 documentation says:

There are 3 different data modes:

*

*writeback mode
  In data=writeback mode, ext4 does not journal data at all.  This mode provides
  a similar level of journaling as that of XFS, JFS, and ReiserFS in its default
  mode - metadata journaling.  A crash+recovery can cause incorrect data to
  appear in files which were written shortly before the crash.  This mode will
  typically provide the best ext4 performance.

*ordered mode
  In data=ordered mode, ext4 only officially journals metadata, but it logically
  groups metadata information related to data changes with the data blocks into a
  single unit called a transaction.  When it's time to write the new metadata
  out to disk, the associated data blocks are written first.  In general,
  this mode performs slightly slower than writeback but significantly faster than journal mode.

*journal mode
  data=journal mode provides full data and metadata journaling.  All new data is
  written to the journal first, and then to its final location.
  In the event of a crash, the journal can be replayed, bringing both data and
  metadata into a consistent state.  This mode is the slowest except when data
  needs to be read from and written to disk at the same time where it
  outperforms all others modes.  Enabling this mode will disable delayed
  allocation and O_DIRECT support.

So you can have both metadata (e.g. file name) and actual data (i.e. file contents) residing in your journal file.
If you're interested in details on the format in which transaction data is actually stored in the journal, you should refer to the respective header file:
http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/linux/jbd2.h
There's also a wiki page which explains how these structures are laid out on the disk:
https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
There's a packet in debian called sleuthkit, in which you have some tools like jls or jcat. The jls tool can list all journal entries of an ext4 file system, for example:
# jls grafi.img

JBlk    Description
0:      Superblock (seq: 0)
sb version: 4
sb version: 4
sb feature_compat flags 0x00000000
sb feature_incompat flags 0x00000000
sb feature_ro_incompat flags 0x00000000
1:      Allocated Descriptor Block (seq: 2)
2:      Allocated FS Block 161
3:      Allocated Commit Block (seq: 2, sec: 1448889478.49360128)
4:      Allocated Descriptor Block (seq: 3)
5:      Allocated FS Block 161
6:      Allocated Commit Block (seq: 3, sec: 1448889494.3355841024)
7:      Allocated Descriptor Block (seq: 4)
8:      Allocated FS Block 145
9:      Allocated FS Block 1
10:     Allocated FS Block 161
11:     Allocated FS Block 129
12:     Allocated FS Block 8359
13:     Allocated FS Block 8353
14:     Allocated FS Block 0
15:     Allocated FS Block 130
16:     Allocated Commit Block (seq: 4, sec: 1448889528.3540304896)
...

And of course, there's more entries depending on the size of the journal. In this case there was about 16382, most of which were empty. If you want to do something with the log, for instance, recover some file, you have to use jcat in order to extract the i-node block:
jcat grafi.img 8 10 > blok-161

And inspect the single i-node. The block is 4096 bytes in size, and covers 16 i-nodes, each of which is 256 bytes long. Anyways in that way you can get the first block of an extent, the number of blocks in the extent, how many extents were used to describe that particular file, its size and other stuff like this. All you need to recover that file from the disk based only on the i-node entry that you got from the journal.
There's also debugfs in e2fsprogs package. It has logdump tool, which is similar to the jls.

A: I would like to refer the definition of the journaling file system (from wikipedia) and hopefully you will get the answer:

A journaling file system is a file system that keeps track of changes
  not yet committed to the file system's main part by recording the
  intentions of such changes in a data structure known as a "journal",
  which is usually a circular log. In the event of a system crash or
  power failure, such file systems can be brought back online quicker
  with lower likelihood of becoming corrupted

Refer to:
https://en.wikipedia.org/wiki/Ext4#Features
and
https://en.wikipedia.org/wiki/Journaling_file_system#Logical_journals
For more informatio.


text:
Q: select min and max depending of a flag So I have this table "dump" :
_____________________________________
| id_seller | client | price | flag  |
|====================================|
|     1     |   a    |  12   | True  |
|     1     |   a    |  10   | True  |
|     1     |   a    |  13←  | True  |
|     1     |   a    |  14   | False |
|     1     |   a    |  9←   | False |
|     1     |   a    |  11   | False |
|     2     |   a    |  15←  | True  |
|     2     |   a    |  13   | True  |
|     2     |   a    |  14   | True  |
|     2     |   a    |  21   | False |
|     2     |   a    |  23   | False |
|     1     |   a    |  20←  | False |
|     1     |   b    |  14   | True  |
            [...]

I'm trying  to get the minimum and maximum price for some clients and sellers depending of the flag something like this :
_________________________________________________________
| min_price_flag0 | max_price_flag1 | client | id_seller |
|========================================================|
|         9       |       13        |    a   |    1      |
|         20      |       15        |    a   |    2      |
|         42      |       21        |    b   |    1      |
|         84      |       10.5      |    b   |    2      |
etc..

I'm using this request at the moment which works but I'm not sure if it's performant nor elegant , it also gives me trouble to join it with other select in aggregated tables:
SELECT min_price_flag0,
       max_price_flag1,
       client,
       id_seller
  FROM (
           SELECT min(price) AS min_price_flag0,
                  client,
                  id_seller
             FROM dump_table
            WHERE id_seller IN (1,2,3) AND
                  client IN ("a", "b", "c") AND
                  flag = "False"
            GROUP BY client
       )
       AS min_price_flag0_select
       INNER JOIN
       (
           SELECT max(price) AS max_price_flag1,
                  client,
                  id_seller
             FROM dump_table
            WHERE id_seller IN (1,2,3) AND
                  client IN ("a", "b", "c") AND
                  flag = "True"
            GROUP BY client
       )
       AS max_price_flag1_select ON min_price_flag0_select.id_seller = max_price_flag1_select.id_seller AND
                                    min_price_flag0_select.client = max_price_flag1_select.client

I'm not very good at sql and have very limited access to the databases so I'm looking for advices to better that select.

A: You want conditional aggragtion (CASE WHENinside MIN//MAX):
SELECT
  MIN(CASE WHEN flag = 'False' THEN price END) AS min_price_flag0,
  MAX(CASE WHEN flag = 'True' THEN price END) AS max_price_flag1,
  client,
  id_seller
FROM dump_table
WHERE id_seller IN (1,2,3)
AND client IN ('a', 'b', 'c')
GROUP BY client, id_seller
ORDER BY client, id_seller;


text:
Q: Setting object type property in QML from C++ (Editted to add more context)
I've started using QML and I'd like to set some sort of reference property on a QML type, linking two QML objects (ideally, without a parent/child relationship as I'd like to connect multiple QML objects).
For example, I have the following files.
qmldir:
A 1.0 A.qml

A.qml
import QtQuick 2.2

Rectangle {
    width: 100
    height: 100
    color: 'red'
    // Other stuff later
}

main.qml:
import QtQuick 2.2
import QtQuick.Window 2.1
import "qrc:/"

Rectangle {
    objectName: "Main window"
    visible: true
    width: 360
    height: 360

    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }

    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }

    property A referencedObject;

    Rectangle {
        id: subView
        objectName: "subView"
    }
}

What I'd like to do with this is set the value of 'referencedObject' to an object created by C++ at runtime. However, the function for setting properties doesn't allow for QObject pointers or QQuickItem pointers, as QVariant objects can't be constructed that way.
Something like:
QQmlComponent aTemplate(&engine, QString("qrc:/A.qml"), &parentObject);
QQuickItem* aInstance = aTemplate.create();

aInstance->setParent(&parentObject);
mainView.setProperty("referencedObject",aInstance); // Won't work.

I'd like to keep the 'A' type object in QML because a) less boilerplate than C++ for this, and b) its meant to be a separate graphical object with life of its own, and QML works better for that use-case.
Thanks for any help posted.

A: The following example shows how to set properties of objects of your custom type defined in QML from C++.
A.qml
import QtQuick 2.2
Rectangle {
    width: 0
    height: 0
    color:"red"
}

main.qml
import QtQuick 2.2
Rectangle {
    visible: true
    width: 640
    height: 480

    property alias referencedObject:aProperty;

    A
    {
        id:aProperty
        objectName: "aPropertyObject"//Needed to access it from C++
    }
}

Now we have defined a qml type A. main.qml has a property of this Custom type. We need to change properties of this object from C++. Lets change the width,height and color.
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QQuickItem>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QQmlApplicationEngine engine;
    QQmlComponent aTemplate(&engine, QUrl(("qrc:///A.qml")));
    QQuickItem* aInstance =qobject_cast<QQuickItem*>(aTemplate.create());
    aInstance->setWidth(100);
    aInstance->setHeight(100);
    aInstance->setProperty("color",QColor("green"));
    if(aInstance)
    {
        QQuickView *mainView = new QQuickView;
        mainView->setSource(QUrl(QStringLiteral("qrc:///main.qml")));
        mainView->show();
        QQuickItem * aPropertyObject = mainView->rootObject()->findChild<QQuickItem*>("aPropertyObject");
        if(aPropertyObject)
        {
           //Now you have pointers to both source and destination.
           //You can write a helper function which assigns the values
           //of source to the destination.
           //For the sake of demonstration, I am just setting some properties.
           aPropertyObject->setWidth(aInstance->width());
           aPropertyObject->setHeight(aInstance->height());
           aPropertyObject->setProperty("color",aInstance->property("color"));
        }
    }
    return app.exec();
}


text:
Q: i18next is not using the correct language in Vue project I have a file called i18n.js and am trying to setup localization in my Vue + Vite app. It's working in the sense that a translation is taking place, but it appears that my setup is wrong based on what I am seeing in the console log.
So my browser culture is English (United States) so the code is en-US. I have a locales located here src/locales/ with the locales files having names like this:
en-US.json
de-DE.json
en-AU.json
en-CA.json
en-GB.json
en-IE.json
en-IN.json
en-PH.json
es-MX.json
fr-CA.json
fr-FR.json
ja-JA.json
nl-NL.json
pt-BR.json
zh-CN.json

The problem is that the translation file that is getting used is en-CA instead of en-US.
This is the code:
import i18next from 'i18next'
import I18NextVue from 'i18next-vue'
import LanguageDetector from 'i18next-browser-languagedetector'
import i18nextXHRBackend from 'i18next-xhr-backend'

async function loadLocales (url, options, callback, data) {
  try {
    const theUrlPath = './locales/' + url + '.json'
    console.log(theUrlPath)
    const waitForLocale = await import(theUrlPath);

    callback(waitForLocale, { status: '200' })
  } catch (e) {
    console.log(e)
    callback(null, { status: '404' })
  }
}

i18next.use(i18nextXHRBackend).use(LanguageDetector)
  .init({
    detection: {
      caches: false
    },
    fallbackLng: {
      'in-ID': ['id-ID', 'id', 'en-US'],
      'zh-TW': ['zh-CN', 'zh', 'en-US'],
      'zh-HK': ['zh-CN', 'zh', 'en-US'],
      'zh-CN': ['zh-TW', 'zh', 'en-US'],
      'en-AT': ['en-GB', 'en-US'],
      'en-AU': ['en-GB', 'en-US'],
      'en-CA': ['en-GB', 'en-US'],
      'en-IN': ['en-GB', 'en-US'],
      'en-IE': ['en-GB', 'en-US'],
      'en-IT': ['en-GB', 'en-US'],
      'en-NL': ['en-GB', 'en-US'],
      'en-PH': ['en-GB', 'en-US'],
      'en-CH': ['en-GB', 'en-US'],
      cs: ['cs-CZ', 'en-US'],
      de: ['de-DE', 'en-US'],
      es: ['es-ES', 'en-US'],
      fr: ['fr-FR', 'en-US'],
      id: ['id-ID', 'en-US'],
      in: ['id-ID', 'id', 'en-US'],
      it: ['it-IT', 'en-US'],
      ja: ['ja-JA', 'en-US'],
      ko: ['ko-KR', 'en-US'],
      nl: ['nl-NL', 'en-US'],
      pt: ['pt-BR', 'en-US'],
      ru: ['ru-RU', 'en-US'],
      sk: ['sk-SK', 'en-US'],
      zh: ['zh-CN', 'en-US'],
      default: ['en-US']
    },
    interpolation: { escapeValue: false },
    whitelist: [
      'cs',
      'cs-CZ',
      'de',
      'de-DE',
      'en',
      'en-AT',
      'en-AU',
      'en-CA',
      'en-CH',
      'en-GB',
      'en-IE',
      'en-IN',
      'en-IT',
      'en-NL',
      'en-PH',
      'en-US',
      'es',
      'es-CO',
      'es-CR',
      'es-ES',
      'es-MX',
      'es-PR',
      'fr',
      'fr-CA',
      'fr-FR',
      'id',
      'id-ID',
      'in',
      'in-ID',
      'it',
      'it-IT',
      'ja',
      'ja-JA',
      'ko',
      'ko-KR',
      'nl',
      'nl-NL',
      'pt',
      'pt-BR',
      'ru',
      'ru-RU',
      'sk',
      'sk-SK',
      'zh',
      'zh-CN',
      'zh-HK',
      'zh-TW'],
    backend: {
      loadPath: '{{lng}}',
      parse: (data) => data,
      ajax: loadLocales
    },
    saveMissing: true,
    saveMissingTo: 'all',
    missingKeyHandler: (lng, ns, key, fallbackValue) => {
      console.log('missing locale key', lng, ns, key, fallbackValue)
    },
    missingInterpolationHandler: (text, value) => {
      console.log('missing locale interpolation', text, value)
    }
  });

export default function (app) {
  app.use(I18NextVue, { i18next })
  return app
}

Also, on the line that says console.log(theUrlPath), for some reason, this prints out:
./locales/en-CA.json
./locales/en.json
./locales/en-GB.json
./locales/en-US.json

So this brings up a few questions:

*

*Why is it printing all of these? I would think that once a translation has been found (which it is, because the translation for en-CA is showing in my app), then there wouldnt be a need to run that function again.

*Why is en-CA first since my browser culture is set to en-US?

*Where is en.json coming from? I don't have a file named that and en is not a fallback language for any of the other languages.

Please help clarify this for me. Googling has gotten me no where.

A: Turns out there was somehow a culture that was saved in my local storage and i18next was using that so just had to clear me local storage and it worked.


text:
Q: Maximum number of pointers? Each Pointer is identified with a [PointerPoint.PointerId][1]. Is there a maximum number of pointers supported by WinRT or is this hugely device dependent?

A: It is device dependant. There are readily available monitors with 30 simultaneous contact points.
You can query the number of points on a specific device from the PointerDevice.MaxContacts property. https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.input.pointerdevice.maxcontacts.aspx