text:
Q: How to get two templated classes implicitly convertible to one another I have recently encountered a scenario which causes the Microsoft Visual Studio 2013 compiler to produce an internal error (C1001: An internal error has occured in the compiler.).
If we have the header file Foo.h:
#pragma once
#ifndef FOO_H
#define FOO_H

#include "Bar.h"

template <typename T>
class Foo {
public:
      operator Bar<T>() const
      {
          Bar<T> bar;

          for( unsigned int i = 0; i < 5; ++i )
               bar.m_tArray[i] = m_tArray[i];

          return bar;
      }

private:
      template <typename U>
      friend class Bar<U>;

      T m_tArray[5];
};

#endif // FOO_H

And Bar.h:
#pragma once
#ifndef BAR_H
#define BAR_H

#include "Foo.h"

template <typename T>
class Bar {
public:
      operator Foo<T>() const
      {
          Foo<T> foo;

          for( unsigned int i = 0; i < 5; ++i )
               foo.m_tArray[i] = m_tArray[i];

          return foo;
      }

private:
      template <typename U>
      friend class Foo<U>;

      T m_tArray[5];
};

#endif // BAR_H

I can then cause the error by instantiating either class, for instance:
int main() {
    Foo<int> foo;
}

I'm guessing the error is occurring because each class refers to the other's definition within it's own definition and so there is an infinite recursion depth; however, I'm not sure how to resolve this problem as I can only have templates defined inline; I can not declare them and then define them elsewhere (when both templates have been declared and the internals exposed to one another).

A: You have to use forward declaration for your template classes. Example:
template <typename T>
class Foo;

template <typename T>
class Bar {
      template <class U>
      friend class Foo;
public:
      operator Foo<T>() const
      {
          Foo<T> foo;

          for( unsigned int i = 0; i < 5; ++i )
               foo.m_tArray[i] = m_tArray[i];

          return foo;
      }

private:

      T m_tArray[5];
};

template <typename T>
class Foo {
      template <class U>
      friend class Bar;
public:
      operator Bar<T>() const
      {
          Bar<T> bar;

          for( unsigned int i = 0; i < 5; ++i )
               bar.m_tArray[i] = m_tArray[i];

          return bar;
      }

private:

      T m_tArray[5];
};

int main() {
    Foo<int> foo;
}


text:
Q: JDBC connection issue with wampserver 2.4 Thank you for giving me you important time.
I am trying to make a connection between the application and the database using WampServer 2.4 My configuration file contains settings (root with no password) that correspond to the default MySQL privileged account. My MySQL server is running with this default,
I am using this code to make connection.
import java.lang.ClassNotFoundException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;

public class implementation {

    public static void main(String[]arg)
    {

        Connection connection = null;
        Statement statement = null;

        try
        {
            System.out.println("conneting to Database...");
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:80/db","root","");
            System.out.println("Connection Successful");

        }
        catch(ClassNotFoundException error)
        {
            System.out.println("Error:" + error.getMessage());
        }

        catch(SQLException error)
        {
            System.out.println("Error:" + error.getMessage());
        }
        finally
        {
            if (connection != null)
                try {
                    connection.close();
                    }
            catch(SQLException ignore)
            {

            }

            if (statement != null)
                try {
                    statement.close();
                    }

            catch(SQLException ignore)
            {

            }
        }
    }

}

when I am running this code, it doesn't connect me to database. So I tried to get the right port, I checked into phpinfo()  and I found this Hostname:Port  |  localhost:0
So I changed the one line code into this,
connection = DriverManager.getConnection("jdbc:mysql://localhost:0/db","root","");

when I am running this new line, getting this error.
conneting to Database...
Error:Communications link failure
Last packet sent to the server was 0 ms ago.
please give me your guidance to sort this out.
thank you

A: This is your likely error:
 connection = DriverManager.getConnection("jdbc:mysql://localhost:80/db","root","");

port 80 which you have used on this command is the port the Apache Listens on. MySQL listens on port 3306 by default.
If you have not changed that then you probably dont actually need to put the :xxx port numbr on this cmmand at all.
So try
 connection = DriverManager.getConnection("jdbc:mysql://localhost/db","root","");

and see if that works for you
Otherwise try
 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","");

A: Frist check on which port Number used is by JDBC and that port number is used by other application or not.
Check your Port Number 80 is used by other application or not, if yes then you have to killed port number 80 or you have to do reconfiguration of JDBC server to run on other port number
check below link :
http://ye5.blogspot.in/2011/01/wamp-server-localhost-shows-blank-page.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: ionic 3 phonegap-plugin-push plugin_not_installed i have to use the push notifications in my app so i followed this tutorial to add the ionic native push , when i run the app on android
the console prints this warning message "plugin_not_installed"
i tried to remove the platform with cordova platform remove android and
then reinstall it but nothing has changed and i'm still getting the same problem
this is the environment informations :
cli packages: (/usr/local/lib/node_modules)
@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:
cordova (Cordova CLI) : 8.0.0

local packages:
@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0 browser 5.0.4
Ionic Framework    : ionic-angular 3.9.2

System:
Android SDK Tools : 26.1.1
Node              : v8.9.1
npm               : 3.5.2
OS                : Linux 4.15

Environment Variables:
ANDROID_HOME : /home/hamza/Android/Sdk

Misc:
backend : pro

A: try android platform version 7.1.0

ionic cordova platform add android@7.1.0


text:
Q: react native: how to store complete state and all it's props using AsyncStorage I have a Reminder Component with a simple form comprising of one TextInput from react-native and one DatePicker from native-base and one submit to store the value on click.
I am trying to implement AyncStorage to store those values locally and later display them on another screen. But I am unable to do so, as I am getting an error 'Value is not defined.'
Whatever blog posts and tuts, the person was storing only one single property. I want to store complete state i.e input field and the date onclick of the save button.
This is my ReminderComponent
import React, { Component } from 'react';
import { View,StyleSheet, AsyncStorage, TextInput } from 'react-native';
import {
    Form,
    Button, Icon,
    DatePicker, Text
} from 'native-base';
import PropTypes from 'prop-types';
class Reminder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            input: '',
            chosenDate: new Date(),
        };
        this.setDate = this.setDate.bind(this);
        this.handleChangeInput = this.handleChangeInput.bind(this);
        this.saveData = this.saveData.bind(this);
    }

    setDate(newDate) {
        this.setState({
            chosenDate: newDate
        });
    }

    handleChangeInput = (text) =>  {
        this.setState({input:text});
    }

    //On application loads, this will get the already saved data and set
    //the state true when it's true.
    componentDidMount() {
        AsyncStorage.getItem("key").then((value) => {
            this.setState({'key':value});
        });
    }

    //save the input
    saveData(value) {
        console.log('value', value);
        AsyncStorage.setItem("key", value);
        this.setState({'key':value});
    }
    render() {
      const {input} = this.state;
        return (
            <View>
                <Form style={styles.formContainer}>
                    <View style={styles.formView}>

                            < TextInput
                            placeholder = "Set your reminder"
                            onChangeText={this.handleChangeInput}
                            value={this.state.input}
                            />

                        <DatePicker
                            defaultDate={new Date()}
                            minimumDate={new Date(2018, 1, 1)}
                            maximumDate={new Date(2019, 12, 31)}
                            locale={"en"}
                            timeZoneOffsetInMinutes={undefined}
                            modalTransparent={false}
                            animationType={"fade"}
                            androidMode={"default"}
                            placeHolderText="Select date"
                            textStyle={{ color: "green" }}
                            placeHolderTextStyle={{ color: "#d3d3d3" }}
                            onDateChange={this.setDate}
                        />
                        <Text style={styles.datePicker}>
                            {this.state.chosenDate.toString().substr(4, 12)}
                        </Text>
                    </View>
                    <View style={styles.footer}>
                        <Button block success style={styles.saveBtn}
                        onPress={ () =>
                            {this.saveData()
                            console.log('save data', value);}
                        }
                           >
                            <Icon type='MaterialIcons' name='done' />
                        </Button>
                    </View>
                </Form>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    formContainer: {
        marginTop: 10,
        padding: 10,
    },
    editIcon:{
        color: '#28F1A6',
        fontSize: 26,
    },
    editBtn:{
        flex: 1,
        alignSelf: 'flex-end',
    },
    datePicker:{
        alignSelf: 'auto',
        paddingLeft: 10
    },
    footer:{
        position: 'relative',
        top: 350
    },
    saveBtn: {
        position:'relative',
        marginTop: 35,
    }
});

export default Reminder;

This is my ReminderScreen.
import React, { Component } from 'react';
import { View, StatusBar } from 'react-native';
import PropTypes from 'prop-types';

import Reminder from '../components/Reminder';

const ReminderScreen = ({navigation}) => (
    <View >
        <Reminder navigation={navigation} >
            <StatusBar backgroundColor = "#28F1A6" />
         </Reminder >
    </View>
);

Reminder.propTypes = {
    navigation: PropTypes.object.isRequired
}

export default ReminderScreen;

