text:
Q: Placeholder of Datepicker changes with selected date in react native, I want to make the placeholder constant, not changing I am new to react native, I need a help.
I use a datepicker of native base in the react native, I place an icon at placeholder of that, when I click on the datepicker and select date the place holder icon changes with the selected date, so I want to make placeholder showing the icon only not the selected date, so how can I implement that.
My date picker code.
import React, { Component } from 'react';
import { Alert, Image, ScrollView, View, AppRegistry, StyleSheet, AsyncStorage, SafeAreaView, FlatList, ActivityIndicator, TouchableOpacity, Platform  } from 'react-native';
import { fetchUpdateAsync } from 'expo/build/Updates/Updates';
import DateTimePicker from "react-native-modal-datetime-picker";
import DateSelect from 'react-native-datepicker';
import { TextInput } from 'react-native-gesture-handler';
import moment from "moment";
import { Container, Header, Label, Button, Content, Item, Input, Textarea, DatePicker, Body, Title, Text, Icon, Picker, Form } from 'native-base';

var datepicker='';
var leavetype='';
var reason='';
var access_token_receieved='';
var chosenDate='';
var newDate='';
class RequestLeave extends Component {
    state = {choosenLabel: '', choosenindex: ''}
    constructor(props) {
        super(props);
        this.state = {
            chosenDate:'',
            date: '',
            selected: undefined,
            datepicker:'',
            reason:'',
            leavetype:'',
         };
        this.setDate = this.setDate.bind(this);
    }
    setDate(newDate)
    {
      this.chosenDate= new Date(),
      this.setState({ chosenDate: newDate });
    }
    onIconclick(){
      //this.setDate();
      chosenDate= new Date()
      this.setState({ chosenDate: newDate });
    }
    onValueChange(value)
    {
        this.setState({choosenLabel: itemValue, choosenIndex: itemIndex})
    }
    componentDidMount() {
      AsyncStorage.getItem("token").then(async (res) => {
        access_token_receieved = await res;
        console.log('Access_Token from storage');
        console.log(access_token_receieved);
      });
        var that = this;
        var date = new Date().getDate(); //Current Date
        var month = new Date().getMonth() + 1; //Current Month
        var year = new Date().getFullYear(); //Current Year
        var hours = new Date().getHours(); //Current Hours
        var min = new Date().getMinutes(); //Current Minutes
        var sec = new Date().getSeconds(); //Current Seconds
        that.setState({
          //Setting the value of the date time
          date:
            date + '/' + month + '/' + year,
        });
    }
    fetchData(access_token_receieved)
    {
      console.log('inside render');
      console.log('token inside :'+access_token_receieved);
      leavetype= this.state.choosenLabel;
      datepicker= this.state.chosenDate.toString().substr(3, 12);
      datepicker=moment(datepicker).format("DD-MM-YYYY");
      const { reason } = this.state;
      console.log(leavetype);
      console.log(datepicker);
      console.log(reason);
      console.log(access_token_receieved);
      var that = this;
      var url ='apiurl';
      console.log('url: '+url);
      fetch(url,{
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type':'application/json',
            'Authorization': 'Bearer '+ access_token_receieved,
          },
          body: JSON.stringify({
            "datepicker":datepicker,
            "leavetype": leavetype,
            "reason": reason
          })
        })
        .then(response => {

            if(response.status == 200){
              Alert.alert('Leave Request send');
              //this.setTimeout(() => this.props.navigator.navigate('LeaveScreen'), 5000);
              setTimeout(
                () => { this.props.navigation.navigate('LeaveScreen') },
                2000
              )
            } else{
              Alert.alert('Leave Request not send');
            }
            console.log('result: '+response.status);
        })
        .catch(function (error) {
          console.log("-------- error ------- "+error);
         alert("result:"+error)
        });
    }
    render() {
      const { selectedStartDate } = this.state;
      const startDate = selectedStartDate ? selectedStartDate.toString() : '';
      const { navigation } = this.props.navigation;
      return (
        <ScrollView style={styles.body}>

      <Text style={styles.taskItemHeader}>REQUEST LEAVE</Text>
      <View style={styles.container}>
        <TouchableOpacity style={styles.buttonContainerRight}>
          <View >
          <Form>
            <Picker
              style={styles.taskItemContent}
              mode="dropdown"
              iosIcon={<Icon name="arrow-down" />}
              headerBackButtonText="Baaack!"
              selectedValue={this.state.choosenLabel}
              onValueChange={(itemValue, itemIndex) =>
                this.setState({choosenLabel: itemValue, choosenIndex: itemIndex})}
            >
            <Picker.Item label="Leave Type"/>
            <Picker.Item label="Casual Leave" value="1" />
            </Picker>
            </Form>
          </View>
        </TouchableOpacity>
      </View>

      <View style={styles.container1}>
        <View style={styles.buttonContainerRight}>
          <View style={styles.middlecontainer}>
            <View style={styles.calenderContainerLeft}>
                <DatePicker
                style={styles.datepickerstyle}
                date={this.state.date}
                showIcon={false}
                hideText={true}
                format="DD-MM-YYYY"
                showIcon = {true}
                modalTransparent={false}
                animationType={"fade"}
                placeHolderText={<Icon type="FontAwesome" name='calendar' style={styles.iconstyle} onPress={() => this.setDate}/>}
                onDateChange={this.setDate}
                disabled={false}
              />
            </View>
            <View style={styles.calenderContainerRight}>
              <Text onPress={this.setDate}>
            <Text note numberOfLines={1} style={styles.dateItemContent} disabled>{this.state.chosenDate.toString().substr(4, 11)}</Text>
            </Text>
            </View>
          </View>
        </View>
      </View>

      <View style={styles.container}>
        <View style={styles.textinputContainerRight}>
          <TextInput style={styles.taskItemContent} multiline={true} placeholder='Reason for Leave..'></TextInput>
          </View>
      </View>

      <View style={styles.btncontainer}>
        <TouchableOpacity style={styles.buttoncontainer} onPress={() => this.fetchData(access_token_receieved)}>
          <View>
            <Body style={styles.bodyStyle}>
              <Text note numberOfLines={1} style={styles.buttontemContent}>APPLY</Text>
            </Body>
          </View>
        </TouchableOpacity>
      </View>

      </ScrollView>
    );

  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    alignItems:'center',
    alignContent:'center',
    justifyContent:'center',
    paddingBottom:15,
},

container1: {
  flex: 1,
  flexDirection: 'row',
  alignItems:'center',
  alignContent:'center',
  justifyContent:'center',
  paddingBottom:15,
},

middlecontainer: {
  flex: 1,
  flexDirection: 'row',
  justifyContent: 'center',
  alignContent: 'center',
  paddingBottom:15,
},

btncontainer: {
  flex: 1,
  flexDirection: 'row',
  alignContent:'center',
  alignItems: 'center',
  justifyContent: 'center',
  paddingBottom:15,
},

buttoncontainer: {
  flex: 1,
  backgroundColor:'#a0bfff',
    alignContent:'center',
    justifyContent:'center',
    marginLeft:15,
    marginTop:0,
    marginRight:15,
    marginBottom:0,
    height:60,
    borderRadius:10,
    shadowColor: "#000",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 0,
    },
    shadowOpacity: 0.50,
    shadowRadius: 12.35,
    elevation: 10,
},

containerLast: {
  flex: 1,
  flexDirection: 'row',
  alignItems: 'center',
  justifyContent: 'center',
  paddingBottom:25,
},
iconstyle:{
  fontSize: 35,
  color: '#a0bfff',
},
taskItemContent: {
  color: 'black',
  fontSize: 15,
  marginLeft:10,
},
dateItemContent:{
  color: 'black',
  fontSize: 15,
  marginLeft:10,
},

datepickerstyle:{color:'white'},

buttontemContent: {
  color: 'white',
  fontWeight:'bold',
  fontSize: 15,
  alignItems:'center',
},

bodyStyle:{
  borderWidth:0,
  justifyContent:'center',
},

textbodyStyle:{
  borderWidth:0,
  justifyContent:'center',
  alignContent:'flex-start',
},

taskItemHeader: {
  color: 'black',
  fontSize: 25,
  alignContent:'flex-start',
  paddingBottom:15,
  paddingLeft:15,
},
buttonContainerLeft: {
    flex: 1,
    alignItems:'center',
    alignContent:'center',
    justifyContent:'center',
    marginLeft:15,
    marginTop:0,
    marginRight:0,
    marginBottom:0,
    backgroundColor: '#ffffff',
    height:120,

    borderRadius:8,
    shadowColor: "#000",
shadowColor: "#000",
shadowOffset: {
  width: 0,
  height: 0,
},
shadowOpacity: 0.50,
shadowRadius: 12.35,
elevation: 10,
},
buttonContainerRight: {
    flex: 1,
    alignContent:'center',
    justifyContent:'center',
    marginLeft:15,
    marginTop:0,
    marginRight:15,
    marginBottom:0,
    backgroundColor: '#ffffff',
    height:60,
    borderRadius:8,
    shadowColor: "#000",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 0,
    },
    shadowOpacity: 0.50,
    shadowRadius: 12.35,
    elevation: 10,
},

textinputContainerRight: {
  flex: 1,
  alignContent:'flex-start',
  marginLeft:15,
  marginTop:0,
  marginRight:15,
  marginBottom:0,
  backgroundColor: '#ffffff',
  height:160,
  borderRadius:8,
  shadowColor: "#000",
  shadowColor: "#000",
  shadowOffset: {
    width: 0,
    height: 0,
  },
  shadowOpacity: 0.50,
  shadowRadius: 12.35,
  elevation: 10,
},

viewstyle1:{
  alignItems:'flex-start',
  alignContent:'center',
  justifyContent:'center',
},
viewstyle2:{
  alignItems:'flex-end',
  alignContent:'center',
  justifyContent:'center',
},

calenderContainerRight: {
  flex: 1,
  justifyContent:'center',
  alignItems:'flex-end',
  marginLeft:15,
  marginTop:0,
  marginRight:5,
  marginBottom:0,
  height:60,
  borderRadius:8,
},

calenderContainerLeft: {
  flex: 1,
  justifyContent:'center',
  marginLeft:5,
  marginTop:0,
  marginBottom:0,
  height:60,
  borderRadius:8,
},

calenderContainerRight1: {
  flex: 1,
  alignItems:'center',
  alignContent:'center',
  alignContent:'center',
  height:60,
  borderRadius:8,
},

textContainerRight: {
  flex: 1,
  alignItems:'center',
  alignContent:'center',
  justifyContent:'center',
  marginLeft:15,
  marginTop:0,
  marginRight:15,
  marginBottom:0,
  backgroundColor: '#ffffff',
  height:120,
  borderRadius:8,
  shadowColor: "#000",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 0,
},
shadowOpacity: 0.50,
shadowRadius: 12.35,
elevation: 10,
},

