问:
Nuke pulldown Choice knob returns integer instead of string when used getValue()
Im trying to getvalue() of custom pulldown choice Knob in nuke, when I print it returns integer instead of knob value which is a string

ks = nuke.toNode('nodename').knob('pulldownchoice').getValue()
print ks
```

I expect the output to be string, but the output im getting is 1.0

答:
Although in some cases both methods getValue() and value() are interchangeable, you have to use value() method for strings and getValue() method for numbers.

In your case there are three methods available for accessing Enumeration_Knob values and one method for setting new ones:

getValue() brings you a number (an index of enum's chosen pair)

value() brings you a string (a name of enum's chosen pair)

values() brings you a list of all the strings (all names)

setValue() sets a new value for a knob (you can use index or name here)

You can use getValue() method for getting numeric properties like scale or rotate:

```<code>nuke.toNode('Transform1').knob('rotate').getValue()

nuke.toNode('Transform1')['rotate'].getValue()

nuke.selectedNode()['rotate'].getValue()
</code>```

To print all the knob's names and corresponding values of the selected node use this method:

```<code>print(nuke.selectedNode())
</code>```

For pulldown menus 3 main methods are used – getValue(), value() and values() as well as setValue() method:

getValue()

```<code>g = nuke.toNode('Transform1')['filter'].getValue()
print(g)

# getValue() method brings properties' index (because it's enumerator)
# If your filter="Notch" getValue() brings 7.0 – i.e. eight element

# Result: 7.0
</code>```

value()

```<code>v = nuke.toNode('Transform1')['filter'].value()
print(v)

# value() method brings a name of a chosen filter

# Result: Notch
</code>```

values()

```<code>vv = nuke.toNode('Merge1')['bbox'].values()
print(vv)

# values() method brings a list of all strings stored in enum

# Result: ['union', 'intersection', 'A', 'B']
</code>```

setValue()

```<code>s1 = nuke.toNode('Merge2')['operation'].setValue(0)

# setValue() method sets a new existing value in enum with index 0

# Result: atop

s2 = nuke.toNode('Merge3')['operation'].setValue("xor")

# setValue() method sets a new existing value in enum with name "xor"

# Result: xor
</code>```

Body:
Im trying to getvalue() of custom pulldown choice Knob in nuke, when I print it returns integer instead of knob value which is a string

ks = nuke.toNode('nodename').knob('pulldownchoice').getValue()
print ks

I expect the output to be string, but the output im getting is 1.0

Body:
Although in some cases both methods getValue() and value() are interchangeable, you have to use value() method for strings and getValue() method for numbers.

In your case there are three methods available for accessing Enumeration_Knob values and one method for setting new ones:

getValue() brings you a number (an index of enum's chosen pair)

value() brings you a string (a name of enum's chosen pair)

values() brings you a list of all the strings (all names)

setValue() sets a new value for a knob (you can use index or name here)

You can use getValue() method for getting numeric properties like scale or rotate:

nuke.toNode('Transform1').knob('rotate').getValue()

nuke.toNode('Transform1')['rotate'].getValue()

nuke.selectedNode()['rotate'].getValue()

To print all the knob's names and corresponding values of the selected node use this method:

print(nuke.selectedNode())

For pulldown menus 3 main methods are used – getValue(), value() and values() as well as setValue() method:

getValue()

g = nuke.toNode('Transform1')['filter'].getValue()
print(g)

# getValue() method brings properties' index (because it's enumerator)
# If your filter="Notch" getValue() brings 7.0 – i.e. eight element

# Result: 7.0

value()

v = nuke.toNode('Transform1')['filter'].value()
print(v)

# value() method brings a name of a chosen filter

# Result: Notch

values()

vv = nuke.toNode('Merge1')['bbox'].values()
print(vv)

# values() method brings a list of all strings stored in enum

# Result: ['union', 'intersection', 'A', 'B']

setValue()

s1 = nuke.toNode('Merge2')['operation'].setValue(0)

# setValue() method sets a new existing value in enum with index 0

# Result: atop

s2 = nuke.toNode('Merge3')['operation'].setValue("xor")

# setValue() method sets a new existing value in enum with name "xor"

# Result: xor


来源: stackexchange

问:
Portable array indexing in both bash and zsh
Array indexing is 0-based in bash, and 1-based in zsh (unless option KSH_ARRAYS is set).

As an example: To access the first element of an array, is there something nicer than:

```<code>if [ -n $BASH_VERSION ]; then
    echo ${array[0]}
else
    echo ${array[1]}
fi
</code>```

答:
TL;DR:

To always get consistent behaviour, use:

```<code>${array[@]:offset:length}
</code>```

Explanation

For code which works in both bash and zsh, you need to use the offset:length syntax rather than the [subscript] syntax.

Even for zsh-only code, you'll still need to do this (or use emulate -LR zsh) since zsh's array subscripting basis is determined by the option KSH_ARRAYS.

Eg, to reference the first element in an array:

```<code>${array[@]:0:1}
</code>```

Here, array[@] is all the elements, 0 is the offset (which always is 0-based), and 1 is the number of elements desired.

ContentLicense: CC BY-SA 4.0

Body:
Array indexing is 0-based in bash, and 1-based in zsh (unless option KSH_ARRAYS is set).

As an example: To access the first element of an array, is there something nicer than:

if [ -n $BASH_VERSION ]; then
    echo ${array[0]}
else
    echo ${array[1]}
fi

Body:
TL;DR:

To always get consistent behaviour, use:

${array[@]:offset:length}

Explanation

For code which works in both bash and zsh, you need to use the offset:length syntax rather than the [subscript] syntax.

Even for zsh-only code, you'll still need to do this (or use emulate -LR zsh) since zsh's array subscripting basis is determined by the option KSH_ARRAYS.

Eg, to reference the first element in an array:

${array[@]:0:1}

Here, array[@] is all the elements, 0 is the offset (which always is 0-based), and 1 is the number of elements desired.


问:
Remove the navigation header from the react-native screen - stack navigation
I have a screen which has tab-bar navigation where each screen is of type stack navigation with a couple of screens defined in each. When I navigate from FamilyMembers to SingleContact screen I don't want to see the navigation bar with the back button on top. I want my view (the blue one) in single contact to start from the top. But it appears although I set the header to null! Please help.

//------------------- Single Contact Screen----------//

```<code>    import { Text, AsyncStorage, Image, FlatList, Alert, ActivityIndicator, Platform, StyleSheet, View } from 'react-native';
    import { Icon, Container, Spinner, Content, Left, Right, Header, ListItem } from 'native-base'
    import profileService from '../services/Api/ProfileService';
    import { SafeAreaView } from 'react-navigation';

    HEADER_MAX_HEIGHT = 100
    HEADER_MIN_HEIGHT = 60
    PROFILE_IMAGE_MAX_HEIGHT = 80
    PROFILE_IMAGE_MIN_HEIGHT = 40

    export default class SingleContact extends Component {

        constructor(props) {
            super(props);
            this.state = { userName: "", contacts: [], userID: "", cookie: null, memberShips: [] };
        }
        async componentDidMount() {

        }
        onDataLoaded(result, userName) {

        }
        render() {
            return (
                <SafeAreaView>
                    <View style={{ flex: 1 }}>
</code>```

//--------------------App.js navigation setup --------------------------//

```<code>    const FamilyMembersStack = createStackNavigator({
  FamilyMembers: {
    screen: FamilyMembers,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Family members",
      }
    }
  },
  SingleContact: {
    screen: SingleContact,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Contact"
      }
    }
  },
}
  , {
    mode: 'modal',
    headerMode: 'none'
  });

const HomeScreenStack = createStackNavigator({
  Home: {
    screen: HomeScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  },
  FamilyMembersStack: {
    screen: FamilyMembersStack,
    navigationOptions: ({ navigation }) => {
      return {
        header: null
      }
    }
  },
  AttendanceHistory: {
    screen: AttendanceHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Attendance history"
      }
    }
  },
  OrderHistory: {
    screen: OrderHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Order history"
      }
    }
  }
});

HomeScreenStack.navigationOptions = {
  tabBarLabel: 'My info',
  tabBarIcon: ({ tintColor }) => (
    <FaIcon name="user" size={20} color={tintColor} />
  ),
};
const ScheduleScreenStack = createStackNavigator({
  Schedule: {
    screen: ScheduleScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  }
});

ScheduleScreenStack.navigationOptions = {
  tabBarLabel: 'Find a class',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-calendar" size={20} color={tintColor} />
  ),
};

const ShopScreenStack = createStackNavigator({
  Shop: {
    screen: ShopScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  }
});

ShopScreenStack.navigationOptions = {
  tabBarLabel: 'Get a pass',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-basket" size={20} color={tintColor} />
  ),
};

const NotificationsScreenStack = createStackNavigator({
  Notifications: {
    screen: NotificationsScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  }
});

NotificationsScreenStack.navigationOptions = {
  tabBarLabel: 'Notifications',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-alert" size={20} color={tintColor} />
  ),
};

const EventsStack = createStackNavigator({
  Events: {
    screen: Events,
    navigationOptions: ({ navigation }) => {
      return {
        tabBarLabel: "Events",
        tabBarIcon: ({ tintColor }) => (
          <Icon name="md-calendar" size={20} />
        ),
        headerLeft: (
          <Icon name="md-menu" style={{ paddingLeft: 10 }}
            onPress={() => navigation.openDrawer()}
            size={30} />
        )
      }
    }
  }
});

EventsStack.navigationOptions = {
  tabBarLabel: 'Events',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-calendar" size={20} color={tintColor} />
  ),
};
const DashboardTabNavigator = createBottomTabNavigator({
  HomeScreenStack,
  ScheduleScreenStack,
  ShopScreenStack,
  NotificationsScreenStack
},
  {
    navigationOptions: ({ navigation }) => {
      const { routeName } = navigation.state.routes[navigation.state.index];
      return {
        header: null,
        headerTitle: routeName,
      }
    },
    tabBarOptions: {
      activeTintColor: 'white',
      inactiveTintColor: 'silver',
      labelStyle: {
        fontSize: 12,
      },
      style: {
        backgroundColor: 'rgba(24,130,201,1);',
      },
    }
  }, { initialRouteName: HomeScreenStack }
);

const DashboardStackNavigator = createStackNavigator({
  DashboardTabNavigator: DashboardTabNavigator
});

const AppDrawerNavigator = createDrawerNavigator({
  Dashboard: {
    screen: DashboardStackNavigator
  }
}, {
    contentComponent: props => <DrawerContent {...props} />
  });
const AppSwitchNavigator = createSwitchNavigator({
  AuthLoading: AuthLoadingScreen,
  Login: { screen: Login },
  Dashboard: { screen: AppDrawerNavigator }
}, {
    initialRouteName: 'AuthLoading',
  }
);