A: Some tweaks needed in the saveData function and get items from Asyncstorage.
While storing the data in AsyncStorage just convert entire state as a string and save it. For retrieving just convert the string to JSON object and set the value in setState function.
Please see the modified code below for Remainder component.
import React, { Component } from 'react';
import { View,StyleSheet, AsyncStorage, TextInput } from 'react-native';
import {
    Form,
    Button, Icon,
    DatePicker, Text
} from 'native-base';
import PropTypes from 'prop-types';
class Reminder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            input: '',
            chosenDate: new Date(),
        };
        this.setDate = this.setDate.bind(this);
        this.handleChangeInput = this.handleChangeInput.bind(this);
        this.saveData = this.saveData.bind(this);
    }

    setDate(newDate) {
        this.setState({
            chosenDate: newDate
        });
    }

    handleChangeInput = (text) =>  {
        this.setState({input:text});
    }

    //On application loads, this will get the already saved data and set
    //the state true when it's true.
    componentDidMount() {
        AsyncStorage.getItem("key").then((value) => {
            this.setState(JSON.parse(value));
        });
    }

    //save the input
    saveData() {
        AsyncStorage.setItem("key", JSON.stringify(this.state));
    }
    render() {
      const {input} = this.state;
        return (
            <View>
                <Form style={styles.formContainer}>
                    <View style={styles.formView}>

                            < TextInput
                            placeholder = "Set your reminder"
                            onChangeText={this.handleChangeInput}
                            value={this.state.input}
                            />

                        <DatePicker
                            defaultDate={new Date()}
                            minimumDate={new Date(2018, 1, 1)}
                            maximumDate={new Date(2019, 12, 31)}
                            locale={"en"}
                            timeZoneOffsetInMinutes={undefined}
                            modalTransparent={false}
                            animationType={"fade"}
                            androidMode={"default"}
                            placeHolderText="Select date"
                            textStyle={{ color: "green" }}
                            placeHolderTextStyle={{ color: "#d3d3d3" }}
                            onDateChange={this.setDate}
                        />
                        <Text style={styles.datePicker}>
                            {this.state.chosenDate.toString().substr(4, 12)}
                        </Text>
                    </View>
                    <View style={styles.footer}>
                        <Button block success style={styles.saveBtn}
                        onPress={ () =>
                            {this.saveData()
                            console.log('save data', value);}
                        }
                           >
                            <Icon type='MaterialIcons' name='done' />
                        </Button>
                    </View>
                </Form>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    formContainer: {
        marginTop: 10,
        padding: 10,
    },
    editIcon:{
        color: '#28F1A6',
        fontSize: 26,
    },
    editBtn:{
        flex: 1,
        alignSelf: 'flex-end',
    },
    datePicker:{
        alignSelf: 'auto',
        paddingLeft: 10
    },
    footer:{
        position: 'relative',
        top: 350
    },
    saveBtn: {
        position:'relative',
        marginTop: 35,
    }
});

export default Reminder;


text:
Q: ¿Para qué sirve y cómo funciona la palabra clave "with" en Python? He encontrado bloques de código de este tipo:
with a as b:
    c = b.algo()

Parecería alguna dinámica similar a namespaces, pero el siguiente código
a = 1
with a as b:
    print a, b

regresa el siguiente error:
AttributeError: __exit__

Entonces, ¿para qué sirve la palabra clave with, y cómo funciona? ¿Cuál es el rol de __exit__?

A: La claúsula with no tiene en python la función de delimitar el espacio de nombres ("namespaces") como se hace en otros lenguajes como VB. Es más para determinar la configuración local que tendrá un bloque de código, lo que se conoce como "contexto".
Un "contexto" básicamente se establece con una configuración inicial y una finalización para recuperar los valores anteriores. Un ejemplo sería la apertura de un fichero:
with open("fichero.txt") as f:
    print(f.read())

Empezamos el bloque abriendo el fichero y, al acabar, se cerrará el fichero automáticamente, aunque no se haya indicado explícitamente.
Para controlar un contexto, se usan los "gestores de contexto" ("context manager") que son objetos que tienen definidos los métodos __enter__ y __exit__. El primero para inicializar el contexto, el segundo para finalizarlo.
Los objetos files en python implementan el interface de gestor de contexto, por lo que su uso en contextos asegurarán que los ficheros se van a cerrar correctamente.
Hay muchos más objetos en la librería estándar que implementan el interface de gestor de contextos. Uno de los más significativos es el tipo Decimal, donde a través de un contexto puedes especificar la precisión decimal de las operaciones que se realizarán dentro del bloque:
from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Precisión de 42 cifras significativas
    s = calculate_something() # cálculo de alta precisión

s = +s  # regreso a la precisión por defecto del tipo decimal

Hay también librerías, como fabric, que usan los contextos para establecer la configuración de las conexiones de los servidores sobre los que ejecutar un script.
En tu caso, el error que te da es que la variable a no tiene definidos los métodos de gestor de contextos.
Para información más detallada, mírate el PEP-343