btn:{
  borderRadius:0,

},
body:{
  paddingTop:15,
  paddingBottom:30,
  backgroundColor: '#efefef',
}
});
export default RequestLeave

So can someone please help me with this.

these are the out put pages, as I don't want to show date at the left side, there I want to show the icon only.


text:
Q: Open a .msg file with Outlook 2016? How do I open a .msg file with Outlook 2016, with a Powershell script?
Tried the following, nothing occurred - no errors:
Invoke-Item "L:\PAM\Day1.msg"

$Filepath = "L:\PAM\Day1.msg"

A: Found a resolution myself - pretty simple
Start-Process -FilePath "L:\PAM\Day1.msg"

redpajama_set_name: RedPajamaStackExchange


text:
Q: qemu-nbd connected device is very slow I used following command to create the qcow2:
qemu-img create -f qcow2 test2019.qcow2 10G
sudo qemu-nbd -c /dev/nbd1 test2019.qcow2

Then I created an ext4 on device /dev/nbd1. The formatting process is supper slow. And after that I used the dd to test the writing speed:
time dd if=/dev/zero of=./largefile2 oflag=dsync bs=500MB count=1
1+0 records in
1+0 records out
500000000 bytes (500 MB, 477 MiB) copied, 656.736 s, 761 kB/s

real    10m56.755s
user    0m0.001s
sys     0m0.424s

This is too slow to be useful. Any idea what happens?

A: this is because we have not give the high performance parameters to qcow2, following parameters make it 1000x faster:
qemu-nbd -c /dev/nbd1 test.qcow2 --cache=unsafe --discard=unmap


text:
Q: Read cookies with js or jquery which is created by asp.net I've created a couple of cookies using by ASP.Net C# and I want to read them from client side which of I can use jquery datepicker regional.
HttpCookie cookies = new HttpCookie("lang");
        cookies["Language_ID"] = "2";
        cookies["CultureInfo"] = "en";
        cookies.Expires = DateTime.Now.AddMonths(1);
        Response.Cookies.Add(cookies);

This is my asp.net code and result of cookies:
http://i.stack.imgur.com/lYzYP.png
I want to change language of datepicker paramatically, and this is the jquery code for it. How can I modify it for returning lang>CultureInfo cookies.
$.datepicker.setDefaults($.datepicker.regional[mycookiecultureinfo]);

A: If you are using webforms you can put a hiddenfield control on you ASPX page:
<asp:hiddenfield id="hdfCultureInfo" value="" runat="server"/>

And you have to set the value on your code behind:
hdfCultureInfo.Value = "en";

Now, you can get this value on your script using JQuery:
var ci= $('<%=hdfCultureInfo.ClientID%>').val();
$.datepicker.setDefaults($.datepicker.regional[ci]);

Another way, if you want to share this data along other pages, you can store on a Session:
Session["CultureInfo"] = "us"

On the ASPX page, just include this on header before starting your script files:
<script type="text/javascript">
var ci = '<%=(string)Session["CultureInfo"]%>';
</script>

But if you are using MVC, you can pass values with the ViewData and write anywhere using Razor.


text:
Q: How to Improve Cross Join Performance in Hive TEZ? I have a hive table with 5 billion records. I want each of these 5 billion records to be joined with a hardcoded 52 records.
For achieving this I am doing a cross join like
select *
from table1 join table 2
ON 1 = 1;

This is taking 5 hours to run with the highest possible memory parameters.
Is there any other short or easier way to achieve this in less time ?

A: Turn on map-join:
set hive.auto.convert.join=true;

select *
 from table1 cross join table2;

The table is small (52 records) and should fit into memory. Map-join operator will load small table into the distributed cache and each reducer container will use it to process data in memory, much faster than common-join.

A: Your query is slow because a cross-join(Cartesian product) is processed by ONE single reducer. The cure is to enforce higher parallelism. One way is to turn the query into an inner-join, so as to utilize map-side join optimization.
with t1 as (
  selct col1, col2,..., 0 as k from table1
)
,t2 as (
  selct col3, col4,..., 0 as k from table2
)
selct
  *
from t1 join t2
    on t1.k = t2.k

Now each table (CTE) has a fake column called k with identical value 0. So it works just like a cross-join while only a map-side join operation takes place.


text:
Q: JQL: Find the latest closed sprint How can I find the last closed sprint?I tried using
ORDER BY updatedDate DESC

but this returns all the closed sprints. I need only the latest one.

A: JIRA does not provide a JQL function out of the box that supports listing the issues in the last completed sprint. The best it offers is displaying the issues in a sprint by name, e.g.:
sprint = "<sprint name>"

You can find the documentation about the JQL support for the sprint field here.
If you use JIRA standalone, then there are a few add-ons that provide additional JQL functions. For example, Script Runner adds a function previousSprint that does what you want. Your JQL then looks like:
issueFunction in previousSprint("<board name>")

There is also a cloud version of this add-on, but it does not support the agile functions yet. To see what they do support, check this table.


text:
Q: Subtract value of double array element from the previous array element I have retrieved values from a sqlite database into a double array. Suppose i have a double array like this:
double[] n = { 1.2, 3.0, 4.5, 6.7.... };

My aim is to perform the following calculations,
double total = (3.0 - 1.2) + (4.5 - 3.0) + (6.7 - 4.5) ...

The array values are from a database. How can i achieve this?. Thanks in advance.

A: You can use a for loop starting from index 1
double x = 0;
for (int i = 1; i < array.length; i++) {
  x += (array[i] - array[i-1]);
}


text:
Q: Blogname and Blogdescription in Pagelines DMS Options Panel I am attempting up set up a front end options panel in the pagelines-dms framework, from which users will be able to change the blogname and blogdescription. So far I have set up the form which has the text fields 'blogname' & 'blogdescription' as below
add_filter('pl_sorted_settings_array', 'add_global_panel2');
function add_global_panel2($settings){
    $settings['privacy'] = array(
        'name' => 'Blog Name',
        'icon' => 'icon-eye-open',
        'opts' => array(
            // Regular Options Engine
            array(
            'key' => 'blogname',
        'type' => 'text',
                'label' => 'blog Name'
        ),
            // Regular Options Engine
            array(
                'id'   => 'blogdescription',
        'type' => 'text',
                'label' => 'blog description'

            ),
        )
    );
    // Finally we return the new array
    return $settings;
}

However, I'm unsure of how to link this up with the wordpress options. I have found the following functions in the pagelines-dms editor.settings.php which I beleive holds the key to my success but I'm unsure how to implement it in the right way:
/*
 * This class contains all methods for interacting with WordPress' data system
 * It has no dependancy so it can be used as a substitute for WordPress native functions
 * The options system inherits from it.
 */
class PageLinesData {

    function meta($id, $key, $default = false){

        $val = get_post_meta($id, $key, true);

        if( (!$val || $val == '') && $default ){

            $val = $default;

        } elseif( is_array($val) && is_array($default)) {

            $val = wp_parse_args( $val, $default );

        }

        return $val;

    }

    function meta_update($id, $key, $value){

        update_post_meta($id, $key, $value);

    }

    function opt( $key, $default = false, $parse = false ){

        $val = get_option($key);

        if( !$val ){

            $val = $default;

        } elseif( $parse && is_array($val) && is_array($default)) {

            $val = wp_parse_args( $val, $default );

        }

        return $val;

    }

    function opt_update( $key, $value ){

        update_option($key, $value);

    }

    function user( $user_id, $key, $default = false ){

        $val = get_user_meta($user_id, $key, true);

        if( !$val ){

            $val = $default;

        } elseif( is_array($val) && is_array($default)) {

            $val = wp_parse_args( $val, $default );

        }

        return $val;

    }

    function user_update( $user_id, $key, $value ){
        update_user_meta( $user_id, $key, $value );
    }

}

(a copy of the entire file can be found here: http://themes.svn.wordpress.org/dms/1.0.2/editor/editor.settings.php)
If anyone could help I would be more than grateful.
Thanks in advance!

A: Ok,
So I have found a solution to my problem;
Pagelines encodes each key and value pair into a json string, within in its own option called pl_settings in the wp_options table.
They also give you access to each of these key->value pairs using the following: $value = pl_setting('option_key')
Thus I have taken the approach of using the following code to fulfil my needs:
add_filter('pl_sorted_settings_array', 'add_global_panel2');
function add_global_panel2($settings){
    $settings['privacy'] = array(
        'name' => 'About Your Loved One',
        'icon' => 'icon-heart',
        'opts' => array(
            // Regular Options Engine
        array(
                'key' => 'blogname',
                'type' => 'text',
                'label' => 'the name of your loved one',
                'help' => 'test'
        ),
            // Regular Options Engine
            array(
                'key'   => 'blogdescription',
                'type' => 'text',
                'label' => 'a message to your loved one',
                'help' => 'test'
            ),
        )
    );
    update_option('blogname', $value = pl_setting('blogname'));
    update_option('blogdescription', $value = pl_setting('blogdescription'));
    // Finally we return the new array
    return $settings;
}

The only downside of working it in this way is that I need to refresh the browser twice once updating either of the values for it to actually take effect on it's corresponding option.
If anyone could better this then please let me know.


text:
Q: MySqlDataAdapter error: Type of value has a mismatch with column type I have this code running on development machine perfectly:
    MySqlCommand cmd = new MySqlCommand("select * from orders where id=1", conn);
    System.Data.DataTable dt = new System.Data.DataTable();
    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
    da.Fill(dt);

But when I run the same code with same database on the prodcution server it throws this error:
[ArgumentException: Type of value has a mismatch with column type]
   System.Data.Common.ObjectStorage.Set(Int32 recordNo, Object value) +2256750
   System.Data.DataColumn.set_Item(Int32 record, Object value) +60

[ArgumentException: Type of value has a mismatch with column typeCouldn't store <1.1.0001 00:00:00> in myTimeColumn Column.  Expected type is MySqlDateTime.]
   System.Data.DataColumn.set_Item(Int32 record, Object value) +6632812
   System.Data.DataTable.NewRecordFromArray(Object[] value) +6638777
   System.Data.DataTable.LoadDataRow(Object[] values, Boolean fAcceptChanges) +111
   System.Data.ProviderBase.SchemaMapping.LoadDataRow() +148
   System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) +141
   System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) +292
   System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) +657
   System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +368
   System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) +487
   System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) +293

Note: myTimeColumn is datetime in the table.
Same things of the development and production machine:

*

*MySQL server version: 5.6.20

*data

*.NET Framework version: 4.5.1

*MySQL Connector/Net 6.8.3

Different things:

*

*Production OS: Windows Server 2012 R2 (with IIS 8.5)