const AppContainer = createAppContainer(AppSwitchNavigator);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}
</code>```

答:
Did you already modify your FamilyMembersStack inside HomeScreenStack like this?

```<code>    const HomeScreenStack = createStackNavigator({
  Home: {
    screen: HomeScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  },

  // modify this Stack

  FamilyMembersStack:{
    screen: FamilyMembersStack,
    navigationOptions: ({ navigation }) => {
      return {
        header: null
      }
    }
  }
  AttendanceHistory: {
    screen: AttendanceHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Attendance history"
      }
    }
  },
  OrderHistory: {
    screen: OrderHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Order history"
      }
    }
  }
});
</code>```

Follow up answer, remove the following. so that the header will render on the designated screen:

```<code> export default class SingleContact extends Component {
    static navigationOptions = {

        header: null, // remove this
    }
    constructor(props) {
        super(props);
        this.state = { userName: "", contacts: [], userID: "", cookie: null, memberShips: [] };
    }
    async componentDidMount() {

    }
    onDataLoaded(result, userName) {

    }
    render() {
</code>```

//------------------------------//

```<code>const FamilyMembersStack  = createStackNavigator({
  FamilyMembers: {
    screen: FamilyMembers,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Family members",
        header:null
      }
    }
  },
  SingleContact: {
    screen: SingleContact,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Contact",
        header:null // and remove this
      }
    }
  },
});
</code>```

Body:
I have a screen which has tab-bar navigation where each screen is of type stack navigation with a couple of screens defined in each. When I navigate from FamilyMembers to SingleContact screen I don't want to see the navigation bar with the back button on top. I want my view (the blue one) in single contact to start from the top. But it appears although I set the header to null! Please help.

//------------------- Single Contact Screen----------//

    import { Text, AsyncStorage, Image, FlatList, Alert, ActivityIndicator, Platform, StyleSheet, View } from 'react-native';
    import { Icon, Container, Spinner, Content, Left, Right, Header, ListItem } from 'native-base'
    import profileService from '../services/Api/ProfileService';
    import { SafeAreaView } from 'react-navigation';

    HEADER_MAX_HEIGHT = 100
    HEADER_MIN_HEIGHT = 60
    PROFILE_IMAGE_MAX_HEIGHT = 80
    PROFILE_IMAGE_MIN_HEIGHT = 40

    export default class SingleContact extends Component {

        constructor(props) {
            super(props);
            this.state = { userName: "", contacts: [], userID: "", cookie: null, memberShips: [] };
        }
        async componentDidMount() {

        }
        onDataLoaded(result, userName) {

        }
        render() {
            return (
                <SafeAreaView>
                    <View style={{ flex: 1 }}>

//--------------------App.js navigation setup --------------------------//

    const FamilyMembersStack = createStackNavigator({
  FamilyMembers: {
    screen: FamilyMembers,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Family members",
      }
    }
  },
  SingleContact: {
    screen: SingleContact,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Contact"
      }
    }
  },
}
  , {
    mode: 'modal',
    headerMode: 'none'
  });

const HomeScreenStack = createStackNavigator({
  Home: {
    screen: HomeScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  },
  FamilyMembersStack: {
    screen: FamilyMembersStack,
    navigationOptions: ({ navigation }) => {
      return {
        header: null
      }
    }
  },
  AttendanceHistory: {
    screen: AttendanceHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Attendance history"
      }
    }
  },
  OrderHistory: {
    screen: OrderHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Order history"
      }
    }
  }
});

HomeScreenStack.navigationOptions = {
  tabBarLabel: 'My info',
  tabBarIcon: ({ tintColor }) => (
    <FaIcon name="user" size={20} color={tintColor} />
  ),
};
const ScheduleScreenStack = createStackNavigator({
  Schedule: {
    screen: ScheduleScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  }
});

ScheduleScreenStack.navigationOptions = {
  tabBarLabel: 'Find a class',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-calendar" size={20} color={tintColor} />
  ),
};

const ShopScreenStack = createStackNavigator({
  Shop: {
    screen: ShopScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  }
});

ShopScreenStack.navigationOptions = {
  tabBarLabel: 'Get a pass',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-basket" size={20} color={tintColor} />
  ),
};

const NotificationsScreenStack = createStackNavigator({
  Notifications: {
    screen: NotificationsScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  }
});

NotificationsScreenStack.navigationOptions = {
  tabBarLabel: 'Notifications',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-alert" size={20} color={tintColor} />
  ),
};

const EventsStack = createStackNavigator({
  Events: {
    screen: Events,
    navigationOptions: ({ navigation }) => {
      return {
        tabBarLabel: "Events",
        tabBarIcon: ({ tintColor }) => (
          <Icon name="md-calendar" size={20} />
        ),
        headerLeft: (
          <Icon name="md-menu" style={{ paddingLeft: 10 }}
            onPress={() => navigation.openDrawer()}
            size={30} />
        )
      }
    }
  }
});

EventsStack.navigationOptions = {
  tabBarLabel: 'Events',
  tabBarIcon: ({ tintColor }) => (
    <Icon name="md-calendar" size={20} color={tintColor} />
  ),
};
const DashboardTabNavigator = createBottomTabNavigator({
  HomeScreenStack,
  ScheduleScreenStack,
  ShopScreenStack,
  NotificationsScreenStack
},
  {
    navigationOptions: ({ navigation }) => {
      const { routeName } = navigation.state.routes[navigation.state.index];
      return {
        header: null,
        headerTitle: routeName,
      }
    },
    tabBarOptions: {
      activeTintColor: 'white',
      inactiveTintColor: 'silver',
      labelStyle: {
        fontSize: 12,
      },
      style: {
        backgroundColor: 'rgba(24,130,201,1);',
      },
    }
  }, { initialRouteName: HomeScreenStack }
);

const DashboardStackNavigator = createStackNavigator({
  DashboardTabNavigator: DashboardTabNavigator
});

const AppDrawerNavigator = createDrawerNavigator({
  Dashboard: {
    screen: DashboardStackNavigator
  }
}, {
    contentComponent: props => <DrawerContent {...props} />
  });
const AppSwitchNavigator = createSwitchNavigator({
  AuthLoading: AuthLoadingScreen,
  Login: { screen: Login },
  Dashboard: { screen: AppDrawerNavigator }
}, {
    initialRouteName: 'AuthLoading',
  }
);

const AppContainer = createAppContainer(AppSwitchNavigator);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}

Body:
Did you already modify your FamilyMembersStack inside HomeScreenStack like this?

    const HomeScreenStack = createStackNavigator({
  Home: {
    screen: HomeScreen,
    navigationOptions: ({ navigation }) => {
      return {
        header: null,
      }
    },
  },

  // modify this Stack

  FamilyMembersStack:{
    screen: FamilyMembersStack,
    navigationOptions: ({ navigation }) => {
      return {
        header: null
      }
    }
  }
  AttendanceHistory: {
    screen: AttendanceHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Attendance history"
      }
    }
  },
  OrderHistory: {
    screen: OrderHistory,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Order history"
      }
    }
  }
});

Follow up answer, remove the following. so that the header will render on the designated screen:

 export default class SingleContact extends Component {
    static navigationOptions = {

        header: null, // remove this
    }
    constructor(props) {
        super(props);
        this.state = { userName: "", contacts: [], userID: "", cookie: null, memberShips: [] };
    }
    async componentDidMount() {

    }
    onDataLoaded(result, userName) {

    }
    render() {

//------------------------------//

const FamilyMembersStack  = createStackNavigator({
  FamilyMembers: {
    screen: FamilyMembers,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Family members",
        header:null
      }
    }
  },
  SingleContact: {
    screen: SingleContact,
    navigationOptions: ({ navigation }) => {
      return {
        headerTitle: "Contact",
        header:null // and remove this
      }
    }
  },
});


问:
vhdl error : near "ladder": (vcom-1576) expecting IS. #
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.

```<code>LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.std_logic_arith.ALL;

ENTITY tb ladder IS

END tb ladder;
ARCHITECTURE behavior OF tb ladder  IS

COMPONENT ladder

PORT(A : IN std_logic_vector(3 downto 0);
     B : IN std_logic_vector(3 downto 0);
     CIN : IN std_logic;
     SUM : OUT std_logic_vector(3 downto 0);
     COUT : OUT std_logic
     );
END COMPONENT;

signal A : std_logic_vector(3 downto 0) := (others => '0100');
signal B : std_logic_vector(3 downto 0) := (others => '1001');
signal CIN : std_logic := '0';
signal SUM : std_logic_vector(3 downto 0);
signal COUT : std_logic;

BEGIN

uut: ladder PORT MAP (
A => A,
B => B,
CIN => CIN,
SUM => SUM,
COUT => COUT
);

stim_proc: process begin

wait for 2 ns;
A <= "0100";
wait for 5 ns;
B <= "1001";
wait for 3 ns;
CIN <= "O";

wait for 2 ns;
A <= "1101";
wait for 5 ns;
B <= "0011";
wait for 3 ns;
CIN <= "1";

wait for 2 ns;
A <= "0100";
wait for 5 ns;
B <= "0110";
wait for 3 ns;
CIN <= "0";

wait for 2 ns;
A <= "1101";
wait for 5 ns;
B <= "1100";
wait for 3 ns;
CIN <= "1";

wait for 2 ns;
A <= "0100";
wait for 5 ns;
B <= "1001";
wait for 3 ns;
CIN <= "0";

end process;

END ;
</code>```

so, my error is:

Error: C:\Modeltech_pe_edu_10.4a\examples\tb ladder.vhd(7): near "ladder": (vcom-1576) expecting IS.

And if you know my error, correct my code for me please.

答: Entity names must be a single word. You have tb ladder and the compiler is expecting there to be a single word followed by IS. Use a name like tb_ladder to fix this.

Body:
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.
near "ladder": (vcom-1576) expecting IS.

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.std_logic_arith.ALL;

ENTITY tb ladder IS

END tb ladder;
ARCHITECTURE behavior OF tb ladder  IS

COMPONENT ladder

PORT(A : IN std_logic_vector(3 downto 0);
     B : IN std_logic_vector(3 downto 0);
     CIN : IN std_logic;
     SUM : OUT std_logic_vector(3 downto 0);
     COUT : OUT std_logic
     );
END COMPONENT;

signal A : std_logic_vector(3 downto 0) := (others => '0100');
signal B : std_logic_vector(3 downto 0) := (others => '1001');
signal CIN : std_logic := '0';
signal SUM : std_logic_vector(3 downto 0);
signal COUT : std_logic;

BEGIN

uut: ladder PORT MAP (
A => A,
B => B,
CIN => CIN,
SUM => SUM,
COUT => COUT
);

stim_proc: process begin

wait for 2 ns;
A <= "0100";
wait for 5 ns;
B <= "1001";
wait for 3 ns;
CIN <= "O";

wait for 2 ns;
A <= "1101";
wait for 5 ns;
B <= "0011";
wait for 3 ns;
CIN <= "1";

wait for 2 ns;
A <= "0100";
wait for 5 ns;
B <= "0110";
wait for 3 ns;
CIN <= "0";

wait for 2 ns;
A <= "1101";
wait for 5 ns;
B <= "1100";
wait for 3 ns;
CIN <= "1";

wait for 2 ns;
A <= "0100";
wait for 5 ns;
B <= "1001";
wait for 3 ns;
CIN <= "0";

end process;

END ;

so, my error is:

Error: C:\Modeltech_pe_edu_10.4a\examples\tb ladder.vhd(7): near "ladder": (vcom-1576) expecting IS.

And if you know my error, correct my code for me please.


问:
Finding End of Line of an EditText
I have a multi-line EditText box in Android Studio and some buttons that can direct the cursor to different places in the text (i.e. beginning of the text, end of text, beginning of a line, or end of line); however, the beginning/end or a line buttons, send me to the beginning and ending of the text respectively, and not the lines.

I went through the debugger and discovered that even if the text reaches the end of a line and begins on the next line, a "\n" is not added to the string, though it reaches the next line of the text box.

So, how can I move the cursor to the  beginning and end of a line when I can search for the new line character?

答:
First, you need to get the line index on which the cursor lies. I am including that code but you can see it here.</p>

```<code>val lineIndex = getCursorLinePosition( editText )