text:
Q: How to remove elements from a LinkedList in Java? How to set the first element to be the head of the Linked List in Java? I'm learning Linked Lists, and I'm a bit confused by the Node that is created when the LinkedList is created in the first place. So I use an empty constructor just to create the List but it also creates the root node and sets "next" to "null", but then the initial value of "int data" is always "0", and I don't want that (if I do print details it prints the 0).
See the printing below the code, the initial 0 remains after new elements appear on the list. In fact, it continues to exist, which should not be the case.
Another thing, my remove function does not work, what is the issue?
public class LinkedList {
    Node root;//the beginning  - root element of type Node(check inner class below
    int size;//keeps track of the size of the list

    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();
        System.out.println(linkedList.getSize());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.prepend(234);
        linkedList.prepend(45);
        linkedList.prepend(33);
        linkedList.prepend(222);
        System.out.println("Root: " + linkedList.root);
        System.out.println(linkedList.printDetails());
        System.out.println(linkedList.getSize());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.remove(222);
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.find(33).setData(34);
        System.out.println(linkedList.printDetails());
        System.out.println("Root: " + linkedList.root.getData());
        linkedList.append(6565);
        linkedList.append(144);
        System.out.println("Root: " + linkedList.root.getData());
        System.out.println(linkedList.getSize());
        System.out.println(linkedList.printDetails());
    }

    public LinkedList() {
        root = new Node();
        size = 0;
    }

    public int getSize() {
        System.out.println("Size: " + size);
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public StringBuilder printDetails() {
        System.out.print("Linked List: ");
        StringBuilder details = new StringBuilder("[");
        Node currentNode = this.root;
        while (currentNode != null) {
            details.append(currentNode.getData()).append(",");
            currentNode = currentNode.getNext();
        }
        details.deleteCharAt(details.length() - 1);
        details.append("]");
        return details;
    }

    public void prepend(int data) {
        this.root = new Node(data, root);
        this.size++;
    }

    public void append(int data) {
        Node currentNode = this.root;
        Node newNode = new Node(data);
        while (currentNode.getNext() != null) {
            currentNode = currentNode.getNext();
        }
        currentNode.setNext(newNode);
        this.size++;
    }

    public Node find(int data) {
        Node currentNode = this.root;
        while (currentNode != null) {
            if (currentNode.getData() == data)
                return currentNode;
            currentNode = currentNode.getNext();
        }
        return null;
    }

    public void remove(int data) {
        Node currentNode = this.root;
        Node previousNode = new Node();

        while (currentNode != null) {
            if (currentNode.getData() == data) {
                previousNode.setNext(currentNode.getNext());
                this.setSize(this.getSize() - 1);
                return;
            } else {
                previousNode = currentNode;
                currentNode = currentNode.getNext();
            }
        }
    }

    private static class Node {
        private int data;
        private Node next;

        public int getData() {
            return data;
        }

        public void setData(int data) {
            this.data = data;
        }

        public Node getNext() {
            try {
                return next;
            } catch (NullPointerException e) {
                System.out.println((char[]) null);
            }
            return null;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        private Node() {
        }

        private Node(int data, Node next) {
            this.data = data;
            this.next = next;
        }

        private Node(int data) {
            this.data = data;
        }
    }
}

The printing:
Size: 0
0
Root: 0
Root: LinkedList$Node@548c4f57
Linked List: [222,33,45,234,0]
Size: 4
4
Root: 222
Size: 4
Root: 222
Linked List: [222,34,45,234,0]
Root: 222
Root: 222
Size: 5
5
Linked List: [222,34,45,234,0,6565,144]

A: Your remove method's implementation does not take into consideration that root element can be the one which you wan't to remove. Append this to the head of your remove method
  if (this.root.getData() == data) {
    this.root = this.root.getNext() != null
      ? this.root.getNext()
      : new Node();
  }

And about the fact that data is always initialized with 0. Im not sure if i understand the issue, what do you wan't it to be?

A: In your remove method there were cases that you weren't taking into account, I have explained in the comments on the code. Here is a first approach
    public void remove(int data) {
        Node currentNode = this.root;
        Node previousNode = null;
        while (currentNode != null && currentNode.data != data) {
//Here we are searching if the element exists on the list
            previousNode = currentNode;
            currentNode = currentNode.next;
        }
        if (currentNode == null) //If we enter here, the element doesn't exist
        {
            System.out.println("Value not found");
        } else {
            int value = currentNode.data;
            if (previousNode == null) { //Check if the element is the first one in our list
                this.root = currentNode.next;
                this.setSize(this.getSize() - 1);
                return;
            }
            if (currentNode.next != null) { //Check if the element is the last one in our list
                previousNode.next = currentNode.next;
                System.out.println("Value " + value +  " found");

            } else {
                previousNode.next = null;
                System.out.println("Value " + value + " found");
            }
            this.setSize(this.getSize() - 1);
        }
    }

PS: You should keep track of both ends


text:
Q: Time complexity of the program using recurrence relation This program calculate fibonacci numbers. I want to find out its time complexity using recurrence relation.
Fib(n)
if n<=1
  return n
else
  x= Fib(n-1)
  y= Fib(n-2)
  return x+y

The recurrence equation for this program is
  T(n)=T(n-1)+T(n-2)+c
I tried to expend it , but couldn't find the solution.
 =2T(n-1)+T(n-3)+c+c
 =3T(n-3)+2T(n-4)+c+c+3c
 =5T(n-4)+3T(n-3)+c+c+3c+5c
 -------------------------
 -------------------------
 -------------------------

A: You need to think about how many calls you make to your function.
Each call makes 2, so it makes a binary tree:
n
(n-1)--------------(n-2)
(n-2)--(n-3)------(n-3)---(n-4)
and so on.
Consider the level of the tree when you first reach 1 and ignore everything below.
This happens on level n/2 (since the lowest number of each level is the rightmost and it always decreases by 2).
It's clear that the nodes on each level up to n/2 are always twice as many as on the previous level.
Thus the total number of nodes is 1 + 2 + 2^2 + ... + 2^(n/2) = 2^(n/2+1) - 1 = O(2^(n/2))
This means that the time complexity is at least exponential.
You can probably compute it even more accurately, but for all practical purposes this should be enough to avoid this implementation.

A: The given recurrence relation is,
T(n) = T(n-1) + T(n-2) + c   ------ 1
T(n-1)= T(n-2) + T(n-3) + c ------ 2

1-2 -> T(n) = 2T(n-1) - T(n-3) ----- 3
T(n) - 2T(n-1) + T(n-3) = 0 ----- 4

The characteristic equation of 4 is x3 - 2x2 + 1 = 0   ----   5
Solve equation 5,
The solutions are x = 1, x = (1 + √5)/2 and x = (1 −√5)/2
There for the general solution is,
Tn = a((1 + √5)/2)n + b((1 - √5)/2)n + c . 1n
There for Tn = a((1 + √5)/2)n + b((1 - √5)/2)n + c
Let us assume T(0) = 0, from equation 1 we get T(1) = c and T(2) = 2c
There for,
 T(0) = a + b + c = 0 ---- 6
T(1) = a((1 + √5)/2) + b((1 - √5)/2) + c = c
There for a((1 + √5)/2) + b((1 - √5)/2) = 0  ----- 7
T(2) = a((1 + √5)/2)2 + b((1 - √5)/2)2 + c = 2c
There for a((1 + √5)/2)2 + b((1 - √5)/2)2 = c ---- 8
solve 6, 7 and 8, to get the values of a, b and c.
The general solution is,
Tn = a((1 + √5)/2)n + b((1 - √5)/2)n + c
since (1 + √5)/2 < 2,
T(n) = O(2n).

A: The thing to note about your recurrence relation is that it's the same as the Fibonacci recurrence itself. This means that you're doing c units of work times whatever Fibonacci number you're calculating. You can see it yourself from the first few steps that you computed. The c's start growing like the Fibonacci numbers.
Basically your recurrence comes down to O(Fib(n)).  Fibonacci numbers are exponential in n, so you're going to do exponential work.
A better way to do this is to remember one of the numbers. Like this:
Fib(n):
    if n <= 2:
        return 1,0
    else:
        x,y = Fib(n-1)
        return x+y,x

So when you call Fib(n), you're getting two values, Fib(n) and Fib(n-1). That extra x that you return "remembers" Fib(n-2) so you don't have to compute it twice. This recurrence comes down to T(n) = T(n-1) + c, which is O(n).
Once you have that, you can reduce this to a nice little for loop:
x = 1, y = 0
for i from 3 to n:
    x,y = x+y,x


text:
Q: Simultaneous Message Boxes So I have created an event driven program that is supposed to prompt users when triggered by the specific event handler with message dialogs. Is there any way to instantiate these message dialogs simultaneously in the event that they coincide?
################################################################################
# Create Listener ##############################################################
################################################################################

# listens to a local directory for files

watch = Watcher(LOCAL_DIRECTORY, callback)

# set the appropriate flags for a listener

watch.flags = FILE_NOTIFY_CHANGE_FILE_NAME

################################################################################
# Start Listener ###############################################################
################################################################################

watch.start()

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

A: it should just work, consider the following
import wx

def handle(e):
    wx.MessageBox("Hello","world")

a = wx.App(redirect=False)
t = wx.Timer()
t.Bind(wx.EVT_TIMER,handle)
t.Start(3000)
f = wx.Frame(None)
a.MainLoop()

this will open the message box every 3 seconds regardless of the previous one being open...
[edit]
after further discussion I will make an assumtion that your event is one you must poll for ... you should put the polling logic in its own thread
def poll_data(data_callback):
    def check_new_event():
        if do_something_to_check():
           wx.CallAfter(data_callback) # this will cause the callback to be executed in the main thread (All gui updates *should* be done in the main thread)
    while True:
       check_new_event()
       sleep(1) # force thread to surrender control for a while

def on_callback(*args,**kwargs):
    wx.MessageBox("Some Message","Title")

def my_app():
    a= wx.App(redirect=False)
    f=wx.Frame(None)
    th = threading.Thread(target=poll_data,args=(on_callback,))
    th.start()
    a.MainLoop()

[edit 2]
after your edit I will make another assumption that your watch library blocks until callback returns ... just use wx.Callafter like follows
def old_callback(*args):
    wx.MessageBox("Whatever","blah")
def callback(*args):
    wx.CallAfter(old_callback,*args)

watch.bind(callback) # or however

this allows the callback to return and watch to continue listening ... regardless of a blocking dialog
[edit 3]
here is a complete example using watch library
import watcher,wx
a = wx.App(redirect=False)
TARGET_DIR="/py_exp/testing"
def real_callback(*args):
    wx.MessageBox(str(args),"QQQQ")
def callback(*args):
    wx.CallAfter(real_callback,*args)
w = watcher.Watcher(TARGET_DIR, callback)
w.flags = watcher.FILE_NOTIFY_CHANGE_FILE_NAME
w.start()
f = wx.Frame(None)
a.MainLoop()

then just add and remove files from the directory (note the new popups might popup behind the existing one...but if you move them you should see all of them)


text:
Q: Node-RED cannot find local module I am developing a Node-RED Custom Node in TypeScript using a Nx monorepository with following hierarchy:
reponame
 + packages
 | + package-a
 | + package-b
 | + custom-node

The Custom Node imports package-b which imports package-a via import { TestClass } from "@reponame/package-b". I performed npm installs and it compiles to my repo's ./dist/ like a charm.
Now I'm struggeling to get my Custom Node into Node-RED. I did npm install pathToRepo/dist/packages/custom-node and the same for package-a and package-b.
However, when starting Node-RED this error is raised:
Error: Cannot find module '@reponame/package-b' in the .js-file containing the Custom Node.
In other words, my local dependencies in my custom node could not be resolved.
I tried to do npm install package-b inside pathToNodeRed/node_modules/@reponame/custom-node but that did not work as it through errors while trying to fetch package-a from the internet.
How can I correctly resolve this issue?


text:
Q: Failed to Start DHCP in Linux Redhat, Need Help ASAP I tried to configure /etc/dhcp/dhcpd.conf file in Linux but it failed as static addressing. How do I fix it? Am I missing any data and is it accurate? I need help.
Below is screenshot of my contents for the file.
ddns-update-style interim;
ignore client updates;
subnet 192.168.56.1     netmask 255.255.255.0
option subnet mask 255.255.255.0;
range dynamic bootp 192.168.0.25 192.168.0.200;
default-lease-time 43200
max-lease-time 86400

A: your subnet and your range are in different networks. the range definition must be in the same network the subnet defines. Also, set your subnet address to .0, not 1. .1 is a host, .0 is a network. finally, every option must end with a semicolon (;)
...
subnet 192.168.56.0 netmask 255.255.255.0 {
       range dynamic bootp 192.168.56.25 192.168.56.200;
       default-lease-time 43200;
       max-lease-time 86400;
}
...

should work, assuming you are actually defining a pool for 192.168.56.0/24.
more info here: http://linux.die.net/man/5/dhcpd.conf


text:
Q: Some kind of php flush Let me describe what I've made ar first:
I have to import large ammount of data from different xml's to my database and because it last a lot I had to put a progress bar and I did it like this: I split the whole import into tiny little AJAX requests and I import little data at a time (when an ajax request completes the progress bar increases a bit). This whole idea is great but the data just keeps getting bigger and bigger and I can't optimize the code anymore (it's as optimized as it gets).
The problem is that everytime I do a AJAX call I lose a lot of time with things specific to the framework (model initializations and stuff), with the browser handling the url and so on. So I was wondering if I could use the flush function from php.
But I've been reading that the flush function doesn't work great on all browsers (which is weird cause it's a server-side function). If I would use the flush function I would just write <script>increase_progressbar</script> or whatever I want and I could do it.
So, any opinions on the flush function? I've been testing it on little scripts but I want to know if someone really used it with big scripts. Also, I can listen to any other suggestion of doing what I want to do :)

A: I wont give you direct advise, but I will tell you how I did it in one of my projects. In my case I need to upload an Excel files and then parse them. The data exceeding 3000 rows and I had to check all columns of each row for some data. When I parse it directly after the upload, the parser often crashes somewhere and it was really not safe.
So how I did it? The upload process has been split in 2 parts:

*

*Upload physically the file (regular upload field and submit). When the button is clicked some CSS and JS "magic" hide the form and one nice loading bar appears on the screen. When the upload has been done the page just refreshes and the form appear again for the next file

*Start parsing the data on the background using php-cli as @Dragon suggest with exec().
In the database I had a table which stores information about the files and there is a boolean field called "parsed". When the parser finishes the job, the last task is to update that field to true.
So here is the whole process from user point of view:

*

*select a file and upload it.

*wait until the file has been uploaded on the server. Till then a message and loading bar appear indicating that something is working. The upload form has been hidden with CSS and JS, so preventing user to upload another file.

*When it's over the page has been refreshed (because I did normal _POST submit) the form appear on the screen again as well as a list of recently uploaded files (this I've stored this in the session).

*In each of the nodes of that list I had an indicator (an icon). In the first time it's a spinner (ajax spinning wheel).

*On a regular basis (30 sec or 1 min) I've checked the file table through Ajax call and reading the parsed field. If the background process has been over, the field was set to true and with some JS and CSS I've changed the icon to "Done". Otherwise the spinner remain.

In my project I doesn't have requirement to show extra details about the imports, but you can always go wild with other extra data.
Hope this help you with your project.


text:
Q: How can I get integer values from binary file I have some files they look like this with hex/octal dump:
hexdump file:
0000000 0002 0000 0c3e 0000 0ac5 0000
000000c

od file:
0000000 000002 000000 006076 000000 005305 000000
0000014

I dont know really what this "000002" and "0000014" is good for but, I know I need this "006076" and "005305" as interger value, so I did this in python2:
hex(006076)
'0xc3e'

int(0xc3e)
3134

I don't know really how I should open/and read this file/values in python2...
simple open/read the file looks like this:
x = open("file", "rb")
x.read()
'\x02\x00\x00\x00>\x0c\x00\x00\xc5\n\x00\x00'

A: You want to use struct.unpack.
>>> import struct
>>> struct.unpack("4x H 2x H 2x", '\x02\x00\x00\x00>\x0c\x00\x00\xc5\n\x00\x00')
(3134, 2757)

The format string used as the first argument tells unpack to ignore the first 4 bytes, then unpack the next two bytes as an integer, ignore 2 more bytes, unpack another 2-byte integer, and ignore the last 2 bytes. This assumes the byte string uses the same endianness as your machine's default; see the documentation for the struct module for more details.

A: The functions hex(int) and oct(int) take an integer in base 10 (decimal) and convert it into a string that looks like a number in base 8 or base 16 (hex or octal).  The function int() just takes a string that looks like a number and converts it from a string into an integer in base 10.
You should be able to use the int() function to do this with the format int([string representing number], [base of number]).  Here's how it works:
In a base n number system, the value of the number is (1st digit) * n^0 + (2nd digit) * n^1 + (3rd digit) ^ n^2 + ....  For example, if you have the number 472 in octal (base 8), you could calculate the value like so:
2 * 8^0  +  7 * 8^1  +  4 * 8^2
2 * (1)  +  7 * (8)  +  4 * (64)
2 + 56 + 256
314

So 472 in octal is equivalent to 314 in decimal.  To make a function out of this, I'd do something like this:
def convertToDecimal(number, baseOfNumber):
    counter = 0
    for c in reversed(number)
        newNumber += (c * (baseOfNumber ^ counter))
        counter += 1
    return newNumber

Hope this helps!


text:
Q: Lombok builder methods return the instance of the class itself instead of returning builder class I have a class User
public class User {
    private String firstName;
    private String lastName;
    private int age;

    public User withFirstName(String firstName) {
        this.firstName = firstName;
        return this;
    }

    public User withLastName(String lastName) {
        this.lastName = lastName;
        return this;
    }

    public User withAge(int age) {
        this.age = age;
        return this;
    }
}

So I can initialize it use User user = new User().withFirstName("Tom").withAge(30);, and after user is initialized, I can still modify it by user.withLastName("Bob").withAge(31);.
How can I leverage Lombok to save the "withXXX" methods? @Builder is not designed for this use case.

A: Try this:
@Data
@Builder
@Accessors(fluent = true) // <— This is what you want
public class User {
    private final String firstName;
    private final String lastName;
    private final int age;
}

Then to use:
User user = User.builder()
    .firstName("foo")
    .lastName("bar")
    .age(22)
    .build();

And later:
user.setFirstName("baz").setAge(23); // fluent setters

Note how User can be made immutable (best practice) by making all fields final. If you want mutability, remove final keywords.


text:
Q: Count number of words in range of cells separated by "-" in google sheets i'm having some issues with a formula to count number of words in a range of cells separated by "-".
The formula that I have is working but if the cells are empty, it still shows "1" instead of "0".
Formula : =COUNTA(SPLIT(ARRAYFORMULA(CONCATENATE(D16:G16&CHAR(45)));CHAR(45)))
It also works for 2 ranges of cells but not 3. If anyone can help me out it'll be apreciated !
Thanks in advance!

A: Your SPLIT is returning an error, which counts as a non-empty cell.
Add an IFERROR to handle the error. You can also use TEXTJOIN instead of CONCATENATE.
=COUNTA(IFERROR(SPLIT(ARRAYFORMULA(TEXTJOIN(CHAR(45),1,D16:G16)),CHAR(45))))


text:
Q: Class serialization when member function is invoked by JobLib I would appreciate any help or suggestion from the community regarding the following code example, see below.
In this example I invoke class member function from another member function in parallel.
It turns out, when a member function self.print_id() is called by JobLib framework, then

*

*the entire class is cloned (without calling the constructor), serialized and passed to a process.

*a new unique ID is assigned to each copy of the class.

Questions:

*

*Is this a correct construction?

*Is there any apparent side effect that might happen?

*What if the "class A" is inherited, can I expect the correct behaviour of self.print_id() member of a derived class?

Thank you in advance.
from joblib import Parallel, delayed

class A:
    def __init__(self):
        self.state = -1
        print(f"constructor is called, id: {id(self)}", flush=True)

    def print_id(self, index):
        self.state += 1
        print(f"state: {self.state}, id: {id(self)}, index: {index}")

    def parallel(self):
        Parallel(n_jobs=8, prefer="processes")(
            delayed(self.print_id)(i) for i in range(8))

a = A()
a.print_id(777)
a.parallel()

constructor is called, id: 140331251437424
state: 0, id: 140331251437424, index: 777
state: 1, id: 140226941702448, index: 0
state: 1, id: 140520215830832, index: 1
state: 1, id: 140520209383920, index: 2
state: 1, id: 140520215850624, index: 3
state: 1, id: 140520209384352, index: 4
state: 1, id: 140520215621200, index: 5
state: 1, id: 140520209384832, index: 6
state: 1, id: 140520215621296, index: 7


text:
Q: Convert text to number format in Excel How can I convert text representations of numbers into Excel numbers, especially negative values? For example, the string "9,669.34" (without quotes) should become the number 9,669.34 and the string "2,553.57-" (again, without quotes) should become the number (2,553.57).
When I used the formula =SUBSTITUTE(A1,CHAR(160),"")+0, it worked well, but only for positive values. I received the result #VALUE! for all negative values.

A: For (2,553.57), you can use VALUE, such as VALUE("(2,553.57)").
Excel doesn't seem to recognize 2,553.57- as a valid number when it is a string, so assuming you have a value of "2,553.57-" in A1, you would have to do a little more work:
=VALUE(IF(RIGHT(A2,1)="-","-"&SUBSTITUTE(A2,"-","")))
EDIT
=VALUE(IF(RIGHT(A2,1)="-","-"&SUBSTITUTE(A2,"-",""),A2))

From the Microsoft site:

*

*Text can be in any of the constant number, date, or time formats recognized
   by Microsoft Excel. If text is not in one of these formats, VALUE returns the
   #VALUE! error value.

*You do not generally need to use the VALUE function in a formula because Excel
  automatically converts text to numbers as necessary. This function is provided
  for compatibility with other spreadsheet programs.

More information can be found at Microsoft's website:  Value Function

A: If you have a column of these text-based numbers, select the column and use Data ► Data Tools ► Text to Columns ► Fixed Width ► Finish. The trailing negative signs will be used to determine the sign of the resulting number, spaces (leading and/or trailing) will be removed and you will be left with raw numbers that you can apply a currency or number format to.
If the column is originally formatted as Text, change it to General before applying the Text to Columns command.

A: Another option: Select the column. Copy. Paste Special with "Multiply" option.
Then, as above, you can select Currency or Number in the droplist, decimal places, etc.


text:
Q: Durandal in chrome addin I want to develop a google chrome addin. For MVVM composition I would like to use DurandalJS. As I am new to chrome addin development I would like to know wether this is possible or if chrome's sandboxing mechanism would block Durandal or one of it's sub-APIs like sammyJS or requireJS.

A: Without trying this specific case, it should just work like in any other webpage.
From the Chrome developer website:

If you want to use a library that the browser doesn't provide (for
  example, jQuery), you can bundle that library's JavaScript files with
  your extension. Bundled libraries work in extensions just as they do
  in other web pages.

(emphasis mine)
Source: http://developer.chrome.com/extensions/api_other.html
If anything, you can do more in a chrome addon than on a regular website. If not, what would be the use of an addon if you could just use a bookmark instead?


text:
Q: Assigning additional private IP to azure vm scale set instances Would like to know if it is possible to assign additional private ip address(secondary) to the azure instance which is part of virtual machine scale set.
For standalone azure instances, multi ip feature is available. I can easily assign additional ip via azure portal(NIC >> IP configuration) or by using azure python SDK.
Can anyone answer if it is possible to do the same thing right now to instance that is part of a vmss?

A: This feature is in preview right now, you can register and learn about this feature here.


text:
Q: JavaScript only works when alert() is called I'm trying to send a POST request to a Java method that creates an account with the given form parameters in a database.
If the account is successfully created the method returns true, and then I should get redirected to a link. But the code below doesn't work unless the alert("") function is there.
I assume it has something to do with asynchronous mode, but I'm new to JavasScript and would really appreciate any help :)
Here's the code:
function createAccount(){

var xhr = new XMLHttpRequest();

var fname = document.getElementById("fname").value;
var surname = document.getElementById("surname").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var rpassword = document.getElementById("rpassword").value;
var emp_no = document.getElementById("emp_no").value;

xhr.open('POST','http://localhost:8080/di24_app/di24/create',true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send('fname='+fname+'&surname='+surname+'&email='+email+'&password='+password+'&rpassword='+rpassword+'&emp_no='+emp_no);
xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
            document.getElementById("result").innerHTML = "Error creating account!";
            document.getElementById("result").style.textAlign = "center";
        }
        else if(this.responseText == "true"){
            window.location.href = "http://localhost:8080/di24_app/html/home_page/home.html";
        }
    }

}
alert("");
}