*Development OS: Windows 7 64 bit (with IIS 7.5)

Yes:

*

*I have added Allow Zero Datetime=True and Convert Zero Datetime=True in the connection string.

Thanks for any help,

A: removing Allow Zero Datetime=True solved the problem.

A: Removing "Convert Zero Datetime=True" instead Allow Zero Datetime=True is worked for me..... try it


text:
Q: Unable to delete row from table in Microsoft SQL Server Management Studio (SSMS) I highlighted a row in my table, and pressed right-click >> delete.
My error message is as follows:

No rows were deleted.
A problem occurred attempting to delete row 1.
  Error Source: .Net SqlClient Data Provider.
Error Message: The select list for the INSERT statement contains more items than the insert list.  The number of SELECT values must match the number of INSERT columns.
Correct the errors and attempt to delete the row again or press ESC to cancel the change(s).
  [OK]

The show SQL pane reveals the following:
    SELECT     TOP (200) ReceiptID, fkSID, fkStudyID, Amount, Paymentdt, Purpose, dtCreated, CreatedBy, dtChanged, ChangedBy, MedicalExam, NPT, LP, MRI, Food, Transportation,
                      TransportationDetail, Other, OtherSpecify, FR, TR, OtR, fkLocationID, Notes, CashAmountOut, CashOutby, CashOutApprovedby, Cashoutdt, CashAmountReturned,
                      CashReturnedby, CashReturnReceivedby, CashReturnReceiveddt, AllDocumentationComplete, ReceiptStatus, AddCashRequests, fkBatchSubmissionsID, Parking,
                      ParkingStickerID, Other2, OtherSpecify2
FROM         tblReceipts
ORDER BY ReceiptID DESC

I do not know how to correct the errors.  Does anyone know what to do in this situation?
Thank you.

A: If you want to delete Table Content do it like this:

Delete from your table where ReceiptID < 201

If you want to delete 1 - 200 record


text:
Q: Creating a bijection between Dyck paths and 231-avoiding permutations As a background, 231-avoiding permutations are well described here.
I have done some reading and found this paper but I don't really understand the argument. I was wondering if anyone could go more into detail about the proof.


text:
Q: Hiding data label on data bar if 0 I've got a Data Bar and I'm only showing the percentage label on the bottom area. But if that portion is 0 I do not want to show a label at all.
If I use:
=IIf(sum(count(Fields!SEStatusID.Value = 2 And Fields!MathStatusID.Value=2)) > 0, true, false)

Then I get all data labels shown.
If I use:
=IIf(count(Fields!SEStatusID.Value = 2 And Fields!MathStatusID.Value=2) > 0, true, false)

Then I get all data labels shown.
How do I not show a data label if there are no Fields!SEStatusID.Value = 2 AND no Fields!MathStatusID.Value=2?

A: I was missing an inner IIF statement.
=IIF(Sum(IIF(Fields!SEStatusID.Value = 2 And Fields!MathStatusID.Value = 2, 1,0))=0,False,True)


text:
Q: OpenCL Compute Units Infos I am currently working on an i.MX6.Q platform embedding a Vivante GC2100 GPU. On the (VERY SHORT) technical specifications provided Vivante, it says I got 4 shader cores if I vectorize and 16 if I don't (http://www.vivantecorp.com/index.php/en/technology/gpgpu.html).
When I directly recover OpenCL infos about my GPU it says I got 4 compute units and the preferred vector width is 4.
Does that mean the GPU will automatically detect if I vectorize or not?
Will it always correctly use all the cores he can (in the current version of my program I didn't developed vectorization) and is there a way to be sure of it?
If I dont use aligned data, does I still have to vectorize to benefit the gpu capabilities or can I just keep using my gpu without vectorization? I am currently benching the i.MX6.Q for OpenCL so I will vectorize what I can anyway and see it by myself, but if you guys know some theory about it, I take it !!
Baptiste

A: It depends on whether your kernel is vectorizable by the particular OpenCL compiler you're using. If you keep your data unpacked (all single floats) then it is possible that your compiler may be able to perform work-item vectorization.
In fact, for this reason CUDA does not implement vector types or operations unlike OpenCL. I would advise against manual packing just because it makes things more complicated for a compiler to auto-vectorize.
The GPU doesn't detect or "use" vectorization - the compiler generates the correct object code that uses vectorized instructions where possible (based on your logic). As for finding out if your particular kernel was vectorized or not, you'll have to refer to the documentation/tools of your implementation. As for using all cores, that depends on the global worksize. If you don't submit enough work for all the SMs on the GPU to be busy then it will be underutilized.
Also, Note that most OpenCL implementation will prefer (and allocate) aligned data unless you specifically prevent it using the packed attribute.


text:
Q: Gaussian elimination iteration with pivoting in python with back substitution I am implementing a code for solving Ux = b  and I don't get the same results as for linalg.solve(). I have created a function implementing back substitution that I was using in my gauelim function but I have the feeling that it does not take into consideration my iteration inside gauelim function. Does anyone sees the problem?:/ You can find the code below. Tank you very much in advance!
import numpy as np

#To solve Ux = b for n=3 (3x3 non-triangular matrix)

U = np.array([[2, 1, 1],[1, 1, -2],[1, 2, 1]])
#print(U)
bs = np.array([8, -2, 2])
#print(bs)

def backsub(U,bs):
    # i=0
    n = bs.size
    xs = np.zeros(n)
    for i in reversed(range(n)):
        xs[i] = (bs[i] - U[i,i+1:] @ xs[i+1:]) / U[i,i]
    return xs

def gauelim(U,bs):
    n = bs.size
    for j in range(n-1):
        for i in range(j+1,n):
            coeff = U[i,j]/U[j,j]
            U[i,j:] - coeff*U[j,j:]
            bs[i] - coeff*bs[j]
    xs = backsub(U,bs)
    return xs

print(gauelim(U,bs))

#solving Ux = b with linalg.solve()
x_sol = np.linalg.solve(U,bs)
print(x_sol)

I was trying to implement a code solving Ux=b with x being a 3x3 non-triangular matrix by doing Gaussian elimination.


text:
Q: Extract text with random numbers inside using C# In C#, if I have a long string that will always contains somewhere a format such as W##S##Q## where # can be any number, how can I get that sequence of W##S##Q## extracted from the string. Bare in mind that the string may have more before or after but I am only interested in that sequence.
Regards.

A: Wobbles comment is correct, a regular expression such as @"W\d{2}S\d{2}Q\d{2}" will do what you need. \d matches any any decimal digit and the {2} afterwards tells it to match exactly twice.
This fiddle gives an example of how you would extract the string you want from a longer string.

A: Wobbles is right, Regular Expressions are the best way to do it generally. For your specific example, if you know in advance that the W,S,Q portions are always going to be in the same place you could use:
        string testString = "WSomethingW01S02Q03SomethingElse";
        bool TheRightString = false;

        string WNumString = string.Empty;
        string SNumString = string.Empty;
        string QNumString = string.Empty;

        int StartPosition = 0;
        do
        {
            StartPosition = testString.IndexOf('W', StartPosition);
            WNumString = testString.Substring(StartPosition, 3);
            SNumString = testString.Substring(StartPosition + 3, 3);
            QNumString = testString.Substring(StartPosition + 6, 3);

            StartPosition += 1;

            if (SNumString.StartsWith("S") && QNumString.StartsWith("Q"))
                TheRightString = true;

        } while (TheRightString == false);

        Console.WriteLine(WNumString + SNumString + QNumString);
        Console.ReadKey();


text:
Q: How to convert R Date into Excel numeric serial date? Excel stores dates internally as floating-point serial date. We know how to convert it into R - using as.Date(var2, origin="1899-12-30", tz='UTC').
The question is: how to convert it back into Excel? I tried all the obvious things, but I still get a mismatch.

A: One approach is, for example for the date '2017-05-15' :
d0 <- as.Date(0, origin="1899-12-30", tz='UTC')
d1 <- as.Date('2017-05-15')

d <- as.numeric(d1-d0)
# or in one line
d <- as.numeric(as.Date('2017-05-15') -as.Date(0, origin="1899-12-30", tz='UTC'))
print(d)
[1] 42870

In excel the date '2017-05-15' gives the same number when expressed as numeric serial date.


text:
Q: Auto update custom folder in Oh My Zsh I have my own custom theme for Oh My Zsh that lives in the .oh-my-zsh/custom folder. I have it hosted on GitHub (as described in the OMZ docs under Version control of customizations) so all I have to do is
cd ~/.oh-my-zsh/custom ; git pull ; popd

and it updates fine but then I have to visit every machine/VM where I use this custom theme and run the command manually. How can I tie into the auto-update system for Oh My Zsh to update my custom theme?

A: After trying to contribute a pull request that was mostly ignored, I hacked a way to tie into Oh My Zsh's updates. By watching the mod date of .git's FETCH_HEAD file I am able to trigger my update whenever Oh My Zsh fetches from github which is more than sufficient for my use.
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# self-update

ts_file=~/.zsh-custom-update

upgrade_custom() {
  printf '\033[0;34m%s\033[0m\n' "Upgrading the custom files"
  cd "$ZSH_CUSTOM"
  if git pull --rebase --stat origin master
  then
    printf '\033[0;34m%s\033[0m\n' 'Hooray! The custom files have been updated and/or are at the current version.'
  else
    printf '\033[0;31m%s\033[0m\n' 'There was an error updating. Try again later?'
  fi
}

upgrade_custom_update() {
  echo -n "$1" >! $ts_file
}

upgrade_custom_check() {
  if [[ "$OSTYPE" == darwin* ]]; then
    ts=$(stat -f '%Sm' $ZSH/.git/FETCH_HEAD || echo 'missing' )
  else
    ts=$(stat -c %y $ZSH/.git/FETCH_HEAD || echo 'missing' )
  fi

  if [[ "$ts" == $( cat $ts_file || echo 'missing' ) ]] ; then
    #echo 'up to date'
  else
    upgrade_custom_update "$ts"
    upgrade_custom
  fi
}

upgrade_custom_check

I'm inexperienced at writing zsh scripts so feedback is welcome. I use both Mac & Linux but I'm not sure the stat command will work on BSDs.

A: You can use OhMyZsh Full-autoupdate plugin.
It updates both plugins and themes.


text:
Q: Organize uploads by year, month and day As of now my uploaded files are organized by year and month.  But I would like to organize them by year, month and day.  I mean like this 2012/10/30/image goes here
PS: There is a plugin available to do this. But I don't want to use a plugin for this simple task. Thanks

A: As far as I can tell, the filter 'upload_dir' is only called once in wp-includes\functions.php
I find this solution to be much simpler. It will place all uploads into the year/month/day directory for the date it is uploaded.
function upload_dir_filter($uploads){
    $day = date('d');
    $uploads['path'] .= '/' . $day;
    $uploads['url']  .= '/' . $day;
    return $uploads;
}
add_filter('upload_dir', 'upload_dir_filter');

A: Code based in other Answer of mine and this SO Answer.
It uses the post/page/cpt publish date to build the paths.
Note that $the_post->post_date_gmt is also available.
add_filter('wp_handle_upload_prefilter', 'wpse_70946_handle_upload_prefilter');
add_filter('wp_handle_upload', 'wpse_70946_handle_upload');

function wpse_70946_handle_upload_prefilter( $file )
{
    add_filter('upload_dir', 'wpse_70946_custom_upload_dir');
    return $file;
}

function wpse_70946_handle_upload( $fileinfo )
{
    remove_filter('upload_dir', 'wpse_70946_custom_upload_dir');
    return $fileinfo;
}

function wpse_70946_custom_upload_dir($path)
{
    /*
     * Determines if uploading from inside a post/page/cpt - if not, default Upload folder is used
     */
    $use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
    if( !empty( $path['error'] ) || $use_default_dir )
        return $path; // Error: not uploading from a post/page/cpt

    $the_post = get_post( $_REQUEST['post_id'] );
    $y = date( 'Y', strtotime( $the_post->post_date ) );
    $m = date( 'm', strtotime( $the_post->post_date ) );
    $d = date( 'd', strtotime( $the_post->post_date ) );

    $customdir = '/' . $y . '/' . $m . '/' . $d;

    $path['path']    = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
    $path['url']     = str_replace($path['subdir'], '', $path['url']);
    $path['subdir']  = $customdir;
    $path['path']   .= $customdir;
    $path['url']    .= $customdir;

    return $path;
}

A: I have made a new code out of these 2 code. The images will be uploaded to the post date folder not the uploaded date folder:
function upload_dir_filter($uploads){

    $the_post = get_post( $_REQUEST['post_id'] );
    $y = date( 'Y', strtotime( $the_post->post_date ) );
    $m = date( 'm', strtotime( $the_post->post_date ) );
    $day = date( 'd', strtotime( $the_post->post_date ) );
    $uploads['path'] .= '/' . $day;
    $uploads['url']  .= '/' . $day;
    return $uploads;
}
add_filter('upload_dir', 'upload_dir_filter');


text:
Q: Error even after starting mysql server with --skip-grant-tables I have forgotten the password for mysql server. Even after starting the server with --skip-grant-tables I get the below error.
ER

ROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using
  password: NO)