val startPos = editText.layout.getLineStart( lineIndex )
// for beginning for a line
editText.setSelection( startPos )

val endPos = editText.layout.getLineEnd( lineIndex )
// for end of the line
editText.setSelection( endPos )
</code>```

Title: Finding End of Line of an EditText

Body:
First, you need to get the line index on which the cursor lies. I am including that code but you can see it here.

val lineIndex = getCursorLinePosition( editText )

val startPos = editText.layout.getLineStart( lineIndex )
// for beginning for a line
editText.setSelection( startPos )

val endPos = editText.layout.getLineEnd( lineIndex )
// for end of the line
editText.setSelection( endPos )


问:
Creating a new table with cumsum - code doesn't seem to be working?
So I am using dplyr to create a new data frame to plot: date in column 1, IDCount in column 2 and CumulativeIDCount in column 3. Here is the code that I am using to do it:

```<code>df2 <- df %>%
  group_by(Date)%>%
  summarise(IDCount =n(),CumulativeIDCount=cumsum(n()))
</code>```

but the cumulativeIDCount column isn't cumulative, it's exactly the same as the IDCount column. Where am I going wrong with this code?

答:
We can use data.table

```<code>library(data.table)
setDT(df)[, .(IDCount = .N), Date][, CumulativeIDCount = cumsum(IDCount)][]
</code>```

Or with dplyr

```<code>library(dplyr)
df %>%
   count(Date) %>%
   mutate(CumulativeIDCount = cumsum(n))
</code>```

Body:
So I am using dplyr to create a new data frame to plot: date in column 1, IDCount in column 2 and CumulativeIDCount in column 3. Here is the code that I am using to do it:

df2 <- df %>%
  group_by(Date)%>%
  summarise(IDCount =n(),CumulativeIDCount=cumsum(n()))

but the cumulativeIDCount column isn't cumulative, it's exactly the same as the IDCount column. Where am I going wrong with this code?

Body:
We can use data.table

library(data.table)
setDT(df)[, .(IDCount = .N), Date][, CumulativeIDCount = cumsum(IDCount)][]

Or with dplyr

library(dplyr)
df %>%
   count(Date) %>%
   mutate(CumulativeIDCount = cumsum(n))


问:
Is it possible to have the same prompt and profile settings across both Bash and Zsh shells?
I start to get itchy when my code isn't DRY, and for various reasons, I jump back and forth between Bash and Zsh. Instead of copy/pasting between multiple profiles, is there a way to point to a central file, andsourceit in each profile, keeping my prompts, aliases, RVM config and settings together in one file?

Looking at Ryan Bates' dotfiles, it seems like .bashrc is the place to do this. Is this the preferred solution? https://github.com/ryanb/dotfiles/commit/ac7e0c55ce038cbeadd8da2f521eb034d09eb131

答:
My dotfiles are written to be runnable in both {ba,z}sh and have the same behaviour in both shells.

Prompt setup must be done on a per-shell basis.

Use zsh's emulate bash before sourceing bash files

Array indexing requires more verbose syntax to be portable

To determine which shell, you're in, use:

```<code>if [ -n $BASH_VERSION ]; then
    # Bash specific
else
    # zsh specific
fi
</code>```

Also, see my common bash and zsh functions for a grab-bag of useful functions which work equivalently in both bash and zsh.

ContentLicense: CC BY-SA 3.0

Body:
My dotfiles are written to be runnable in both {ba,z}sh and have the same behaviour in both shells.

Prompt setup must be done on a per-shell basis.

Use zsh's emulate bash before sourceing bash files

Array indexing requires more verbose syntax to be portable

To determine which shell, you're in, use:

if [ -n $BASH_VERSION ]; then
    # Bash specific
else
    # zsh specific
fi

Also, see my common bash and zsh functions for a grab-bag of useful functions which work equivalently in both bash and zsh.


问:
how to get value of checkbox in table in javascript
I need to get the value of a checkbox provided with span in table rows. The code below is part of my project. The HTML code is for dynamic my table and javascript code is for getting the value of elements which does not work for the checkbox (it works for other input elements).

my table:

```<code>var html = '<tr class="rows" id="r'+row_id+'" style="">';
html += '<td><input type="text" id = "abc" style="height:30px" class="rtl form-control" size="20" name="" /></td>';
html += '<td><input type="text" style="height:30px" class="rtl form-control" size="25" name="" /></td>';
html += '<td style="text-align: center;">'+
'<label class="switch switch-label switch-pill switch-primary switch-sm" style="direction:ltr;">'+
'<input type="checkbox" value="1" data-size="mini" class="switch-input">'+
'<span class="switch-slider" data-checked="✓" data-unchecked="✕" unchecked></span></label>'+
'</td>'+
'<td><button class="btn btn-warning DT_action_minus" id="btn'+row_id+'" style="height:25px;width:25px;padding:0px;" href="#" title="delete">'+
'<i class="fa fa-minus" style="align:center" aria-hidden="true"></i></button></td>'+
'</tr>';
</code>```

getting the values:

```<code>var tbl = document.getElementById('descriptive-table');
var rCount = tbl.rows.length;
var cCount = 3;
var allArray = [];
for (var i = 1; i <rCount; i++){
    var rowArray = [];
    for (var j = 0; j <cCount; j++){
        rowArray.push(tbl.rows[i].cells[j].children[0].value);
    }
    allArray.push(rowArray);
}
console.log(allArray);
</code>```

答:
I fixed it like this and it works for me:</p>

```<code>$('.en-ajax-button').on('click', function(e){
     var tbl = document.getElementById('descriptive-table');
     var rCount = tbl.rows.length;
     var cCount = 3;
     var allArray = [];
     for (var i = 1; i <rCount; i++){
          var rowArray = [];
          for (var j = 0; j <cCount; j++){
              if (j != 2){
                   rowArray.push(tbl.rows[i].cells[j].children[0].value);
              }
              else{
                   rowArray.push(tbl.rows[i].cells[j].children[0].children[0].checked);
              }
          }
          allArray.push(rowArray);
    }
    console.log(allArray);
});

</code>```

Body:
I need to get the value of a checkbox provided with span in table rows. The code below is part of my project. The HTML code is for dynamic my table and javascript code is for getting the value of elements which does not work for the checkbox (it works for other input elements).

my table:

var html = '
';
html += '<input type="text" id = "abc" style="height:30px" class="rtl form-control" size="20" name="" />	';
html += '<input type="text" style="height:30px" class="rtl form-control" size="25" name="" />	';
html += ''+
''+
'<input type="checkbox" value="1" data-size="mini" class="switch-input">'+
''+
'	'+
'<button class="btn btn-warning DT_action_minus" id="btn'+row_id+'" style="height:25px;width:25px;padding:0px;" href="#" title="delete">'+
'</button>	'+
'
';

getting the values:

var tbl = document.getElementById('descriptive-table');
var rCount = tbl.rows.length;
var cCount = 3;
var allArray = [];
for (var i = 1; i <rCount; i++){
    var rowArray = [];
    for (var j = 0; j <cCount; j++){
        rowArray.push(tbl.rows[i].cells[j].children[0].value);
    }
    allArray.push(rowArray);
}
console.log(allArray);

Body:
I fixed it like this and it works for me:

$('.en-ajax-button').on('click', function(e){
     var tbl = document.getElementById('descriptive-table');
     var rCount = tbl.rows.length;
     var cCount = 3;
     var allArray = [];
     for (var i = 1; i <rCount; i++){
          var rowArray = [];
          for (var j = 0; j <cCount; j++){
              if (j != 2){
                   rowArray.push(tbl.rows[i].cells[j].children[0].value);
              }
              else{
                   rowArray.push(tbl.rows[i].cells[j].children[0].children[0].checked);
              }
          }
          allArray.push(rowArray);
    }
    console.log(allArray);
});


问:
jQuery DataTables export pdf cuts off columns
I have a dataset with large number of colums.

When exporting the pdf , columns that dont fit on the page get cut off.

I tried using the 'orientation' and 'page-size' options but its not enough.

```<code>    buttons: [
                {
                    extend: 'pdfHtml5',
                    orientation: 'landscape',
                    pageSize: 'LEGAL'
                }
            ]
</code>```

Ideally it should do one of the following:

Fit the data on one page ( making the font really small )

Continue the data in another page in the the pdf

答:
There is a solution, in that case, if you set all the column to equal length, I checked for 16 columns and found it all columns are appearing correctly.

you can set the width manually or you can also set the width dynamically if you are not aware of the number of columns.

add the following line first:

```<code>doc.content[0].layout = objLayout;
</code>```

Now you can set the table widths different way. Choose the one you want.

Method 1:

```<code>//For equal column size
doc.content[0].table.widths = ["*", "*", "*", "*", "*", "*","*","*", "*"];
</code>```

Method 2:
For setting fixed column size if you want to set a fixed width for different different columns:

```<code>doc.content[0].table.widths = ["5%", "5%", "8%", "8%", "8%", "8%","7%", "7%", "8%", "6%", "8%", "8%","7%", "7%"];
</code>```

Method 3:
 Dynamically set the equal size (if there are different tables with different number of columns)

```<code>//Get the column length
var colCount = table.columns().header().length;
//use a loop
for(var col=0;col<colCount;col++)
{
   size[col]='*';
}
doc.content[0].table.widths = size;
</code>```

Body:
I have a dataset with large number of colums.

When exporting the pdf , columns that dont fit on the page get cut off.

I tried using the 'orientation' and 'page-size' options but its not enough.

    buttons: [
                {
                    extend: 'pdfHtml5',
                    orientation: 'landscape',
                    pageSize: 'LEGAL'
                }
            ]

Ideally it should do one of the following:

Fit the data on one page ( making the font really small )

Continue the data in another page in the the pdf

Body:
There is a solution, in that case, if you set all the column to equal length, I checked for 16 columns and found it all columns are appearing correctly.

you can set the width manually or you can also set the width dynamically if you are not aware of the number of columns.

add the following line first:

doc.content[0].layout = objLayout;

Now you can set the table widths different way. Choose the one you want.

Method 1:

//For equal column size
doc.content[0].table.widths = ["*", "*", "*", "*", "*", "*","*","*", "*"];

Method 2:
For setting fixed column size if you want to set a fixed width for different different columns:

doc.content[0].table.widths = ["5%", "5%", "8%", "8%", "8%", "8%","7%", "7%", "8%", "6%", "8%", "8%","7%", "7%"];

Method 3:
 Dynamically set the equal size (if there are different tables with different number of columns)

//Get the column length
var colCount = table.columns().header().length;
//use a loop
for(var col=0;col<colCount;col++)
{
   size[col]='*';
}
doc.content[0].table.widths = size;


问:
How to record a call in android?
```<code>Recorder = new MediaRecorder();
Recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
Recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
Recorder.setOutputFile(FileName);
Recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
</code>```

this is my Code and i am not able to record the voice of other person.so what should i use instead of AudioSorce.MIC.
plz help me

答:
Sorry to disappoint you, but you can't, not in the general case. Most Android running phones have the wiring in hardware/firmware so that the media of the call does not pass through the application processor at all - it goes from the audio to the DSP and vice versa, so you cannot access it.

You can catch the audio of the person using the phone, but not the other way around, disregarding silly hacks like asking the person to use the speakers and recording the sound from there via the phone mic...

Title: How to record a call in android?

Body:
Recorder = new MediaRecorder();
Recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
Recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
Recorder.setOutputFile(FileName);
Recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

this is my Code and i am not able to record the voice of other person.so what should i use instead of AudioSorce.MIC.
plz help me


问:
Python - Find second smallest number
I found this code on this site to find the second largest number:

```<code>def second_largest(numbers):
    m1, m2 = None, None
    for x in numbers:
        if x >= m1:
            m1, m2 = x, m1
        elif x > m2:
            m2 = x
    return m2