A: The issue is that you have a button with type="submit" and onclick="createAccount()" is inside a <form/> , the browser will automatically post the data and refresh your page, after clicking that button, So the execution of the function createAccount() will never reach the end.
On the html button tag do this:
<button type ="submit" onclick="return createAccount()">Create</button>
add return before createAccount()
On the function createAccount() at the end add return false.
Returning a false when calling a method from a submit type button, will indicate to the browser to not automatically post form data.
function createAccount(){

....

xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
            document.getElementById("result").innerHTML = "Error creating account!";
            document.getElementById("result").style.textAlign = "center";
        }
        else if(this.responseText == "true"){
            window.location.href = "http://localhost:8080/di24_app/html/home_page/home.html";
        }
    }

}
//alert("");
return false; // important
}

A: You can use callback methods inside your onreadystatechange function like below;
function createAccount(successCallback, errorCallback) {
   ...

   xhr.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200) {
        if(this.responseText == "false"){
           errorCallback();
        }
        else if(this.responseText == "true"){
           successCallback();
        }
    }
  }
}

Then you can call createAccount method with below two function params;
createAccount(
   function () { console.log('success') },
   function () { console.log('error') }
)

And you can write your dom manipulation codes into these callback functions.


text:
Q: Disable Saturdays and Sundays from DatePicker Andorid I need to disable past dates and weekends as well in my datePicker. I am using Kotlin.
For past dates this line is working fine
//Disable past dates
datePickerDialog.datePicker.minDate = cal.timeInMillis