This is for windows.
Also I get the error even for mysql -u root
What could be the issue?

A: Here is what you need to do
First ensure that mysqld is not running.
ps aux | grep mysqld

if it is running. Stop it. Then,
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root
FLUSH PRIVILEGES;
SET PASSWORD FOR root@'localhost' = PASSWORD('password');


text:
Q: Freeing a multidimensional array when allocation fails Say I allocate a two-dimensional array:
int main(void)
{
        long int **arr;
        int i;
        int j;

        arr = calloc(2, sizeof(long int *));
        if (!arr) {
                exit(EXIT_FAILURE);
        }

        for (i = 0; i < 2; i++) {
                arr[i] = calloc(10, sizeof(long int));
                if (!arr[i]) {
                        for (j = i; j > 0; j--) {
                                free(arr[j]);
                        }
                        free(arr);
                        exit(EXIT_FAILURE);
                }
        }
}

Should I include the free()-loop in the test condition if memory allocation fails
if (!arr[i]) {
        for (j = i; j > 0; j--) {
                free(arr[j]);
        }
        free(arr);
        exit(EXIT_FAILURE);
}

or is it usually enough to just exit() with failure when I don't want the program to move on?
if (!arr[i]) {
        exit(EXIT_FAILURE);
}

A: Since you are exiting the program in case of allocation failure, therefore no harm in doing this. You can use second snippet.

C does not provide direct support for error handling, aka exception handling. On MSVC you can try this (Note that this is not the part of C standard):
void exceptionExample() {
    int *p = NULL;
    __try {
        p = (int*)malloc(sizeof(int));
        *p = 5;
        printf("%d\n",*p);
    }
    __finally {
        free(p);
    }
}

Suggested readings: C Programming/Error handling, Error handling in C.


text:
Q: is there a way to import csv data into a sqlite db, while not explicitly typing the columns out hoping not to use pandas for this.
#create a sqllite database
#step 1: create a connection

import sqlite3
conn = sqlite3.connect('db.sqlite')
sqlcursor = conn.cursor()

###--------------------------------STEP 2: IMPORT GEOSPATIAL DATA--------------------------------###
import csv
geofile = r'geodata.csv'
with open(geofile, 'r', newline='') as csvfile:
    csvdata = csv.reader(csvfile, delimiter=',')
    next(csvdata, None)
    csvrows = []
    for row in csvdata:
        if len(row[0]) < 5:
            row[0] = row[0].zfill(5)
        if len(row[1]) != 2:
            print('state: '+row[1])
        csvrows.append(tuple(row))

sqlcursor.executemany('SELECT * INTO geodata FROM VALUES(?,?,?,?,?,?);', csvrows)
conn.commit()

obviously this doesn't work, but for example in sql i can do something like this:
select * from
(
values
 ('207-544')
,('208-609')
,('208-601')
,('984-520')
,('989-318')
) AS m(combos)

so looking to use select into vs insert into, since i dont actually have a table - and don't want to make one beforehand

A: If you don't want to store it in a file (as you don't want to create a table) you can do
conn = sqlite3.connect("file::memory:?cache=shared")

and to create the temp table (which would be a similar result as SELECT INTO), notice that you don't need to specify the column types
crt = 'CREATE TEMP TABLE t('
ins = 'INSERT INTO t VALUES('
for n in range(len(csvrows[0])):
    if n:
        crt += ', '
        ins += ', '
    crt += f'c{n}'
    ins += '?'
crt += ');'
ins += ');'
sqlcursor.execute(crt)
sqlcursor.executemany(ins, csvrows)

sqlite has a VALUES keyword that you can use in a SELECT UNION or similar, for example
sqlite> VALUES (0,1,2,3,4),(5,6,7,8,9) UNION SELECT * FROM sqlite_master;
0|1|2|3|4
5|6|7|8|9

but I don't think this could help.


text:
Q: How to validate a formcontrol with prepopulated data in Angular 5? I have a form-group. In the form-group, i have a form-array. I have initialized the array with items created from data in the data model with the method as described in angular's documentation on reactive forms, under the section  Initialize the secretLairs FormArray. The problem is i need to perform validation.required for each form control in the array. However, since the form-controls already hold values, i do not know how to perform validation.required. The documentation did not go further on how to validate formcontrols in a formarray that are prepopulated.
Here are my source codes:
.html

{{question.ques}}

         <input type="radio"  formControlName="choices"
         class="custom-control-input" [value]="choice.choiceText">
         {{choice.choiceText}}

         <button type="submit" class="btn btn-danger"
         [disabled]="!CheckListForm.valid">Submit</button>
         </form>

