text:
Q: Checking doubles for equality and Sonar issues We are checking the quality of our code using Sonar, and Sonar found code which compares a float or double for equality with a constant value like this:
if (x == 0.0) { … }

The value the variable is compared with (0.0) is constant, and in case the variable can be equal to this value, the value also isn't computed but only set via a constant.  This is typically used to check whether a variable hasn't been set yet or is still at initialization state, e. g. -1.0 might be used for "not yet set" in cases where the value can only be positive.
So, since these values are never computed but only set from constants, the Sonar complaint is not useful for us.  Only for computed values (or fractured ones which are not precisely representable as floats or doubles) a complaint about a test for equality makes sense.
The question I have now is:  What is the best practice to change the code so that Sonar does not complain about this anymore?
I see several options:

*

*Extract the "test-for-unset" into a special test function; but that would only reduce the number of occurrences (to 1), not the issue in general.

*Mark the code for Sonar to ignore it with a special decorator.  But we would like to avoid using such decorators.

*Hide the comparison behind sth like (0.0 <= x && x <= 0.0) or !(x != 0.0) (which currently seems to be okay for Sonar).

*Calling Double.doubleToRawLongBits() to compare the bits of the values like this: (Double.doubleToRawLongBits(x) != Double.doubleToRawLongBits(0.0)).

*Other ideas?

None of these solutions I really like and I thought, maybe, there is a better one out there I can't think of.

A: The best option here is to mark the issue as false positive and to leave a comment. This way the issue and associated technical debt will disappear from your SonarQube instance, without polluting your code with annotations.

A: If you only use these constants and comparisons for uninitialized values, one option is to set the fields to Double.NaN and use Double.isNaN() for comparison. E.g.:
double notYetInitialized = Double.NaN;
if (Double.isNaN(notYetInitialized)) {
        // handle uninitialized value
}

This makes (some) sense when reading the code - an unintialized value could possibly be said to "not be a number". And I can not imagine Sonar would have a problem with it.

A: I would go with your second option:

Mark the code for Sonar to ignore it with a special decorator.

Don't be a slave to static code analysis tools.  They're not perfect, and there's nothing wrong with telling them to shut up.  My personal practice when using annotations like @SuppressLint is to include a comment explaining why I'm using it.
That said, I would create a constant so the code is more self-explanatory:
private static final double UNINITIALIZED = 0.0;
if (x == UNINITIALIZED) { … }

A: There is also the correct way of doing this:
private static final double EPSILON = 0.000000000000001;
if (Math.abs(x) < EPSILON) {

}

A: I know this is a really old post, but I faced the same problem, and solved it using the Equals method instead of the "==" operator.
if (x.Equals(0.0)) { … }

In this way SonarQube will not complain.
Bye.

A:
Suggestion :
  One of the good way would be using BigDecimal for checking equality/non-equality to 0:

BigDecimal balance = pojo.getBalance();//get your BigDecimal obj

0 != balance.compareTo(BigDecimal.ZERO)

Explanation :

The compareTo() function compares this BigDecimal with the specified BigDecimal. Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where  is one of the six comparison operators.
(Thanks to SonarQube documentation)
Floating point math is imprecise because of the challenges of storing such values in a binary representation. Even worse, floating point math is not associative; push a float or a double through a series of simple mathematical operations and the answer will be different based on the order of those operation because of the rounding that takes place at each step.
Even simple floating point assignments are not simple:
float f = 0.1; // 0.100000001490116119384765625
double d = 0.1; // 0.1000000000000000055511151231257827021181583404541015625

(Results will vary based on compiler and compiler settings);
Therefore, the use of the equality (==) and inequality (!=) operators on float or double values is almost always an error. Instead the best course is to avoid floating point comparisons altogether. When that is not possible, you should consider using one of Java's float-handling Numbers such as BigDecimal which can properly handle floating point comparisons. A third option is to look not for equality but for whether the value is close enough. I.e. compare the absolute value of the difference between the stored value and the expected value against a margin of acceptable error. Note that this does not cover all cases (NaN and Infinity for instance).

A: How about casting to (int) ?!
That should have the same result as you want to check if it's zero.
If you have a calculation :
double a = c - b
boolean x = (int)(a*100) == 0


text:
Q: Razor View Engine : An expression tree may not contain a dynamic operation I have a model similar to this:
public class SampleModel
{
     public Product Product { get; set; }
}

And in my controller I get an exception trying to print out
@Html.TextBoxFor(p => p.Product.Name)

This is the error:
Exception: An expression tree may not contain a dynamic operation

If anyone can give me some clues on how to fix this I would really appreciate it!

A: In this link explain about @model, see a excerpt:

@model (lowercase "m") is a reserved keyword in Razor views to
  declare the model type at the top of your view. You have put the
  namespace too, e.g.: @model MyNamespace.Models.MyModel
Later in the file, you can reference the attribute you want with
  @Model.Attribute (uppercase "M").

A: Seems like your view is typed dynamic. Set the right type on the view and you'll see the error go away.

A: Before using (strongly type html helper into view) this line
@Html.TextBoxFor(p => p.Product.Name)

You should include your model into you page for making strongly type view.
@model SampleModel

A: It seems to me that you have an untyped view. By default, Razor views in MVC3 RC are typed as dynamic. However, lambdas do not support dynamic members. You have to strongly type your model. At the top of your view file add
@model SampleModel

A: This error happened to me because I had @@model instead of @model... copy & paste error in my case.  Changing to @model fixed it for me.

A: A common error that is the cause of this is when you add
@Model SampleModel

at the top of the page instead of
@model SampleModel

A: On vb.net you must write @ModelType.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Perl using Net::SFTP::Foreign get rid of server welcome message when I connect to a proFTP Server I get the welcome message printed to stdout.
my $sftp = Net::SFTP::Foreign->new($sftserver);

Everything works fine, but how can I get rid of this message?
I don't want to pipe the whole script output to /dev/null  and I don't have access to the server's config.
Thanks.

A: Use the stderr_fh option as documented:

stderr_fh => $fh
redirects the output sent to stderr by the SSH subprocess to the given file handle.
It can be used to suppress banners:
open my $ssherr, '>', '/dev/null' or die "unable to open /dev/null";
my $sftp = Net::SFTP::Foreign->new($host,
                               stderr_fh => $ssherr);


text:
Q: Execution time issue after change the MySQL DB to MariaDB I change the MySQL 5.6 to MariaDB 10.1, the total number of record above 5 Million. Using PHP script export the data with join query. Now the export take time delay for same PHP code.
Before, MYSQL DB : 20 to 30 second
After, MariaDB DB : 50 to 60 second

Please suggest me, how to speed up the execution time.

A: The question is to general to answer it.
You should provide some example code used for export.
To speed up the execution time you could tweak your config file.
There are some differences between MySql and MariaDB settings. Take a
look here https://mariadb.com/kb/en/library/system-variable-differences-between-mariadb-101-and-mysql-56/
You should know what are you using MyISAM or InnoDB.

The most notable differences are that MariaDB includes, by default,
  the Aria storage engine (resulting in extra memory allocation), Galera
  Cluster, uses Percona's XtraDB instead of Oracle's InnoDB, and has a
  different thread pool implementation. For this reason, a default
  implementation of MariaDB 10.1 will use more memory than MySQL 5.6.
  MariaDB 10.1 and MySQL 5.6 also have different GTID implementations.
MariaDB's extra memory usage can be handled with the following rules
  of thumb:
If you are not using MyISAM and don't plan to use Aria:
Set key_buffer_size to something very low (16K) as it's not used.
Set aria_pagecache_buffer_size to what you think you need for
  handling internal tmp tables that didn't fit in memory.
Normally this is what before you had set for key_buffer_size (at
  least 1M).
If you are using MyISAM and not planning to use Aria:
Set aria_pagecache_buffer_size to what you think you need for
  handling internal tmp tables that didn't fit in memory.
If you are planning to use Aria, you should set
  aria_pagecache_buffer_size to something that fits a big part of your
  normal data + overflow temporary tables.

And here are the default values in MySQL 5.6 https://dev.mysql.com/doc/refman/5.6/en/server-default-changes.html


text:
Q: Changing font family of all MUI components Can we change the font family of MUI components with less code. I have tried many ways but still, I can't able to do it. I have to change the font family
individually which is really a lot of work. Are there any other ways to do that?

A: In MUI v5, you can update the fontFamily or any other CSS properties of all Typography variants easily:
const theme = createTheme({
  typography: {
    allVariants: {
      fontFamily: 'serif',
    },
  },
})

To change the fontFamily dynamically in your app, you can use useMemo to create a new theme object based on the latest fontFamily value:
const defaultFontFamily = 'serif';
const [fontFamily, setFontFamily] = React.useState(defaultFontFamily);

const theme = React.useMemo(
  () =>
    createTheme({
      typography: {
        allVariants: { fontFamily },
      },
    }),
  [fontFamily],
);

return (

    <Select
      defaultValue={defaultFontFamily}
      onChange={(e) => setFontFamily(e.target.value)}
    >
      <MenuItem value="serif">serif</MenuItem>
      <MenuItem value="sans-serif">sans-serif</MenuItem>
    </Select>
    <ThemeProvider theme={theme}>
      <Content />
    </ThemeProvider>

);

Live Demo

A: Hoping this can help someone...you need to be really careful with commas and brackets when declaring your styles within createMuiTheme
It's really easy to mess this up. For instance, palette is one big object...so is typography, make sure everything is in the right place. I had random problems caused by doing this wrong.
  palette: {
    primary: {
      light: '#ff8e8c',
      main: '#ff5a5f',
      dark: '#c62035',
      contrastText: '#fff',
    },
    secondary: {
      light: '#4da9b7',
      main: '#017a87',
      dark: '#004e5a',
      contrastText: '#000',
    },
  },
  typography: {
    allVariants: {
      fontFamily: "'Montserrat', sans-serif",
      textTransform: "none",
    }
    button: {
      textTransform: "none",
    }
  },

A: **** UPDATES *****
Adding to the accepted answer by Adeel.
For the latest Material-UI(v4+) components, the imports, as well as MuiThemeProvider, have been changed.
So now in your App.js, do the following:
import { createMuiTheme } from '@material-ui/core/styles';
import { ThemeProvider } from '@material-ui/styles';
import './Styles/App.css';

const theme = createMuiTheme({
  typography: {
    fontFamily: [
      'Nunito',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif'
    ].join(','),
  }
});

class App extends Component {
  render() {
    return (
      <ThemeProvider theme={theme}>

          <MainApp />

      </ThemeProvider>
    );
  }
}

export default App;