</code>```

Source: Get the second largest number in a list in linear time

Is it possible to modify this code to find the second smallest number? So for example

```<code>print second_smallest([1, 2, 3, 4])
2
</code>```

答:
To find second smallest in the list, use can use following approach which will work if two or more elements are repeated.</p>

```<code>def second_smallest(numbers):
     s = sorted(set(numbers))
     return s[1]
</code>```

Title: Python - Find second smallest number

Body:
I found this code on this site to find the second largest number:

def second_largest(numbers):
    m1, m2 = None, None
    for x in numbers:
        if x >= m1:
            m1, m2 = x, m1
        elif x > m2:
            m2 = x
    return m2

Source: Get the second largest number in a list in linear time

Is it possible to modify this code to find the second smallest number? So for example

print second_smallest([1, 2, 3, 4])
2

Body:
To find second smallest in the list, use can use following approach which will work if two or more elements are repeated.

def second_smallest(numbers):
     s = sorted(set(numbers))
     return s[1]


问:
Google Cloud Platform permission question (pub/sub -> Dataflow -> Google Cloud Storage bucket)
I am trying to send data from Google Cloud Pub/Sub, via a DataFlow, to a Google Cloud Storage bucket. I used the template to create the DataFlow.

When I set up the bucket with default permissions, I get a warning in the Job Logs, "somelong#-compute@developer.gserviceaccount.com does not have storage.objects.get access...", and no data shows up in the bucket.

I added Dataflow Admin permissions to the Viewers of project member, and the warning went away.

It seems that the process is writing to the bucket, most just viewing it, so I'm a) confused as to why this solved my problem, b) unsure if this is the correct/appropriate permission to use.

Any info would be appreciated.

答:
somelong#-compute@developer.gserviceaccount.com

The "somelong#" is the Project Number for your project.

I added Dataflow Admin permissions to the Viewers of project member,
  and the warning went away.

The role roles/viewer has permission to list buckets, but not access objects in a bucket.

I am not sure exactly what you did and where you did it based upon the provided information. If you added the role roles/dataflow.admin to each user or the group that the users below to that is OK. The Dataflow Admin is the correct role if users need to create Dataflow jobs and access the resultant data. However, what is missing is where these jobs are being launched from. Probably from a Compute instance and this is why the service account is listed in the error. The service account also needs permissions. As they say, the answer is in the details and your question is missing a few.

If the Dataflow job is being launched from a Compute Engine instance, then the Compute Engine Default service account (the same one from your error message) needs Dataflow and Cloud Storage permissions. Dataflow.admin will give the service account the required permissions.

If the Dataflow job is being launched from outside the cloud (someone's desktop) then that user's IAM member account needs the permissions.

To see the permissions that a role has, you can use the CLI:

```<code>gcloud iam roles describe roles/dataflow.admin
</code>```

This returns the following information. The import items are the list of permissions:

```<code>description: Minimal role for creating and managing dataflow jobs.
etag: AA==
includedPermissions:
- compute.machineTypes.get
- dataflow.jobs.cancel
- dataflow.jobs.create
- dataflow.jobs.get
- dataflow.jobs.list
- dataflow.jobs.updateContents
- dataflow.messages.list
- dataflow.metrics.get
- resourcemanager.projects.get
- resourcemanager.projects.list
- storage.buckets.get
- storage.objects.create
- storage.objects.get
- storage.objects.list
name: roles/dataflow.admin
stage: GA
title: Dataflow Admin
</code>```

From this list, you can see that you gave someone/something permissions to create, get and list objects in your buckets. If the requirement is to provide just the storage permissions, then add the role roles\storage.legacyBucketWriter.

Body:
somelong#-compute@developer.gserviceaccount.com

The "somelong#" is the Project Number for your project.

I added Dataflow Admin permissions to the Viewers of project member,
  and the warning went away.

The role roles/viewer has permission to list buckets, but not access objects in a bucket.

I am not sure exactly what you did and where you did it based upon the provided information. If you added the role roles/dataflow.admin to each user or the group that the users below to that is OK. The Dataflow Admin is the correct role if users need to create Dataflow jobs and access the resultant data. However, what is missing is where these jobs are being launched from. Probably from a Compute instance and this is why the service account is listed in the error. The service account also needs permissions. As they say, the answer is in the details and your question is missing a few.

If the Dataflow job is being launched from a Compute Engine instance, then the Compute Engine Default service account (the same one from your error message) needs Dataflow and Cloud Storage permissions. Dataflow.admin will give the service account the required permissions.

If the Dataflow job is being launched from outside the cloud (someone's desktop) then that user's IAM member account needs the permissions.

To see the permissions that a role has, you can use the CLI:

gcloud iam roles describe roles/dataflow.admin

This returns the following information. The import items are the list of permissions:

description: Minimal role for creating and managing dataflow jobs.
etag: AA==
includedPermissions:
- compute.machineTypes.get
- dataflow.jobs.cancel
- dataflow.jobs.create
- dataflow.jobs.get
- dataflow.jobs.list
- dataflow.jobs.updateContents
- dataflow.messages.list
- dataflow.metrics.get
- resourcemanager.projects.get
- resourcemanager.projects.list
- storage.buckets.get
- storage.objects.create
- storage.objects.get
- storage.objects.list
name: roles/dataflow.admin
stage: GA
title: Dataflow Admin

From this list, you can see that you gave someone/something permissions to create, get and list objects in your buckets. If the requirement is to provide just the storage permissions, then add the role roles\storage.legacyBucketWriter.


问:
Need inputs and guidance on Database Design and Associations for Quiz Application
I am porting an old obsolete Java based Quiz application project onto LoopbackJS.

Background:

It is an MCQ Quiz app for Intelligence Scholarship Examination. Students can register on the app. There will be set number of questions for every grade. Students can practice by solving the questions, and will be rated based on the attempts taken to solve a question. There will be Leaderboards on which Students will be ranked.
There will also be monthly Quizs to solve. these monthly quizs will just be randomly selected questions from the all the avaliable questions, based on the students grade.

Below is the Database schema for the Old Java Project which I will be building on.

Is the above Database design ok, or there is some scope of improvement.

I have also been going through stackoverflow to find similar questions and I found another which fits close my requirement.
But i am bit confused on the #Test Questions part, struggling to fit it to my needs.

Rails Associations and db design for Quiz Application

Suggestions and Guidance would be much appreciated.
Thanks

答:
Do not have redundant data.  I see several cases of a ..._bin and ..._hex; I assume these are the same data, but in different encodings?  It is easy enough to convert (using HEX() and UNHEX()) when fetching/storing.

Don't use UUIDs for keys unless you will be receiving data from multiple clients and they cannot avail themselves of AUTO_INCREMENT Primary Keys.

Think about SET or INT for implementing col_has_% columns in a single column.  (This may or may not be an improvement.)

Be careful of how much sensitive data is being stored.

For ease of reading queries, don't include col_ in front of column names.  Ditto for not including the table name in column names.  When JOINing you have the opportunity (and obligation to the reader) to qualify columns with the table name.

When creating a many:many mapping table between two other tables, don't have an id -- the pair of ids is an excellent composite PRIMARY KEY.


问:
How to use pydub?
I just started using pydub. I am confused that should we download the music to find the path or we need to do something else? Because the example below seems like it already have the file in his terminal or IDE. But I don't see how can I import a music into the IDE.</p>

```<code>from pydub import AudioSegment

song = AudioSegment.from_wav("never_gonna_give_you_up.wav")
</code>```

答:
You need to have the never_gonna_give_you_up.wav audio in the same directory as the Python script for this to work. Or if you want to use it from another directory, you need to provide the full path, for example:

```<code>song = AudioSegment.from_wav("D:\Music\never_gonna_give_you_up.wav")
</code>```

Title: How to use pydub?

Body:
I just started using pydub. I am confused that should we download the music to find the path or we need to do something else? Because the example below seems like it already have the file in his terminal or IDE. But I don't see how can I import a music into the IDE.

from pydub import AudioSegment

song = AudioSegment.from_wav("never_gonna_give_you_up.wav")

Body:
You need to have the never_gonna_give_you_up.wav audio in the same directory as the Python script for this to work. Or if you want to use it from another directory, you need to provide the full path, for example:

song = AudioSegment.from_wav("D:\Music\never_gonna_give_you_up.wav")


问:
css submenu not appearing
CSS submenu no longer appearing

This was working and I did something to it, I dont know if it is a code problem or a css problem. Forgive me if the post is not formatted correctly,
this is my first time posting at Stackoverflow.

html

```<code>    <nav class='navClass'>
          <ul>
             <li>Home</li>
             <li>Things To Do</li>
               <ul class="sub-menu">
                  <li>Shopping</li>
                  <li>Attractions</li>
                  <li>Outdoor Fun</li>
               </ul>
               </li>
             <li>Places To Stay</li>
             <li>Where to Eat</li>
             <li>Contests</li>
             <li>History</li>
             <li>Events</li>
          </ul>
    </nav>

</code>```

css

```<code>    .navClass > ul{
    background-color: #e56109;
    color:#ffffff;
    margin-top: 0px;
    font-size: 20px;
    font-family: Arial;
}

.navClass > ul li{
    list-style-type: none;
    display: inline-block;
    padding-top: 10px;
    padding-bottom: 10px;
    padding-left: 25px;
    padding-right: 25px;
    position: relative;

}

.navClass > ul li:hover{
    background-color: #212121;
    position: relative;

}

ul.sub-menu{
    position: absolute;
    background-color: #e56109;
    list-style-type: none;
    width: 200px;
    margin-left: -25px;
    padding-bottom: 0px;
    margin-top: 10px;
    opacity: 0;

}