.ts
  export class CheckListFormComponent implements OnInit, OnChanges {

  CheckListForm: FormGroup;

  Ques: Questions[];

  employmenttype = ['Permanent', 'contractor'];

   constructor(private fb: FormBuilder,
               private checklistservice: ChecklistService) {
      this.CreateForm();

                                                            }

     ngOnInit() {
    this.checklistservice.getQuestions(1).subscribe(res =>{ this.Ques =res;
    this.setquestions(this.Ques)
                 });

    this.CheckListForm.get('EmploymentType').valueChanges.subscribe(

    (EmploymentType: string) => {
      if (EmploymentType === 'Permanent') {
        this.CheckListForm.get('HRMS').setValidators([Validators.required]);

     this.CheckListForm.get('CompanyName')
      .setValidators([Validators.nullValidator]);
      } else if (EmploymentType === 'contractor') {

        this.CheckListForm.get('CompanyName').
        setValidators([Validators.required]);

        this.CheckListForm.get('HRMS').
        setValidators([Validators.nullValidator]);
                                                 }

         this.CheckListForm.get('HRMS').updateValueAndValidity();
         this.CheckListForm.get('CompanyName').updateValueAndValidity();
                                                               }
                                                                   )
                                                                        }

 CreateForm() {
 this.CheckListForm = this.fb.group({

 name: ['', Validators.required],
 EmploymentType: ['', Validators.required],
 HRMS: [''],
 CompanyName:[''],
 questions: this.fb.array([])
  })
  }

get questions(): FormArray {
return this.CheckListForm.get('questions') as FormArray;
                           }

setquestions(questions: Questions[]) {
const QuestionsFGs = questions.map(questions => this.fb.group(questions));
const QuestionsFormArray = this.fb.array(QuestionsFGs);
this.CheckListForm.setControl('questions', QuestionsFormArray);
 }

A: As usual, as there is no response from anyone, I will post the answer which i have painstakingly solved.
You cannot validate form-controls through the method i have performed(see my codes). The reason is because the form-controls already hold data and is not empty in the first place. Hence, validation.required will not work.
A solution will be to instead push empty form-controls for each item in the array of the data model.
Validation.required will then work for this case.


text:
Q: How to target html5 main element as a parent node using javascript to remove the main elements children Hi as the title say I am wondering how I can target the  tag to use as a parent node  using javascript so I can remove the contents of it (all 's children). Lets start with my html (I want to remove the button)
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css">

    <title></title>

</head>

<body>

    <main>
        <input type="button" id="start" name="startQ" value="Start Quiz">
    </main>
<script src="script.js"></script>
</body>

</html>

now I am kinda lost on how to target that main tag. I know if I change main --> div id=main I could use the js code:
var x = document.getElementById("main");
x.parentNode.removeChild(x);

But id like to use main Any ideas?
Thanks in advanced!

A: to remove main tag
var x = document.getElementsByTagName('main')[0];
x.parentNode.removeChild(x);

to remove button
var x = document.getElementById("start");
x.parentNode.removeChild(x);


text:
Q: NodeJs: not returning correct count fo Dynamodb table I have the following code:
const AWS = require("aws-sdk");
AWS.config.update({region: 'us-eas-1'});
var ddb = new AWS.DynamoDB({region: 'us-east-1'});

async function countData(){
     var params ={TableName: 'tbl_billings_trns'}
     const countdb1 =  await ddb.describeTable(params).promise();
     console.log(countdb1);
    console.log("Total count " + numbers.toString());
     return numbers;

  }

countData()

I also tried:
async function kk(){
var jj = await countData();
console.log(jj);
}

kk()

It is giving count 0, but Table has 12 items.
I used await after promisify it, but unable to achieve it. Any help will be great for me.

A: You're using the DescribeTable API-call to get the count of items.
This is actually not a live-count as per the docs:

ItemCount
The number of items in the specified table. DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.

The data you're receiving may be up to 6 hours old, which is probably why it doesn't match.
To get a more accurate number you'd have to scan through the table, which is very expensive and you really should avoid.

A: If your application needs to fetch more accurate aggregations, you might consider maintaining the count yourself in DynamoDB.  For example, if you need to keep a count of Users/Products/Orders/etc, you could maintain a summary record that gets incremented/decremented as you add/remove items from the table.  This is especially useful if your application has a reporting mechanism that requires aggregates that would otherwise only be available via an expensive scan operation.
A common pattern to maintain your own summary records is to use DynamoDB streams.  When your lambda gets a notification of a new or deleted item, you could update the summary records accordingly.


text:
Q: Interview Solution - Trimming a Gap Buffer An interview question I encountered involves the implementation of the Gap Buffer data structure.  In particular, I'm talking about a data structure that is essentially a LinkedList where each Node is a (fairly small) char array.  This is ideal for text editing because you can insert more characters at any point, allocating new arrays if there is no room where you are looking.
Implementing the Gap Buffer itself is no big deal since it looks exactly like a LinkedList, and implementing methods like Add and Remove are algorithmically straightforward.  Simply insert the new character in the node corresponding to the position if there is room, allocating a new node if more room is needed.
The most difficult question was an efficient implementation of a Trim method with the postcondition that when Trim is run, all the non-whitespace elements in the Gap Buffer will be "compacted" towards the beginning, that is, all the elements move as far forward as they can and spaces are trimmed out.
The naive method would be to simply iterate through every array element one by one, moving it to the next free space until all the elements have been iterated, and then deleting all the empty nodes at the end of the list.  However, this is less than ideal:
If during iteration we approach an array that is empty, we should immediately remove that array from the list, thus joining the 2 arrays around it.  On the other hand, if we approach an array that is completely full, we should skip over the array since it is already compacted.
Are these two cases the only cases we need to consider when it comes to efficiency?  Are there any other potential improvements?  And what would the fully efficient Trim look like algorithmically?

A: One improvement would be to detect that the array is empty after we trimmed it. If it's empty then just delete it, instead of copying next array into it.


text:
Q: Selecting features for classification model I have a dataset that contains some numeric variables. What im doing is trying to check how important these variables are in describing endogenous variable in order to include them in my classifier.
I understand that in order to do so, I need to check p-values of given variables and in order to do so, what I did is i tried to use f_classif and chi2.
I tried to do that in python the same way as in documentation (scikit learn), but i do not understand how to interpret the results. Moreover, in example on sklearn documentation I get this:
selector = SelectKBest(f_classif, k=4)
selector.fit(X_train, y_train)
scores = -np.log10(selector.pvalues_)
scores /= scores.max()

What does this transformation mean and how to interpret this?
Thanks for any help

A: The transformation exists to put tiny numbers on a more meaningful scale. Humans see tiny p-values like $0.00001627$ and $0.0003119$ as just "tiny numbers". Try taking $-\log_{10}$ of those values; you will get $4.789$ and $3.506$. This emphasizes the difference between what might otherwise be seen as a tiny difference. "Tiny" vs "tiny" is harder to compare than $4.8$ vs $3.5$.
Note, however, the issues with feature selection.


text:
Q: Most accurate finite difference result for first derivative I got a problem in my assignment: obtain the most accurate finite difference results possible for the first derivative of f (x) = exp(cos(x)) at x=1, h = 0.5, 0.25, 0.125,...2^{16}. I have to do this in MATLAB. Can any one explain how to find such accurate result, so that I can implement it in MATLAB

A: You can compute the exact derivative to compare against.
The central difference formula
$$
f'(x)=\frac{f(x+h)-f(x-h)}{2h}+O(h^2)
$$
has two error contributions, the discretization error $\sim f''(x) h^2$ and the evaluation error $\sim |f(x)|\mu/h$ where $\mu$ is the floating point machine constant.
The overall error is minimal where both contributions are about equal, which happens at $h\sim\sqrt[3]\mu\approx 2^{-17}\approx 8·10^{-6}$, the last for double precision floats, with an error of about $2^{-34}\approx 6.4·10^{-11}$

If you use then Richardson extrapolation or other methods to get a higher order formula, the next best result would be $O(h^4)$. By the same estimates, the best result is obtained for $h\sim\sqrt[5´]\mu\approx 2^{-10}\approx 10^{-3}$ with error in the region of $2^{-40}\approx 10^{-12}$.

This trend continues, the higher the order, the larger the intersection between the error contributions. However, the gains in using ever higher order formulas quickly reduce to a trickle.

A: Using Taylor Expansion, there are many finite difference derivative estimates one can formulate.
If you have your data in hand, and will not solve a system of DE, then my choice would be a 1 step central difference which has convergence order $h^2$. Other possible "easy" approaches can be forward difference or backward difference.

A: See here and here. You can get arbitrarily accurate results by using arbitrarily high order approximations, so your question is somewhat underspecified.


text:
Q: Late 70s Early 80s Children's SF Book Series Basic premise was a space-crew who were in some sort of rescue role. The books in the series featured a space-ship which was illustrated as very similar to the "Discovery" from "2001", but was based from a 10,000 person wheel-shaped space colony. The crew wore track-suit style outfits (70s futuristic trope) and they had an alien that was a pink blob which communicated via a small computer attached to it, which printed out messages.
One adventure has the crew encountering a ship full of the pink blob aliens.
In another they have to rescue a colony on Venus by dropping the alien into a jammed landing dome.
In another the ship goes out of control and they encounter a long-lost space-colony where the inhabitants have grown into giants.
My local library only ever seemed to have a few books from the whole series. Some of the titles on the cover end-notes sounded quite good.

A: This is a series called Galaxy 1 by, among others, Harriette Sheffer Abels, published by Crestwood House. It follows the adventures of Emergency Spaceship EM88. The pink blob with the computer is named Amorf. Here's a link to the Google books entries.


text:
Q: Cassandra Storage: which read is faster? I have two ways of storing data
Use case:
Storing incoming data for each product
1) CREATE COLUMN FAMILY product_data WITH comparator = TimeUUIDType AND    key_validation_class=UTF8Type AND default_validation_class = UTF8Type;
This will store data like
product_id|timeuuid1     | timeuuid2      |
A         | (some-value) |  (some-value)  |

2) CREATE COLUMN FAMILY product_data(product_id varchar, time TIMESTAMP, some-data varchar, key(product_id, time))
Now my aim is to have better disk reads. In first case entire row is at same place so disk reads are fast for all time range reads. In second case data for one product will be in same replicas but will they be in same disk space?

A: Second statement is the CQL equivalent for the first one: product_id will be translated by the engine to the row key, and time value to column name. CQL range query will be possible on time field (i.e., SELECT * FROM product_data WHERE product_id = ? AND time > ? AND time < ?), but not on product_id. Second way is recommended, since CQL API already slightly outperforms Thrift, and the development is focused on CQL improvements.


text:
Q: Does Spring AOP Load-Time Weaving Require JVM Arguments? For a standalone Java application using Spring AOP, is it necessary to require JVM arguments such as -javaagent:pathto/aspectjweaver.jar to "turn on" AOP support?  When would you want or need to do so?
To be clear, "standalone" means a Maven-built, excecutable .jar; that will be invoked across a variety of platforms.