Now for example, I've added the Nunito font. So I had to add the same to the App.css (which is being imported in App.js) in the following way:
@font-face {
  font-family: 'Nunito';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: local('Nunito Regular'), local('Nunito-Regular'),
   url(https://fonts.gstatic.com/s/nunito/v11/XRXV3I6Li01BKofINeaBTMnFcQ.woff2)
   format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA,
    U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212,
    U+2215, U+FEFF, U+FFFD;
}

A: This is now the preferred method:
const theme = createMuiTheme({
  typography: {
    fontFamily: [
      '-apple-system',
      'BlinkMacSystemFont',
      '"Segoe UI"',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif',
      '"Apple Color Emoji"',
      '"Segoe UI Emoji"',
      '"Segoe UI Symbol"',
    ].join(','),
  },
});

As noted here:
https://material-ui.com/customization/typography/

A: In MUI v5, also make sure ThemeProvider and createTheme is imported from @mui/material/styles and not from @mui/styles. I was stuck for hours thinking why it's not working.
import { ThemeProvider, createTheme } from '@mui/styles'; ❌

import { ThemeProvider, createTheme } from '@mui/material/styles'; ✅

const theme = createTheme({
  typography: {
    allVariants: {
      fontFamily: 'serif',
      textTransform: 'none',
      fontSize: 16,
    },
  },
});

function App() {
  return (
      <ThemeProvider theme={theme}>
        ...
      </ThemeProvider>
  );
}

A: This seem to work for me
GlobalStyleOverrides.js
import { createTheme, responsiveFontSizes } from '@mui/material/styles';

export default function GlobalStyleOverrides() {
  const theme = createTheme({
    typography: {
      fontFamily: [
        '"Bebas Neue"',
        'Roboto',
        '"Helvetica Neue"',
        'Arial',
        'sans-serif',
      ].join(','),
      body1: {
        fontFamily: "'Poppins', Arial, sans-serif",
      },
    },
    components: {
      MuiButton: {
        variants: [
          {
            props: { variant: 'contained' },
            style: {
              textTransform: 'none',
              border: `10px dashed red`,
            },
          },
        ],
      },
    },
  });

  return responsiveFontSizes(theme);
}

App.js
import GlobalStyleOverrides from 'components/_base/global-style-overrides/GlobalStyleOverrides';
...
function App() {
  return (
    <ThemeProvider theme={GlobalStyleOverrides()}>
      <Router>
        ...
      </Router>
    </ThemeProvider>
  );
}

A: You can change the font in material-ui@next library doing the following. Suppose in your <App /> which is defined like the following
// Material UI
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';

const App = () => (
  <MuiThemeProvider theme={THEME}>
    <Provider store={store}>
      <Router history={appHistory} routes={Routes} />
    </Provider>
  </MuiThemeProvider>
 );

 ReactDOM.render(<App />, document.getElementById('app'));

In the theme prop for MuiThemeProvider you provide the following where
const THEME = createMuiTheme({
   typography: {
    "fontFamily": `"Roboto", "Helvetica", "Arial", sans-serif`,
    "fontSize": 14,
    "fontWeightLight": 300,
    "fontWeightRegular": 400,
    "fontWeightMedium": 500
   }
});

Then somewhere in your css or your main index.html file include this @import url('https://fonts.googleapis.com/css?family=Roboto:300,400,500,700');
For a list of all params you can give to createMuiTheme Default Theme Params Regarding the docs itself for changing the MuiTheme they are as follows. Themes Material UI Next
Regarding the <Reboot /> part you can have a look at the documentation here Material UI Reboot Details


text:
Q: Having trouble setting position of UISlider in spritekit for all devices? Im using this code to set the position correctly for all my devices. The problem Im having is if I set the position of the slider in the 4s the iphone 6+ position changes. Same goes for my other devices. How do I get every device to perfectly position the sliders? Im in spritekit btw.
//iphone4s
if UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.maxLength < 568.0 {
    middleSlider = UISlider(frame: CGRectMake(180, 50, 150, 20))
    middleSlider.tintColor = UIColor.whiteColor()
    middleSlider.setThumbImage(UIImage(named: "thumb2"), forState: UIControlState.Normal)
    self.view?.addSubview(middleSlider)
    bottomAudioControlBg.position = CGPointMake(self.size.width / 2, self.size.height / 7)

}

//iphone5
if UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.maxLength == 568.0 {

}

//iphone6
if UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.maxLength == 667.0 {

}

//iphone6+
if UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.maxLength == 736.0 {
    middleSlider = UISlider(frame: CGRectMake(255, 50, 150, 20))
    middleSlider.tintColor = UIColor.whiteColor()
    middleSlider.setThumbImage(UIImage(named: "thumb2"), forState: UIControlState.Normal)
    self.view?.addSubview(middleSlider)

}

//ipad
if UIDevice.currentDevice().userInterfaceIdiom == .Pad && ScreenSize.maxLength == 1024.0 {

}

//ipadpro
if UIDevice.currentDevice().userInterfaceIdiom == .Pad && ScreenSize.maxLength == 1366.0 {

}

A: This is way to much code for such a problem:)
Using a simple scaling-factor you can easily solve this:
 let scaleFactor = UIScreen.mainScreen().bounds.width / 320

        let middleSlider = UISlider(frame: CGRectMake(180 * scaleFactor, 50, 150, 20))
        middleSlider.tintColor = UIColor.whiteColor()
        middleSlider.setThumbImage(UIImage(named: "thumb2"), forState: UIControlState.Normal)
        self.view?.addSubview(middleSlider)


text:
Q: Trouble Compiling Apache POI 5.2.2 Code - Factory.newInstance() methods Apache POI newbie.
I am trying to use Apache POI 5.2.2 to generate footnotes in a Word document.
There are some useful SO posts on this topic:

*

*Need to add a footnote in between texts and the next text should be appeared in the same line not in the next line in Apache poi

*Need to insert the text at the end of the page but the table is still continuing in the next page
However, when I try to run those examples, I get very consistent errors on these 3 Factory.newInstance() methods:

*

*CTFtnEdn.Factory.newInstance();

*CTStyle.Factory.newInstance();

*CTDecimalNumber.Factory.newInstance();

The compiler says:  "error: incompatible types: XmlObject cannot be converted to" either CTFtnEdn, CTStyle or CTDecimalNumber, as applicable.
Here is the full compilation error for one of these, but all 3 are similar:
Footnotes.java:68: error: incompatible types: XmlObject cannot be converted to CTFtnEdn
CTFtnEdn ctfInstance = CTFtnEdn.Factory.newInstance();
poi-ooxml-full-5.2.2.jar is included in the compilation classpath.
I assume I have not included one or more jar files needed to get this working.
Any ideas how to get this working?

A: I believe I had conflicting jar files in the classpath.  Removing one has fixed the issue.  Axel Richter, thanks for helping me identify that.


text:
Q: Navigate among word headings with keyboard shortcut? Is there a way to navigate between headings of the same type in word with keyboard? This would be equivalent to ctrl+arrow in emacs.
In outline or draft view. Can't find anything like it in help files. Thanks!

A: You can add a macro and then assign a keyboard shortcut to it. Here is how the macro code looks (you can also create by recording it).
Sub Movebetweenheaders()
'
' Movebetweenheaders Macro
'
'
    Selection.Find.ClearFormatting
    Selection.Find.Style = Selection.Style
    With Selection.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
End Sub

Sub MovebetweenheadersBack()
'
' MovebetweenheadersBack Macro
'
'
    Selection.Find.ClearFormatting
    Selection.Find.Style = Selection.Style
    With Selection.Find
        .Text = ""
        .Replacement.Text = ""
        .Forward = False
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
End Sub

If you're unsure how to assign a keyboard shortcut to a macro: assign shortcuts
EDIT from OP: I updated the code answer to the full solution to the question.


text:
Q: SQL Statement Using Multiple Tables The database being used for this question is structured as follows with Primary Keys bolded, and Foreign Keys ' '.

Countries (Name, Country_ID, area_sqkm, population)
Teams (team_id, name, 'country_id', description, manager)
Stages (stage_id, took_place, start_loc, end_loc, distance, description)
Riders (rider_id, name, 'team_id', year_born, height_cms, weight_kgs, 'country_id', bmi)
Results ('stage_id', 'rider_id', time_seconds)

I am stuck at the question of:
Q: Create a list (year, numridersborn) where we count the number of riders born in different years. Output columns: year, numridersborn. Order by: year
I am currently at :
SELECT year_born AS "year", COUNT(rider_id) as "numridersborn" WHERE ....
May I know how can I go about getting the solution?
Thank you

A: year_born is in the rider table already so there is no need to Join here.
Just:
SELECT year_born as year, count(*) as numridersborn
FROM Riders
GROUP BY year_born
ORDER BY year_born;

Which is pretty much what you had already with the addition of the GROUP BY and ORDER BY


text:
Q: How to append sting array to html div ni ajax.? Here I have output with string array. Comes from php json. I want to give this output to html div tabcontent but I don't know how to do this. here is my little code any one can help me.

[{"id":"1","p_name":"g_t1","P_Type":"gp_1","paid_type":"0"},{"id":"2","p_name":"g_t2","P_Type":"gp_2","paid_type":"1"},{"id":"3","p_name":"g_t3","P_Type":"gp_3","paid_type":"0"}]

   $("a.tablinks").on('click',function(e){
        e.preventDefault();
        var p_name = $(this).attr('value');
        alert(p_name);
    $.ajax({
            url:"<?php echo base_url(); ?>Gettabdata",
            type: "POST",
            dataType: 'json',
            data:{Paper_name : p_name},

           success : function(data){

                if(data != ""){
                    data = JSON.stringify(data);
                    console.log(data);
                   alert(data);

                }else{
                    data = JSON.stringify(data);
                    console.log(data);
                   $.each(data, function(k, v) {
                      alert(k + ':' + v+ " 1 working else .!");
                   });
                }
           },
           error : function(data){
                data = JSON.stringify(data);
                console.log(data);

                   $.each(data, function(k, v) {
                      alert(k + ':' + v + ' error');
                   });
           }
        });
    });

                                  Label Name

                                    <button class="btn btn-info" type="button">Go!</button>

here is my ajax

I want to add retrieved string array to below  html div tabcontent (tabcontent input-group class will create three times. depends on number of id.).

                                  Label Name

                                    <button class="btn btn-info" type="button">Go!</button>

what to add in html tabcontent.?
Tabcontent id is P_type,
Lable is p_name,

A: You need to create the div dynamically so create a function that will take this json array as parameter and loop over to it to create div dynamically with necessary id and label
First, you need to specify this function inside if block data != ""
if(data != ""){
   createDiv(data);  //this function is responsible to create div dynamically
   data = JSON.stringify(data);
   console.log(data);
   alert(data);
}

Now the createDiv() function goes like this
function createDiv(data){
var dynamicHTML = '';
for(var i=0; i<data.length; i++){
  dynamicHTML += '
'+
                        '
'+
                            ''+ data[i].p_name +''+
                            ''+
                                '<button class="btn btn-info" type="button">Go!</button>'+
                            ''+
                        '
'+
                    '
';
}
$("body").append(dynamicHTML);

}
The dynamically created div is appended right away in the HTML body. You can specify a parent div say,

 and change this line of code inside the createDiv() function
$("body").append(dynamicHTML); to $("#content").append(dynamicHTML);
if you want to append it inside a div in the page.


text:
Q: state not updating with setState react thanks in advance for taking a look my questions.  So I am POSTing to a DB from the CreateItem component via the submitItem function, then when the promise is returned, I call a pullAllItems to GET all rows for the categories table of my DB to update the state of categories:
React Component:
import React, { Component } from 'react';
import CreateItem from './components/CreateItem';
import Categories from './components/Categories';

// stylesheets
import './stylesheets/App.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      categories: [],
      tasks: []
    };

    this.submitItem = this.submitItem.bind(this);
    this.pullAllItems = this.pullAllItems.bind(this);
  }

  componentWillMount() {
    fetch('/api/categories')
      .then(res => res.json())
      .then(res => {
        this.setState({
          categories: res
        });
      });
  }

  submitItem(title) {
    const category = {
      title
    }

    fetch('/api/categories', {
      method: 'POST',
      body: JSON.stringify(category),
      headers: new Headers({
        'Content-Type': 'application/json'
      })
    }).then(this.pullAllItems('categories'));
  }

  pullAllItems(type) {
    const key = type;
    let obj = {};

    fetch('/api/' + type)
      .then(res => res.json())
      .then(res => {
        obj[key] = res;
        this.setState({
          obj
        }, () => {
          console.log(this.state.categories);
        });
      });
}

  render() {
    return (
      <div className="App">
        <CreateItem submitItem={this.submitItem} />
        <Categories categories={this.state.categories} pullAllTasks={this.pullAllItems}/>
      </div>
    );
  }
}