ul.sub-menu li{
    padding-left: 25px;
    padding-top: 5px;
    font-size: 15px;

}

ul.sub-menu li:hover{
    color: #ffffff;
    display: block;

}

.navClass li:hover .sub-menu{
    opacity: 1;

}

</code>```

The sub-menu items need to drop down from the parent item. In this case, the "Things to Do" item.

答:
There is a simple error in your HTML code.

You have closed the
 tag before.

Use This:

```<code>   <nav class='navClass'>
          <ul>
             <li>Home</li>
             <li>Things To Do
               <ul class="sub-menu">
                  <li>Shopping</li>
                  <li>Attractions</li>
                  <li>Outdoor Fun</li>
               </ul>
               </li>
             <li>Places To Stay</li>
             <li>Where to Eat</li>
             <li>Contests</li>
             <li>History</li>
             <li>Events</li>
          </ul>
    </nav>
</code>```

Title: css submenu not appearing

Body:
CSS submenu no longer appearing

This was working and I did something to it, I dont know if it is a code problem or a css problem. Forgive me if the post is not formatted correctly,
this is my first time posting at Stackoverflow.

html

Home

Things To Do

Shopping

Attractions

Outdoor Fun

Places To Stay

Where to Eat

Contests

History

Events

css

    .navClass > ul{
    background-color: #e56109;
    color:#ffffff;
    margin-top: 0px;
    font-size: 20px;
    font-family: Arial;
}

.navClass > ul li{
    list-style-type: none;
    display: inline-block;
    padding-top: 10px;
    padding-bottom: 10px;
    padding-left: 25px;
    padding-right: 25px;
    position: relative;

}

.navClass > ul li:hover{
    background-color: #212121;
    position: relative;

}

ul.sub-menu{
    position: absolute;
    background-color: #e56109;
    list-style-type: none;
    width: 200px;
    margin-left: -25px;
    padding-bottom: 0px;
    margin-top: 10px;
    opacity: 0;

}

ul.sub-menu li{
    padding-left: 25px;
    padding-top: 5px;
    font-size: 15px;

}

ul.sub-menu li:hover{
    color: #ffffff;
    display: block;

}

.navClass li:hover .sub-menu{
    opacity: 1;

}

The sub-menu items need to drop down from the parent item. In this case, the "Things to Do" item.

Body:
There is a simple error in your HTML code.

You have closed the <li> tag before.

Use This:

   <nav class='navClass'>
          <ul>
             <li>Home</li>
             <li>Things To Do
               <ul class="sub-menu">
                  <li>Shopping</li>
                  <li>Attractions</li>
                  <li>Outdoor Fun</li>
               </ul>
               </li>
             <li>Places To Stay</li>
             <li>Where to Eat</li>
             <li>Contests</li>
             <li>History</li>
             <li>Events</li>
          </ul>
    </nav>


问:
Use of undefined constant String - assumed 'String' when calling a class name from variable
After countless wasted hours, I come for help, I can't for the life of me figure what the issue is. assistance in resolving this will be greatly appreciated. Can anyone identify what is going on or what i have failed to do.

The code in question resides in two seperate files file one has Data\Request class that is autoloaded. the error is spat out on line 302, which is a call to the same namespace, seperate file and seperate class, being Data\ClientKey. All of the classes that use this line are all outputting the same error.

the error:
Notice: Use of undefined constant String - assumed 'String' in data/request.data.php on line 302

The code is working and the class in question is being called as the application is working as intended, but am getting this error. I have declared strict_types=1 even removing it does not make the error go away.

the code where the class name variable is set

$NamespaceDataKeys = array('ServerKey', 'ClientKey', 'UserInfo', 'MachineInfo', 'Data');

                    if( in_array($key, $NamespaceDataKeys) ) {

                        $NamespaceKey = "Data\\$key";

                    }else{
                        $NamespaceKey = $key;
                    }

```

<p>line 302:</p>

<pre class="lang-php prettyprint-override"><code>$sub = new $NamespaceKey(json_encode($value));
</code>```

I've tried adding double quotes around $value, when declaring $NamespaceKey setting it to type String nothing has removed the error.

don't know if relevant, but just in case all the items in the array $NamespaceDataKeys are variables in class Request and are also classes in the Data namespace

edit to add the classes in question

Request.data.php

<?php declare(strict_types=1);

Namespace Data;

class Request implements \JsonSerializable {

    Private $Action;

    Private $Direction;

    Private $ServerKey;

    Private $ClientKey;

    public function __construct($json = false) {
        if( DEBUG ) echo '[DEBUG] Class: ' . __CLASS__ . ' Method: ' . __METHOD__ . "\r\n";

        if( $json) {

            $this -> set($json);

            //Log the request to the database
        }

    }

// code removed to keep size small

    private function set( string $JSONData) {

        $data = json_decode($JSONData, true);

        foreach( $data AS $key => $value ) {

            if( DEBUG ) echo "Key: [$key] ";

            if( property_exists(__CLASS__,$key) ) {

                if( is_array($value) ) {
                    if( DEBUG ) echo "Value: [Array]\r\n";

                    $NamespaceDataKeys = array('ServerKey', 'ClientKey', 'UserInfo', 'MachineInfo', 'Data');

                    if( in_array($key, $NamespaceDataKeys) ) {

                        $NamespaceKey = "\\Data\\$key";

                    }else{
                        $NamespaceKey = $key;
                    }

                    if(count(array_filter(array_keys($value), 'is_string')) > 0 && $key <> "Data") { // assositaive array

                        $sub = new $NamespaceKey(json_encode($value));
                        $this -> {$key} = $sub;

                    }else{ // numrical array

                        if($this -> ItemType <= 4 ) $key = "Node";
                        $NamespaceKey = "Data\\$key";
                        for($i=0;$i<=(count($value)-1); $i++) {

                            $sub = $NamespaceKey(json_encode($value[$i]));

                            if($key == 'Node' ) {
                                $this -> Data = (object) $sub;

                            }else{
                                $this -> {$key}[$i] = (object) $sub;

                            }
                        }

                    }

    Public Function ClientKey( $Value = "" ) : UUID {
      if( DEBUG ) echo '[DEBUG] Method: ' . __METHOD__ . "\r\n";

        if( $Value != "" ) {
            $UUID = New UUID();
            $UUID -> Value = $Value;
            $this -> ClientKey = (Object) $UUID;

            #Return (Object) $Value;

        }else{
            if( $this -> ClientKey != Null ) {
                Return (Object) $this -> ClientKey;
            }
        }

        Return new ClientKey;
    } #EoF ClientKey

?>
```

<p>ClientKey.data.php</p>

<pre class="lang-php prettyprint-override"><code><?php declare(strict_types=1);
Namespace Data;

class ClientKey implements \JsonSerializable {

    public $Value = String;