A: It depends. If you are using Spring AOP to do only coarse-grained interception (meaning you'd like to intercept only outer calls to a bean, but not calls inside a bean), you need no JVM arguments at all. Just use code like:
<bean id="myInterceptor" class="com.company.interceptors.MyInterceptor"></bean>

<aop:config>
    <aop:pointcut id="myPointcut"
        expression="execution(* com.company.services..MyService.*(..))" />

    <aop:advisor pointcut-ref="myPointcut"
        advice-ref="myInterceptor" />
</aop:config>

If this is not enough and you need load-time weaving to advise intra-bean calls for example, then You'd need to add a JVM argument as described in the Spring 3.0 docs:

Generic Java applications
You may enable Spring's support for LTW in any Java application (standalone as well as application server based) through the use of the Spring-provided instrumentation agent. To do so, start the VM by by specifying the -javaagent:path/to/spring-agent.jar option. Note that this requires modification of the VM launch script which may prevent you from using this in application server environments (depending on your operation policies).

See here http://static.springsource.org/spring/docs/3.0.0.RC2/reference/html/ch07s08.html#aop-aj-ltw-environments

A: Consider using compile time weaving via maven:
<properties>
    <aspectj.version>1.6.12</aspectj.version>
</properties>

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.4</version>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjtools</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
            </dependencies>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <complianceLevel>1.7</complianceLevel>
                <aspectLibraries>
                    <aspectLibrary>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aspects</artifactId>
                    </aspectLibrary>
                </aspectLibraries>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>compile</goal>
                        <goal>test-compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Doing so covers all the crazy Spring AOP cases, even private transactional methods.

A: Check more doc here http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-aj-ltw. It depends.

A: Typically, it's sufficient to just include weaver jar in the classpath.


text:
Q: How to select the rows of a material table programmatically on onclick event of button -React js I am Working with Material-Table . I need to select multiple rows on clicking a button based on some condition .the condition is written inside the code below. Can anyone guide me on how to select multiple rows based on some condition?
 <MaterialTable
                            icons={tableIcons}title=""

                            columns={[
                                { title: 'Project Name', field: 'Project_Name', render: rowData => <Link to='/projectdetails'>{rowData.Project_Name}</Link> },
                                { title: 'Methods Covered', field: 'Methods_Covered', type: 'numeric' },
                                { title: 'Methods not Covered', field: 'Methods_not_Covered', type: 'numeric' },
                                { title: 'Total Methods', field: 'Total_Methods', type: 'numeric' },

                                    ]}

                            data={this.state.results}

                            components={{
                                Toolbar: props => (

                                        <MTableToolbar {...props} />

                                                <Button color="primary" onClick={rowData =>
                                                 (rowData.Methods_Covered ?
                                                  rowData.tableData.checked = true :
                                                  rowData.tableData.checked = false)}>
                                                 select Highlighted</Button>

                                ),
                            }}
                            onSelectionChange={this.handleSelect}
                            onRowClick={this.handleRowClick}
                            options={{
                                sorting: true,
                                selection: true,
                                search: true,
                                searchAutoFocus: true,
                                searchFieldAlignment: 'right',
                                searchFieldStyle: {
                                    border: 'solid black 2px',
                                },
                              }}
  />

A: <MaterialTable
    // here other params of table component
    options={{
        selection: true,
        selectionProps: (rowData: any) => ({
            color: "primary",
            checked: agentGroups?.includes(rowData.value) ? true: false,
            onClick: (() => {
                let index = agentGroups.findIndex((group:string)=>group==rowData.value);
                index > -1 ? agentGroups.splice(index , 1) : agentGroups.push(rowData.value);
            }),
        }),
    }}
/>

The key is to modify(push or splice) the array in onClick function which you have used in checked key of selectionProps

*

*Remove if already present in array, it will unselect the row

*Push if not already present in array, it will select the row

A: I haven't tried the code of the OP, but someone having this problem can check the selectionProps properties of the options props of the MaterialTable:
options={{
  sorting: true,
  selection: true,
  search: true,
  searchAutoFocus: true,
  searchFieldAlignment: 'right',
  searchFieldStyle: {
      border: 'solid black 2px',
  },
  selectionProps: ({ tableData: { checked } }) => ({
    checked
  }),
}}

Please check the last example here: https://material-table.com/#/docs/features/selection
And the docs for options here: https://material-table.com/#/docs/all-props


text:
Q: C++ Dynamic Arrays - Why am I able to do this? I was trying to use dynamic arrays in my project, but I can't understand why I can do this:
int *a;
a = new int[1];
a[100]=2;

cout << a[100] << endl;

I mean, I created the array 'a' which can store 1 element, so why am I able to use the 100th element of the array? It shouldn't exist, should it?

A: Some basic stuff:
Your array is stored in memory, every cell has its own address. The name of your array a points to the place in memory where it starts. From there a[0], a[1] or just a[index] is the same thing as you'd type*(a+index) - it gets/sets value placed under (a+index) index in a memory.
In fact you can overwrite any of these addresses even if they aren't being used by your variables (arrays etc.). Of course you shouldnt do this, but your compilator won't be mad (you can also declare variable-length arrays, compilator might not care, but you should be aware of that).
I tried to make it as simple as possible, there is no need to elaborate, I believe.


text:
Q: I am unable to use strtok over a char I am unable to use strtok over char *a but on b its working.
Its working with malloc and array
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DELIM ":"

int main()
{
    char *a = "xgdgsf: duh d";//unable to use strtok on it
    char *token=NULL;
    printf("%s",a);
    char *b = malloc(strlen(a) + 1);
    strcpy(b, a);//i can use strtko on it

    token=strtok(b,DELIM);
    printf("\n%s",token);
    token=strtok(a,DELIM);
    printf("\n%s",token);
    return 0;
 }

A: Change
char *a = "xgdgsf: duh d";

to
char *a = strdup("xgdgsf: duh d");

In C, string literals are read only. However, do remember that you need to free the pointer after calling strdup. Do it with free(a) when you are done with the string.

A: You have passed a to strtok which is a string literal. You can't do that because strtok modifies the string.
If you had defined the array as
const char *a = "xgdgsf: duh d";

then the compiler would give you a warning.
The second call to strtok should be
token=strtok(NULL, DELIM);

to extract the second token from b.

A: As others have pointed out, the problem is that a points to a string literal. strtok modifies its input (it overwrites the delimiters with a string terminator) and the behavior on attempting to modify a string literal is undefined - you may get a runtime error, the code may work as expected, or something else may happen.  String literals are supposed to be immutable, but it's not guaranteed that they'll be stored in read-only memory.
There are several ways to resolve this.  One is to declare a as an array and initialize it with the string:
char a[] = "xgdgsf: duh d";

Another is to dynamically allocate a buffer and copy the contents of the string to it:
char *a = malloc( strlen( "xgdgsf: duh d" ) + 1 );
if ( a )
  strcpy( a, "xgdgsf: duh d" );

If it's available on your system, you can use the non-standard function strdup to do the same thing:
char *a = strdup( "xgdgsf: duh d" );

When declaring a pointer to a string literal, it's usually a good idea to qualify it as const:
const char *a = "xgdgsf: duh d";

that way the compiler will yak at you if you try to modify (assign to) *a or a[i] or pass it to a function that expects a plain char * as an input.  That way mistakes like using strtok on a literal are caught at compile time, not runtime.


text:
Q: Steam reviews to MySQL database I'm trying to get all the reviews of a certain game from steam through this method: https://partner.steamgames.com/doc/store/getreviews and dumb the data either in a MySQL DB or at least export it as an Excel spreadsheet. The structure of the db has to be exactly as the returns in the link above (author, review, etc) without the need for further customization.
I'm a total beginner when it comes to json, steamworks and the like so any links to in-depth tutorials regarding similar matters and explanations to any suggestions are welcome.
Thank you

A: Okay so I found the following, which is actual pretty easy but since im an amateur i didnt know how to properly search for it. Heres the solution for any other amateurs out the:
I just copy and paste all my data in the following site: https://json-csv.com
In my case I had to copy/paste multiple parts since the Get List functions from steamworks only brings back batches of 20 reviews per time. (Keep in mind that you must insert this in the URL &start_offset=0 then &start_offset=20" and so on to get all the reviews). You must also insert &filter=recent or &filter=updated or else it wont work.
Then i just download a csv file compatitle with excel and all my data structured and manipulatable any way i want.


text:
Q: Appending a dictionary to a dataframe as a new column I'm very new to Python and was hoping to get some help. I am following an online example where the author creates a dictionary, adds some data to it and then appends this to his original dataframe.
When I follow the code the data in the dictionary doesn't get appended to the dataframe and as such I can't continue with the example.
The authors code is as follows:
from collections import defaultdict
won_last = defaultdict(int)
for index,row in data.iterrows():
    home_team = row['HomeTeam']
    visitor_team = row['AwayTeam']
    row['HomeLastWin'] = won_last[home_team]
    row['VisitorLastWin'] = won_last[visitor_team]
    results.ix[index]=row
    won_last[home_team] = row['HomeWin']
    won_last[visitor_team] = not row['HomeWin']

When I run this code I get the error message (note that the name of the dataframe is different but apart from that nothing has changed)
AttributeError                            Traceback (most recent call last)
<ipython-input-46-d31706a5f745> in <module>
      4     row['HomeLastWin'] = won_last[home_team]
      5     row['VisitorLastWin'] = won_last[visitor_team]
----> 6     data.ix[index]=row
      7     won_last[home_team] = row['HomeWin']
      8     won_last[visitor_team] = not row['HomeWin']

~\anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5137             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5138                 return self[name]
-> 5139             return object.__getattribute__(self, name)
   5140
   5141     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'ix'

If I change the row data.ix[index]=row to data.loc[index]=row the code runs ok but nothing happens to my dataframe
Below is an example of the dataset I am working with
Div   Date      Time    HomeTeam       AwayTeam   FTHG  FTAG    FTR HomeWIn
E0  12/09/2020  12:30   Fulham           Arsenal    0    3       A  FALSE
E0  12/09/2020  15:00   Crystal Palace  Southampton 1    0       H  FALSE
E0  12/09/2020  17:30   Liverpool         Leeds     4    3       H  TRUE
E0  12/09/2020  20:00   West Ham         Newcastle  0    2       A  TRUE
E0  13/09/2020  14:00   West Brom        Leicester  0    3       A  FALSE
and below is the dataset of the example I am working through with the columns added
   Date   Visitor Team  VisitorPts  Home Team   HomePts HomeWin

20  01/11/2013  Milwaukee      105       Boston       98     FALSE
21  01/11/2013  Miami Heat     100     Brooklyn       101    TRUE
22  01/11/2013  Clevland       84      Charlotte      90     TRUE
23  01/11/2013  Portland       113      Denver        98     FALSE
24  01/11/2013  Dallas          91      Houston       113    TRUE
HomeLastWin VisitorLastWIn
FALSE         FALSE
FALSE         FALSE
FALSE         TRUE
FALSE         FALSE
TRUE         TRUE
Thanks
Jon

A: Could you please try this,
Data that used as dataset_stack.csv

from collections import defaultdict
won_last = defaultdict(int)
# Load the Pandas libraries with alias 'pd'
import pandas as pd

# Read data from file 'dataset_stack.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
data = pd.read_csv("dataset_stack.csv")
results=pd.DataFrame(data=data)
#print(results)
# Preview the first 5 lines of the loaded data
#data.head()
for index,row in data.iterrows():
    home_team = row['HomeTeam']
    visitor_team = row['VisitorTeam']
    row['HomeLastWin'] = won_last[home_team]
    row['VisitorLastWin'] = won_last[visitor_team]
    #results.ix[index]=row
    #results.loc[index]=row
    #add new column directly to dataframe instead of adding it to row & appending to dataframe
    results['HomeLastWin']=won_last[home_team]
    results['VisitorLastWin']=won_last[visitor_team]
    results.append(row, ignore_index=True)
    won_last[home_team] = row['HomeWin']
    won_last[visitor_team] = not row['HomeWin']
print(results)

Output:
    Date       VisitorTeam  VisitorPts   HomeTeam  HomePts  HomeWin  \
0  1/11/2013   Milwaukee         105     Boston       98    False
1  1/11/2013  Miami Heat         100   Brooklyn      101     True
2  1/11/2013    Clevland          84  Charlotte       90     True
3  1/11/2013    Portland         113     Denver       98    False
4  1/11/2013      Dallas          91    Houston      113     True

    HomeLastWin  VisitorLastWin
0            0               0
1            0               0
2            0               0
3            0               0
4            0               0


text:
Q: How to resize the thumb image in a seekBar? I can get the thumb to change to different images in mipmap when the progress changes, but I can't change their size.
If I just change the size of the image files, then the bar won't show.
I'm sure some of these lines are unnecessary, but I have no idea which:
Java (in OnFinishInflate):
LevelListDrawable likey_bar_draw;
        likey_bar_draw = (LevelListDrawable) getResources().getDrawable(R.drawable.likey_bar_hearts);
        likey_bar_draw.setBounds(new Rect(0, 0, 50, 50));
        likey_bar_draw.setLevel(5);
        likeyBar.setThumb(likey_bar_draw);

        likeyBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                LevelListDrawable likey_bar_draw;
                likey_bar_draw = (LevelListDrawable) getResources().getDrawable(R.drawable.likey_bar_hearts);
                Integer progressInt = progress; //for some reason it won't let me convert progress to a string
                Log.d(TAG, "likey level: " + progressInt.toString()); //even though it's allegedly an integer...
                likey_bar_draw.setLevel(progress);
                seekBar.setThumb(likey_bar_draw);
            }

layout:
<SeekBar
        android:id="@+id/likey_bar"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:max="10"
        android:progress="5"
        android:thumb="@drawable/likey_bar_hearts"
        android:progressDrawable="@drawable/likey_bar_progress"
        android:layout_marginTop="20dp"
        android:paddingTop="20dp"
        android:paddingBottom="20dp"
        android:minHeight="50dp"
        android:maxHeight="50dp" />

likey_bar_hearts xml:
<?xml version="1.0" encoding="utf-8"?>
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:minLevel="0" android:maxLevel="0" android:drawable="@mipmap/heart_gray_100">
        <shape>
            <size android:height="40dp" android:width="40dp" />
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
...(more items similar to this)

Help??


text:
Q: Unexpected symbol(s) found:"html" error is showed in Netbeans I use *html (in CSS files) before class names for IE6 fixes. But Netbeans shows such *html as errors. How can I avoid it?

A: *html is not a valid selector.
Using the * html selector is one way to target IE6 and below. The reason that it's called a hack is because they aren't any elements above the html tag: the html tag is the root of the DOM tree (except for document, but CSS can't target that). The * html selector implies that the html tag could be a descendant of something, but, being the root, it can't be.
edit: Wikipedia also has a nice explanation of this selector.


text:
Q: Customizing JTextField I would like to know how to customize the ui of a jtextfield so I could create rounded rectangular border without the document going outside the border.
So far I think I have tried the most of what I can think of, I have created a new FieldView class and changed the shape in the paint method according to my customized border that draw rounded rects, the only way I sort of managed to get rid of the white textfield document/view was to set it opaque but I think there should be another way without setting the opaque value.
Have You any experience in customizing the laf of a jtextfield please write back, I have even read the Core Swing advanced book without luck and if you try searching with google please let me know the search phrase as I have tried with keywords like "styling","customizing","ui","plaf","laf" and what not.
I sincerely hope you can give me a nudge in the right direction and I hope nobody will make a flamewar out of this, I have truly used all my resources I can think of.
Sincerely regards.

A: I wanted to solve almost same problem yesterday and I got some inspiration by your thought and I finally find the solution.

*

*To make document inside the border of JTextField, you can use

javax.swing.border.EmptyBorder.EmptyBorder(Insets borderInsets)

2.To avoid the white space in four corners of JTextField, you can use

g2d.setStroke(new BasicStroke(12));

before drawing the round rectangle.The width of stroke is based on your demand and just make it wide enough to cover the space in corner.
It's the code:
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.AbstractBorder;
import javax.swing.border.EmptyBorder;

public class JTextFieldTest {
    JTextField textField;
    boolean activate = false;

    public void createUI(){
        JFrame frame = new JFrame("Test JTextField");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(true);

        MainPanel mainPanel = new MainPanel();
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        frame.add(mainPanel,BorderLayout.CENTER);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        JTextFieldTest jTextFieldTest = new JTextFieldTest();
        jTextFieldTest.createUI();
    }

    public void setActivate(boolean activate){
        this.activate = activate;
    }

    @SuppressWarnings("serial")
    class MainPanel extends JPanel{
        public MainPanel(){

            textField = new JTextField("Please input:");
            Font fieldFont = new Font("Arial", Font.PLAIN, 20);
            textField.setFont(fieldFont);
            textField.setBackground(Color.white);
            textField.setForeground(Color.gray.brighter());
            textField.setColumns(30);
            textField.setBorder(BorderFactory.createCompoundBorder(
                    new CustomeBorder(),
                    new EmptyBorder(new Insets(15, 25, 15, 25))));
            textField.addActionListener(new FieldListener());
            textField.addMouseListener(new FieldMouseListener());

            add(textField,BorderLayout.CENTER);
            setBackground(Color.blue);
            setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        }
    }

    @SuppressWarnings("serial")
    class CustomeBorder extends AbstractBorder{
        @Override
        public void paintBorder(Component c, Graphics g, int x, int y,
                int width, int height) {
            // TODO Auto-generated method stubs
            super.paintBorder(c, g, x, y, width, height);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setStroke(new BasicStroke(12));
            g2d.setColor(Color.blue);
            g2d.drawRoundRect(x, y, width - 1, height - 1, 25, 25);
        }
    }

    class FieldListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            System.out.println(textField.getText());
        }

    }

    class FieldMouseListener implements MouseListener{
        @Override
        public void mouseClicked(MouseEvent e) {
            // TODO Auto-generated method stub
            if(activate == false){
                textField.setText("");
            }
            activate = true;
            textField.setForeground(Color.black);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub

        }
    }
}