If I console log the response, I get the additional row that was POSTed with the submitItem function; however, when I update the state of categories in my pullAllItems function, the state does not update (even in the callback function of setState).  I am new to react, and have looked everywhere I can to see what I am missing, but can't get a clear-cut answer anywhere.  Any help is greatly appreciated!

A: I think you would want to do this.setState(obj) so that they dynamic key gets merged in to the state.


text:
Q: Matplotlib Subfigures too Short I'm trying to render a figure with subfigures. Each subfigure is getting squashed vertically and I don't understand why. I've tried setting the aspect ratio but that just seems to make it narrower, without solving the problem that the image isn't tall enough to be useful. I'm using tight_layout but the output size is more than enough for it to be bigger. I know I can set the size of my images more specifically with grid layouts, but I feel like there's something simpler that I'm missing, since this hasn't been an issue with any of my similar plots with subfigures.
Thanks!

def plot_at_all_intervals_mod(series, series_name, series_file_name, is_date, write, ROLL_NUM = 4):
    plt.close()
    fig, axs = plt.subplots(4, 2)

#     for row in axs:
#         for ax in row:
#             ax.set_aspect('equal')

    #absolute
    if is_date:
        my_range = (unix_time_to_year(min(series)), unix_time_to_year(max(series)))
        values, bins, _ = axs[0,0].hist(unix_time_to_year(series), log=False, bins=200, range=my_range)
    else:
        my_range = (min(series) / SECONDS_IN_A_YEAR, max(series) / SECONDS_IN_A_YEAR)
        values, bins, _ = axs[0,0].hist(series / SECONDS_IN_A_YEAR, log=False, bins=200, range=my_range)
    bins = bins.tolist()[:-1]
    values = circular_moving_average(values.tolist(), ROLL_NUM)
    axs[0,0].plot(bins,values)
    axs[0,0].set_xlabel('Absolute Time')
    axs[0,0].set_ylabel('Number of Logs')
    axs[0,0].set_title(f'Distribution of {series_name} \nOver Time')

    #year
    values, bins, _ = axs[0,1].hist(unix_time_to_day_of_year(series), log=False, bins=365*24)
    bins = bins.tolist()[:-1 ]
    values = circular_moving_average(values.tolist(), ROLL_NUM)
    axs[0,1].plot(bins,values)
    axs[0,1].set_xlabel('Day of Year (Starting Jan 1st)')
    axs[0,1].set_ylabel('Number of Logs')
    axs[0,1].set_title(f'Distribution of {series_name} \nModulo Year')

    #week
    values, bins, _ = axs[1,0].hist(unix_time_to_day_of_week(series), log=False, bins=7*24*60)
    bins = bins.tolist()[:-1]
    values = circular_moving_average(values.tolist(), ROLL_NUM)
    axs[1,0].plot(bins,values)
    axs[1,0].set_xlabel('Day of Week (Starting at 0=Monday)')
    axs[1,0].set_ylabel('Number of Logs')
    axs[1,0].set_title(f'Distribution of {series_name} \nOver Time Modulo Week')

    #day
    values, bins, _ = axs[1,1].hist(unix_time_to_time_of_day(series), log=False, bins=24*60)
    bins = bins.tolist()[:-1 * ROLL_NUM]
    values = moving_average(values.tolist(), ROLL_NUM)
    axs[1,1].plot(bins,values)
    axs[1,1].set_xlabel('Hour of Day')
    axs[1,1].set_ylabel('Number of Logs')
    axs[1,1].set_title(f'Distribution of {series_name} \nOver Time Modulo Day')

    #hour
    values, bins, _ = axs[2,0].hist(unix_time_to_minute_in_hour(series), log=False, bins=60*60)
    bins = bins.tolist()[:-1]
    values = circular_moving_average(values.tolist(), ROLL_NUM)
    axs[2,0].plot(bins,values)
    axs[2,0].set_xlabel('Minute of Hour')
    axs[2,0].set_ylabel('Number of Logs')
    axs[2,0].set_title(f'Distribution of {series_name} \nOver Time Modulo Hour')

    #10 minutes
    values, bins, _ = axs[2,1].hist(unix_time_to_minute_in_hour(series), log=False, bins=60*60)
    bins = bins.tolist()[:-1]
    values = circular_moving_average(values.tolist(), ROLL_NUM)
    axs[2,1].plot(bins,values)
    axs[2,1].set_xlabel('Minute of Hour')
    axs[2,1].set_ylabel('Number of Logs')
    axs[2,1].set_title(f'Distribution of {series_name} \nOver Time Modulo Hour')

    #minute
    ROLL_NUM = 1
    values, bins, _ = axs[3,0].hist(unix_time_to_second_in_minute(series), log=False, bins=60)
    bins = bins.tolist()[:-1 * ROLL_NUM]
    values = moving_average(values.tolist(), ROLL_NUM)
    axs[3,0].plot(bins,values)
    axs[3,0].set_xlabel('Second of Minute')
    axs[3,0].set_ylabel('Number of Logs')
    axs[3,0].set_title(f'Distribution of {series_name} \n Over Time Modulo Minute')

    fig.suptitle(f'Distribution of {series_name} Over Different Periods', fontsize=16)
    fig.tight_layout()
    fig.set_size_inches(20, 20)
    fig.show()
    if write:
        fig.savefig(f'all-times-{series_file_name}.png')


text:
Q: how should I call an external program from inside a C program I am currently working on moving some bash scripts over to C, and one of them call's an external python script, so for instance ./remoteclient01a.py "remotecommand player /something something"
./remoteclient01a.py "remotecommand player /something something"

and Ive been looking for a way to execute this command in C, but Im not really sure as to which I should use, being that System() seems to be the best one, but then a few pages say that it is a bad choice in some cases, so if someone could recommend a method to do this I would really appreciate it, thanks!

A: The only portable ways to do this in C are system and popen. The function popen allows you to read output from the command.

A: *

*For simple problems in unixish environments try popen().

From the man page

The popen() function opens a process by creating a pipe, forking and involking the
shell.

*

*There are other means to call an external program in C. See the following tutorial explaining all the ways :
Executing programs with C(Linux)


text:
Q: OpenCV - Adaptive-thresholding / effective noise reduction? I am new to OpenCV and I just read about cv2.adaptiveThreshold() and decided to try it out.
Sadly there is this huge amount of noise I cannot seem to get rid of.
What are some effective ways to reduce noise so I can draw proper contours? What is the best practice and why?
Here is the snippet:

import cv2
import numpy as np

#####################################
winWidth = 640
winHeight = 840
brightness = 100

cap = cv2.VideoCapture(0)
cap.set(3, winWidth)
cap.set(4, winHeight)
cap.set(10, brightness)

kernel = (5, 5)

###########################################

def preprocessing(frame):
    imgGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # mask = cv2.inRange(imgHsv, lower, upper)
    imgBlurred = cv2.GaussianBlur(imgGray, kernel, 1)
    gaussC = cv2.adaptiveThreshold(imgBlurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
    imgDial = cv2.dilate(gaussC, kernel, iterations=3)
    imgErode = cv2.erode(imgDial, kernel, iterations=1)

    return imgDial

def getcontours(imPrePro):
    contours, hierarchy = cv2.findContours(imPrePro, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        cv2.drawContours(imgCon, cnt, -1, (255, 0, 0), 3)

###################################################

while (cap.isOpened()):
    success, frame = cap.read()
    if success == True:
        frame = cv2.flip(frame, 1)
        imgCon = frame.copy()
        imPrePro = preprocessing(frame)
        getcontours(imPrePro)
        cv2.imshow("Preprocessed", imPrePro)
        cv2.imshow("Original", imgCon)

        if cv2.waitKey(1) & 0xFF == ord("q"):
            break

A: I think it is best if we look at the blockSize and C parameters.
Form the source:

blockSize: Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.

C:    Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well.

In your example you set C to 2:
gaussC = cv2.adaptiveThreshold(imgBlurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)

C=2
C=8

As you can see, you need to play with blockSize and C parameters to get the desired result from adaptive-threshold.
In this question, we achieve less-noise by increasing C parameter.


text:
Q: How to capture two separate group patterns with Regex? I have this pattern in over 10.000 places:
11,1,2,0,0,"Lorem ipsum dolor sit amet, 8 - 14. consectetur adipiscing elit. 6 - 13. Aenean semper fermentum ipsum sed vehicula. In commodo sit amet libero et rhoncus. Cras vitae dapibus nisl. Mauris lacinia dui lacus, ut sodales massa congue vel. Donec at 8 - 11. dapibus mi, ullamcorper porttitor orci. Nullam id dui nibh. Fusce est ante, viverra 4 - 7. et cursus vel, scelerisque imperdiet massa. Donec sit amet nibh porttitor, tincidunt lorem in, maximus elit."
I need to capture all 11,1,2,0,0, patterns at the beginning of the sentence AND ALL the 8 - 14. patterns (they have different numbers between dashes - and before the dot .) throughout the sentence using Regex.
How do I do this?
I have tried (^\d*,\d*,\d*,\d*,\d*)+(\d* - \d*\.)
The desired output is:
11,1,2,0,0, 8 - 14. 6 - 13. 8 - 11. 4 - 7.

A: You can use regex alternation for 2 patterns:
\b((?:\d+,)+|\d+\s*-\s*\d+)

RegEx Demo


text:
Q: Simultaneous condition on all line elements of a tuple I have a tuple in the following format:
[(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, None),
 (None, None), (None, None), (None, datetime.datetime(2012, 9, 14, 16, 0))]

I want to iterate over the tuple, check if both components are null and if so remove them from the item — leaving only these:
[(None, datetime.datetime(2012, 9, 14, 15, 0)),
 (None, datetime.datetime(2012, 9, 14, 16, 0))]

What's the neatest way to perform the checks in a single loop at the same time?

A: output_list = filter(any, input_list)

A: Using list comprehension and tuple unpacking:
>>> lst = [(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, None),
... (None, None), (None, None), (None, datetime.datetime(2012, 9, 14, 16, 0))]
>>> [(a,b) for a,b in lst if a or b]
[(None, datetime.datetime(2012, 9, 14, 15, 0)),
 (None, datetime.datetime(2012, 9, 14, 16, 0))]

A: I would use a list comprehension and any()
left = [x for x in a if any(x)]
>> [(None, datetime.datetime(2012, 9, 14, 15, 0)), (None, datetime.datetime(2012, 9, 14, 16, 0))]


text:
Q: A problem Understanding how a two-body system of planets starts rotating around barycentre Consider,We are Creating a Two-body system in free space,Where no other mass exists,Let's Take First Mass M1 and hold it,Now bring Second Mass M2,hold it up,Now we are giving a suddenly impulse To M1 causing its initial Velocity to be V1 and then releasing M2,now here,How do we derive that These bodies will perform Circular motion About (Barycentre/Centre of masses),What will happen between The the time When Impulse is given and time When They become steady rotating about Centre Of mass(in COM frame).
The Gravitational force is only considered here,So my Question is Centrepetal Force Acts on both which varies inversely to $r^2$,So How are they set into circular motion?

A: In your model, there is no expectation of circular motion.
The usual theoretical understanding is that planets form from gas and dust in an accretion disk. The gas and dust in a disk moves in nearly circular orbits: frictional effects (not considered in your model) are assumed to damp radial motion. The planets (initially) share that motion.

A: Planets and stars are formed from already rotating protoplanetary disk of dust and gas, from which planets "borrow" angular speed. Of course there's still question remains - how and when (presumably first) protoplanetary disks acquired angular momentum ? I believe root causes lies in Navier-Stokes equations and turbulence. Dust/Gas mass in the galaxy is affected randomly by local gravitational sources (many-body problem), which produces friction between layers of dust, and consequently - relative angular motion and turbulence, which fragments dust into disks.

A: The velocity $\mathbf v_1$ of $M_1$ must be such that there is not radial component when $M_2$ is released. If this condition is fulfilled, there is a specific $|\mathbf v_1|$  for a circular orbit.

A: Your question seems to indicate that you think of the rotational motion around the barycentre as some stationary state the two-body system reaches after some short time after the initial conditions are set, and only at that point is it possible to speak about circular motion.
This is not the way Newtonian mechanics works. The rotation starts as soon as the two bodies are set at their initial positions with their initial velocities. However, to have it, not all the initial conditions are good. If you put the two bodies at any distance with zero speeds or with non-zero collinear velocities, their motion will remain confined to a line segment. This is a consequence of starting with zero (conserved) angular momentum. Instead, the angular momentum is different from zero if the initial velocities are not aligned with the relative position vector. In such conditions, the motion remains confined in a plane. Still, the trajectories of the two bodies immediately start to bend as a consequence of the existence of an acceleration not aligned with the velocity.
Then, for a general attractive force between the two bodies, it is possible to show that the motion in the system frame where the center of mass is at rest will remain confined in the region between two concentric circles (annulus). In general, the trajectory will fill this region densely, but for the Newtonian forces with intensity proportional to $\frac{1}{r^2}$, the trajectory is a closed ellipse in general.
I stress that such behavior is something characterizing the motion immediately from the starting conditions. It is not some final stage of the motion.


text:
Q: array of comma separated string IN in clause mysql I have a array like that :
 $myarray=  'zzz,aaa,bbb'  ;

and want use it in mysql IN clause like that :
 "...  WHERE ids IN ($myarray) "   // didnt work
 "...  WHERE ids IN ('$myarray') " // didnt work

the error im getting is that the first value in that array zzz says that zzz is not a column name . so i understand that i must separate the values with quotes to be like that :
 $myarray=  ' "zzz","aaa","bbb" '  ;

But i have no clue to do that . any help would be much appreciated.

A: $myarray = 'zzz,aaa,bbb';
$myarray = implode("','",explode(',',$myarray));
$query   = "..... WHERE ids IN ('$myarray')";

A: You need to explode() your string and then implode() it -
$myarray = 'zzz,aaa,bbb';
$realArray = explode(',', $myarray);
$stringForIn = "'" . implode("','", $realArray) . "'";
echo "WHERE ids IN ($stringForIn)";

A: Try that :
$myarray=  'zzz,aaa,bbb'  ;
echo implode '"' . ('","', explode(',', $myarray)) . '"';


text:
Q: div content over spilling, inline-block useless Im a self learner for web designing, so i might missed out some fundamentals coding.
So the problem is the  content is overspilling the div from the right in one line.
The code as below
THE HTML

    <link rel="stylesheet" type="text/css" href="style.css">

    <title></title>

                                asdfasdfasdfasdvvasdvasdvasdvfasdvsdasdas
                                dfasdfasdfasdvvasdvasdvasdvfasdvsdasdasdfasdfas

                    asdfasdf

THE CSS AS BELOW
/* ---------------------------------------------------------------*/
/* --------------------->  RESET  <<<-------------------------*/
/* ---------------------------------------------------------------*/
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td {
margin:0;
padding:0;
border:0;
outline:0;
font-size:100%;
vertical-align:baseline;
background:transparent;
}

body {
line-height:1;
}

body {
font-family:Arial,sans-serif;
font-size:100%;
line-height:1.3em;
_font-size:16px;
color:#504e45;
background:#ebe9e1 url(pics/bg.jpg) top left repeat-x;
}

#bg {
float:left;
display:block;
height:600px;
width:100%;
background:url(pics/hotel-bg.jpg) top center no-repeat;
margin:0 0 0 0;
}

#mainwrapper {
float:left;
display:block;
width:1000px;
margin:0 auto;
}