https://www.freakyjolly.com/android-material-datepicker-and-timepicker-by-wdullaer-tutorial-by-example/
Here on this link I've found how to disable Saturday and Sunday, but for this line
 datePickerDialog.setDisabledDays(disabledDays);

I do not have the option to select setDisabledDays or something similar like that from the datePicker, and I thought that had changed since 2019 (the post is posted then). Do you have any idea how should I specify the days that I need to disable?

A: Try using the following instead. You have to pass array of Calendar as an parameter which contains all the select-able dates.
datePickerDialog.setSelectableDays(Calendar[] days)

EDIT: Since you do not have the library. You need to add the dependencies as follows in your build.gradle
dependencies {
    implementation 'com.wdullaer:materialdatetimepicker:4.2.3'
}

You also need to add the Java8 compatibility
android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

You can find the necessary info here.
https://github.com/wdullaer/MaterialDateTimePicker


text:
Q: How do I add underbrackets to express antisymmetrization of a tensor How can I write the following equation?

I want to start from
\begin{equation}
  R_{\alpha\mu\beta\nu} = \partial_{\alpha\beta}\phi_{\mu\nu}
\end{equation }

and add the underbrackets as in the figure I have posted.

A: A simple solution with pstricks: I defined the indices as nodes, and linked them with the node connection \ncbar with the relevant parameters:
\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage{pst-node}
\usepackage{auto-pst-pdf}

\begin{document}

  \begin{postscript}%
  \everypsbox{\scriptstyle}
  \begin{equation}
        R_{\alpha\mu\beta\nu} = \partial_{\Rnode{a}{\alpha}\Rnode{b}{\beta}}\phi_{\Rnode{m}{\mu}\Rnode{n}{\nu}}
  \end{equation}
    \psset{linewidth=0.4pt, linearc=0.03, angle=-90, nodesep=2pt}
    \ncbar[arm=1.6mm, nodesepB=0.5pt]{a}{m}
    \ncbar[arm=2.4mm, nodesepA=0.5pt]{b}{n}
  \end{postscript}

\end{document}


text:
Q: Xcode 4: Files get stuck outside of project, unable to be deleted Lots of my files in my Xcode project get "stuck" outside of my project and I'm unable to delete them. This happens occasionally when creating new files (maybe 50% of the time).
Here's a screenshot of what happens:

Any ideas?
Thanks.

A: Same problem, solved editing manually the project bundle:

*

*quit xcode

*right click on "Philly Shows.xcodeproj" and show its content

*same operation on "project.xcworkspace"

*open "contents.xcworkspacedata" with a text editor: you'll find references to your stuck groups and files, remove what you want to remove, basically your file should be something like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <Workspace version = "1.0">
        <FileRef
            location = "self:Philly Shows.xcodeproj">
        </FileRef>
    </Workspace>

Michele


text:
Q: DOM PDF cutting watermark background when the text is small i have a watermark bg on a page and that image is being cut off where the text ends. If the text that i write on the page is bigger than the image, it works, else the image gets cut off where the text ends.
Any ideas?
Thanks.

body  { width: 100%; min-height: 800px }
#container { margin:0 auto !important; width: 750px; overflow: hidden; }
* { font-family: 'Times New Roman' !important; font-size : 14px !important; text-decoration: none !important; margin : 0px;}

#container { width: 100%; }

#watermark { position: fixed; width: 382px; height: 470px; margin-left: 120px; margin-top: 190px; opacity: .07; }

@page {
  margin-left: 3cm !important;
  margin-top: 3cm !important;
  margin-right: 2cm !important;
  margin-bottom: 2cm !important:
}

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

A: I'm not sure where the bug is occurring, but the #watermark element appears to be clipped to the size of the #container object even though it is styled with position: fixed which should take it out of the normal flow of the document.
The easiest fix would be to move the #watermark element outside the #container element.

body  { width: 100%; min-height: 800px }
#container { margin:0 auto !important; width: 750px; overflow: hidden; }
* { font-family: 'Times New Roman' !important; font-size : 14px !important; text-decoration: none !important; margin : 0px;}

#container { width: 100%; }

#watermark { position: fixed; width: 382px; height: 470px; margin-left: 120px; margin-top: 190px; opacity: .07; }

@page {
  margin-left: 3cm !important;
  margin-top: 3cm !important;
  margin-right: 2cm !important;
  margin-bottom: 2cm !important:
}

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t

t


text:
Q: .NET General Number Formatting with Thousands Separator Is it possible in .NET to have the most compact number formatting like  "G"eneral Number formatting, with extra thousands separator.
I can't use the following
String.Format("{0:#,###.###}",32445.324777M)

Because I get "32,445.325", and instead the result I want should be "32.445,325777". Is should also work with an arbitrary number of significant digits in the fractional part.
PS: I only need this for decimals.

A: That's where formatting culture comes in. You need to get a format specifier that matches your requirements. The default you have is usually the current culture, UI culture or invariant culture. The results you're getting imply you're using the US culture.
If you have a specific culture you want to output the number in, use that. If not, you can create your own:
var nfi =
  new NumberFormatInfo
  {
    NumberDecimalSeparator = ",",
    NumberGroupSeparator = "."
  };

var ci =
  new CultureInfo(CultureInfo.InvariantCulture.LCID) { NumberFormat = nfi };

return string.Format(ci, "{0:#,###.########}", 32445.324777M)

If you want to also get the most compact number, you'll have to use your own code. The easiest way would be to try both, and return the smaller resulting string.
If you want to, you can still use the string.Format syntax too - you can code your own ICustomFormatter to handle that:
void Main()
{
    var number = 32445.324777M;

    string.Format(new MyNumberFormatter(),  "{0:MyG}", number).Dump();
}

class MyNumberFormatter : IFormatProvider, ICustomFormatter
{
  public object GetFormat(Type type)
  {
    return this;
  }

  public string Format(string fmt, object arg, IFormatProvider formatProvider)
  {
    if (fmt != "MyG" || !(arg is decimal)) return string.Format(CultureInfo.CurrentCulture, "{0:" + fmt + "}", arg);

    return "Hi";
  }
}

This implementation is somewhat hacky, of course, I'm sure you can find better examples. But it does work. In the Format method, you can choose the format that fits better for the given number, or even just try something like doing the usual ToString("G", CultureInfo.InvariantCulture) and adding the decimal separators to that string. Whatever floats your boat :)

A: From the .NET documentation

The "#" custom format specifier serves as a digit-placeholder symbol.
  If the value that is being formatted has a digit in the position where
  the "#" symbol appears in the format string, that digit is copied to
  the result string.
Otherwise, nothing is stored in that position in
  the result string. Note that this specifier never displays a zero that
  is not a significant digit, even if zero is the only digit in the
  string. It will display zero only if it is a significant digit in the
  number that is being displayed.
The "##" format string causes the
  value to be rounded to the nearest digit preceding the decimal, where
  rounding away from zero is always used. For example, formatting 34.5
  with "##" would result in the value 35.

It's not possible to format an unspecified amount of decimal places with the default formatting possibilities. So you should consider writing your own implementation if needed.
Also about the decimal and thousands separator, it depends upon your system settings, but you can override them by using a different culture as @Luaan described it in his answer.
You should also probably look into this answer.

A: If you want full control create yoru own formatter lik below. See case "U" for your format.
public class CustomerFormatter : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    public string Format(string format,
                          object arg,
                          IFormatProvider formatProvider)
    {
        if (!this.Equals(formatProvider))
        {
            return null;
        }
        else
        {
            // generic formatter if no formater specified
            if (String.IsNullOrEmpty(format))
                format = "G";

            // not a decimal type object
            if (!(arg is decimal))
                return null;

            // get value
            decimal val = (decimal)arg;

            // convert value into generic culture string for control of format
            string valueString = val.ToString();

            // get string in required format type
            format = format.ToUpper();
            switch (format)
            {
                // our user format
                case "U":

                    // get decimals
                    string decimals = val.ToString("G", CultureInfo.InvariantCulture);
                    decimals = decimals.Substring(decimals.IndexOf('.') + 1);

                    // get current culture info
                    NumberFormatInfo nfi = new CultureInfo(CultureInfo.CurrentCulture.Name).NumberFormat;

                    // set our separators
                    nfi.NumberGroupSeparator = ",";
                    nfi.NumberDecimalSeparator = ".";

                    // set numebr of decimals
                    nfi.NumberDecimalDigits = decimals.Length;

                    // convert value to our format
                    valueString = val.ToString("N", nfi);
                    break;
                default:
                    break;
            }

            return valueString;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        decimal dec = 32445.324777M;
        Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", dec));
        Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", dec));
        Console.WriteLine(String.Format(new CustomerFormatter(), "{0:U}", dec));
        Console.WriteLine(String.Format(new CustomerFormatter(), "{0:T}", dec));

        Console.ReadLine();
    }
}