It's the effect:

For more details , you can browse How to make a round rectangle JTextField

A: You should be able to do this with Swing borders.  I published some code for how to do rounded borders long ago, here - perhaps you can adapt it:
http://weblogs.java.net/blog/timboudreau/archive/2005/02/jnn_just_got_pr.html

A: If you want to customizing single components, there's a way to do that, in any component actually.
Please check this tutorial : http://www.eecchhoo.wordpress.com/2012/11/05/screencast-swingmakeover-extreme-java-gui-programming
It contains a short brief and a link to download the video tutorial. FYI, the videos are in indonesian language, so if you have problem to follow the step, there's also another link to download the project that he used to create the tutorial.
Please tell me if you have any problem. I hope that link will help


text:
Q: How to diagnose App engine module Routing Requests not working? the following dispatch.xml doesn't work for our appengine app (java):
<?xml version="1.0" encoding="UTF-8"?>
<dispatch-entries>
<dispatch>
    <url>*/favicon.ico</url>
    <module>default</module>
</dispatch>
<dispatch>
    <url>*/*</url>
    <module>x-frontend</module>
</dispatch>
</dispatch-entries>

Both modules have been uploaded, but nothing hits the x-frontend module.
The code is derived from https://github.com/GoogleCloudPlatform/appengine-modules-sample-java
I put the dispatch.xml under appengine-modules-sample-java/root/src/main/webapp/WEB-INF. root is the default module I added.

A: The output of the mvn command says:
Skipping dispatch.xml - consider running "appcfg.sh update_dispatch <war-dir>"

which means we have to run it manually. mvn plugin doesn't do the job.


text:
Q: Why the process is not running on background? I have a XX method which takes 2 seconds. I want to do something before it and when XX method finishes I want to do another thing.
The problem is:
It works fine but the problem is everything does when the XX method finish , I mean the method which must run before XX and  the method which must run after XX work togeter after XX method finish.
What I did is:
runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     beforeXX();
                }
            });

XX();//takes 2 seconds

runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     afterXX();
                }
            });

afterXX(); and  beforeXX(); are both of them are change the view.
(I also tried AsyncTask method)
thanks in advance

A: Moved from comment
I think you might be creating a race condition there, because beforeXX may or may not finish before xx() is even called, and given the naming - before needs to be run completely before xx starts.  Then xx blocks until you're done.  An AsyncTask is definitely a better approach.
Take for example:
// The three generics here are:
// 1) What is passed into doInBackground (invoked via .execute())
// 2) onProgressUpdate params (I didn't include that)
// 3) What is passed into onPostExecute
public class DoMyBackendWork extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        // do beforeXX(); stuff here, this runs on the UI thread
    }

    @Override
    protected String doInBackground(String... filePaths) {
        // do the xx(); code here.  It will be sequential, such as:
        // data = expensiveSetup();
        // procData = processData(data);
        // expensivePostDataThatCanBeDoneInBackground(procData);
        // return strings...;  This goes to onPostExecute
    }

    @Override
    protected void onPostExecute(String result) {
        // do afterXX(); stuff here, this runs on the UI thread
        // this data comes from the return of doInBackground
    }
    private void expensiveSetup() {}
    private ProcessedData processData(Data data) {}
    private void expensivePostDataThatCanBeDoneInBackground(ProcessedData data) {}
}

Then in wherever you are calling that from:
DoMyBackendWork dmbw = new DoMyBackendWork(/* add ctor and params if needed */);
dmbw.execute(/* string params */);

A: Why not simply run the code in the lines of
beforeXX();
XX();
afterXX();

?
What you wrote is not guaranteed to be executed in the order that your code is written and in the way you expect, because thread management belongs to the operating system and not to you as a programmer.
The least you can do to solve your problem is to wait for the threads beforeXX and afterXX to finish. First thing I'm thinking of is use an Object as a lock and syncrhonize your threads on it. If you don't know how to do that, ask and I'll update my answer.


text:
Q: JSON DECODE using PHP I am doing some JSON decodes - I followed this tutorial well explained - How To Parse JSON With PHP
and the PHP code, I used
 <?php
 $string='{"person":[
            {
                "name":{"first":"John","last":"Adams"},
                "age":"40"
            },
            {
                "name":{"first":"Thomas","last":"Jefferson"},
                "age":"35"
            }
         ]}';

$json_a=json_decode($string,true);

$json_o=json_decode($string);

// array method
foreach($json_a[person] as $p)
{
echo '

Name: '.$p[name][first].' '.$p[name][last].'

Age: '.$p[age].'

';

}

// object method
foreach($json_o->person as $p)
{
echo '

 Name: '.$p->name->first.' '.$p->name->last.'

Age: '.$p->age.'

';
}

 ?>

It is working correctly... But my concern I need only details of Thomas' last name and age. I need to handle this to extract only certain features, not all the objects.