    public function __construct( String $json = 'false') {
        $this->Value = Null;
        if( DEBUG ) echo '[DEBUG] Class: ' . __CLASS__ . ' Method: ' . __METHOD__ . "\r\n";
        if( $json <> 'false' ) { $this -> set($json); }

    private function set($JSONData) {
      if( DEBUG ) echo '[DEBUG] Method: ' . __METHOD__ . "\r\n";
        $data = json_decode($JSONData, true);

        foreach( $data AS $key => $value ) {

            if( property_exists(__CLASS__,$key) ) {

                if( DEBUG ) echo "Key: [$key] ";

                if( is_array($value) ) {
                    if( DEBUG ) echo "Value: [Array]\r\n";

                    $sub = new $key(json_encode($value));
                    $this -> {$key} = (object) $sub;

                }else{
                    if( DEBUG ) echo "Value: [$value]\r\n";
                    $this -> {$key} = $value;

                }
            }
        }
    } # EoF Set

    Public Function jsonSerialize($pretty = false) {

        if( $pretty ) {
            return json_encode(get_object_vars($this), JSON_PRETTY_PRINT);
        }else{
            return json_encode(get_object_vars($this));
        }
    }

} # EoF Class

?>
</code>```

App debug: This debug output is from the app itself.
It shows the following:

Request.Data.phpwas passed JSON string with a key of ClientKey

autoloaded ClientKey.Data.php,

E_NOTICE warning output

ran method Data\ClientKey::__Construct

set the Property, Value of class Data\ClientKey::Value _

the simple of what I'm trying to achieve without errors, is to serialize/deserialize JSON data to a cclass. which I'm acheiving but with E_NOTICE

```<code>Key: [ClientKey] Value: [Array]
[DEBUG] Autoload Method: {closure}-Class Name: Data\ClientKey
[DEBUG] Autoload path: data/ClientKey.data.php
<br />
<b>Warning</b>:  Use of undefined constant String - assumed 'String' (this will throw an Error in a future version of PHP) in <b>/var/www/html/data/Request.data.php</b> on line <b>302</b><br />
[DEBUG] Class: Data\ClientKey Method: Data\ClientKey::__construct
[DEBUG] Method: Data\ClientKey::set
Key: [Value] Value: [D49AD5645F8310896545C0D3354ECC0A]

</code>```

application flow: JSON data deserialized to class Request.data.php. Client.Data.php is a sub type to Request.data.php the stage that this app is within is the "deSerialize" phase

答: solution found, the property $Value within Data\ClientKey was being incorrectly set with String, removed this and the error has gone away.

Body:
After countless wasted hours, I come for help, I can't for the life of me figure what the issue is. assistance in resolving this will be greatly appreciated. Can anyone identify what is going on or what i have failed to do.

The code in question resides in two seperate files file one has Data\Request class that is autoloaded. the error is spat out on line 302, which is a call to the same namespace, seperate file and seperate class, being Data\ClientKey. All of the classes that use this line are all outputting the same error.

the error:
Notice: Use of undefined constant String - assumed 'String' in data/request.data.php on line 302

The code is working and the class in question is being called as the application is working as intended, but am getting this error. I have declared strict_types=1 even removing it does not make the error go away.

the code where the class name variable is set

$NamespaceDataKeys = array('ServerKey', 'ClientKey', 'UserInfo', 'MachineInfo', 'Data');

                    if( in_array($key, $NamespaceDataKeys) ) {

                        $NamespaceKey = "Data\\$key";

                    }else{
                        $NamespaceKey = $key;
                    }

line 302:

$sub = new $NamespaceKey(json_encode($value));

I've tried adding double quotes around $value, when declaring $NamespaceKey setting it to type String nothing has removed the error.

don't know if relevant, but just in case all the items in the array $NamespaceDataKeys are variables in class Request and are also classes in the Data namespace

edit to add the classes in question

Request.data.php

<?php declare(strict_types=1);

Namespace Data;

class Request implements \JsonSerializable {

    Private $Action;

    Private $Direction;

    Private $ServerKey;

    Private $ClientKey;

    public function __construct($json = false) {
        if( DEBUG ) echo '[DEBUG] Class: ' . __CLASS__ . ' Method: ' . __METHOD__ . "\r\n";

        if( $json) {

            $this -> set($json);

            //Log the request to the database
        }

    }

// code removed to keep size small

    private function set( string $JSONData) {

        $data = json_decode($JSONData, true);

        foreach( $data AS $key => $value ) {

            if( DEBUG ) echo "Key: [$key] ";

            if( property_exists(__CLASS__,$key) ) {

                if( is_array($value) ) {
                    if( DEBUG ) echo "Value: [Array]\r\n";

                    $NamespaceDataKeys = array('ServerKey', 'ClientKey', 'UserInfo', 'MachineInfo', 'Data');

                    if( in_array($key, $NamespaceDataKeys) ) {

                        $NamespaceKey = "\\Data\\$key";

                    }else{
                        $NamespaceKey = $key;
                    }

                    if(count(array_filter(array_keys($value), 'is_string')) > 0 && $key <> "Data") { // assositaive array

                        $sub = new $NamespaceKey(json_encode($value));
                        $this -> {$key} = $sub;

                    }else{ // numrical array

                        if($this -> ItemType <= 4 ) $key = "Node";
                        $NamespaceKey = "Data\\$key";
                        for($i=0;$i<=(count($value)-1); $i++) {

                            $sub = $NamespaceKey(json_encode($value[$i]));

                            if($key == 'Node' ) {
                                $this -> Data = (object) $sub;

                            }else{
                                $this -> {$key}[$i] = (object) $sub;

                            }
                        }

                    }

    Public Function ClientKey( $Value = "" ) : UUID {
      if( DEBUG ) echo '[DEBUG] Method: ' . __METHOD__ . "\r\n";

        if( $Value != "" ) {
            $UUID = New UUID();
            $UUID -> Value = $Value;
            $this -> ClientKey = (Object) $UUID;

            #Return (Object) $Value;

        }else{
            if( $this -> ClientKey != Null ) {
                Return (Object) $this -> ClientKey;
            }
        }

        Return new ClientKey;
    } #EoF ClientKey

?>

ClientKey.data.php

<?php declare(strict_types=1);
Namespace Data;

class ClientKey implements \JsonSerializable {

    public $Value = String;

    public function __construct( String $json = 'false') {
        $this->Value = Null;
        if( DEBUG ) echo '[DEBUG] Class: ' . __CLASS__ . ' Method: ' . __METHOD__ . "\r\n";
        if( $json <> 'false' ) { $this -> set($json); }

    private function set($JSONData) {
      if( DEBUG ) echo '[DEBUG] Method: ' . __METHOD__ . "\r\n";
        $data = json_decode($JSONData, true);

        foreach( $data AS $key => $value ) {

            if( property_exists(__CLASS__,$key) ) {

                if( DEBUG ) echo "Key: [$key] ";

                if( is_array($value) ) {
                    if( DEBUG ) echo "Value: [Array]\r\n";

                    $sub = new $key(json_encode($value));
                    $this -> {$key} = (object) $sub;

                }else{
                    if( DEBUG ) echo "Value: [$value]\r\n";
                    $this -> {$key} = $value;

                }
            }
        }
    } # EoF Set

    Public Function jsonSerialize($pretty = false) {

        if( $pretty ) {
            return json_encode(get_object_vars($this), JSON_PRETTY_PRINT);
        }else{
            return json_encode(get_object_vars($this));
        }
    }

} # EoF Class

?>

App debug: This debug output is from the app itself.
It shows the following:

Request.Data.phpwas passed JSON string with a key of ClientKey

autoloaded ClientKey.Data.php,

E_NOTICE warning output

ran method Data\ClientKey::__Construct

set the Property, Value of class Data\ClientKey::Value _

the simple of what I'm trying to achieve without errors, is to serialize/deserialize JSON data to a cclass. which I'm acheiving but with E_NOTICE

Key: [ClientKey] Value: [Array]
[DEBUG] Autoload Method: {closure}-Class Name: Data\ClientKey
[DEBUG] Autoload path: data/ClientKey.data.php

Warning:  Use of undefined constant String - assumed 'String' (this will throw an Error in a future version of PHP) in /var/www/html/data/Request.data.php on line 302

[DEBUG] Class: Data\ClientKey Method: Data\ClientKey::__construct
[DEBUG] Method: Data\ClientKey::set
Key: [Value] Value: [D49AD5645F8310896545C0D3354ECC0A]

application flow: JSON data deserialized to class Request.data.php. Client.Data.php is a sub type to Request.data.php the stage that this app is within is the "deSerialize" phase


问:
How do I pass parameters from a component into an event listener in React?
In my App.jsx I have an event handler and a returned component:

```<code>handleSell = (price) => (event) => {
        console.log(price);

}
render() {
    return(
    <SellCatalogLine
        key = {item.ORDERID}
        price = {item.PRICE}
        title = {item.TITLE}
        handleSell = {this.handleSell}/>
    )}
</code>```

My component looks like this:

```<code>
function SellCatalogLine(props){

    const currentprice = props.price
    const cheaperprice = currentprice - 100;

    return (
        <div>
        <h3>{props.title}</h3>
        <p>Lowest Price: ${currentprice}</p>
        <button type="submit" onClick = {() => props.handleSell(currentprice)}>List item at ${currentprice} </button>
        <button type="submit" onClick = {() => props.handleSell(cheaperprice)}>List item at ${cheaperprice} </button>
        </div>
    )
};
</code>```

I'm trying to make it so that the console will log cheaperprice or currentprice depending on which button I click. How do I do that?

答:
Since handleSell method when called returns another function so you need to call props.handleSell(currentprice) in SellCatalogLine component.

i.e.

```<code>handleSell = (price) => (event) => {
   console.log(price);
}
</code>```

And use it as

```<code><button type="submit" onClick = {props.handleSell(currentprice)}>List item at ${currentprice} </button>
</code>```

If handleSell method did not return a function then you could use an anonymous function. In which you could call props.handleSell(currentprice)

i.e

```<code>handleSell = (event, price) => {
    console.log(price);
}
</code>```

And use it as

```<code><button type="submit" onClick = {(e) => props.handleSell(e, currentprice)}>List item at ${currentprice} </button>
</code>```

Body:
In my App.jsx I have an event handler and a returned component:

handleSell = (price) => (event) => {
        console.log(price);

}
render() {
    return(
    <SellCatalogLine
        key = {item.ORDERID}
        price = {item.PRICE}
        title = {item.TITLE}
        handleSell = {this.handleSell}/>
    )}

My component looks like this:

function SellCatalogLine(props){

    const currentprice = props.price
    const cheaperprice = currentprice - 100;

    return (

{props.title}

Lowest Price: ${currentprice}

        <button type="submit" onClick = {() => props.handleSell(currentprice)}>List item at ${currentprice} </button>
        <button type="submit" onClick = {() => props.handleSell(cheaperprice)}>List item at ${cheaperprice} </button>

    )
};

I'm trying to make it so that the console will log cheaperprice or currentprice depending on which button I click. How do I do that?

Body:
Since handleSell method when called returns another function so you need to call props.handleSell(currentprice) in SellCatalogLine component.

i.e.

handleSell = (price) => (event) => {
   console.log(price);
}

And use it as

<button type="submit" onClick = {props.handleSell(currentprice)}>List item at ${currentprice} </button>

If handleSell method did not return a function then you could use an anonymous function. In which you could call props.handleSell(currentprice)

i.e

handleSell = (event, price) => {
    console.log(price);
}

And use it as

<button type="submit" onClick = {(e) => props.handleSell(e, currentprice)}>List item at ${currentprice} </button>


问:
Pass variable as condition for if statement in php
I have dynamic condition for if statement that stored as a variable. How to make if statement worked using that variable as as its condition?

I have tried using eval function but it's still didn't work

Here is my code:

```<code>$a = 2;
$b = 2;
$c = '$a==$b';
$d = eval('return $c;');

if($d === true){
    echo 'yes';
}
else{
    echo 'no';
}
</code>```

It should be return 'yes', but my current code return 'no'.

答:
After some experiments, I have found this solution. So what I need to do is put the eval function inside if condition:</p>

```<code><?php
$a = 2;
$b = 2;
$c = '$a==$b';

if(eval("return $c;")){ //must using double quotes
    echo 'yes';
}
else{
    echo 'no';
}
</code>```

Body:
I have dynamic condition for if statement that stored as a variable. How to make if statement worked using that variable as as its condition?

I have tried using eval function but it's still didn't work

Here is my code:

$a = 2;
$b = 2;
$c = '$a==$b';
$d = eval('return $c;');

if($d === true){
    echo 'yes';
}
else{
    echo 'no';
}

It should be return 'yes', but my current code return 'no'.

Body:
After some experiments, I have found this solution. So what I need to do is put the eval function inside if condition:

<?php
$a = 2;
$b = 2;
$c = '$a==$b';

if(eval("return $c;")){ //must using double quotes
    echo 'yes';
}
else{
    echo 'no';
}


问:
How to delete duplicate emails from a database having over 100k records?
I have a database of around 126K entries, It has many entries having duplicate emails. I want to delete all the entries with duplicate ones and just the keep the one that was created earliest.

I tried using the following query but it takes forever and maxes out my server bandwidth.

Can anyone help?

```<code>DELETE n1 FROM table n1, table n2 WHERE n1.ID > n2.ID AND n1.email = n2.email
</code>```

Database Specifications

PhpMyAdmin Version information: 3.5.3

Server: Localhost via UNIX socket

Software: MySQL

Software version: 5.0.67-community - MySQL Community Edition (GPL)

Protocol version: 10

Server charset: UTF-8 Unicode (utf8)

答:
Maybe you can create a temporary table with unique emails and after delete all the email whose are more than once in the database .

```<code>CREATE TEMPORARY TABLE tab_temp
SELECT * FROM table GROUP BY email;
</code>```

Then

```<code>DELETE FROM table
WHERE id NOT IN ( SELECT id FROM tab_temp );
</code>```

With that you can delete those that are repeated

Body:
I have a database of around 126K entries, It has many entries having duplicate emails. I want to delete all the entries with duplicate ones and just the keep the one that was created earliest.

I tried using the following query but it takes forever and maxes out my server bandwidth.

Can anyone help?

DELETE n1 FROM table n1, table n2 WHERE n1.ID > n2.ID AND n1.email = n2.email

Database Specifications

PhpMyAdmin Version information: 3.5.3

Server: Localhost via UNIX socket

Software: MySQL

Software version: 5.0.67-community - MySQL Community Edition (GPL)

Protocol version: 10

Server charset: UTF-8 Unicode (utf8)

Body:
Maybe you can create a temporary table with unique emails and after delete all the email whose are more than once in the database .

CREATE TEMPORARY TABLE tab_temp
SELECT * FROM table GROUP BY email;

Then

DELETE FROM table
WHERE id NOT IN ( SELECT id FROM tab_temp );

With that you can delete those that are repeated


答:
You just need to use double quotes instead of single quote</p>

```<code><?php
$a = 2;
$b = 2;
$c = "$a==$b";
$d = eval("return $c;");

if($d === true){
    echo 'yes';
}
else{
    echo 'no';
}
?>
</code>```

Title: Pass variable as condition for if statement in php

Body:
You just need to use double quotes instead of single quote

<?php
$a = 2;
$b = 2;
$c = "$a==$b";
$d = eval("return $c;");

if($d === true){
    echo 'yes';
}
else{
    echo 'no';
}
?>


问:
cumulative frequency given certain conditions in R
I am new at R and I do not really know how to count cumulative number of occurrences of a row if it is the same ID but different date.Also, if the first date appears more than once, it should not count in the first attempt.Look at the rows 2 and 3, that is why the column I am trying to build is called "count" and equals to zero. "count" represents the times that the id has appeared but it follows the next two rules:

1.If it is the first appearence of the Id ever, it assigns zero. For example, for Id 1 despite there are two different registers for the very first date of this Id, "count" equals zero.

2.For the next Id 1 appereance (row 3 of Id1 ) it has a different date, that is why "count" equals 2. Because the 01/01/2018 Id1 appeared twice.

This is the DT and the result that I am looking for is in the "count" column:

答:
An option with data.table where we convert the 'data.frame' to 'data.table' (setDT(df)), grouped by 'id', create the 'count' as the sum of the logical vector (date == first(date)), then change the first row of 'count' for each 'id' to 0

```<code>library(data.table)
setDT(df)[,  count := sum(date == first(date)), id]
df[df[, .I[1], id]$V1, count := 0][]
#   id       date count
#1:  1 01/01/2018     0
#2:  1 01/01/2018     2
#3:  1 02/01/2018     2
#4:  2 03/02/2018     0
#5:  2 04/04/2018     1
</code>```

data

```<code>df <- data.frame(id = c(1, 1, 1, 2, 2), date = c("01/01/2018", "01/01/2018",
 "02/01/2018", "03/02/2018", "04/04/2018"), stringsAsFactors = FALSE)
</code>```

Body:
An option with data.table where we convert the 'data.frame' to 'data.table' (setDT(df)), grouped by 'id', create the 'count' as the sum of the logical vector (date == first(date)), then change the first row of 'count' for each 'id' to 0

library(data.table)
setDT(df)[,  count := sum(date == first(date)), id]
df[df[, .I[1], id]$V1, count := 0][]
#   id       date count
#1:  1 01/01/2018     0
#2:  1 01/01/2018     2
#3:  1 02/01/2018     2
#4:  2 03/02/2018     0
#5:  2 04/04/2018     1

data

df <- data.frame(id = c(1, 1, 1, 2, 2), date = c("01/01/2018", "01/01/2018",
 "02/01/2018", "03/02/2018", "04/04/2018"), stringsAsFactors = FALSE)


问:
Jquery DataTable column Sum
I just refer this link to get idea how to get the column total in jquery data tables. But I have done half of my project. I do not have any definition in html page. all include in Jquery side.

In HTML

```<code> <table id="tblCollection" class="display" cellspacing="0" width="100%">
                                        </table>
</code>```

Defined data table like below in Jquery.

```<code>   tblColectionData = $("#tblCollection").DataTable({
        "ordering": true,
        columns: [
            { title: 'OrderId', data: 'OrderId' },
            { title: 'Ordered Date', data: 'OrderPlaceDateTime' },
            { title: 'Customer Name', data: 'CustomerName' },
            { title: 'Restaurant Name', data: 'RestaurantName' },
            { title: 'Order Total', data: 'OrderTotalAmount' }
        ],
    });
</code>```

How to add footerCallback part in my case? The example in web link is defined the total in tfoot. In my case it is not. How to do this?

EDIT 1

Fill data to datatable

```<code>$.ajax({
    type: 'post',
    url: serverLocation + "/api/dashboard/getOrderData",
    dataType: 'json',
    data: JSON.stringify(reqJson),
    contentType: "application/json; charset=UTF-8",
    success: function (response) {
        tblColectionData.clear().draw();
        tblColectionData.rows.add(response).draw();
    },
    error: function (textStatus, errorThrown) {
        console.log('Err');
    }
});
</code>```

答:
The easiest way to get sum of any field do this:

Add the 'footerCallback' function into DataTable() as follow and get 'data' parameter.

Example:

```<code>$("#example_table").DataTable({
     "footerCallback": function (row, data, start, end, display) {
                //Get data here
                console.log(data);
                //Do whatever you want. Example:
                var totalAmount = 0;
                for (var i = 0; i < data.length; i++) {
                    totalAmount += parseFloat(data[i][4]);
                }
                console.log(totalAmount);
       }
})
</code>```

Be careful about the position of data index you want.

Enjoy it!!!

Title: Jquery DataTable column Sum

Body:
I just refer this link to get idea how to get the column total in jquery data tables. But I have done half of my project. I do not have any definition in html page. all include in Jquery side.

In HTML

Defined data table like below in Jquery.

   tblColectionData = $("#tblCollection").DataTable({
        "ordering": true,
        columns: [
            { title: 'OrderId', data: 'OrderId' },
            { title: 'Ordered Date', data: 'OrderPlaceDateTime' },
            { title: 'Customer Name', data: 'CustomerName' },
            { title: 'Restaurant Name', data: 'RestaurantName' },
            { title: 'Order Total', data: 'OrderTotalAmount' }
        ],
    });

How to add footerCallback part in my case? The example in web link is defined the total in tfoot. In my case it is not. How to do this?

EDIT 1

Fill data to datatable

$.ajax({
    type: 'post',
    url: serverLocation + "/api/dashboard/getOrderData",
    dataType: 'json',
    data: JSON.stringify(reqJson),
    contentType: "application/json; charset=UTF-8",
    success: function (response) {
        tblColectionData.clear().draw();
        tblColectionData.rows.add(response).draw();
    },
    error: function (textStatus, errorThrown) {
        console.log('Err');
    }
});

Body:
The easiest way to get sum of any field do this:

Add the 'footerCallback' function into DataTable() as follow and get 'data' parameter.

Example:

$("#example_table").DataTable({
     "footerCallback": function (row, data, start, end, display) {
                //Get data here
                console.log(data);
                //Do whatever you want. Example:
                var totalAmount = 0;
                for (var i = 0; i < data.length; i++) {
                    totalAmount += parseFloat(data[i][4]);
                }
                console.log(totalAmount);
       }
})

Be careful about the position of data index you want.

Enjoy it!!!


问:
Make using statement usable for multiple disposable objects
I have a bunch of text files in a folder, and all of them should have identical headers. In other words the first 100 lines of all files should be identical. So I wrote a function to check this condition:

```<code>private static bool CheckHeaders(string folderPath, int headersCount)
{
    var enumerators = Directory.EnumerateFiles(folderPath)
        .Select(f => File.ReadLines(f).GetEnumerator())
        .ToArray();
    //using (enumerators)
    //{
        for (int i = 0; i < headersCount; i++)
        {
            foreach (var e in enumerators)
            {
                if (!e.MoveNext()) return false;
            }
            var values = enumerators.Select(e => e.Current);
            if (values.Distinct().Count() > 1) return false;
        }
        return true;
    //}
}
</code>```

The reason I am using enumerators is memory efficiency. Instead of loading all file contents in memory I enumerate the files concurrently line-by-line until a mismatch is found, or all headers have been examined.

My problem is evident by the commented lines of code. I would like to utilize a using block to safely dispose all the enumerators, but unfortunately using (enumerators) doesn't compile. Apparently using can handle only a single disposable object. I know that I can dispose the enumerators manually, by wrapping the whole thing in a try-finally block, and running the disposing logic in a loop inside finally, but is seems awkward. Is there any mechanism I could employ to make the using statement a viable option in this case?

Update

I just realized that my function has a serious flaw. The construction of the enumerators is not robust. A locked file can cause an exception, while some enumerators have already been created. These enumerators will not be disposed. This is something I want to fix. I am thinking about something like this:

```<code>var enumerators = Directory.EnumerateFiles(folderPath)
    .ToDisposables(f => File.ReadLines(f).GetEnumerator());
</code>```

The extension method ToDisposables should ensure that in case of an exception no disposables are left undisposed.

答:
I'm going to suggest an approach that uses recursive calls to Zip to allow parallel enumeration of a normal IEnumerable<string> without the need to resort to using IEnumerator<string>.

```<code>bool Zipper(IEnumerable<IEnumerable<string>> sources, int take)
{
    IEnumerable<string> ZipperImpl(IEnumerable<IEnumerable<string>> ss)
        => (!ss.Skip(1).Any())
            ? ss.First().Take(take)
            : ss.First().Take(take).Zip(
                ZipperImpl(ss.Skip(1)),
                (x, y) => (x == null || y == null || x != y) ? null : x);

    var matching_lines = ZipperImpl(sources).TakeWhile(x => x != null).ToArray();
    return matching_lines.Length == take;
}
</code>```

Now build up your enumerables:

```<code>IEnumerable<string>[] enumerables =
    Directory
        .EnumerateFiles(folderPath)
        .Select(f => File.ReadLines(f))
        .ToArray();
</code>```

Now it's simple to call:

```<code>bool headers_match = Zipper(enumerables, 100);
</code>```

Here's a trace of running this code against three files with more than 4 lines:

```
Ben Petering at 5:28 PM ACST
Ben Petering at 5:28 PM ACST
Ben Petering at 5:28 PM ACST
  From a call 2019-05-23, James mentioned he’d like the ability to edit the current shipping price rules (eg in shipping_rules.xml) via the admin.
  From a call 2019-05-23, James mentioned he’d like the ability to edit the current shipping price rules (eg in shipping_rules.xml) via the admin.
  From a call 2019-05-23, James mentioned he’d like the ability to edit the current shipping price rules (eg in shipping_rules.xml) via the admin.
He also mentioned he’d like to be able to set different shipping price rules for a given time window, e.g. Jan 1 to Jan 30.
He also mentioned he’d like to be able to set different shipping price rules for a given time window, e.g. Jan 1 to Jan 30.
He also mentioned he’d like to be able to set different shipping price rules for a given time window, e.g. Jan 1 to Jan 30.
These storyishes should be considered when choosing the appropriate module to use.
These storyishes should be considered when choosing the appropriate module to use.X
These storyishes should be considered when choosing the appropriate module to use.
```

Note that the enumerations stop when they encountered a mismatch header in the 4th line on the second file. All enumerations then stopped.

Body:
I have a bunch of text files in a folder, and all of them should have identical headers. In other words the first 100 lines of all files should be identical. So I wrote a function to check this condition:

private static bool CheckHeaders(string folderPath, int headersCount)
{
    var enumerators = Directory.EnumerateFiles(folderPath)
        .Select(f => File.ReadLines(f).GetEnumerator())
        .ToArray();
    //using (enumerators)
    //{
        for (int i = 0; i < headersCount; i++)
        {
            foreach (var e in enumerators)
            {
                if (!e.MoveNext()) return false;
            }
            var values = enumerators.Select(e => e.Current);
            if (values.Distinct().Count() > 1) return false;
        }
        return true;
    //}
}

The reason I am using enumerators is memory efficiency. Instead of loading all file contents in memory I enumerate the files concurrently line-by-line until a mismatch is found, or all headers have been examined.

My problem is evident by the commented lines of code. I would like to utilize a using block to safely dispose all the enumerators, but unfortunately using (enumerators) doesn't compile. Apparently using can handle only a single disposable object. I know that I can dispose the enumerators manually, by wrapping the whole thing in a try-finally block, and running the disposing logic in a loop inside finally, but is seems awkward. Is there any mechanism I could employ to make the using statement a viable option in this case?

Update

I just realized that my function has a serious flaw. The construction of the enumerators is not robust. A locked file can cause an exception, while some enumerators have already been created. These enumerators will not be disposed. This is something I want to fix. I am thinking about something like this:

var enumerators = Directory.EnumerateFiles(folderPath)
    .ToDisposables(f => File.ReadLines(f).GetEnumerator());

The extension method ToDisposables should ensure that in case of an exception no disposables are left undisposed.

Body:
I'm going to suggest an approach that uses recursive calls to Zip to allow parallel enumeration of a normal IEnumerable<string> without the need to resort to using IEnumerator<string>.

bool Zipper(IEnumerable<IEnumerable<string>> sources, int take)
{
    IEnumerable<string> ZipperImpl(IEnumerable<IEnumerable<string>> ss)
        => (!ss.Skip(1).Any())
            ? ss.First().Take(take)
            : ss.First().Take(take).Zip(
                ZipperImpl(ss.Skip(1)),
                (x, y) => (x == null || y == null || x != y) ? null : x);

    var matching_lines = ZipperImpl(sources).TakeWhile(x => x != null).ToArray();
    return matching_lines.Length == take;
}

Now build up your enumerables:

IEnumerable<string>[] enumerables =
    Directory
        .EnumerateFiles(folderPath)
        .Select(f => File.ReadLines(f))
        .ToArray();

Now it's simple to call:

bool headers_match = Zipper(enumerables, 100);

Here's a trace of running this code against three files with more than 4 lines:

Ben Petering at 5:28 PM ACST
Ben Petering at 5:28 PM ACST
Ben Petering at 5:28 PM ACST
  From a call 2019-05-23, James mentioned he’d like the ability to edit the current shipping price rules (eg in shipping_rules.xml) via the admin.
  From a call 2019-05-23, James mentioned he’d like the ability to edit the current shipping price rules (eg in shipping_rules.xml) via the admin.
  From a call 2019-05-23, James mentioned he’d like the ability to edit the current shipping price rules (eg in shipping_rules.xml) via the admin.
He also mentioned he’d like to be able to set different shipping price rules for a given time window, e.g. Jan 1 to Jan 30.
He also mentioned he’d like to be able to set different shipping price rules for a given time window, e.g. Jan 1 to Jan 30.
He also mentioned he’d like to be able to set different shipping price rules for a given time window, e.g. Jan 1 to Jan 30.
These storyishes should be considered when choosing the appropriate module to use.
These storyishes should be considered when choosing the appropriate module to use.X
These storyishes should be considered when choosing the appropriate module to use.

Note that the enumerations stop when they encountered a mismatch header in the 4th line on the second file. All enumerations then stopped.


问:
code for how to perform calling and cancel the calling in iphone
I am new to developing iPhone applications.

I am looking for an example on calling phone numbers, specifically starting a call and ending one.

Is this possible ? If so, how would one accomplish this ?

答:
```<code> [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:374347347"]];
</code>```

I don't think Apple allows you to cancel calls from within your app.

Body:
 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:374347347"]];

I don't think Apple allows you to cancel calls from within your app.


问:
Generate random timeseries data with dates
I am trying to generate random data(integers) with dates so that I can practice pandas data analytics commands on it and plot time series graphs.

```<code>             temp     depth   acceleration
2019-01-1 -0.218062 -1.215978 -1.674843
2019-02-1 -0.465085 -0.188715  0.241956
2019-03-1 -1.464794 -1.354594  0.635196
2019-04-1  0.103813  0.194349 -0.450041
2019-05-1  0.437921  0.073829  1.346550

</code>```

Is there any random dataframe generator that can generate something like this with each date having a gap of one month?

Body:
I am trying to generate random data(integers) with dates so that I can practice pandas data analytics commands on it and plot time series graphs.

             temp     depth   acceleration
2019-01-1 -0.218062 -1.215978 -1.674843
2019-02-1 -0.465085 -0.188715  0.241956
2019-03-1 -1.464794 -1.354594  0.635196
2019-04-1  0.103813  0.194349 -0.450041
2019-05-1  0.437921  0.073829  1.346550

Is there any random dataframe generator that can generate something like this with each date having a gap of one month?

Body:
Use numpy.random.rand or numpy.random.randint functions with DataFrame constructor:

np.random.seed(2019)
N = 10
rng = pd.date_range('2019-01-01', freq='MS', periods=N)
df = pd.DataFrame(np.random.rand(N, 3), columns=['temp','depth','acceleration'], index=rng)

print (df)
                temp     depth  acceleration
2019-01-01  0.903482  0.393081      0.623970
2019-02-01  0.637877  0.880499      0.299172
2019-03-01  0.702198  0.903206      0.881382
2019-04-01  0.405750  0.452447      0.267070
2019-05-01  0.162865  0.889215      0.148476
2019-06-01  0.984723  0.032361      0.515351
2019-07-01  0.201129  0.886011      0.513620
2019-08-01  0.578302  0.299283      0.837197
2019-09-01  0.526650  0.104844      0.278129
2019-10-01  0.046595  0.509076      0.472426

If need integers:

np.random.seed(2019)
N = 10
rng = pd.date_range('2019-01-01', freq='MS', periods=N)
df = pd.DataFrame(np.random.randint(20, size=(10, 3)),
                  columns=['temp','depth','acceleration'],
                  index=rng)

print (df)
            temp  depth  acceleration
2019-01-01     8     18             5
2019-02-01    15     12            10
2019-03-01    16     16             7
2019-04-01     5     19            12
2019-05-01    16     18             5
2019-06-01    16     15             1
2019-07-01    14     12            10
2019-08-01     0     11            18
2019-09-01    15     19             1
2019-10-01     3     16            18


答:
You can either use pandas.util.testing

```<code>import pandas.util.testing as testing
import numpy as np
np.random.seed(1)

testing.N, testing.K = 5, 3  # Setting the rows and columns of the desired data

print testing.makeTimeDataFrame(freq='MS')
>>>
                   A         B         C
2000-01-01 -0.488392  0.429949 -0.723245
2000-02-01  1.247192 -0.513568 -0.512677
2000-03-01  0.293828  0.284909  1.190453
2000-04-01 -0.326079 -1.274735 -0.008266
2000-05-01 -0.001980  0.745803  1.519243
</code>```

Or, if you need more control over the random values being generated, you can use something like

```<code>import numpy as np
import pandas as pd
np.random.seed(1)

rows,cols = 5,3
data = np.random.rand(rows,cols) # You can use other random functions to generate values with constraints
tidx = pd.date_range('2019-01-01', periods=rows, freq='MS') # freq='MS'set the frequency of date in months and start from day 1. You can use 'T' for minutes and so on
data_frame = pd.DataFrame(data, columns=['a','b','c'], index=tidx)
print data_frame
>>>
                   a         b         c
2019-01-01  0.992856  0.217750  0.538663
2019-02-01  0.189226  0.847022  0.156730
2019-03-01  0.572417  0.722094  0.868219
2019-04-01  0.023791  0.653147  0.857148
2019-05-01  0.729236  0.076817  0.743955
</code>```

Title: Generate random timeseries data with dates

Body:
You can either use pandas.util.testing

import pandas.util.testing as testing
import numpy as np
np.random.seed(1)

testing.N, testing.K = 5, 3  # Setting the rows and columns of the desired data

print testing.makeTimeDataFrame(freq='MS')
>>>
                   A         B         C
2000-01-01 -0.488392  0.429949 -0.723245
2000-02-01  1.247192 -0.513568 -0.512677
2000-03-01  0.293828  0.284909  1.190453
2000-04-01 -0.326079 -1.274735 -0.008266
2000-05-01 -0.001980  0.745803  1.519243

Or, if you need more control over the random values being generated, you can use something like

import numpy as np
import pandas as pd
np.random.seed(1)

rows,cols = 5,3
data = np.random.rand(rows,cols) # You can use other random functions to generate values with constraints
tidx = pd.date_range('2019-01-01', periods=rows, freq='MS') # freq='MS'set the frequency of date in months and start from day 1. You can use 'T' for minutes and so on
data_frame = pd.DataFrame(data, columns=['a','b','c'], index=tidx)
print data_frame
>>>
                   a         b         c
2019-01-01  0.992856  0.217750  0.538663
2019-02-01  0.189226  0.847022  0.156730
2019-03-01  0.572417  0.722094  0.868219
2019-04-01  0.023791  0.653147  0.857148
2019-05-01  0.729236  0.076817  0.743955


问:
Any way to to include original parameters in fscanf in C
I'm trying to see if when I do

```<code>fscanf(inputSTREAM, "$%s$", out)
</code>```

I can also return the $ signs - is there a way?

答:
I don't think there's a way to retrieve the string with the dollar signs and the non-blank string between them using the scanf() family of functions.  The closest approach would probably be using a scanset, but scansets are not the same as regular expressions, and you'd need a regular expression to specify the pattern you are looking for.

In practice, you could probably get the first dollar sign into the string using:

```<code>fscanf(inputSTREAM, " %1[$]%[^$]%*[$]", &out[0], &out[1]);
</code>```

You can't pull the same stunt for the latter dollar sign, even if you know the exact length of the string.  The trouble is that you'd need to overwrite the null at the end of the string with the second dollar sign, and you'd want a NUL '\0' after the string.  Adding the final dollar is much easier than inserting the first at the beginning of the string.  The third scanset contains an assignment-suppressing '*' and requires a dollar at the end.  The leading space in the format skips spaces.

This isn't guaranteed behaviour; the first conversion would write a NUL over out[1], and the second conversion would then write the string over out[1], but the C standard does not guarantee that it will work.

```<code>#include <stdio.h>
int main(void)
{
    char out[20];

    scanf(" %1[$]%[^$]%*[$]", &out[0], &out[1]);
    printf("<<%s>>\n", out);
    return 0;
}
</code>```

Body:
I'm trying to see if when I do

fscanf(inputSTREAM, "$%s$", out)

I can also return the $ signs - is there a way?

Body:
I don't think there's a way to retrieve the string with the dollar signs and the non-blank string between them using the scanf() family of functions.  The closest approach would probably be using a scanset, but scansets are not the same as regular expressions, and you'd need a regular expression to specify the pattern you are looking for.

In practice, you could probably get the first dollar sign into the string using:

fscanf(inputSTREAM, " %1[$]%[^$]%*[$]", &out[0], &out[1]);

You can't pull the same stunt for the latter dollar sign, even if you know the exact length of the string.  The trouble is that you'd need to overwrite the null at the end of the string with the second dollar sign, and you'd want a NUL '\0' after the string.  Adding the final dollar is much easier than inserting the first at the beginning of the string.  The third scanset contains an assignment-suppressing '*' and requires a dollar at the end.  The leading space in the format skips spaces.

This isn't guaranteed behaviour; the first conversion would write a NUL over out[1], and the second conversion would then write the string over out[1], but the C standard does not guarantee that it will work.

#include <stdio.h>
int main(void)
{
    char out[20];

    scanf(" %1[$]%[^$]%*[$]", &out[0], &out[1]);
    printf("<<%s>>\n", out);
    return 0;
}