#header {
float:left;
display:block;
}

#logo {
width:274px;
height:44px;
background:url(pics/logo.png) no-repeat;
margin:50 0 0 100;
}

p {
float:left;
display:inline-block;
line-height:1.7em;
margin:1em 0;
-webkit-margin-before:1em;
-webkit-margin-after:1em;
-webkit-margin-start:0px;
-webkit-margin-end:0px;
}

#contentwrapper {
float:left;
display:block;
width:1000px;
}

#leftwrapper {
float:left;
display:block;
width:593px;
}

#contentspacing {
float:left;
display:block;
margin:0;
padding:0;
border:0;
outline:0;
font-size:100%;
vertical-align:baseline;
background:transparent;
}

#content {
float:left;
display:block;
height:auto;
width:593px;
border:1px solid #bdc9f4;
background:url(pics/bg2.png) top left repeat-x;
margin:35 120;
}

#rightwrapper {
float:left;
display:block;
}

A: Add word-wrap: break-word; word-break: break-all; to #content
Demo here http://jsfiddle.net/ZK6yR/

A: This occurs when you are using rather long words. Try this:
word-wrap: no-break;


text:
Q: Take tabulated data with start and end dates and transpose to a roadmap view, with items aligned to date columns I have a table where each entry includes assignee, task name, start date, and due date.
Here is sample data:

Owner
Task
Start Date
Due Date
Duration (days)

Jake
Task 1
2/21/2022
2/24/2022
4

Jake
Task 2
2/28/2022
3/10/2022
9

Jake
Task 3
3/14/2022
3/17/2022
4

Fred
Task 4
3/21/2022
4/28/2022
29

Fred
Task 5
5/2/2022
5/12/2022
9

Jake
Task 6
5/16/2022
6/16/2022
24

Jake
Task 7
6/20/2022
6/30/2022
9

Jake
Task 8
7/4/2022
7/14/2022
9

Jake
Task 9
7/18/2022
8/11/2022
19

Jake
Task 10
8/15/2022
12/8/2022
84

Jake
Task 11
12/12/2022
1/5/2023
19

Erica
Task 1
1/9/2023
2/2/2023
19

Erica
Task 2
2/6/2023
3/2/2023
19

Erica
Task 3
3/6/2023
6/15/2023
74

Erica
Task 4
2/21/2022
2/24/2022
4

Erica
Task 5
2/28/2022
3/10/2022
9

Erica
Task 6
3/14/2022
3/17/2022
4

Erica
Task 7
3/21/2022
6/16/2022
64

Erica
Task 8
6/20/2022
6/23/2022
4

Erica
Task 9
6/27/2022
6/30/2022
4

I need to take that information, and display it on a roadmap, but with all tasks for one individual on a single row. Currently, I have tried the following:
=TRANSPOSE(QUERY(Sheet1!A1:E21, "Select B Where A='"&D5&"'", 1))
I would like the task name to appear when the start date matches, and the ability to conditionally format all cells that are part of the duration. I have tried several approaches but don't seem to be making progress beyond my current point.

Assignee
Num    Tasks
Mar-7
Mar-14
Mar-21
Mar-28
Apr-4
Apr-11
Apr-18
Apr-25
May-2
May-9
May-16
May-23
May-30
Jun-6
Jun-13
Jun-20
Jun-27
Jul-4
Jul-11
Jul-18
Jul-25

Jake
14
Task1
Task2
Task3,
Task4
Task5,
Task6
Task7,
Task8
Task9,
Task10
Task11

Erica
6
Task1
Task2
Task3
Task4
Task5
Task6
Task7
Task8
Task9

Here is an image of the desired output as well.

A: Given this question type's popularity that Matt refers to in his answer, perhaps it is worthwhile to mention the "conventional" filter() pattern often used to create these sorts of timelines.
With task owner name, task name, start date and due date in columns A2:D, you can list task owners in cell G2 with =unique(A2:A) and the number of tasks in cell H2 with =counta( iferror( filter( B$2:B, A$2:A = G2 ) ) ).
To list all the weeks from the first start date to the last due date, put this in cell I1:
=sequence(1, (max(C2:D) - min(C2:D)) / 7, min(C2:D), 7)
Format the sequence() results as Format > Number > Date.
Finally, to list task names by owner name and week, put this in cell I2:
iferror( textjoin( ", ", true, filter( $B$2:$B, $A$2:$A = $G2, $C$2:$C <= I$1, I$1 <= $D$2:$D) ) )
See the 'Conventional solution' tab in the sample spreadsheet Matt kindly created.
Further, the recently introduced lambda functions let you create the whole result table with one formula, like this:
=lambda(
  uniqueNames, names, tasks, startDates, dueDates,
  lambda(
    weeks,
    makearray(
      rows(uniqueNames), columns(weeks) + 2,
      lambda(
        row, column,
        lambda(
          name, week,
          lambda(
            numTasksByName, filterTasksByWeek,
            ifs(
              (row = 1) * (column = 1), "Assignee",
              (row = 1) * (column = 2), "Num tasks",
              row = 1, week,
              column = 1, name,
              column = 2, numTasksByName,
              true, iferror( textjoin( ", ", true, filterTasksByWeek) )
            )
          )(
             counta(iferror(filter(tasks, names = name))),
             filter(tasks, names = name, startDates <= week, week <= dueDates)
           )
        )(
           index(uniqueNames, row - 1, 1),
           index(weeks, 1, column - 2)
         )
      )
    )
  )(sequence(1, (max(dueDates) - min(startDates)) / 7, min(startDates), 7))
)(unique(A2:A), A2:A, B2:B, C2:C, D2:D)

The benefit of this pattern is that it is fairly easy to adjust the contents of the table, and there is no need to copy formulas down when more data becomes available. The use of nested lambdas lets us use readable names instead of range references within the various functions.
See the 'Lambda solution' tab in Matt's spreadsheet. The formula in cell G1 creates the whole result table automatically.

A: this is an extremely common question, and there are many answers out there on the internet, but there is not a common enough syntax in describing what you want to make it easy to google.
I built something in two steps rather than one, because I've found that with this solution, people often hadn't thought of having their task data "flattened" the way I've done on the helper tab.  The database structure of the task dates for the gantt chart will likely be useful for you for lots of other things.  I'd recommend that you leave it in place, (but possibly hidden) on your real sheet so that you can reference it for other dashboard-ey purposes.
I made a new tab on this sheet and put this formula in cell D3.
=ARRAYFORMULA(IFERROR(VLOOKUP(B3:B5&D2:2,{MK_Help_Back_End!A:A&MK_Help_Back_End!C:C,MK_Help_Back_End!B:B},2,0)))

It relies on a "back end" helper tab with this formula in cell A1:
=ARRAYFORMULA(QUERY(SPLIT(FLATTEN('Data from OP'!A2:A&"|"&'Data from OP'!B2:B&"|"&'Data from OP'!C2:C+SEQUENCE(1,MAX('Data from OP'!E2:E),0)&"|"&'Data from OP'!D2:D),"|",0,0),"select Col1,Col2,Col3 where Col3<=Col4 label Col1'Name',Col2'Task',Col3'Date'"))