text:
Q: Using 'should' in function names This is a question with no definite answer so apologies if I posted this wrongly however at my place of work alot of the code I see written by our developers have function names with the keyword 'should', must I add they base this on 'should' and 'should not'. From a point of semantics, whats your view on this? I've mentioned before that I don't believe this should be used because it has too many possibilities (where does it end) however they insist its a good practice.
Example use;
$this->it_should_render_template_partially($params);

$this->it_should_show_module_parameters($params);

$this->it_should_not_return_module_parameters($params);

I am curious on others thoughts. Just to add, this is production code and not unit tests.

A: While I like long, descriptive, names, I don't like redundancy. When I read the documentation of a function, I expect it to do what it is supposed to do. Yes, functions are written by humans that make a lot of mistakes, so they can have bugs, which means they do not behave as intended. But this is implied when one uses a function. We hope that out functions do what they should (and we try to make sure that is the case using tests). But specifying the should part in the name of a function is just redundant, which is, in my opinion, a bad practice, as it results in longer names, harder to read/write.


text:
Q: Excel not showing formula result on sheet, but F9 shows correct value I'm working on an excel sheet and I've encountered an issue I've never come across before. I'm trying to sum the results of an array function, but I'm not getting any results from the sum on the sheet - just blank cells. The weird part is when I press F9 in the formula bar it shows the correct summed value that should show in the cells on the sheet. I just don't get why the value would appear in the formula bar, but not in the cells on the sheet. Other forums mentioned changing the calculation option (on automatic of course) or to 'show zeros', which just changed the cells to zero instead of blank. F9 still shows the correct value. Here's the formula:
{=SUM(OFFSET(INDIRECT("Sheet1!E"&IF(ISERROR(MATCH($A$2:$A$15&$C$1,Sheet1!$C$2:$C$51,0)),
1000,MATCH($A$2:$A$15&$C$1,Sheet1!$C$2:$C$51,0))),0,ROW(1:1)))}