A: Give the JSON data that you provided the link to, this should return the currency value for the given country:
$country_data = json_decode(file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json"), TRUE);

function get_currency($name) {
    global $country_data;

    $name = strtolower($name);
    $output = reset(array_filter($country_data, function ($value, $key) use($name) {
        if(strtolower($value['name']['common']) === $name || strtolower($value['name']['official']) === $name) {
            return true;
        }
    }, ARRAY_FILTER_USE_BOTH))['currency'];
    return ($output) ? $output : array();
}

/* Return same results */

echo "
";
print_r(get_currency("Islamic Republic of Afghanistan"));
echo "
";

echo "
";
print_r(get_currency("Afghanistan"));
echo "
";

NOTE: The above function is case-insensitive. If you need case sensitivity supported, remove the strtolower() function references.
EDIT:

*

*Corrected a bug in the snippet.

EDIT 2:

*

*Returns an array of currencies if the country name is found or an empty array array() if the country cannot be found.

*The name passed into get_currency() is now checked against the common name and the official name. Passing either will return a value.

A: Actually  Thomas is the first name not last name
try this code..
print "names:", ",".join(x["last"] for x in obj if x["first"] == "Thomas")

A: Given this JSON, you can get the currency of a country as follows:
function getCurrencyFor($arr, $findCountry) {
    foreach($arr as $country) {
        if ($country->name->common == $findCountry) {
            $currency = $country->currency[0];
            break;
        }
    }
    return $currency;
}

$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Angola");

echo "Angola has $currency as currency";


text:
Q: How many distinct clones can be generated using functions from $P_2(n)$? Suppose $P_2(n)$ is the set of all $n$-ary boolean functions, $P_2 := \bigcup_{n \in \mathbb{N}} P_2(n)$. Now for $A \subset P_2$ define $[A]$ as the minimal boolean clone containing $A$ as a subset. Let's define $Cl_2(n) := \{[A]|A \subset P_2(n)\}$
Is there a way to explicitly calculate $|Cl_2(n)|$? Or (if it is too complicated) what is its asymptotic?
The only thing I was able to get was the following upper bound:
$$|Cl_2(n)| \leq 2^{2^{n^2}}$$
It follows from $|P_2(n)| = 2^{n^2}$.

A: First of all, it is not true that $|P_2(n)|=2^{n^2}$, rather $|P_2(n)|=2^{2^n}$. This affects your estimate for $|Cl_2(n)|$.
Second, it is possible to compute $|Cl_2(n)|$ exactly using Post's lattice. I won't attempt to calculate $|Cl_2(n)|$ for $n=0,1,2,3$, but for $n\geq 3$ it is easy to see from Post's lattice that $|Cl_2(n+1)|=|Cl_2(n)|+8$. Thus $|Cl_2(n)|=8n+C$ for some constant $C$ whenever $n\geq 3$.


text:
Q: Why is VLC slower than MPV/MPlayer? Every time I try to seek a local video with VLC, there is a noticable lag, as opposed to MPlayer/MPV, no matter what "ultrafast" x264 presets or loop filter skipping is used.
What's the fundamental reason for that?

A: Try this :

*

*Go to the Menu Tools / Preferences

*Click at the bottom at Show Settings on All

*Click on Input / Codecs

*Ensure that Fast seek is checked

*Click Save

A: VLC has an issue known for long with seeking, when running it alongside a nVidia GPU. It seems to have a relationship with GPU hardware acceleration, not fully supported.
To try and resolve this, assuming you have the last version of VLC (2.2.1), and if you have a powerful enough CPU, you can deactivate the GPU acceleration:
Tools -> Preferences (Simple settings) -> Video -> Uncheck Accelerated video output (Overlay)


text:
Q: Strip timestamp from the date field in Datatables I am using jquery Datatables plugin. I followed the link http://www.codeproject.com/Articles/190718/jQuery-DataTables-and-J2EE-web-application-integra
I am passing a Date in the JSON object to the datatables plugin. The format from webservice call is like

"Sat Jan 10 00:08:00 EST 2009"

, I need to strip off the time, EST and the day, I mean it should look something like

"Jan 10, 2009"

and the column is sorted on the server side. All I need is to strip off the data on the fly on the client side. I am still in the process of learning datatables plugin, I am not sure of implementing this. Experts please point me to the right direction.

A: [Edit] Since it looks like the date comes back from the server as a string then you're easiest solution is probably a regular expression.  Try this:
function reformatDate(dateStr) {
  var r = /^\w{3}\s+(\w{3})\s+(\d{1,2})\s+.*?(\d{4})$/
    , m = (''+dateStr).match(r);
  return (m) ? m[1]+' '+m[2]+', '+m[3] : dateStr;
}

[Original] Assuming you are working with an actual Date object and you don't want to incur the overhead of a proper JavaScript date wrangling library (such as the excellent Datejs) you could format the date like so:
var formatDate = (function() {
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  return function(dt) {
    return months[dt.getMonth()] + ' ' + dt.getDate() + ', ' + dt.getFullYear();
  };
})();
formatDate(new Date()); // => "Mar 15, 2012"

A: I'm not sure if you can do this with bServerSide set to true but you might be able to setup column definitions using the aoColumns option for the datatable and then apply column rendering via
fnRender: function (o, val) {
    parse your date here...
    return newDateString;
}


text:
Q: Does GROUP negate using ORDER BY in Pig? I have a Pig script where I'm trying to order certain user events by datetime (UNIX timestamps) and then group the events by userid. The script doesn't generate any errors, and it does group the event by userid, but the events are not ending up sorted by datetime. This leads me to wonder if doing a group after an order by operation might undo the sorting?

A: Order is only guaranteed immediately following the use of ORDER BY. Further processing may destroy the order.
Alternatively, you can perform the grouping and then use ORDER BY in a nested foreach to order each bag of records separately.


text:
Q: Powershell -parallel and thread safe usage? 6 hours later and I am getting closer. Started learning Visual Studio Code vs ISE so I can easily use PowerShell 7.  Learned about -Parallel, then how you can't call variables in the Script Block without using $using:. (That took forever!) Tried the -Asjob part but that doesn't seem right for this.  I am basically taking a text file with 20 lines and search for matches in a 300k+ lines of a CSV.
I believe I have gotten to a part I just can't figure out. I think I need to know how to use "thread safe" objects based upon the error.
$textfile = "C:\test_delete\key_words.txt"
$loglocation = "C:\test_delete\datablob.csv"
$outputfile = "C:\test_delete\test5.csv"

New-Item -Path $outputfile

Get-Content $textfile | ForEach-Object -Parallel {
    Select-String  -Raw -Path $using:loglocation -Pattern $_ |
    Out-File -append $using:outputfile
}

Error
Out-File:
Line |
   3 |      Out-File -append $using:outputfile
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The process cannot access the file 'C:\test_delete\test5.csv' because it is being used by another process.
In the ForEach-Object help, Example 11, it talks about thread safe usage and the example declares the variable = the thread safe syntax.  That makes sense (kinda).  Except in this case, I am wanting to eventually have a paramenter declared for $outfile which will need to be called in a tread safe manner. I am getting ahead of myself but just can't figure out how to make that thread safe call to $outfile.
Sorry for be verbose, this is my first post and just want to relay I have spent some time trying to get this.  Thanks in advance!

A: Here's my preferred alternative - don't use ForEach-Object -Parallel here, it's unecessary:
Select-String -Path $loglocation -Pattern (Get-Content $textfile) | Out-File $outputfile -Append

That's it, you're done, no need to worry about concurrent write access :)

If you still insist, below are a couple of examples of how to handle this specific example.
The "thread-safe" dictionary assignment in the help file works because the data type in question (ConcurrentDictionary<string,object>) is implemented with thread safety in mind.
If you want to write to a file in a thread safe manner, you'll need to maintain a lock or a mutex manually:
$fileLock = [System.Threading.ReaderWriterLockSlim]::new()

Get-Content $textfile | ForEach-Object -Parallel {
    $lock = $using:fileLock
    try{
        $lock.EnterWriteLock()
        Select-String  -Raw -Path $using:loglocation -Pattern $_ |
        Out-File -append $using:outputfile
    }
    finally{
        if($lock.IsWriteLockHeld){
            $lock.ExitWriteLock()
        }
    }
}

Alternatively, move the write operations outside the parallel loop:
Get-Content $textfile | ForEach-Object -Parallel {
    Select-String  -Raw -Path $using:loglocation -Pattern $_
} | Out-File -append $using:outputfile


text:
Q: Examples of costly consequences from improper use of statistical tools I suspect that most users of statistical tools are ancillary users (folks who have had little to no formal training in statistics).  It's very tempting for researchers and other professionals to apply statistical methods to their data simply because they have seen it "done before" in peer-reviewed papers, grey literature, the web or at a conference.   However, doing so without a clear understanding of the required assumptions and the statistical tool's limitations can lead to erroneous results—errors often unacknowledged!
I find that undergraduate students (particularly in the social and natural sciences) are either unaware of the statistical pitfalls or find these pitfalls inconsequential (the latter being most often the case).  Though examples of improper use of statistical tools can be found in many introductory level text books, the web or StackExchange, I have a difficult time finding real-world examples that have had detrimental results (e.g. cost in $, lives impacted and careers lost).  To that end, I am looking for real-world examples that highlight the misuse of statistical methods for which:

*

*the statistical methods  used are typically covered in introductory stats courses (i.e. inferential stats, regressions, etc…)

*the end result have had costly consequences (dollars lost, lives impacted, careers shattered etc…)

*the data are readily available for use as working examples in a course (the purpose is to have students work through real world examples that have had real world consequences.)

One non-statistical example I like to bring up to students when discussing the importance of properly defining the units in a research project is the "metric mishap" that led to the loss of a $125M satellite! This usually invokes an :-o factor from the students and seems to have a lasting impression (at least throughout their short academic lives).

A: I'm not sure about data availability, but a great (if that's the right word) example of poor statistics is the Harvard Nurses' Study on the effectiveness of hormone replacement therapy (HRT) in menopausal women.
What's the general idea? The Nurses' Study suggested that HRT was beneficial for post-menopausal women. Turns out that this result arose because the control group was very different from the treatment group and these differences were not account for in the analysis. In subsequent randomized trials, HRT has been linked to cancer, heart attack, stroke, and blood clots. With appropriate corrections, the Nurses' study reveals these patterns as well.
I can't find estimates for US deaths related to HRT, but the magnitude was tens of thousands. One article links 1000 deaths in the UK to HRT.
This New York Times Magazine article provides good statistical background of the issues of confounding present in the study.
There's an academic discussion in this issue of the American Journal of Epidemiology. The articles compare the results of the observational Nurses' study to that of the Women's Health Initiative, based upon randomized trials.
There is also discussion (by many of the same individuals) in an issue of Biometrics See Freedman and Petitti's comment in particular [prepub version].

A: A wonderful historical example is afforded by the 1933 publication of Horace Secrist's Triumph of Mediocrity in Business.  At the time, Secrist was a well-established statistician, author of a textbook (c. 1919, I recall), well-connected in the American Statistical Association, and head of a statistical research group at Northwestern University.  He and his staff had spent the previous decade compiling time series of business data, which are reproduced and painstakingly analyzed in the book.  It was meant to be a chef d'oeuvre by an ambitious statistician.
Harold Hotelling's review of the book, which appeared in JASA later that year, pointed out that Secrist had merely documented hundreds of examples of regression to the mean (a fundamental topic in any introductory statistics course today, point #1 of the question).  Secrist objected in a published reply.  Hotelling's response to that is a classic:

To "prove" such a mathematical result by a costly and prolonged numerical study ... is analogous to proving the multiplication table by arranging elephants in rows and columns, and then doing the same for numerous other kinds of animals.  The performance, though perhaps entertaining, and having a certain pedagogical value, is not an important contribution either to zoology or to mathematics.

[JASA v. 29 #186, June 1934, p. 199.]
Secrist seems to have faded quickly from the statistical scene shortly after that ("careers ruined," point #2 in the question).  His book is still available.  (A few years ago I obtained a nice clean copy, obviously little read, through Interlibrary Loan.)  From it you can extract any number of example datasets (point #3 of the question).
Steven Stigler recounts this story in a book and a paper, The history of statistics in 1933.

A: Seems to me that Wired's take on the 2008 stock market crash might be an informative example. Can't comment on whether it's conclusions are correct or not, but the idea of using correlations over data which are not a representative sample seems like something that might be appropriate to the circumstances you suggest. It's also current, and so might keep them interested.

A: I thought you might find this Ted Talk interesting and relevant :

*

*http://www.ted.com/talks/ben_goldacre_battling_bad_science.html