A: try:
=INDEX(LAMBDA(x, IF(x<>"", IFERROR(TEXT(x*1, "m/d/e"), x), ))
 (QUERY(QUERY(SPLIT(FLATTEN(Sheet1!A2:A&"|"&Sheet1!B2:B&"|"&Sheet1!C2:C+
 SEQUENCE(1, MAX(Sheet1!E2:E),0)&"|"&Sheet1!D2:D), "|",,),
 "where Col3<=Col4 and Col4 is not null", ),
 "select Col1,max(Col2)
  where Col3*1>="&DATEVALUE("4/1/2022")&"
  group by Col1 pivot Col3 label Col1''" )))


text:
Q: Version numbering basics? Suppose I have a web application with some basic functions. I want to market it. So I would like to assign a version number  - something like 0.0.1. What I want to know is are there any constraints that should apply to that numbering system?
Hope you understood my question, thanks in advance.

A: You can use whatever numbers you want in your versioning - who's going to constrain you?
If you want your first version to be 0.0.0.0.0.0.0.1, that's fine, albeit a little silly.  If you want your first version to be 106.3, you can do that too, but that's a little more ridiculous.
Check out the Wikipedia article on Software Versioning for some tried-and-true ideas of realistic version numbering schemes.

A: I've always used (rewrite).(feature added).(bug fix).
But set your own rules and make them public so your users understand them.

A: Take a look here. python setuptools has a very interesting and clear specification for version numbering. I'm sure you can obtain some very insightful hints from it.

A: Most places use something like this:
Major Release.Minor Release.Hot Fix.Build
Your version numbers would look like 1.5.0.15, etc.

A: To the best of my knowledge, there is as yet no government agency dictating how you number versions. But don't worry, I'm sure it will come soon enough.
Ditto on those suggesting major-dot-minor-revision. My general approach is: Major changes get a new major version. Like, if we've added important new features. Small changes, like added some little convenience features or one new report, get a minor revision. Hot bug fix changes get a revision.
I would definately avoid calling your first published version "0.l" for simple marketing reasons: Numbers less than 1.0 sound like a preliminary version or a beta version. I've known people to call their first version 2.3 or some such just to make it sound like it's been around a little while to inspire more confidence, though that strikes me as a little dishonest.

A: how about the software which is not distributed to public like a webmail source code? do you think that the build or bug fix number is still important in this case?

A:
10.50.1600.1
  major.minor.build.revision

MAJOR changes is backward incompatible and require changing project name, path to files, GUIDs, etc.
MINOR changes is backward compatible. Mark introduction of new features.
REV for security/bug fixes. Backward and forward compatible.
eg. In SQL server 2008 RTM version number is 10.00.1600.22 and In SQL server 2012 version is 11.00.2100.60
First field is changed due to change in project name i.e. 10 and 11
In SQL server 2008 R2 RTM version number is 10.50.1600.1 and In SQL server 2008 version is 11.00.1600.22
Second field is changed due to introduction of new features.
Third field indicate build(developed)
Forth field indicates revision i.e. hotfixes applied...

A: A lot of free software uses a three point system: X.Y.Z where

*

*X is for compatibility breaking releases.

*Y is for other releases, with even numbers being stable and odd numbers being unstable.

*Z is for fixes.

This way version 0.28.1 is a stable release with one fix and 2.9.0 is an alpha release with zero fixes.
Some people also have fun developing their own schemes. E.g. Tex which by each release approxed Pi, with version numbers: 3, 3.1, 3.14, etc.

A: It does not really matter, as long as you can use the version number to identify your versions (i. e. either add your source control system's internal revision number into the version number) or use it for tagging your releases.
When you do so, you might want to use that number as your third (or fourth) component. It looks confusing if some product jumps from version 1.12345 to 2.12346, but jumping from 1.4.12345 to 2.0.12345 is more common.
About which number to start, I just want to quote Eric S. Raymond:

In the closed-source world, Version
  1.0 means "Don't touch this if you're prudent."; in the open-source world
  it reads something more like "The
  developers are willing to bet their
  reputations on this."

A: You might want to start by taking a look at the Software versioning article on wikipedia, which gives some informations about the possibilities you have ;-)
It might give you some ideas of what you could do in your specific case...

A: I've used
Major.Minor.Release.Build
1.02.4.15
and also
Year.Month.Date
2009.12.10
but anything that allows you to individually track releases would work. As long as you're consistent.

A: We use major.minor.revision.build where revision is the SVN revision and build is the build number which is based on the current date (in YYDDD format where YY is the year and DDD the day number, so 18001 would be Jan 1st 2018.)
Having the SVN revision is incredibly useful and has saved us on more than one occasion.

A: Version numbers are not a concrete specification in software development.
In other words, one team may use 1.0.0.0, others may use 1.0.0 and so on. It matters not.
Just choose something that works for you.
Typically major.minor.revision is the most simple and straight forward method to use. Visual Studio for example can assign version numbers automatically for you, as can other tools. So all you are required to update is the major/minor values. The build/revision numbers are updated automatically.

A: I seem to remember that in the old days (I am talking Commodore here) we used a syntax like
release.version.revision
which could be appended with either fix and/or build, where fix would usually be a letter stuck directly to the revision. So a full number would read something like:
2.1.44a.786
But like most have already said, it doesn't really matter, there is no true standard for this. Just use whatever is most convenient for you.

A: After reading a lot of articles/QAs/FAQs/books I become to think
that [MAJOR].[MINOR].[REV] is most useful versioning schema to
describe compatibility between project version (versioning schema
for developer, does not for marketing).
MAJOR changes is backward incompatible and require changing
project name, path to files, GUIDs, etc.
MINOR changes is backward compatible. Mark introduction of new
features.
REV for security/bug fixes. Backward and forward compatible.
This versioning schema inspired by libtool versioning semantics and by articles:
http://www106.pair.com/rhp/parallel.html
NOTE: I also recommend provide build/date/custom/quality as additional info (build
number, build date, customer name, release quality):
Hello app v2.6.34 for National bank, 2011-05-03, beta, build 23545
But this info is not versioning info!!

A: You can use any form of version numbering you desire.
I just recommend using something that makes sense.  The Major.Minor.Revision numbering is popular, but any numbering scheme you wish is "valid".

A: When developing software libraries, I recommend using the version number to communicate the level of source and binary compatibility between two releases.
Since you're developing a web application, a two part version number is probably sufficient. The first part is for new functionality and the second is for fixes.


text:
Q: multiple join with two table with two condtions in laravel I have notification table and quote_policy table in that 2 id will be similar. notification.policy_id = quote_policy.policy_id and notification.user_id ','=','quote_policy.user_id i have to join in the code.  got this error production.ERROR: PDOException: SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'quote_policy' in.  Please help me.
  $policyCreate = DB::table('notification')->select('*')
  ->join('quote_policy','notification.policy_id','=','quote_policy.policy_id' )
  ->join('quote_policy','notification.user_id ','=','quote_policy.user_id')
  ->groupBy('notification.id')
  ->get();

A: Try this Query:
$policyCreate = DB::table('notification')->select('*')
  ->join('quote_policy as q1','notification.policy_id','=','q1.policy_id' )
  ->join('quote_policy as q2','notification.user_id ','=','q2.user_id')
  ->groupBy('notification.id')
  ->get();

2nd way:
  $policyCreate = DB::table('notification')->select('*')
  ->join('quote_policy', function($join){
    $join->on('notification.policy_id', '=', 'quote_policy.policy_id');
    $join->on('notification.user_id','=', 'quote_policy.user_id');
  });
  ->groupBy('notification.id')
  ->get();


text:
Q: Swiper slider SVG icon doesn't show sometime in angular material svg icon Swiper doesn't display SVG icons sometimes when I am using angular material SVG icon.
I am using svg icon this way - Svg Icon Reference here
HTML CODE
<swiper [config]="expertExperienceConfig">

                                <mat-icon svgIcon="certificationProcess"></mat-icon>

CERTIFICATION PROCESS

                                All your qualifications in one place

                                <mat-icon svgIcon="connectExperts"></mat-icon>

CONNECT WITH EXPERTS

                                Talk to other users. Reach out and introduce yourself.

                                <mat-icon svgIcon="linkRecruiters"></mat-icon>

DIRECT LINK TO RECRUITERS

                                Share and be seen

                                <mat-icon svgIcon="blockchainVerification"></mat-icon>

BLOCKCHAIN VERIFICATION

                                Trust, Validity, Convenience

                                <mat-icon svgIcon="planJourney"></mat-icon>

CERTIFICATION PROCESS

                                All your qualifications in one place

                                <mat-icon svgIcon="improveEfficiency"></mat-icon>

CERTIFICATION PROCESS

                                All your qualifications in one place

                </swiper>

TYPE SCRIPT CODE(Configration code)
expertExperienceConfig: SwiperOptions = {
  loop: true,
  direction: 'vertical',
  slidesPerView: 4,
  autoplay: 1000};

For more clarify, I just attached the image. So have a look, please Sometime icons show or sometimes not show.
I am using Angular 6 and swiper "swiper": "^3.4.2" package this

A: I was able to fix the error, thank to this thread https://github.com/nolimits4web/swiper/issues/2629#issuecomment-737897281.
Solution
Add into your configuration the following
private swiper: Swiper
isSwiperReady = false

expertExperienceConfig: SwiperOptions = {
    loop: true,
    slidesPerView: 2,
    navigation: true,
    on: { // <-- Fix the mat-icon error
      slideChangeTransitionStart: (swiper) => {
        if (!this.isSwiperReady) return

        let $wrapperEl = swiper.$wrapperEl
        let params = swiper.params
        $wrapperEl
          .children('.' + params.slideClass + '.' + params.slideDuplicateClass)
          .each(function () {
            let idx = this.getAttribute('data-swiper-slide-index')
            this.innerHTML = $wrapperEl
              .children(
                '.' +
                  params.slideClass +
                  '[data-swiper-slide-index="' +
                  idx +
                  '"]:not(.' +
                  params.slideDuplicateClass +
                  ')',
              )
              .html()
          })
      },

      slideChangeTransitionEnd: (swiper) => {
        if (!this.isSwiperReady) return

        swiper.slideToLoop(swiper.realIndex, 0, false)
      },
    },
};

constructor() {}

ngOnInit() {
  this.swiper = new Swiper('.my-swiper-ref', expertExperienceConfig)
  this.isSwiperReady = true
}

Caution

*

*It's only required if you're using mat-icon with custom svg

*It will copy the DOM element and paste it as it would be the next one

*The auto option didn't worked for me

*isSwiperReady is used to fix firefox display error


text:
Q: Writing to a .plist file I have a .plist with 2 key values in it. It is of type Dictionary. I am trying to write value to one of the key values. What's wrong with the code below? I also tried using type "Array". That option also does not work. How can I get it to work using Dictionary & also Array? Anyone has working code example? Thanks. I would appreciate any help.
NSString *filePath = @"myprefs.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:@"test@test.com" forKey:@"Email"];
[plistDict writeToFile:filePath atomically: YES];

A: You did not initialize the path properly.
If "myprefs.plist" is inside the resources folder of your project then initialize like this:
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"myprefs" ofType:@"plist"];

If its somewhere else in your computer, specify the whole path


text:
Q: I have a long string which contains dates in multiple formats (dd-mm-yyyy, mm-dd-yyyy etc.) . How do I convert them all into the same format? I am working on Python. I have many long texts of data. Each text can be treated as a string. Within each string, I need to separate the string into elements of a list where ever a date is present.
eg. long string1 (date format: mm.dd.yyyy):

05.12.2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.13.2016 15:58:31  sdfasjdcakscsdv
01.14.2016fsdkjgfdhkvjxdbvxd

eg. long string2 (date format: dd/mm/yyyy):

05/12/2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.1.2016 15:58:31  sdfasjdcakscsdv
21/11/2016fsdkjgfdhkvjxdbvxd

Step1: I need to write a generalized code such that I can pass both strings in the same code.
Step2: Objective of the code is to convert string into list with elements
  separated by date.

eg. long string 1 to list 1
[05.12.2016 15:58:31 jsfkgskdlfsgfdslkcbj, 05.13.2016 15:58:31  sdfasjdcakscsdv, 01.14.2016fsdkjgfdhkvjxdbvxd]

Step 3: and then take the element with the earliest date
output from above example: 01.14.2016fsdkjgfdhkvjxdbvxd

I got help for doing Step 2 and 3 and I can do it when all strings have the same date format. But my challenge is first reading a string and figuring out which date format it is using and then parsing and sorting it on the basis of date
I have code if one date format is given.
text = '05/12/2016 15:58:31 jsfkgskdlfsgfdslkcbj 05.1.2016 15:58:31  sdfasjdcakscsdv 21/11/2016fsdkjgfdhkvjxdbvxd'

list1 = list()
for d, t in zip(*[iter(re.split(r'(\d+[\/.]\d+[\/.]\d+ \d+:\d+:\d+)', text)[1:])]*2):
    list1.append(d + t)

from datetime import datetime
list_sorted=sorted(list1,key=lambda s: datetime.strptime(s[0:19], "%d.%m.%Y %H:%M:%S") if '.' in s[0:19] else datetime.strptime(s[0:19], "%d/%m/%Y %H:%M:%S"))

complaint = list_sorted[0]
print(complaint)

The above code works well for a single string for a single date format. How do I generalize it to first detect the date format in the string and then parse it accordingly

A: You can use dateutil.parser present in the dateutil module which can parse the date-time string for you irrespective of the format
In [17]: from dateutil import parser

In [18]: parser.parse('05/12/2016 15:58:31', fuzzy=True)
Out[18]: datetime.datetime(2016, 5, 12, 15, 58, 31)

In [19]: parser.parse('05.1.2016 15:58:31', fuzzy=True)
Out[19]: datetime.datetime(2016, 5, 1, 15, 58, 31)

In [20]: parser.parse('21/11/2016', fuzzy=True)
Out[20]: datetime.datetime(2016, 11, 21, 0, 0)

Or another example which collects the datetime objects and sort the original list according to it
from dateutil import parser

#List of textdate srings
textdate = ['5.13.2001 21:23:54 fgdsgd', '05.12.2001 09:43:32 arfehfks']

#Collect datetime objects
dates = []
for item in textdate:
    dates.append(parser.parse(item, fuzzy=True))

#Sort datetime objects and obtained original list on sorting
res = [textdate[i[0]] for i in sorted(enumerate(dates), key=lambda x:x[1])]
print(res)

The output will be
['05.12.2001 09:43:32 arfehfks', '5.13.2001 21:23:54 fgdsgd']


text:
Q: Node postgres constraints I'm trying to write a constraint code that will display a message when someone tries to search for an id that doesn't exist in the database (PostgreSQL) but the if statement code below doesn't seem to do anything I keep getting status 200 ok on postman even though the id doesn't seem to exist. How can I fix this?
Code below:
Database query:
const findFruit = async (req, res) => {

    const {id } = req.params;
    try {
        const findfru = await pool.query("SELECT * FROM fruits WHERE fruit_id=$1", [id]);

        if (!findfru ) {
            return res.status(400).send(e)
        }

        res.json(findfru .rows[0])

    } catch (e) {
        res.status(500).send(e)

    }
}

Route API:
router.get("Fruits/:id", findFruit )

A: If the ID isn't in the database the query still succeeds, it just returns no rows. You should check the number of rows explcitily:
if (findfru.rows.length === 0) {
    return res.status(400).send(`${id} not found`);
}


text:
Q: Saving the duplicate rows in a seperate dataframe I am able to delete the duplicate rows using pandas,
df.drop_duplicates(subset=['issuer_id', 'hios_plan_identifier', 'group_or_individual_plan_type']) .
For I know , it drops all the duplicates keeping the first occurrence which is the default functionality.
My requirement is that I want to save the dropped data to a another dataframe checking on a subsets of columns.
I have my dataframe df,
  issuer_id hios_plan_identifier  plan_year group_or_individual_plan_type
0        484      99806CAAUSJ-TMP       2018                         Group
1        484      99806CAAUSJ-TMP       2018                         Group
2        484      99806CAAUSJ-TMP       2018                         Group
3        484      99806CAAUSJ-TMP       2018                         Group

I want to drop the duplicates from df(will have only 1 row) and save the rest in another dataframe df1 (will have 3 rows).

A: Use duplicated and assign the values to df1 and then drop_duplicates on df:
subset_col = ['issuer_id', 'hios_plan_identifier', 'group_or_individual_plan_type']
df1 = df.loc[df.duplicated(subset=subset_col),:]
df = df.drop_duplicates(subset=subset_col)

print(df)
   issuer_id hios_plan_identifier  plan_year group_or_individual_plan_type
0        484      99806CAAUSJ-TMP       2018                         Group

print(df1)
   issuer_id hios_plan_identifier  plan_year group_or_individual_plan_type
1        484      99806CAAUSJ-TMP       2018                         Group
2        484      99806CAAUSJ-TMP       2018                         Group
3        484      99806CAAUSJ-TMP       2018                         Group


text:
Q: Numerical instability FFTW <> Matlab I am trying to numerically solve the Swift-Hohenberg equation http://en.wikipedia.org/wiki/Swift%E2%80%93Hohenberg_equation using a pseudo-spectral scheme, where the linear terms are treated implicitly in Fourier space, while the nonlinearity is evaluated in real space. A simple Euler scheme is used for the time integration.
My problem is that the Matlab code I have come up with works perfectly, while the C++ code, which relies on FFTW for the Fourier transforms, becomes unstable and diverges after a couple thousand time steps. I have tracked it down to the way the nonlinear term is treated (see the comments in the C++ code). If I use only the real part of Phi, the instability occurs. However, Phi should only have a negligible imaginary part due to numerical rounding errors, and Matlab is doing something similar, keeping Phi purely real.
The Matlab code also runs fine under Octave. The initial condition can be something like
R=0.02*(rand(256,256)-0.5);
in Matlab (small amplitude fluctuations).

TLDR;
Why do these pieces of code do different things? Specifically, how can I make the C++ code work the same way the Matlab version does?
Edit 1:
For completeness, I have added the code using the R2C/C2R functions provided by FFTW. See http://fftw.org/fftw3_doc/Multi_002dDimensional-DFTs-of-Real-Data.html for details (I hope I got the data layout right). This code always shows the instability after about 3100 time steps. If I reduce dt to e.g. 0.01, it occurs 10 times later.
C++ code using complex DFTs
#include <iostream>
#include <fstream>
#include <cmath>
#include <fftw3.h>

int main() {

const int N=256, nSteps=10000;
const double k=2.0*M_PI/N, dt=0.1, eps=0.25;

double *Buf=(double*)fftw_malloc(N*N*sizeof(double));
double *D0=(double*)fftw_malloc(N*N*sizeof(double));

// complex arrays
fftw_complex *Phi=(fftw_complex*)fftw_malloc(N*N*sizeof(fftw_complex));
fftw_complex *PhiF=(fftw_complex*)fftw_malloc(N*N*sizeof(fftw_complex));
fftw_complex *NPhiF=(fftw_complex*)fftw_malloc(N*N*sizeof(fftw_complex));

// plans for Fourier transforms
fftw_plan phiPlan=fftw_plan_dft_2d(N, N, Phi, PhiF, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_plan nPhiPlan=fftw_plan_dft_2d(N, N, NPhiF, NPhiF, FFTW_FORWARD, FFTW_ESTIMATE);
fftw_plan phiInvPlan=fftw_plan_dft_2d(N, N, Phi, Phi, FFTW_BACKWARD, FFTW_ESTIMATE);

std::ifstream fin("R.dat", std::ios::in | std::ios::binary); // read initial condition
fin.read(reinterpret_cast<char*>(Buf), N*N*sizeof(double));
fin.close();
for(int i=0; i<N*N; i++) {
    Phi[i][0]=Buf[i];   //initial condition
    Phi[i][1]=0.0;  //no imaginary part
}

fftw_execute(phiPlan);  //PhiF contains FT of initial condition

for(int j=0; j<N; j++) {
    for(int i=0; i<N; i++) {

        double kx=(i-(i/(N-N/2)*N))*k;
        double ky=(j-(j/(N-N/2)*N))*k;
        double k2=kx*kx+ky*ky;

        D0[j*N+i]=1.0/((1.0 - dt*(eps-1.0 + 2.0*k2 - k2*k2)));  // array of prefactors
    }
}

const double norm=1.0/(N*N);

for(int n=0; n<=nSteps; n++) {

    if(n%100==0) {
        std::cout<<"n = "<<n<<'\n';
    }

    for(int j=0; j<N*N; j++) {
        // nonlinear term Phi^3
        //NPhiF[j][0]=Phi[j][0]*Phi[j][0]*Phi[j][0]; // unstable
        //NPhiF[j][1]=0.0;
            NPhiF[j][0]=Phi[j][0]*Phi[j][0]*Phi[j][0] - 3.0*Phi[j][0]*Phi[j][1]*Phi[j][1];
            NPhiF[j][1]=-Phi[j][1]*Phi[j][1]*Phi[j][1] + 3.0*Phi[j][0]*Phi[j][0]*Phi[j][1];
    }

    fftw_execute(nPhiPlan); // NPhiF contains FT of Phi^3

    for(int j=0; j<N*N; j++) {
        PhiF[j][0]=(PhiF[j][0] - dt*NPhiF[j][0])*D0[j]; // update
        PhiF[j][1]=(PhiF[j][1] - dt*NPhiF[j][1])*D0[j];

        Phi[j][0]=PhiF[j][0]*norm; // FFTW does not normalize
        Phi[j][1]=PhiF[j][1]*norm;
    }

    fftw_execute(phiInvPlan); // Phi contains the updated Phi in real space
}

for(int i=0; i<N*N; i++) {
    Buf[i]=Phi[i][0];   // saving the real part of Phi
}
std::ofstream fout("Phi.dat", std::ios::trunc | std::ios::binary);
fout.write(reinterpret_cast<char*>(Buf), N*N*sizeof(double));
fout.close();

for(int i=0; i<N*N; i++) {
    Buf[i]=Phi[i][1];   // saving the imag part of Phi
}
fout.open("PhiImag.dat", std::ios::trunc | std::ios::binary);
fout.write(reinterpret_cast<char*>(Buf), N*N*sizeof(double));
fout.close();

fftw_free(D0);
fftw_free(Buf);

fftw_free(Phi);
fftw_free(PhiF);
fftw_free(NPhiF);

fftw_destroy_plan(phiPlan);
fftw_destroy_plan(phiInvPlan);
fftw_destroy_plan(nPhiPlan);

return EXIT_SUCCESS;
}

C++ code using R2C/C2R

#include <iostream>
#include <fstream>
#include <cmath>
#include <fftw3.h>

int main() {

const int N=256, nSteps=3100;
const int w=N/2+1;
const double k=2.0*M_PI/N, dt=0.1, eps=0.25;

double *Buf=(double*)fftw_malloc(N*N*sizeof(double));
double *D0=(double*)fftw_malloc(N*w*sizeof(double));

fftw_complex *Phi=(fftw_complex*)fftw_malloc(N*w*sizeof(fftw_complex));
fftw_complex *PhiF=(fftw_complex*)fftw_malloc(N*w*sizeof(fftw_complex));
fftw_complex *NPhi=(fftw_complex*)fftw_malloc(N*w*sizeof(fftw_complex));

fftw_plan phiPlan=fftw_plan_dft_r2c_2d(N, N, (double*)PhiF, PhiF, FFTW_ESTIMATE);
fftw_plan nPhiPlan=fftw_plan_dft_r2c_2d(N, N, (double*)NPhi, NPhi, FFTW_ESTIMATE);
fftw_plan phiInvPlan=fftw_plan_dft_c2r_2d(N, N, Phi, (double*)Phi, FFTW_ESTIMATE);

std::ifstream fin("R.dat", std::ios::in | std::ios::binary);
fin.read(reinterpret_cast<char*>(Buf), N*N*sizeof(double));
fin.close();
for(int j=0; j<N; j++) {
    for(int i=0; i<N; i++) {
        ((double*)PhiF)[j*2*w+i]=Buf[j*N+i];
        ((double*)Phi)[j*2*w+i]=Buf[j*N+i];
    }
}

fftw_execute(phiPlan); //PhiF contains FT of IC

for(int j=0; j<N; j++) {
    for(int i=0; i<w; i++) {

        double kx=(i-(i/(N-N/2)*N))*k;
        double ky=(j-(j/(N-N/2)*N))*k;
        double k2=kx*kx+ky*ky;

        D0[j*w+i]=1.0/(1.0 - dt*(eps-1.0 + 2.0*k2 - k2*k2));
    }
}

const double norm=1.0/(N*N);

//begin first Euler step
for(int n=0; n<=nSteps; n++) {

    if(n%100==0) {
        std::cout<<"n = "<<n<<'\n';
    }

    for(int j=0; j<N; j++) {
        for(int i=0; i<N; i++) {
            ((double*)NPhi)[j*2*w+i]=((double*)Phi)[j*2*w+i]  *((double*)Phi)[j*2*w+i]  * ((double*)Phi)[j*2*w+i];
        }
    }

    fftw_execute(nPhiPlan); // NPhi contains FT of Phi^3

    for(int j=0; j<N*w; j++) {
        PhiF[j][0]=(PhiF[j][0] - dt*NPhi[j][0])*D0[j];
        PhiF[j][1]=(PhiF[j][1] - dt*NPhi[j][1])*D0[j];
    }

    for(int j=0; j<N*w; j++) {
        Phi[j][0]=PhiF[j][0]*norm;
        Phi[j][1]=PhiF[j][1]*norm;
    }

    fftw_execute(phiInvPlan);

}

for(int j=0; j<N; j++) {
    for(int i=0; i<N; i++) {
        Buf[j*N+i]=((double*)Phi)[j*2*w+i];
    }
}

std::ofstream fout("Phi.dat", std::ios::trunc | std::ios::binary);
fout.write(reinterpret_cast<char*>(Buf), N*N*sizeof(double));
fout.close();

fftw_destroy_plan(phiPlan);
fftw_destroy_plan(phiInvPlan);
fftw_destroy_plan(nPhiPlan);

fftw_free(D0);
fftw_free(Buf);
fftw_free(Phi);
fftw_free(PhiF);
fftw_free(NPhi);
}

Matlab code
function Phi=SwiHoEuler(Phi, nSteps)
epsi=0.25;
dt=0.1;

[nR nC]=size(Phi);
if mod(nR, 2)==0
    kR=[0:nR/2-1 -nR/2:-1]*2*pi/nR;
else
    kR=[0:nR/2 -floor(nR/2):-1]*2*pi/nR;
end
Ky=repmat(kR.', 1, nC);

if mod(nC, 2)==0
    kC=[0:nC/2-1 -nC/2:-1]*2*pi/nC;
else
    kC=[0:nC/2 -floor(nC/2):-1]*2*pi/nC;
end
Kx=repmat(kC, nR, 1); % frequencies
K2=Kx.^2+Ky.^2; % used for Laplacian in Fourier space
D0=1.0./(1.0-dt*(epsi-1.0+2.0*K2-K2.*K2)); % linear factors combined

PhiF=fft2(Phi);

for n=0:nSteps
    NPhiF=fft2(Phi.^3); % nonlinear term, evaluated in real space
    if mod(n, 100)==0
        fprintf('n = %i\n', n);
    end
    PhiF=(PhiF - dt*NPhiF).*D0; % update

    Phi=ifft2(PhiF); % inverse transform
end
return

A: Look at these lines:

for ...
  double kx=(i-(i/(N-N/2)*N))*k;
  double ky=(j-(j/(N-N/2)*N))*k;
  double k2=kx*kx+ky*ky;
...

I have to admit that I did not look into the algos but "i/(N-N/2)" consists of integers and I suspect that your kx, ky, and k2 are calculated as expected. You may try something like this which avoids potential integer rounding errors:

for ...
  double kx=( double(i) -( double(i)/(0.5*double(N*N)))*k; // where in our case: (N-N/2)*N) = 0.5*N*N
  ...
...

A: EDIT The below is not correct OP had it right.
A pointer to the real part is stored in [0], the imaginary stored in [1]
 (i.e. NPhi[1][j] is what you should be referencing - at least according to Their site). So that is probably one problem. The fixed lines (I believe) should be the following:
NPhiF[0][j]=Phi[0][j]*Phi[0][j]*Phi[0][j] - 3.0*Phi[0][j]*Phi[1][j]*Phi[1][j];
NPhiF[1][j]=-Phi[1][j]*Phi[1][j]*Phi[1][j] + 3.0*Phi[0][j]*Phi[0][j]*Phi[1][j];

That will fix one part - you will have to fix the rest.


text:
Q: performance issues with finding nth occurence of a character with a regular expression I have a regex to find the nth occurrence of a character in a string, here's the code:
 public static int NthIndexOf(this string target, string value, int n)
    {
        Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");

        if (m.Success)
        {
            return m.Groups[2].Captures[n - 1].Index;
        }
        else
        {
             return -1;
        }
    }

Now, I have 1594 entries in this string, with 1593 semicolons. If I write:
tempstring.NthIndexOf(";", 1593)

The answer comes back immediately and correctly. If I give it anything over 1594 it hangs. Does anyone know how to fix this?
Test Case
 string holder = "test;test2;test3";
        string test = "";
        for (int i = 0; i < 600; i++)
        {
            test += holder;
        }
        int index = test.NthIndexOf(";", 2000);

This takes a very long time. Change 600 to 6 and it is very fast. Make 2000 to 1700 and it is very fast as well.
Why is my regular expression so slow?

A: If you're really only looking for character repetitions, and not string repetitions, then you should be able to replace you method with something simple like
public static int NthIndexOf(this string target, char testChar, int n)
{
   int count = 0;

   for(int i=0; i<target.Length; i++)
   {
      if(target[i] == testChar)
      {
         count++;
         if(count == n) return i;
      }
   }

   return -1;
}

and use that.  It should have far fewer limitations.
As for why your original regex is going slow, here's what I suspect:

*

*For your fast case, it's working because it can find a match on it's first pass through (with each group matching exactly one character)

*For the slow case is because it can't find a match (and won't ever find one, because there aren't enough semicolons to satisfy the regex), but it  recursively tries every possible way to break up the string (which is a really big operation)

A: Try to use a more distinct and efficient regular expression:
"^(?:[^" + value + "]*" + value + "){" + (n - 1) + "}([^" + value + "]*)

This will build the following regular expression for tempstring.NthIndexOf(";", 1593):
^(?:[^;]*;){1592}([^;]*)

But this will only work for single characters as separator.
Another approach would be to step through each character and count the occurences of the character you were looking for.


text:
Q: New to Java, need help on storing elements from textfields into custom type object and storing the object into an ArrayList I need help on how to store user string input from the textfields into the Appointment) inside an ArrayList. The error I'm getting is 'cannot convert string to object Appointment', I can't figure out how to store both the time and appointment into the custom type object and then storing it into the ArrayList.
I'm attempting this within my ButtonListener method
class appointment{

    private String time;
    private String appt;

    public appointment()
    {
        time = " ";
        appt = " ";
    }

    public appointment(String time, String appt)
    {
        this.time = time;
        this.appt = appt;
    }

    public String getTime()
    {
        return this.time;
    }

    public String getAppt()
    {
        return this.appt;
    }

    public void setTime(String time1)
    {
        time1 = time;
    }

    public void setAppt(String appt1)
    {
        appt1 = appt;
    }
}

    private class ButtonListener implements EventHandler<ActionEvent>

    {
        private Button pressedButton = new Button();
        List<appointment> str = new ArrayList<appointment>();

        @Override
        public void handle(ActionEvent e)
        {
            if(e.getSource() instanceof Button)
            {
                pressedButton = (Button) e.getSource();

                if(pressedButton == submit)
                {
                    appointment i = time1.getText();
                    appointment g = appt1.getText();
                    str.add(i, g);
                    JOptionPane.showMessageDialog(null, "Added");
                }
            }
        }
    }

}

A: Define the Appointment object and put the values to the constructor then add the object to
the ArrayList, like this:
if(pressedButton == submit) {
    Appointment appointment = new Appointment(time1.getText(), appt1.getText());
    str.add(appointment);
    JOptionPane.showMessageDialog(null, "Added");
}

A: You need to create new Appointment object and then insert into str.
Appointment appointment = new Appointment(time1.getText(), appt1.getText());
str.add(appointment);

A: The problem is that you have an ArrayList of Appointment objects and you're trying to give it a couple of time and string , what you will have to do is to create a new instance of Appointment and add it to the list , like this :
String time = time1.getText();
String appt = appt1.getText();
Appointment app = new Appointment(time,appt);
str.add(app);


text:
Q: Unable to login after db upgrade I upgraded postgresql from 8.4.2 to 12.3. I created a dump of the db from the old version, and restored into the new version.
The port for the new version is 5532. The old one uses 5432. After I restore the dump, I check that the service is running for the new version, and the server is listening on port 5532 for all interfaces.
I even copy the pg_hba.conf entries from the old version to the new version. But instead of "password" I change all the entries to "md5" because this is a newer version. After changes, I reload pg_hba.conf.
However, when we test access to the new db now, it does not work. It fails with error :

Your login attempt was not successful, try again. Reason : Could not
get JDBC Connection; nested exception is
org.postgresql.util.PSQLException: FATAL: no pg_hba.conf entry for
host "192.168.130.209", user "app_support", database "bosupportdb"

Postgres ports :
[root@reportv2 data]# ss -tulpn | grep postgres
tcp    LISTEN     0      128       *:5432                  *:*                   users:(("postgres",pid=3454,fd=3))
tcp    LISTEN     0      128       *:5532                  *:*                   users:(("postgres",pid=4763,fd=3))
tcp    LISTEN     0      128      :::5432                 :::*                   users:(("postgres",pid=3454,fd=4))
tcp    LISTEN     0      128      :::5532                 :::*                   users:(("postgres",pid=4763,fd=4))
[root@reportv2 data]#

These are my pg_hba.conf entries :
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD

# "local" is for Unix domain socket connections only
local   all         all                               md5
# IPv4 local connections:
host   all              all             127.0.0.1/32            md5
host    all             all             192.168.130.0/24        md5
#host   all             all             192.168.8.0/24          md5
host    all             all             192.168.90.8/32         md5
host    all             all             192.168.8.175/32        md5
host    all             all             192.168.112.0/23        md5

Please help me resolve this. I am clueless.

A: Make sure that the HBA rules that PostgreSQL is actually using are the ones you expect:
select *
from pg_hba_file_rules
where type = 'host'
order by line_number ;

Check the error column for anything amiss with the file syntax.


text:
Q: Create Zend extensible application I'm looking for a way to create zend-based application (web store) which I would extend by plugins in the future. For now I have base functionality (browsing products, make orders etc).
What I need is make possibility to attach plugins to this app. By "plugin" I mean some static files structure in sepearated directory. One of plugins, which I want to write in future is allegro(polish eBay like)-integration  tool. it would operate on existing models (user, product etc). It needs to have their own controller which would be executed in backend; Some other should be like public-accessible simple gallery for front-end. Some of other plugins should be able to attach content on previously definied spots in view.
I have no idea how can I reach this. Every of these plugins should have their own directory and It's very important;
Maybe there is some free extensible zend-based CMS? what would be yours choice?
Please for ideas and thanks for help

A: You are looking for zend module. Each module will be having independent functionality.
Module structure is below
zf2-tutorial/
    /module
        /Album
            /config
            /src
                /Album
                    /Controller
                    /Form
                    /Model
            /view
                /album
                    /album

Likewise you can have modules like Oerder, Payment, User etc etc.
And you can create some interface to communicate through modules.
Below link will help you
http://framework.zend.com/manual/2.0/en/user-guide/modules.html
http://framework.zend.com/manual/2.0/en/modules/zend.module-manager.intro.html

A: If you are using ZF2, then modules are the way to go, as EVERYTHING in ZF2 can be a module.
Check out http://modules.zendframework.com/ for an idea of what's available. Whats more is that you can drop a module into your application, try it out and then remove it if you dont think its right for your project. Everything about a module can be modified and modules should provide hooks that your other modules can listen to.
Evan Coury (who wrote the core of the ModuleManager for zf2) has been working on https://github.com/speckcommerce which will probably cover alot of what you need


text:
Q: How to access array elements inside vue.js conditional css class I'm getting starting with Vue.js and I have a simple page set up to experiment with conditional css.

and then my js
new Vue({
  el: "#app",
  data: {
    attachRed: [false, false, false]
  },
  methods: {
    handleClick: function(index) {
      this.attachRed[index] = !this.attachRed[index];
      console.log(this.attachRed)
    }
  }
});

Each div is a grey block. When attaching the "red" class, the block turns red. attachRed array is updating every time a demo div is clicked. But the class is never added. If I start the attachRed property off as being true,  then the red class is attached initially, but this isn't toggled when clicked. This works if these values aren't stored in an array though.
Is it possible to make the view bindings watch for these changes or to manually trigger one? Or is there some sort of gotcha when it comes to array properties?

A: It is a gotcha. This page goes into it a bit: https://vuejs.org/2016/02/06/common-gotchas/
In short, you want to do
var val = this.attachedRed[index]
this.attachedRed.$set(index, !val);


text:
Q: django serializer field not recognizing attribute clearly defined when i try to run a view I get this error:
AttributeError: Got AttributeError when attempting to get a value for field `inreplytouser` on serializer `ContentFeedPostCommentSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'inreplytouser'.

Here is my model:
class ContentFeedPostComments(models.Model):
   inreplytouser = models.ForeignKey(SiteUsers, null=True, related_name='replytouser', blank=True, on_delete=models.CASCADE)
   inreplytotopcomment = models.BigIntegerField(null=True, blank=True)
   timecommented = models.DateTimeField(auto_now_add=True)
   user = models.ForeignKey(SiteUsers, on_delete=models.CASCADE)
   contentcreator = models.ForeignKey(ContentCreatorUsers, on_delete=models.CASCADE)
   contentfeedpost = models.ForeignKey(ContentFeedPost, on_delete=models.CASCADE)
   text = models.CharField(max_length=1000)

here is the serializer:
class ContentFeedPostCommentSerializer(ModelSerializer):
    id = IntegerField()
    inreplytouser = SiteusersSerializer()
    user = SiteusersSerializer()
    contentcreator = ContentCreatorSerializer()

    class Meta:
        model = ContentFeedPostComments
        fields = ('id','inreplytouser', 'inreplytotopcomment', 'timecommented',
                  'user', 'contentcreator', 'contentfeedpost', 'text')

here is the view:
class ContentFeedPostsComments(APIView):
    def get(self, request, *args, **kwargs):
        postid = kwargs.get('postid')
        contentfeedpost = get_object_or_404(ContentFeedPost, id=postid)
        topcomments = ContentFeedPostComments.objects.filter(contentfeedpost= contentfeedpost, inreplytotopcomment= None).order_by('timecommented')
        replycomments = ContentFeedPostComments.objects.filter( contentfeedpost = contentfeedpost, inreplytotopcomment__isnull = False).order_by('timecommented')
        serializedtopcomments = ContentFeedPostCommentSerializer(topcomments)
        serializedreplycomments = ContentFeedPostCommentSerializer(replycomments)
        payload = {
            'topcomments': serializedtopcomments.data,
            'replycomments': serializedreplycomments.data
        }
        return Response(payload)

I was reading something about source being passsed into the inreplytouser field of the serializer field but that makes no sense. Your wisdom and knowledge on this situation is greatly appreciated.

A: Since querysets are a collection of objects, many=True..[DRF-doc] needs to be set in the serializer:
serializedtopcomments = ContentFeedPostCommentSerializer(topcomments, many=True)
serializedreplycomments = ContentFeedPostCommentSerializer(replycomments, many=True)


text:
Q: Is there an R function that can create an adjacency list / edge list / adjacency dataframe from a csv, to then use in iGraph? I am trying to perform a Social Network Analysis of Congressional Roll Call data. The data I have comes as a csv, from voteview.com, and has the following format:
Format of the csv
There are a high number of unique bills (represented by roll number) that I need to loop through to see how often politicians (represented by icpsr) agree in their vote (represented by cast_code).
However, I am really unsure of how I would loop through this data frame, check if two politicians vote the same on a unique bill, and then add that to a new data frame which would have three columns [politician 1|politican 2|weight (how many times they voted the same on unique bills)].
I have produced the following code when there was just a single bill being considered, which was able to get me a network map:
    #1. creating a dataframe with all the yayers and one with all the nayers

yay_list <- S117 %>% filter(cast_code == '1')
nay_list <- S117 %>% filter(cast_code == '6')

#2. a list of the icpsr numbers who agree for yay and nay

y_list <- list(yay_list$icpsr)
n_list <- list(nay_list$icpsr)

#3. trying to use this list to make an igraph graph - BUT it does not recognise it
# I am not sure where to go next

make_ring(yay_list)
a1 <- as_adj_list(y_list)

#4. Alternative method - using only columns for icpsr & cast_code
# this will make an edge/adjency style data frame

foo <- S117[, c("icpsr", "cast_code")]

library(plyr)

# define a function returning the edges for a single group
group.edges <- function(x) {
  edges.matrix <- t(combn(x, 2))
  colnames(edges.matrix) <- c("Sen_A", "Sen_B")
  edges.df <- as.data.frame(edges.matrix)
  return(edges.df)
}

# apply the function above to each group and bind altogether
all.edges <- do.call(rbind, lapply(unstack(foo), group.edges))

# add weights if needed
#all.edges$weight <- 1
#all.edges <- aggregate(weight ~ Sen_A + Sen_B, all.edges, sum)

all.edges

#convert to a dataframe for igraph
df <- data.frame(all.edges)
df

# use igraph function on new datafame and plot
g <- graph_from_data_frame(df)
print(g, e=TRUE, v=TRUE)
plot(g)

# a plot is produced, which is good, but I do not know how to do this for
# a situation where there are multiple bills - it seems very complicated

Does anyone have any advice on how I would create a similar style edge list data frame, ideally with weights (as there are many bills in the data frame not just 1)?
The weight should show how many times politicians vote the same way (either yay or nay) on unique bills.
Thanks!


text:
Q: Displaying data from a JSON file with Angular As all questions look like they are outdatet i'm asking this Question.
First of all I need to mention that I just started Angular 4 days ago, so please explain everything like you would to your child ( or sth. that comes near that haha).
I currently try to retrieve a JSON from a Flask Server.
It has this format.
{"id":[1,2,3],"name":["Test 1","Test 2","Test 3"]}

The examples will be missing the Imports because it worked properly when testing and now the data should come from a Server.
When I try to Iterate using *ngFor the following error shows up.
Error: "Error trying to diff 'Test 1,Test 2,Test 3'. Only arrays and iterables are allowed"

The HTML for this is:

          {{test.id}} {{test.name}}

In my test.service.ts it looks the following.
...
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TestService {

private testUrl = 'http://my.server/tests';

constructor(
  private http: HttpClient
  ) { }

getTests(): Observable<Test[]> {
        return this.http.get<Test[]>(this.testUrl);
        }
...

And in my tests.component.ts like this:
...
@Component({
  selector: 'app-tests',
  templateUrl: './tests.component.html',
  styleUrls: ['./tests.component.css']
})
export class TestsComponent implements OnInit {
  tests: Test[];

  getTests(): void {
        this.testService.getTests()
                .subscribe(tests => this.tests = tests);

  }

  constructor(private testService: TestService) { }

  ngOnInit(): void {
  this.getTests();
  }

}

After trying to figure it out for 2 hours I don't know how any further.
If something is missing tell me.
Cheers!

A: let test of tests

This is the root of your problem. This is not an iterables or array. tests.id  and tests.name these are arrays. It is very clear by looking at the response from server. ngFor will work on tests.id or tests.name. tests is just an object.

A: As you can see from the log, the *ngForOf is only available for an array.
{"id":[1,2,3],"name":["Test 1","Test 2","Test 3"]}

You receive this json object(which is not array) and tried to use *ngForOf on it.


text:
Q: How can I plot multiple y variables stacked in a bubble plot? I am trying to visualise some data for a construction project. Each week, for a few years, different vehicles will be accessing the site. I need to produce a graph showing when each vehicle will be accessing the site. The way I'd like to do this is to have a single graph that shows all vehicles on, so that weeks without any vehicles are empty and can be clearly identified, where as busy weeks will have lots of data visible at the same time.
I want to have the y axis be vehicle type (let's say cars, vans and trucks for now) and x axis be time (weeks of the year). I want to use bubbles to display the number of each vehicle, so if there is a dot at the coordinates (Van, Week 1) you will know that vans will be used during week 1, and the bubble size will tell you how many.
My question is essentially - what is this graph called? I want it to be called something like a "discrete stacked bubble plot" or something but that doesn't exist. Please see my example below. Any ideas on how to do this? Or am I approaching the problem the wrong way?
Example of what I want it to look like


text:
Q: How do rockets create thrust in a vacuum? I understand that rockets create a lot of gas which is pushed out of the back and because of equal and opposite reactions the rocket is propelled forwards.
What I don't quite understand is this:
The interstellar space is a vacuum so the gas that the rocket creates is going to naturally want to try to fill this empty space. If this is the case then how is it creating a force that pushes the rocket?
So in the classic gun example where a bullet is shot which in turn pushes back on the gun, there is a gas pressure pushing them both. In space, there is nothing for the gas to push on. It seems that it is simply moving to fill an empty space so I don't understand where the force is coming from.
Would it be that the rockets just create so much gas that pressure is able to build up in the back of the rocket even though the gas is trying to leave naturally?

A: How do you move on Earth? You push the Earth in one direction and you accelerate in the other direction.
How do you move in space? You don't have an Earth handy, so you carry whatever you will push with yourself. The thing you push in a rocket is called "rocket propellant". You can't carry much, that's why you push it really hard. And you can't carry much of anything in a rocket, that's why you get a propellant that can push itself out of the engine nozzle.
In both cases, you rely on "momentum conservation". You + Earth (as a whole) don't accelerate, a rocket + its propellant don't accelerate as well.
On the other hand, the Earth with its really great mass builds our intuition that pushing it is the only practical way of accelerating.
This is not true. You can accelerate by interacting with anything.
p.s. In space, sometimes, you in fact do have a planet handy, because some forces (e.g. gravity) act pretty well at a distance. That's how gravity-assisted maneuvers are done and that's how satellites stay in orbit in the first place.
p.s2 In regard to the gas that left the combustion chamber: you can leave it alone. It doesn't interact with the rocket anymore. It already did its job by pushing the combustion chamber walls and not pushing the opening.

A: I believe you already gave the explanation: in the combustion chamber, the pressure is very high and pushes back. While the pressure at the outlet of the nozzle is much lower. The fact that gas escapes into a vacuum does not remove the pressure difference.