The match gets me the row index for the numbers I need to sum. (E1000 is just a default for when there isn't a match and references a cell with 0 in it). If I remove the sum from the function and use F9 I can see the actual array with the numbers to be summed. This is what is so confusing to me. Everything seems to evaluate correctly, it just doesn't show on the sheet. Thanks for the help!

A: I know this thread is a couple months old, but for anyone having this issue, try checking for Circular References. It is likely that your formula has at least one.
To check: click the Formulas tab, click the arrow next to Error Checking, point to Circular References, and then click the first cell listed in the submenu.
Reasoning: When using the Evaluate Formula function (F9), it only does a one time calculation and is able to give a complete result. However, if a circular reference is present, the formula in the sheet itself will continuously recalculate so may never have a definitive result.

A: I came here because I had the same issue, and the above did not initially work for me.
I found that to execute the array function you must highlight the entire formula and then (for Mac) press Control+Shift+Enter.
Once I did this it worked like a charm!!

A: Try "Recalculate All" on the formulas tab.
This solved a similar issue for me with an AVERAGEIF function, whose value would show up correctly in the formula viewer, but not in the sheet. Forcing the sheet to recalculate everything fixed the problem in my case.
The problem seems to occur when defining a cell that is based on another cell, that is based on other cells, that are based on other cells, that are based on other cells...at some point Excel seems to give up and assume that there's a circular reference somewhere, even though there isn't in my case.
When Excel calculates all sheets, it re-uses results, and ignores cells until their precedents are known, rather than working backward from a particular cell, so it doesn't freak out if a cell relies on too many preceding cells.

A: Having the same problem, very frustrating. I have found an insane solution. I don't know why it works but it does... I thought that I would try the formula in another cell. So I copied and pasted the cell in another cell... And the formula in the original cell worked and the correct value appeared.

A: I came across this problem when using SUMIFS with three queries on an array. I found the solution was to encapsulate the whole function in brackets. I think the problem must arise from the order in which excel evaluates the constituents of the formula when it derives its answer.
So for example I had to add the following brackets [highlighted in bold] =
SUMIFS( [00_COMBINED_NO_DUPLICATES.xlsx]COMBINED!$CK$2:$CK$60067,
        [00_COMBINED_NO_DUPLICATES.xlsx]COMBINED!$F$2:$F$60067,
        [@RR1],
        [00_COMBINED_NO_DUPLICATES.xlsx]COMBINED!$S$2:$S$60067,
        ">="&[@[Quarter_Starting]],
        [00_COMBINED_NO_DUPLICATES.xlsx]COMBINED!$S$2:$S$60067,
        "<"&EOMONTH([@[Quarter_Starting]],
        2
      )+1)

A: This was happening to me. I solved it by pressing Ctrl and '
OR you can go to View, and unselect Show formulas.
In 'normal' Excel Ctrl+' would insert the data from the cell above.
Hope this helps someone.

A: Make Calculate option as automatic. It should solve the probelem
See the screen shot

A: Sorry to reopen this but here is a new solution.
I do have circular references, deliberately, so I set Excel to allow them to evaluate only once. Default is OFF - do not evaluate, hence why your formulae returned false / 0 every time even if they appeared true.
To switch on Iterative calculations (i.e. do something with circular references instead of nothing): File -> Options -> Formulas -> Enable Iterative Calculations -> Change from 100 (a little excessive except in special applications) to 1.
Link (scroll down to the bit about iterative calculations): https://support.office.com/en-ie/article/remove-or-allow-a-circular-reference-8540bd0f-6e97-4483-bcf7-1b49cd50d123
Hope this helps some more folks!

A: Sometimes it is a problem if you are using arrays with OFFSET or INDIRECT.
You can solve it using =N(INDIRECT(... or =N(OFFSET(
You can find the explanation below
Array Formula Confusion

A: Many of us have old ways to correct the formula, but let me tell you something: The iterative formula which shows correct results using "F9" means that you do not have to check the formula again and again.
You also do not have to check except the type="general" - that's it.
Now please please, please allow FILE>OPTIONS>FORMULAS>ENABLE ITERATIVE CALCULATION, maximum iteration = 300 (assuming you have 300 cells for iteration), maximum change = 0.001.
This is because we have to check whether the iteration is allowed or not. Hope your problem gets solved.

A: This problem also occurred when using an excel table reference. Converting the table to normal cells fixed it. Alternatively, changing the references from table to normal references fixed it too.
This part of a formula caused a #value / #wert error
VERGLEICH(LF5;DATWERT('Inzidenz RKI_20211129.xlsx'!Table6[[#Kopfzeilen];[27.09.2021]:[26.11.2021]]);0)

This did not:
VERGLEICH(LF5;DATWERT('[Inzidenz RKI_20211129.xlsx]LK_7-Tage-Fallzahl-aktualisiert'!$C$3:$C$173);0)

(vergleich is match, and datwert is datevalue in german excel, and it uses ; instead of commas)


text:
Q: Create a code Generator Addin for Visual Studio So I understand this may appear to be a strange question but I couldnt really find any information on this (maybe I was searching for the wrong thing)
I have a selection of code snippets ive created in visual studio. The snippets work great but what I want to do is to build some sort of code builder addin that will create the .CS files in the project based on several inputs.
Its for use with Selenium in C# to essentially build up a page object model. So for example the user would choose and object they want to add to the page from a dropdown, then click add, and it would add it to the c# code.
Can I create an addin for this and if so wheres the best place to read on up on how to do this, any useful tutorials are articles would be helpful.
Any help would be much appreciated.

A: Your question is off topic for asking for tutorials, however there are two ways to do what you are looking for.
COM based plugins and T4 code template generators.
The COM plugin kind is if you want a code generator that you expect to use over and over again across all projects you write. They might be "easier" to write as you are just writing C# code but the plugin must be "installed" in to visual studio and if you give the project to someone else the plugin does not travel with the project. The recipient would also need to "install" your plugin to get it to compile on his machine.
The T4 style lets you write the code generation code right inside your project but has a odd syntax, It is fairly similar to how ASP.NET .cshtml pages are generated, you just are generating compliable code instead of a web page. The editor for T4 templates built in to visual studio is not very good, I don't think it even does code highlighting, but there are plugins for visual studio you can get that add more features to the T4 Editor. I have used this one in the past, but a lot of the features are restricted if you do not use the paid version. There are other fully free ones out there.


text:
Q: Function return value can't be assigned to a const char value I am using OpenGL, don't worry my problem is with C and not something related to OpenGL. In OpenGL, we have something called shaders. It is a text file. All I want to do is to read that text file and pass it to a function that accepts only const char * const*. (eg. func(&shaderSource) and shaderSource must be const char* shaderSource.). I just want this terminology with multiple files. Can I? I saw people doing this with C++, but I chose C over C++ in the project. Here is some of my failed attempts.
char vertexShaderContent[1000] = readfile("Shader/default.frag.txt");
const char *vertexShaderSource;
strcpy(vertexShaderSource, vertexShaderContent);

Here I tried to get a new variable (By the way this is in the main function) that executes the function and gets the return value of that function. Now I did copy that string (using strcat) to assign the value of vertexShaderContent to vertexShaderSource. By the way here is my readfile code:
char *readfile(const char* filename) {
    char *res = malloc(sizeof(char *) * 100);
    char *word = malloc(sizeof(char *));
    FILE *file = fopen(filename, "r");

    while (fgets(word, sizeof(word), file) != NULL) {
        strcat(res, word);
    }

    strcat(res, "\n\0");

    fclose(file);

    return res;
}

Summary
All my problem is that I want to pass a char* to a function accepting const char*s. If I can't, is there is any way I can get this 'multiple' files to work?
Thanks.

A: In char vertexShaderContent[1000] = readfile("Shader/default.frag.txt");, readfile returns a pointer to char, but vertexShaderContent is an array of char. To initialize an array, one needs to provide values for each element to be initialized. A pointer to char is not a correct type for initializing char values.
What may work here is char *vertexShaderContent = readfile("Shader/default.frag.txt");. That defines vertexShaderContent to be a pointer to the memory returned by readfile. However, it is not clear what you want to do, because the code that follows it is confusing:
const char *vertexShaderSource;
strcpy(vertexShaderContent, vertexShaderSource);

This would overwrite the data at vertexShaderContent with new data, so it loses the data that readfile returned. And it attempts to copy from vertexShaderSource, but vertexShaderSource has not been set to point to anywhere. Its value is indeterminate. This strcpy cannot do anything useful. Since we do not know what you are trying to do here, we cannot recommend a solution.
These lines in readfile are incorrect:
char *res = malloc(sizeof(char *) * 100);
char *word = malloc(sizeof(char *));

The first allocates space for 100 char *. To allocate space for 100 char, use char *res = malloc(100 * sizeof *res);.
The second allocates space for one char *. But it looks like you want space for one "word", which would likely be some varying number of characters. Maybe you would want to start with space for at least 100 characters:
char *word = malloc(100 * sizeof *word);

That could help get the code going at first, although a good eventual solution would ensure the allocated spacer could not be overflowed.
In strcat(res, word), the data pointed to by res has not yet been initialized. Before using strcat, you must have some string in the destination. That can be the empty string, which you can create by putting a null terminator character in res:
*res = '\0';

All my problem is that I want to pass a char* to a function accepting const char*s.

Nothing in the question shows any attempt to pass a char * for a const char * parameter that would not work, except for the issues noted above.


text:
Q: How to access another page's elements to use in javascript? Not JQuery please Say I have a page a.php and want to get a table element using it's id  from another page b.php. Know it have been asked but only answers were in Jquery, any way of doing it with pure js?
Thanks!

A: If you mean accessing data from another tab/window, that is possible via acquiring a reference to it. For example if you open it yourself:

        <button onclick="create()">Create</button>
        <button onclick="check()">Check</button>
        <button onclick="modify()">Modify</button>

When you click on the first button, the window.open line opens a new window/tab, and a reference to its document is kept. "about:blank" could be an actual URL - here instead a table is written there manually.
The other two buttons access and modify a cell in the table.
Suggested sequence for pushing the buttons: Create, Check, Modify, Check.


text:
Q: Changing column of enum through DB::statement I have a column of type enum I want to change it to type varchar but it brings an error that the sql syntax is not correct, please what's the solution
This is the table creation migration code
 class CreateCurrenciesTable extends Migration
{
    /**
   * Run the migrations.
   *
   * @return void
   */
 public function up()
 {
    $symbols = ['₦', '$', '£'];
    Schema::create('currencies', function (Blueprint $table) use($symbols) {
        $table->increments('id');
        $table->string('name', 50);
        $table->string('code', 5);
        $table->enum('symbol', $symbols);
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    DB::statement('SET FOREIGN_KEY_CHECKS = 0');
    Schema::dropIfExists('currencies');
    DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}

This is the migration code I want to use to change the column type but keep on getting an error
class AddSymbolToImagesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('images', function (Blueprint $table) {
       DB::statement('ALTER TABLE images ALTER COLUMN symbol VARCHAR(200)');
       // $table->text('symbol')->change();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('images', function (Blueprint $table) {
       // $symbols = ['₦', '$', '£'];
       // $table->enum('symbol', $symbols)->change();
        DB::statement('ALTER TABLE images ALTER COLUMN symbol enum ');
    });
}
}

A: This does not really have anything to do with Laravel and you should also include the error next time.
To change the column type you can use MODIFY or MODIFY COLUMN.
So this would work:
ALTER TABLE images MODIFY symbol varchar(200)
There is a few to change the column name as you can see in the docs here: https://dev.mysql.com/doc/refman/8.0/en/alter-table.html#alter-table-redefine-column


text:
Q: Show an image on whole page How can i show an image on whole page when user click a button?
(means i have several controls on page and want to show this image over all of them)

A: You can write this line in button click event
ClientScript.RegisterClientScriptBlock(GetType(), "key", "javascript: document.body.background = 'Untitled.jpg'; document.body.style.backgroundRepeat = 'no-repeat'; document.body.style.backgroundPosition = '300px 300px'; ", true);

A: Your looking for a Modal window, there are some great jQuery plugins for that. I really like one called Reveal.
To do it yourself. Set a "position: absolute" and a "z-index" that is higher than your other elements on a div, and trigger it to show/hide with javascript and you should be fine.


text:
Q: Gcloud triggers not working for pushes from bitbucket pipeline We have a bitbucket pipeline set up for increasing semantic versioning and a tag according to it to the repository
In gcloud I've set up a trigger which listens for the push of a new tag.
When I push a tag manually the trigger works completely fine, however when a tag is pushed through the bitbucket pipeline, the trigger does not trigger.
Any help here?
Manual test to target the issue correctly.


text:
Q: Rx.net - synchronous vs async observers - depends on source? I'm very new to Rx and trying to wrap my head around it. Haven't read a whole lot but trying to go through a hands on lab first.
class Program
{
    static void Main(string[] args)
    {
        // one source, produces values with delays
        IObservable<int> source = Observable.Generate(0, i => i < 2, i => ++i, i => i*i, i => TimeSpan.FromMilliseconds(100));
        IObserver<int> handler = null;

        IDisposable subscription = source.Subscribe(
            i =>
            {
                Console.WriteLine("Sub 1 [tid:{0}] received {1} from source", Thread.CurrentThread.ManagedThreadId,i);
                Thread.Sleep(500);
            },
            exception => Console.WriteLine("Sub 1 Something went wrong {0}", exception),
            () => Console.WriteLine("Sub 1 Completed observation"));

        IDisposable subscription2 = source.Subscribe(
            i => Console.WriteLine("Sub 2 [tid:{0}] received {1} from source", Thread.CurrentThread.ManagedThreadId, i),
            exception => Console.WriteLine("Sub 2 Something went wrong {0}", exception),
            () => Console.WriteLine("Sub 2 Completed observation"));

        Console.WriteLine("press to cancel");
        Console.ReadLine();
        subscription.Dispose();
        subscription2.Dispose();

    }
}

This produces async interleaved execution as expected.
On the other hand, if I change the source to be synchronous, even the observers become blocking and synchronous (same thread id, doesn't go to sub2 without fully consuming sub1).
Can someone help me understand this? Here's the sync version
class Program
{
    static void Main(string[] args)
    {
        // one source, produces values
        IObservable<int> source = Observable.Generate(0, i => i < 2, i => ++i, i => i*i);
        IObserver<int> handler = null;

        // two observers that consume - first with a delay and the second immediately.
        // in this case, the behavior of the observers becomes synchronous?
        IDisposable subscription = source.Subscribe(
            i =>
            {
                Console.WriteLine("Sub 1 [tid:{0}] received {1} from source", Thread.CurrentThread.ManagedThreadId,i);
                Thread.Sleep(500);
            },
            exception => Console.WriteLine("Sub 1 Something went wrong {0}", exception),
            () => Console.WriteLine("Sub 1 Completed observation"));

        IDisposable subscription2 = source.Subscribe(
            i => Console.WriteLine("Sub 2 [tid:{0}] received {1} from source", Thread.CurrentThread.ManagedThreadId, i),
            exception => Console.WriteLine("Sub 2 Something went wrong {0}", exception),
            () => Console.WriteLine("Sub 2 Completed observation"));

        Console.WriteLine("press to cancel");
        Console.ReadLine();
        subscription.Dispose();
        subscription2.Dispose();

    }
}

A: I believe the reason is the selected default IScheduler for the operator. Take a look at the accepted answer here.
For Generate it depends on the overload. Based on the answer, these are the default schedulers used. You can verify them for source if you like

*

*Default IScheduler for the temporal operator is DefaultScheduler.Instance

*Default IScheduler for the latter operator is CurrentThreadScheduler.Instance
You can confirm this by providing a "non-blocking" scheduler in your sync version
IObservable<int> source = Observable.Generate(0, i => i < 2, i => ++i, i => i * i, DefaultScheduler.Instance);


text:
Q: Has Leia ever shown any reaction to Darth Vader being her Father? In Return of the Jedi Luke tells Leia he is her brother and that Darth Vader is their father.
Leia's reaction to this revelation has always confused me, she has just found out that the man who destroyed her home planet, killed many of her friends, enslaved the Galaxy and tortured the man she loves is her father, but yet she seems remarkably calm.
I know that her feelings towards her father are explored in the Extended Universe/Legends novels, but has it ever been dealt with in any of the (now) canon sources?

A: If we go by Legends Canon there was an entire book about Leia dealing with the fact Darth Vader was her father.
http://starwars.wikia.com/wiki/Tatooine_Ghost
Leia getting to grips with her father's identity was also a big part of the Thrawn Trilogy, from the point where she lands on Honoghr and learns about the fate of the Noghri and their devotion to Darth Vader.
http://starwars.wikia.com/wiki/Noghri#Lady_Vader

A: She reacts when first informed.
While subtle, the script has Leia clearly reacting to the news from Luke. However even before confirming that she's his sister, Leia has pieced together the puzzle. She is shown being distraught and frightened.

LUKE
  He's my father.
LEIA
  Your father?
LUKE
  There's more. It won't be easy for you to hear it, but you must. If I
  don't make it back, you're the only hope for the Alliance.
Leia is very disturbed by this. She moves away, as if to deny it.
LEIA
  Luke, don't talk that way. You have a power I--I don't understand and
  could never have.
LUKE
  You're wrong, Leia. You have that power too. In time you'll learn to
  use it as I have. The Force is strong in my family. My father has
  it...I have it...and...my sister has it.
Leia stares into his eyes. What she sees there frightens her. But she
  doesn't draw away. She begins to understand.
LUKE
  Yes. It's you Leia.
LEIA
I know. Somehow...I've always known.
Return of the Jedi Script - IMSDB

Now while her tone changes quite quickly, and the revelation to her doesn't lead to the same emotionally charged outburst that it did for Luke, she clearly still shows surprise. The way she took the news seems to reflect on her character. A hardened rebel who'd grown up royal but amongst the hardships of the rebellion fighting for what she believed to be right. Whether she ever accepted Anakin as her father is unclear. However in The Force Awakens and The Last Jedi, she kept her name of Organa and seems to value her adoptive parents more than her biological father.
In the official canon junior novelisation published in 2015, Leia's reaction is further described.

And now a lot of things begin to make sense to Leia. Things that have never made sense before.
  "Yes. It's you, Leia. You are my sister."
  Yes, just like Luke, she feels the truth of this immediately. But what a truth to finally acknowledge! Finding out that Luke is her brother should bring her joy…but to learn that the dreaded Darth Vader—who captured her, imprisoned her, even tortured her—is her father? Alas, the joy of gaining a brother is lost for now in the shadow of their dark father.
Star Wars: Return of the Jedi: Beware the Power of the Dark Side! Chapter 49:
   In which Leia Learns the Truth at Last

A: In the current canon, the fact she was Vader's daughter was something that was kept quiet, initially known only to Luke, herself, and Han (well, and probably Snoke), until the events of the novel Bloodline when the secret was revealed and essentially destroyed her political career.
She wasn't happy about Vader being her biological father, and based on her actions very much considered Bail to be her real, if adopted, one.


text:
Q: Objective-C: multi-parameter method syntax into Swift Package's functions Goal: to master the ObjC <--> Swift API syntax
Problem: Working with multi-parameter function API.
I haven't been doing ObjC in years and now I need to interface ObjC with Swift packages.

Here's the Swift-Package code:
import Foundation

public struct RicStruct {
    public private(set) var text = "Hello, World!"

    public init() {}

    public func sayHello() -> String {
        "Hello Ric!"
    }
}

public class RicClass: NSObject {
    @objc public var msg = "Mother has a feeling, I might be too appealing."
    @objc public let text = "Hello Everybody!"

    override public init() {}

    @objc public func sayHello() {
        print(text)
    }

    @objc public func doSomething(msg: String) {
        print("Inside doSomething: \(msg)")
    }

    @objc public func doSomething(msg: String, answer: String) {
        print("Inside doSomething with msg: \(msg) and answer: \(answer)")
    }

    @objc public func sayHelloTo(whom: String) -> String {
        "Hello \(whom)!"
    }
}

I'm having trouble with the multi-parameter syntax.
Objective-C likes to append 'with' or 'to', etc. to parameter names.  I've learned this via trial & error.
But I'm having trouble with the multi-parameter syntax:

Question: What's the correct syntax for multi-parameter Objective-C method calls?

A: Simple Solution, adding the appropriate label:


text:
Q: "The specified key does not exist" for VueJS app deployed on deployed on S3 with CloudFront I have deployed a VueJS app with S3 and CloudFront using Route53. It seemed like everything was working fine. I'm able to visit the site at https://my-domain.com, and I can navigate to different routes that I have set up with Vue router. However, when I try to access https://my-domain.com/about directly, I see the following error:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<link type="text/css" id="dark-mode" rel="stylesheet" href=""/>


text:
Q: Problem C++ STD Iterator comparison operators Good day sirs,
because it looks like mine isn't going to be that good.
I have a class C, which doesn't have any children but has a vector made of pointers to instances of another class, let's call it B:
class C
{
    public:
       ...
       std::vector<B*> elements;
       ...
}

B also has a vector of pointers to instances of another class, let's call it A:
class B
{
    public:
       ...
       std::vector<A*> elements2;
       ...
}

C has a method that iterates through the elements of elements and elements2, and works like this:
std::vector<B*>::iterator it1;
std::vector<A*>::iterator it2;

for (it1=this->elements.begin(); it1!=this->elements.end(); ++it1)
{
    for (it2 = it1->elements2.begin(); it12=it1->elements2.end(); ++it2)
    {
        it2->do_something(); //method of class A
    }
}

But the compiler (g++) keeps telling me there is no match for operator!= in (class hierarchy).
Does anybody know what I did wrong? Other operators like '<' don't seem to work, as well.
I'm not a newbie but it's the first time I got to use iterators in C++ (former Python programmer) and I can't really figure out what's wrong with my code.
Thanks for the help in advance, I'm losing my hair over this!
Edit: I'm adding the whole error for reference. I edited it to fit the question, I hope I didn't mess anything up:

no match for 'operator!=' in 'it1 != ((C*)this)->C::elements.std::vector<_Tp, _Alloc>::end with _Tp = B*, _Alloc = std::allocator'

A: You should try this :
std::vector<B*>::iterator it1;
std::vector<A*>::iterator it2;

for (it1=this->elements.begin(); it1 != this->elements.end(); ++it1)
{
    for (it2 = (*it1)->elements2.begin(); it2 != (*it1)->elements2.end(); ++it2)
    {
        (*it2)->do_something(); //method of class A
    }
}

*

*In the inner loop, you tried to compare it1 (of type std::vector<B*>::iterator) with it1->elements2.end() (of type std::vector<A*>::iterator), so the compiler is right to complain.

*You have to dereference the iterator it2 to 'reach' an element of type A* : (*it2)->do_something()
On a side note, there are probably several ways to improve your existing code, but I'll only state a few :

*

*I would avoid using this->

*Use typedef to clarify your code involving iterators

*If it1 and it2 aren't used outside the loop, narrow their scope

You could write (obviously, the vector typedef'ed names should be more meaningful) :
typedef std::vector<A*> vector_of_A;
typedef std::vector<B*> vector_of_B;
for (vector_of_B::iterator it1 = elements.begin(), end1 = elements.end(); it1 != end1; ++it1)
{
    vector_of_A &innerVector = (*it1)->elements2;
    for (vector_of_A::iterator it2 = innerVector.begin(), end2 = innerVector.end(); it2 != end2; ++it2)
    {
        /* ... */
    }
}

A: This should compile:
std::vector<B*>::iterator it1;
std::vector<A*>::iterator it2;

for (it1 = elements.begin(); it1 != elements.end(); ++it1)
{
    for (it2 = elements2.begin(); it2 != elements2.end(); ++it2)
    {
        it2->do_something(); //method of class A
    }
}

But I don't know what you want to really do.

A: You have a vector to a pointer.  As such to call a function on that pointer you have to first dereference the iterator (to get the pointer) than call the function on it.
for ( it1 = elements.begin(); it1 != elements.end(); ++it1)
{
    for (it2 = (*it1)->elements2.begin(); it2 != (*it1)->elements2.end(); ++it2)
    {
        (*it2)->do_something(); //method of class A
    }
}

Edit:  I think the problem lies elsewhere.  The following code compiles fine on VS2008 and VS2010
class A
{
public:
    void Fn()
    {
    }
};

class B
{
    public:
       std::vector<A*> elements2;
};

class C
{
    public:
       std::vector<B*> elements;

    void Fn()
    {
        std::vector< B* >::iterator it1;
        std::vector< A* >::iterator it2;

        for ( it1 = elements.begin(); it1 != elements.end(); ++it1 )
        {
            for ( it2 = (*it1)->elements2.begin(); it2 != (*it1)->elements2.end(); ++it2 )
            {
                (*it2)->Fn();
            }
        }
    }
};

A: Following code works with gcc 4.2.0 on linux. What version are you using?
Maybe its the order in which you are declaring the classes or some other issue.
#include <vector>

class A;
class B;
class C;

class A {
  public:
    void do_something() {};
};
class B
{
  public:
    std::vector<A*> elements2;
};

class C
{
  public:
    std::vector<B*> elements;

    void do_this() {
      std::vector<B*>::iterator it1;
      std::vector<A*>::iterator it2;

      for (it1=this->elements.begin(); it1!=this->elements.end(); ++it1)
      {
        for (it2 = (*it1)->elements2.begin(); it2 != (*it1)->elements2.end(); ++it2)
        {
          (*it2)->do_something(); //method of class A
        }
      }
    };
};

int main() {
  C c;
};

~
~


text:
Q: Цикл for и счетчик типа double Почему неверно отображается значение самого счетчика и уходит точность во время выполнения?
public class DoubleFor {

public static void main(String[] args) {

    for (double d = 0.1; d <= 1; d += 0.1 ){

        System.out.println("d = " + d);
    }
}

}
компиляция:

d = 0.1
  d = 0.2
  d = 0.30000000000000004
  d = 0.4
  d = 0.5
  d = 0.6
  d = 0.7
  d = 0.7999999999999999
  d = 0.8999999999999999
  d = 0.9999999999999999
Process finished with exit code 0

A: Позаимствую объяснение у Ильи Кантора. У него речь про javascript, но всё это применимо к большинству языков программирования без каких либо изменений:

Число 0.1 (одна десятая) записывается просто в десятичном формате. Но
  в двоичной системе счисления это бесконечная дробь, так как единица на
  десять в двоичной системе так просто не делится. Также бесконечной
  дробью является 0.2 (=2/10).
Двоичное значение бесконечных дробей хранится только до определенного
  знака, поэтому возникает неточность.
Когда мы складываем 0.1 и 0.2, то две неточности складываются,
  получаем незначительную, но всё же ошибку в вычислениях.

https://learn.javascript.ru/number#неточные-вычисления
Более подробно на английском можно познакомиться по ссылке: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html#680

A: Всё дело в том, что в стандарте IEEE 754 на число выделяется ровно 8 байт(=64 бита), не больше и не меньше.
Для примера число 0.1 (одна десятая) записывается просто в десятичном формате. Но в двоичной системе счисления это бесконечная дробь, так как единица на десять в двоичной системе так просто не делится. Также бесконечной дробью является 0.2 (=2/10).
Двоичное значение бесконечных дробей хранится только до определенного знака, поэтому возникает неточность.
Когда мы складываем например 0.1 и 0.2, то две неточности складываются, получаем незначительную, но всё же ошибку в вычислениях.
В данном же примере тоже самое: конечное значение никогда не будет равно единице.
то же самое происходит в любом другом языке, где используется формат IEEE 754, включая JavaScript, C, PHP, Ruby, Perl.
Взято с сайта по JavaScript