text:
Q: Calculate Number of Minutes Between Two times Gravity Forms WP I am working with Wordpress ang Gravity Forms. I have two time fields and one nuber field. Number field is in minutes and must be number of minutes between two times.
Example:
Field 1 (time): 03:20
Field 2 (time): 04:20
Calculated field:
Field 3 (number of minutes between field 1 and field 3): 60
I found something very similar but is code for Calculate Number of Days Between Two Dates:
<?php
/**
* Gravity Wiz // Calculate Number of Days Between Two Gravity Form Date Fields
*
* Allows you to calculated the number of days between two Gravity Form date fields and populate that number into a
* field on your Gravity Form.
*
* @version   1.1
* @author    David Smith <david@gravitywiz.com>
* @license   GPL-2.0+
* @link      https://gravitywiz.com/calculate-number-of-days-between-two-dates/
* @copyright 2013 Gravity Wiz
*/
class GWDayCount {
    private static $script_output;
    function __construct( $args ) {
        extract( wp_parse_args( $args, array(
            'form_id'          => false,
            'start_field_id'   => false,
            'end_field_id'     => false,
            'count_field_id'   => false,
            'include_end_date' => true,
            ) ) );
        $this->form_id        = $form_id;
        $this->start_field_id = $start_field_id;
        $this->end_field_id   = $end_field_id;
        $this->count_field_id = $count_field_id;
        $this->count_adjust   = $include_end_date ? 1 : 0;
        add_filter( "gform_pre_render_{$form_id}", array( &$this, 'load_form_script') );
        add_action( "gform_pre_submission_{$form_id}", array( &$this, 'override_submitted_value') );
    }
    function load_form_script( $form ) {
        // workaround to make this work for < 1.7
        $this->form = $form;
        add_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
        if( self::$script_output )
            return $form;
        ?>

        <script type="text/javascript">
        (function($){
            window.gwdc = function( options ) {
                this.options = options;
                this.startDateInput = $( '#input_' + this.options.formId + '_' + this.options.startFieldId );
                this.endDateInput = $( '#input_' + this.options.formId + '_' + this.options.endFieldId );
                this.countInput = $( '#input_' + this.options.formId + '_' + this.options.countFieldId );
                this.init = function() {
                    var gwdc = this;
                    // add data for "format" for parsing date
                    gwdc.startDateInput.data( 'format', this.options.startDateFormat );
                    gwdc.endDateInput.data( 'format', this.options.endDateFormat );
                    gwdc.populateDayCount();
                    gwdc.startDateInput.change( function() {
                        gwdc.populateDayCount();
                    } );
                    gwdc.endDateInput.change( function() {
                        gwdc.populateDayCount();
                    } );
                    $( '#ui-datepicker-div' ).hide();
                }
                this.getDayCount = function() {
                    var startDate = this.parseDate( this.startDateInput.val(), this.startDateInput.data('format') )
                    var endDate = this.parseDate( this.endDateInput.val(), this.endDateInput.data('format') );
                    var dayCount = 0;
                    if( !this.isValidDate( startDate ) || !this.isValidDate( endDate ) )
                        return '';
                    if( startDate > endDate ) {
                        return 0;
                    } else {
                        var diff = endDate - startDate;
                        dayCount = diff / ( 60 * 60 * 24 * 1000 ); // secs * mins * hours * milliseconds
                        dayCount = Math.round( dayCount ) + this.options.countAdjust;
                        return dayCount;
                    }
                }
                this.parseDate = function( value, format ) {
                    if( !value )
                        return false;
                    format = format.split('_');
                    var dateFormat = format[0];
                    var separators = { slash: '/', dash: '-', dot: '.' };
                    var separator = format.length > 1 ? separators[format[1]] : separators.slash;
                    var dateArr = value.split(separator);
                    switch( dateFormat ) {
                    case 'mdy':
                        return new Date( dateArr[2], dateArr[0] - 1, dateArr[1] );
                    case 'dmy':
                        return new Date( dateArr[2], dateArr[1] - 1, dateArr[0] );
                    case 'ymd':
                        return new Date( dateArr[0], dateArr[1] - 1, dateArr[2] );
                    }
                    return false;
                }
                this.populateDayCount = function() {
                    this.countInput.val( this.getDayCount() ).change();
                }
                this.isValidDate = function( date ) {
                    return !isNaN( Date.parse( date ) );
                }
                this.init();
            }
        })(jQuery);
        </script>

        <?php
        self::$script_output = true;
        return $form;
    }
    function add_init_script( $return ) {
        $start_field_format = false;
        $end_field_format = false;
        foreach( $this->form['fields'] as &$field ) {
            if( $field['id'] == $this->start_field_id )
                $start_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
            if( $field['id'] == $this->end_field_id )
                $end_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
        }
        $script = "new gwdc({
                formId:             {$this->form['id']},
                startFieldId:       {$this->start_field_id},
                startDateFormat:    '$start_field_format',
                endFieldId:         {$this->end_field_id},
                endDateFormat:      '$end_field_format',
                countFieldId:       {$this->count_field_id},
                countAdjust:        {$this->count_adjust}
            });";
        $slug = implode( '_', array( 'gw_display_count', $this->start_field_id, $this->end_field_id, $this->count_field_id ) );
        GFFormDisplay::add_init_script( $this->form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );
        // remove filter so init script is not output on subsequent forms
        remove_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
        return $return;
    }
    function override_submitted_value( $form ) {
        $start_date = false;
        $end_date = false;
        foreach( $form['fields'] as &$field ) {
            if( $field['id'] == $this->start_field_id )
                $start_date = self::parse_field_date( $field );
            if( $field['id'] == $this->end_field_id )
                $end_date = self::parse_field_date( $field );
        }
        if( $start_date > $end_date ) {
            $day_count = 0;
        } else {
            $diff = $end_date - $start_date;
            $day_count = $diff / ( 60 * 60 * 24 ); // secs * mins * hours
            $day_count = round( $day_count ) + $this->count_adjust;
        }
        $_POST["input_{$this->count_field_id}"] = $day_count;
    }
    static function parse_field_date( $field ) {
        $date_value = rgpost("input_{$field['id']}");
        $date_format = empty( $field['dateFormat'] ) ? 'mdy' : esc_attr( $field['dateFormat'] );
        $date_info = GFCommon::parse_date( $date_value, $date_format );
        if( empty( $date_info ) )
            return false;
        return strtotime( "{$date_info['year']}-{$date_info['month']}-{$date_info['day']}" );
    }
}
# Configuration
new GWDayCount( array(
    'form_id'        => 16,
    'start_field_id' => 1,
    'end_field_id'   => 2,
    'count_field_id' => 4
) );

So far i came to that but i still have problems with date format:
class GWDayCount {
    private static $script_output;
    function __construct( $args ) {
        extract( wp_parse_args( $args, array(
            'form_id'          => false,
            'start_field_id'   => false,
            'end_field_id'     => false,
            'count_field_id'   => false,
            'include_end_date' => true,
            ) ) );
        $this->form_id        = $form_id;
        $this->start_field_id = $start_field_id;
        $this->end_field_id   = $end_field_id;
        $this->count_field_id = $count_field_id;
        $this->count_adjust   = $include_end_date ? 1 : 0;
        add_filter( "gform_pre_render_{$form_id}", array( &$this, 'load_form_script') );
        add_action( "gform_pre_submission_{$form_id}", array( &$this, 'override_submitted_value') );
    }
    function load_form_script( $form ) {
        // workaround to make this work for < 1.7
        $this->form = $form;
        add_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
        if( self::$script_output )
            return $form;
        ?>

        <script type="text/javascript">
        (function($){
            window.gwdc = function( options ) {
                this.options = options;
                this.startDateInput = $( '#input_' + this.options.formId + '_' + this.options.startFieldId );
                this.endDateInput = $( '#input_' + this.options.formId + '_' + this.options.endFieldId );
                this.countInput = $( '#input_' + this.options.formId + '_' + this.options.countFieldId );

                startDateInput1 = $( '#input_' + this.options.formId + '_' + this.options.startFieldId );
                endDateInput2 = $( '#input_' + this.options.formId + '_' + this.options.endFieldId );

                this.init = function() {
                    var gwdc = this;
                    // add data for "format" for parsing date
                    gwdc.startDateInput.data( 'format', this.options.startDateFormat );
                    gwdc.endDateInput.data( 'format', this.options.endDateFormat );
                    gwdc.populateDayCount();
                    gwdc.startDateInput.change( function() {
                        gwdc.populateDayCount();
                    } );
                    gwdc.endDateInput.change( function() {
                        gwdc.populateDayCount();
                    } );
                    $( '#ui-datepicker-div' ).hide();
                }
                this.getDayCount = function() {
                    var startDate = this.parseDate( this.startDateInput.val(), this.startDateInput.data('format') )
                    min1 = startDateInput1;

                    var endDate = this.parseDate( this.endDateInput.val(), this.endDateInput.data('format') );

                    var dayCount = 0;
                    if( !this.isValidDate( startDate ) || !this.isValidDate( endDate ) )
                        return 'neki ni kul';
                    if( startDate > endDate ) {
                        return 0;
                    } else {
                        var diff = endDate - startDate;
                        dayCount = diff ;
                        var test = min1;
                        dayCount = Math.round( dayCount ) + this.options.countAdjust;
                        return test;
                    }
                }

                this.parseDate = function( value, format ) {
                    if( !value )
                        return false;
                    format = format.split('_');
                    var dateFormat = format[0];
                    var separators = { slash: ':', dash: '-', dot: '.' };
                    var separator = format.length > 1 ? separators[format[1]] : separators.slash;
                    var dateArr = value.split(separator);
                    switch( dateFormat ) {
                    case 'mdy':
                        return new Date( 0, dateArr[0] - 1, dateArr[1] );
                    case 'dmy':
                        return new Date( 0, dateArr[1] - 1, dateArr[0] );
                    case 'ymd':
                        return new Date( dateArr[0], dateArr[1] - 1, 0 );
                    }
                    return false;
                }
                this.populateDayCount = function() {
                    this.countInput.val( this.getDayCount() ).change();
                }
                this.isValidDate = function( date ) {
                    return !isNaN( Date.parse( date ) );
                }
                this.init();
            }
        })(jQuery);
        </script>

        <?php
        self::$script_output = true;
        return $form;
    }
    function add_init_script( $return ) {
        $start_field_format = false;
        $end_field_format = false;
        foreach( $this->form['fields'] as &$field ) {
            if( $field['id'] == $this->start_field_id )
                $start_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
            if( $field['id'] == $this->end_field_id )
                $end_field_format = $field['dateFormat'] ? $field['dateFormat'] : 'mdy';
        }
        $script = "new gwdc({
                formId:             {$this->form['id']},
                startFieldId:       {$this->start_field_id},
                startDateFormat:    '$start_field_format',
                endFieldId:         {$this->end_field_id},
                endDateFormat:      '$end_field_format',
                countFieldId:       {$this->count_field_id},
                countAdjust:        {$this->count_adjust}
            });";
        $slug = implode( '_', array( 'gw_display_count', $this->start_field_id, $this->end_field_id, $this->count_field_id ) );
        GFFormDisplay::add_init_script( $this->form['id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );
        // remove filter so init script is not output on subsequent forms
        remove_filter( 'gform_init_scripts_footer', array( &$this, 'add_init_script' ) );
        return $return;
    }
    function override_submitted_value( $form ) {
        $start_date = false;
        $end_date = false;
        foreach( $form['fields'] as &$field ) {
            if( $field['id'] == $this->start_field_id )
                $start_date = self::parse_field_date( $field );
            if( $field['id'] == $this->end_field_id )
                $end_date = self::parse_field_date( $field );
        }
        if( $start_date > $end_date ) {
            $day_count = 0;
        } else {
            $diff = $end_date - $start_date;
            $day_count = $diff; // secs * mins * hours
            $day_count = round( $day_count ) + $this->count_adjust;
        }
        $_POST["input_{$this->count_field_id}"] = $day_count;
    }
    static function parse_field_date( $field ) {
        $date_value = rgpost("input_{$field['id']}");
        $date_format = empty( $field['dateFormat'] ) ? 'mdy' : esc_attr( $field['dateFormat'] );
        $date_info = GFCommon::parse_date( $date_value, $date_format );
        if( empty( $date_info ) )
            return false;
        return strtotime( "{$date_info['year']}-{$date_info['month']}-{$date_info['day']}" );
    }
}

A: We (Gravity Wiz) have a plugin called GF Date Time Calculator that does. It is available by request for Gravity Perks license-holders. Here's a quick video of how it works.
http://screencast.com/t/ya7Dd5rm0SSf


text:
Q: How to display 3D models in android? I want to display some 3D models (.obj files) in an android app using android studio.
The user enters some data and the models have to be placed relative to each other according to the user input.
So all I need is to display some 3D models placed relative to each other according to the data entered before, and the user will be able to see the models from any direction when swiping the screen.
I don't know how to achieve this. I tried to use OpenGL-ES, but without avail as I can't find enough tutorials and the documentation is hard to be understood.
Any help or suggestion is welcome.
Thanks in advance.

A: Found this 3D Viewer on GitHub (supports OBJ, GLTF)
Also, I believe it is possible to find some converters OBJ ~> GLTF (by Khronos). You can write Android App with embedded Web View in which you can show GLTF.
If someone will work on Android app using some HTML / JS framework like Phonegap or VueJS + Quasar, then GLTF could be good way to go (if OBJ ~> GLTF is not a problem).

A: You can use for this job SceneForm. In a nutshell SceneForm is used as a middleware between ARCore and Filament to create awesome Augmented Reality Apps, but you can also use SceneForm just to visualize GLTF-Models

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Text Box Validation Using Double.parseDouble() I have a Swing JTextBox that basically will hold a double.
I find that using:
  Double.parseDouble(this.myTB.getText());

will throw an exception (and thus program is terminated) whenever Double.parseDouble() gets invalid input.
My question: is there an easy way to NOT throw an exception, and instead return an integer (-1) saying that parseDouble() failed?
I am trying to make a popup for the user saying he or she's data field is invalid.
Thanks

EDIT:
Thanks lol.  How could I forget about catching exceptions? it's been a long day!

A: The best way to handle this is by using a try/catch block.
try {
    return Double.parseDouble(this.myTB.getText());
} catch (NumberFormatException e) {
    JOptionPane.showMessageDialog("Oops");
    return -1;
}

The JOptionPane is a great way to display warning messages to users.

A: Catch the NumberFormatException, and return your desired error value (or take some other action from within the catch clause).
double value = -1;
try {
    value =  Double.parseDouble(this.myTB.getText());
} catch (NumberFormatException e) {
    e.printStackTrace();
}
return value;

A: Use
try{
    return Double.parseDouble(this.myTB.getText());
   } catch(NumberFormatException e) {
       return -1;
   }


text:
Q: Filesystem speed shaper for Linux There is an iprelay (or ip_relay) package to shape TCP bandwidth, and it is really useful to test how stuff works on slow connections.
Is there something similar to iprelay, which will allow me to shape filesystem write (and / or read, independently) speed? Preferably, just for some directory tree that I run my tests against, so that everything else is still fast. (Note that it is for developer machine testing / debugging only, I do not need it to be secure, to do load balancing and other production stuff.)
I'm thinking about using iprelay with sshfs or something, but it seems to me a bit too convoluted. Any better methods out there?

A: Check out blkio and cgroups:
http://sourceforge.net/apps/trac/ioband/wiki/blkio-cgroup
There is also an earlier variant for this, only using pids:
http://kerneltrap.org/Linux/Dm-band_Block_IO_Bandwidth_Controller


text:
Q: Return elements of a specified subgrid in a 9x9 grid array? I have a 9x9 array:
+-----+-----+-----+
|4 0 0|0 0 0|0 0 8|
|0 0 3|9 8 7|6 4 5|
|0 0 0|0 0 0|0 0 0|
+-----+-----+-----+
|8 5 6|0 0 0|0 2 0|
|0 0 5|8 1 6|0 0 0|
|6 0 0|0 0 0|0 0 1|
+-----+-----+-----+
|0 6 0|0 0 0|7 5 2|
|5 9 4|7 2 8|1 0 0|
|2 0 0|0 0 0|0 0 4|
+-----+-----+-----+

I want to create a function that returns the elements of a particular sub-grid entered in the argument of the function. For example, if I want to return sub-grid 3, I'd call returnSubgrid(3) and I'd get this result:
+-----+
|0 0 8|
|6 4 5|
|0 0 0|
+-----+

What is the mathematical formula for this? This is what I have so far to return the first sub-grid to a string:
std::string Sudoku::returnSubgrid(int subgrid)
{
   std::string output;
   for(int i = subgrid - 1; i < subgrid + 2; i++) {
      for(int j = subgrid - 1; j < subgrid + 2; j++) {
         output += inputBoard_[i][j];
      }
   }
   return output;
}

A: You can achieve like this,
string returnSubgrid(int subgrid) {
  std::string output;
  subgrid--;
  // inputBoard is 0 based indexing
  int row = 3 * (subgrid / 3);
  int col = 3 * (subgrid % 3);
  for(int i = row; i < row + 3; i++) {
    for(int j = col; j < col + 3; j++) {
       output += inputBoard_[i][j];
    }
  }
  return output;
}


text:
Q: How can I add one class to the div tag and another class to the ul tag with jquery in the same sentence? I added just one...
$(this).replaceWith($('

' + this.innerHTML + '

').addClass('card_tr'));

Here is the image I took for my text editor, I an new.

A: If you use children you'll get a different selector result set, so you can chain methods together to get the effect you want.
$("DIV").addClass("class-for-div")   //Will apply only to the DIV
        .children("UL")
        .addClass("class-for-ul");   //Will apply only to the UL children and not the DIV itself

A: Assuming you code line works correctly... But the only missing thing is a class to add to the ul...
Why not add it when you specify what to replaceWith()?
$(this).replaceWith($('

' + this.innerHTML + '

').addClass('card_tr'));

A: You may try this approach.
// Create temp variable that consist of div tag that is having 'firstClass' class and  ul with a class classed 'secondClass', then add existing html inside the element into ul tag.
var tmp = $('
').addClass('firstClass').append($('
').addClass('secondClass').html($(this).html()));

// Replace current html element with tmp variable above.
$(this).html(tmp);


text:
Q: Fourier Transform of $|f|$ I take the definition of the Fourier transform of $f \in L^2 (\mathbb{R}^3)$ to be
$$ \widehat{f} (k) = \int\limits_{\mathbb{R}^3} e^{-2 \pi i k \cdot x} f(x) dx $$
Question: Can we say anything useful about $\widehat{|f|}$ in terms of $\widehat{f}$?


text:
Q: Binding JQ grid with XML response coming from VB6 dll I want to bind the JQgrid (in a Classic ASP page) with XML response I am getting from a VB6 COM .dll. All attempts to do so has failed so far unfortunately. I'd highly appreciate any help on this matter. Here is the that I have in my classic ASP page. All of the code is in one single .ASP file.
$(function () {
    jQuery("#grid_top").jqGrid({
        datatype: 'xmlstring',
        datastr: strResponse, //
        pager: '#pager',
        height: 250,
        colNames:['Order ID','Segment', 'Terminal','Product','Delivered','Customer','Gross','Manifest ID','Notes'],
        colModel:[
            {name:'OrderID',index:'orderId', width:100, xmlmap: function (obj) {
                    return $(obj).attr('OrderId');}},
            {name:'Segment',index:'segment', width:60, xmlmap: function (obj) {
                    return $(obj).attr('RouteSegment');}},
            {name:'Terminal',index:'terminal', width:100, xmlmap: function (obj) {
                    return $(obj).attr('TerminalId');}},
            {name:'Product',index:'product', width:80, align:"right",xmlmap:  function (obj) {
                    return $(obj).attr('ProductId');}},
            {name:'Delivered',index:'delivered', width:100, align:"right", xmlmap: function (obj) {
                    return $(obj).attr('DeliveredTimestamp');}},
            {name:'Customer',index:'customer', width:150,align:"right", xmlmap: function (obj) {
                    return $(obj).attr('Customer');}},
            {name:'Gross',index:'gross', width:100, xmlmap: function (obj) {
                    return $(obj).attr('Gross');}},
            {name:'Manifest ID',index:'gross', width:100,
                        xmlmap: function (obj) {
                     return $(obj).attr('ManifestId');}},
            {name:'Notes',index:'note', width:150, sortable:false}
        ],
        xmlReader: { root: "Data", row: "Row", repeatitems: false },
        multiselect: true,
        caption: "Deliver Orders for Route:"
    });
});

Here is the code which is calling COM method
<%
Dim strRequest :strRequest = "<?xml version= ""1.0"" encoding= ""iso-8859-1"" ?>"
strRequest = strRequest & " METHOD='FetchOrder'/>"

objMSXML1.async = False
objMSXML1.validateOnParse = True
objMSXML1.setProperty "SelectionLanguage", "XPath"
objMSXML1.loadXML strRequest

strResponse = objManifest1.XMLDriver(CStr(strConnectionString1), objMSXML1.xml)
%>

XML Format in (strResponse)
<?xml version='1.0' encoding='utf-8'?>
<Data>
  <Row OrderId="1" DeliveredTimestamp="6/25/2015 9:27:00 AM" RouteSegment="1" TerminalId="71" Customer="CONSTRUCTION" ProductId="SOU85" Gross="189.7" ManifestId="qw" />
  <Row OrderId="2" DeliveredTimestamp="6/25/2015 10:55:00 AM" RouteSegment="1" TerminalId="71" Customer="DONALD" ProductId="12" Gross="197.7" ManifestId="qw3" />
  <Row OrderId="3" DeliveredTimestamp="6/25/2015 6:46:00 AM" RouteSegment="1" TerminalId="71" Customer="MRS GERALD" ProductId="12" Gross="200" ManifestId="nbvn3" />
</Data>

I am getting the XML response back from the COM method but I don't know how to bind this XML string to the JQGrid. What am I doing wrong here ? Highly appreciate any input...


text:
Q: Upload photo to facebook from app How to upload photo to facebook wall from within an app ? I have seen lot of examples but they only give the call function for url. I have downloaded facebook framework but i am not sure how it works . I have seen sample codes from this framework but how to call the method to post the image to Facebook? Does anyone have complete code to upload the photo to FB ?
    -(void)postUserInformation:(id)sender
  {

    UIImage *tempImage = [UIImage imageNamed:@"house2.jpg"];

    NSData *data = UIImageJPEGRepresentation(tempImage, 1);

    NSMutableDictionary *params =
    [NSMutableDictionary dictionaryWithObjectsAndKeys:
     @"Testing Feed Dialog", @"name",
     @"Feed Dialogs are Awesome.", @"caption",
     @"Check out how to use Facebook Dialogs.", @"description",
     @"http://www.example.com/", @"link",
     data, @"picture",
     nil];

    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

    [[delegate facebook] dialog:@"feed"
           andParams:params
         andDelegate:self];
}

A: Hello please check out the below example of facebook in which you can find out how to share image on facebook here
just check the example in which you found the class HomeViewController in which find method -(void)postUserInformation:(id)sender the commented method will post local image and the running code will share server image.
let me know if you have any query

A: you can find information on that here
Facebook upload photo


text:
Q: Como separa em duas colunas no pandas com \n import pandas as pd

test = pd.read_csv("1.csv")

df = pd.DataFrame(test)

print(df.head())

new = df["Nome"].str.split("\n", n=-1)

df["PT"] = new[0]
df["EN"] = new[1]

df.drop(columns=["Nome"], inplace=True)

print(df.head())

O arquivo "1.csv" esta:
,Nome,Valor
0,['Banimenton\nBanishment'],"['R$ 0,49']"
1,['Anjos de Batalha de Tyr\nBattle Angels of Tyr'],"['R$ 2,22']"
2,"[""Fogo-fátuo Atrativo\nBeckoning Will-o'-Wisp""]","['R$ 94,75']"
3,"[""Hipogrifo Abençoado // Benção de Tyr\nBlessed Hippogriff // Tyr's Blessing""]","['R$ 169,75']"
4,['Contrabandear Gado\nContraband Livestock'],"['R$ 12,25']"
5,['Dragão de Cristal // Roubar o Tesouro\nCrystal Dragon // Rob the Hoard'],"['R$ 0,43']"
6,['Fazer um Acordo\nCut a Deal'],"['R$ 0,24']"

A: Ao ler o arquivo CSV, as colunas Nome e Valor serão do tipo objeto e cada célula do tipo string.
Tendo o exemplo de arquivo do post, a solução mais simples seria:
df["PT"] = df["Nome"].apply(lambda x: x[2:-2].split("\\n")[0])
df["EN"] = df["Nome"].apply(lambda x: x[2:-2].split("\\n")[1])

Repare que x[2:-2] remove [' do inicio e '] do fim.


text:
Q: Strip Values From Post in Nested Loop I have a function that is used for dynamically building an update query that works by having a manually created form with fields that match the names of the table columns, then building the query based on the field names and values being submitted. However I have come across an instance where certain posted fields must be filtered out. I can do it easily if done manually but I am trying to make it work when the number of columns to remove, which are fed in as an array, are not necessarily known in advance.
For example, if I use this in place of one of the foreach loops below, it works:
$FieldName = array_values($Date1Name);
// Remove $Date1Name submit values
if ($key == $FieldName[1]) continue;
if ($key == $FieldName[2]) continue;
if ($key == $FieldName[3]) continue;

but I am trying to do it dynamically similar to the following. Note that in this case, the first value of the array must not be removed as it is the actual field name but in the second foreach loop, all are to be removed. Any ideas?
function formProcess($ID,$DBName,$TableName,$PassName,$Date1Name,$Date2Name,$RemoveFields,$insertGoTo) {
    $Values = array();
    // Update record
    if (isset($_POST["update"])) :
        unset($_POST['update']);
        foreach ($_POST as $key=>$value ) :

            if (is_array($Date1Name)) :
                // ARRAY EXAMPLE
                //$Date1Name = array("StartDate","month1","day1","year1");
                $Field1Name = array_values($Date1Name);

                foreach($Date1Name as $keyrm) :
                    if ($keyrm !== 0 && $key == $Field1Name) continue;
                endforeach;
            endif;

            if (is_array($RemoveFields)) :
                // Remove certain fields from POST using $RemoveFields array values
                // ARRAY EXAMPLE
                //$RemoveFields = array("ID","EndName");
                $FieldRemoved = array_values($RemoveFields);

                foreach($RemoveFields as $keyrm) :
                    if ($keyrm == $FieldRemoved) continue;
                endforeach;
            endif;

            $Values[] = "`$key`=".isNull($value, $DBName);
        endforeach;
        $sqlUpdate = "UPDATE $TableName SET ".implode(",",$Values)
                    ." WHERE ID='".intval($ID)."'";
        DBConnect($sqlUpdate, "Update", $DBName);
        if ($insertGoTo) :
            Redirect(sprintf('%s', $insertGoTo."?ID=".intval($ID)));
        endif;
    endif;
}

A: I have done a similar task in the past, perhaps it will give you some idea(s). This is assuming you are using mysql, if not, the filter may need some degree of manual handling.
1) Create a function that will extract the fields from the table. I have a class that I am feeding in which is labeled as $db. It will run my queries and return associative arrays:
function getFields($table,$db)
    {
        # Run the "describe table" query
        $fields =   $db->query("describe {$table}")->getResults();
        # Extract just the field names from the rows
        foreach($fields as $row) {
            $val[]  =   $row['Field'];
        }
        # Send back the field names
        return $val;
    }

Here is what the above function would return on a simple user table:
Array
(
    [0] => ID
    [1] => username
    [2] => password
    [3] => first_name
    [4] => last_name
    [5] => email
    [6] => country
    [7] => usergroup
    [8] => user_status
    [9] => timestamp
)

2) Next create the filtering function. I would send back a bind array as well, I am using PDO here as my end database, not sure which library you are using.
function filterArray($array,$filter = array())
    {
        $bind   =
        $cols   =   array();

        if(!is_array($filter))
            $filter =   array();

        foreach($array as $key => $value) {
            if(!empty($filter) && !in_array($key, $filter))
                continue;
            $bKey           =   ":{$key}";
            $bind[$bKey]    =   $value;
            $cols[]         =   $key;
        }

        return array(
            'columns'=>$cols,
            'bind' => $bind
        );
    }

3) Make the update function. I have made it simple, you can make it as complex as you need it.
# The first is the filtered array, the $where is which key to update on,
# the $table is obvious, the $op is the operator which could be substituted for
# LIKE or !=
function getUpdateStatement($array,$where,$table,$op = '=')
    {
        # Start off the statement
        $sql['update'][]    =   "UPDATE {$table} SET";
        # Combine and loop the keys/values and assign the WHERE anchor as well
        foreach(array_combine($array['columns'],array_keys($array['bind'])) as $col => $bind) {
            if($col == $where)
                $sql['where'][] =   "WHERE `{$col}` {$op} {$bind}";
            else
                $sql['cols'][]  =   "`{$col}` = {$bind}";
        }
        # Create the statement from the parts
        $statement  =   implode(' ',$sql['update']).' '.implode(", ",$sql['cols']).' '.implode(" AND ",$sql['where']);
        # Send back statement
        return $statement;
    }

To use:
# Get all the columns from the table
$filter = getFields('users',$queryEngine);
# Let's pretend the is a actually your $_POST array...
$POST   =   array(
    'ID' => 123,
    'first_name' => 'John',
    'last_name' => 'Doe',
    'email' => 'test@best.com',
    'update' => 'SAVE',
    'action' => 'update_my_stuff',
    'token' => 'aB23As753hedD6baC213Dsae4'
);
# Create the filtered array
$filtered = filterArray($POST,$filter);
# Create the statement
echo getUpdateStatement($filtered,'ID','user');

This above statement will read:
UPDATE users SET `first_name` = :first_name, `last_name` = :last_name, `email` = :email WHERE `ID` = :ID

Remember the bind values are in the $filtered['bind'] array. Hopefully this is what you are kind of looking for or that it will maybe give you some ideas.

A: Working now and updated to handle Insert, Update and Delete operations. I decided that I couldn't have separate functions for the update and insert query building due to the need for some special field processing so I moved the functionality back into the main formProcess() function. I did need to filter out certain fields rather than say which fields to keep so came up with a way to do that using a combination of array_diff_key() and array_flip() which seems to do the trick. This provides an array of all the fields to be processed. The main reason for this is to filter out day, month and year selectors, then process them into a single field:
$filteredarray = array_diff_key($_POST, array_flip($RemoveFields));
I am sure that some of the programmers here can really simplify this code but here it is as it now stands with some annotations to say what does what. I hope it helps someone!
function formProcess($ID,$DBName,$TableName,$PassName,$Date1Name,$Date2Name,$RemoveFields,$insertGoTo) {
    // Insert record
    if (isset($_POST["insert"])) :
        unset($_POST["insert"]);
        // Remove unneeded fields from $RemoveFields variable
        if (!is_array($RemoveFields)) $RemoveFields = array($RemoveFields);
        $filteredarray = array_diff_key($_POST, array_flip($RemoveFields));
        // Build the INSERT query
        foreach($filteredarray as $col => $val) :
            // Process Password field
            if ($PassName) :
                // Encode password field
                if ($col == $PassName && $val != "") $val=md5($val);
                // If no changes, save original password
                if ($col == $PassName && $val == "") continue;
            endif;
            // Process Date/Time fields using custom dateProcess()
            if (is_array($Date1Name)) :
                $pieces1 = $Date1Name;
                if ($col == $pieces1[0]) $val = dateProcess($Date1Name);
            endif;
            if (is_array($Date2Name)) :
                $pieces2 = $Date2Name;
                if ($col == $pieces2[0]) $val = dateProcess($Date2Name);
            endif;
            $Fields[] = "`$col`";
            $Values[] = isNull($val, $DBName);
        endforeach;

        $sqlInsert = "INSERT INTO $TableName (".implode(",",$Fields).")
                      VALUES (".implode(",",$Values).")";

        // Custom function to process the INSERT query
        $InsertID = DBConnect($sqlInsert, "Insert", $DBName);
        if ($insertGoTo) :
            Redirect(sprintf('%s', $insertGoTo."?ID=".intval($InsertID)));
        endif;
    // Update record
    elseif (isset($_POST["update"])) :
        unset($_POST['update']);
        // Remove unneeded fields using array $RemoveFields variable
        if (!is_array($RemoveFields)) $RemoveFields = array($RemoveFields);
        $filteredarray = array_diff_key($_POST, array_flip($RemoveFields));
        // Build the UPDATE query
        $count = 0;
        $fields = '';
        $Where = '';
        foreach($filteredarray as $col => $val) :
            if ($count++ != 0 && $col != "ID") $fields .= ', ';
            if ($col == "ID") :
                $Where = " WHERE `$col` = " . intval($val);
            else :
                // Process Password field
                if ($PassName) :
                    // Encode password field
                    if ($col == $PassName && $val != "") $val=md5($val);
                    // If no changes, save original password
                    if ($col == $PassName && $val == "") continue;
                endif;
                // Process Date/Time fields
                if (is_array($Date1Name)) :
                    $pieces1 = $Date1Name;
                    // Process first Date/Time field using custom function
                    if ($col == $pieces1[0]) $val = dateProcess($Date1Name);
                endif;
                if (is_array($Date2Name)) :
                    $pieces2 = $Date2Name;
                    // Process second Date/Time field using custom function
                    if ($col == $pieces2[0]) $val = dateProcess($Date2Name);
                endif;
                // Build the UPDATE query
                $val = isNull($val, $DBName);
                $fields .= "`$col` = $val";
            endif;
        endforeach;

        $sqlUpdate = "UPDATE $TableName SET $fields $Where";

        // Custom function to process the INSERT query
        DBConnect($sqlUpdate, "Update", $DBName);
        if ($insertGoTo) :
            Redirect(sprintf('%s', $insertGoTo."?ID=".intval($ID)));
        endif;
    // Delete record
    elseif (isset($_POST["delete"])) :
        // Build the DELETE query
        $sqlDelete = "DELETE FROM $TableName WHERE ID=".intval($ID);
        // Custom function to process the DELETE query
        DBConnect($sqlDelete, "Delete", $DBName);
        if ($insertGoTo) :
            Redirect(sprintf('%s', $insertGoTo));
        endif;
    elseif (isset($_POST["clear"])) : // NOT CURRENTLY FUNCTIONAL
        foreach ($_POST as $key=>$value) :
            if ($key == 'clear') continue;
            if (trim($key)) :
                $key = "";
                $value = "";
            endif;
            if (isset($_POST[$key])) :
                unset($key);
            endif;
        endforeach;
    endif;
}


text:
Q: Setting up Ruby along with android in docker I have an issue while setting up docker container with android and ruby environment to run calabash test. I have this docker file for the android part. Whenever I am editing the docker file to install the latest version of ruby and for calabash just like below code
RUN gem install calabash-android

I am getting error just like

/bin/sh: 1: gem: not found
  The command '/bin/sh -c gem install calabash-android' returned a non-zero code: 127

And after that I have tried
FROM tracer0tong/android-emulator

FROM ruby:2.3.0

RUN gem install calabash-android

like syntax to check whether it is gonna work and seems like not. Is there any way to install both?

A: The reason you're getting an error is that the Android Docker image you're using does not have Ruby installed (rightly so).
And this Github issue expains why multiple FROM directives in one Dockerfile is not a good idea.
IMO your best bet would be to see how Ruby is installed in the Ruby Docker image and copy that over into your Dockerfile that builds off of the Android image. Or vice versa - whichever is less effort.


text:
Q: Understanding behavior of program I'm running the following program:
#include <unistd.h>
#include<time.h>
static void threadStart(void (*function)(void), void* arg) {
    // schedules thread in Queue
    function(void* arg);
}

The compiler giving me two errors:
In function 'threadStart':
sample.c:5:11: error: expected expression before 'void'
 function(void* arg);
       ^
 sample.c:5:11: error: too many arguments to function 'function'

How pass a function to run with a given argument without raising errors?

A: I had started to write-up an answer, that I just deleted that suggested this is what you wanted:
static void threadStart(void (*function)(void*), void* arg) {
    // schedules thread in Queue
    function(arg);
}

But then I looked at what you are trying to do with a function pointer, that nearly resembles a pthread_create start routine.
So it didn't make sense that you've got a function called threadStart that neither starts a thread nor appears to be the start routine for a thread.  I could be wrong, because we don't see anything else in your code that suggests how threadStart is invoked.
So I was wondering if this is what you really meant, a function to be run within a thread:
void* threadStart(void* arg)
{
    someOtherCodeOrFunction(arg); // your code goes here
}

And you meant to instantiate that thread to run that above function with arg as the parameter value:
pthread_create(&thread, NULL, threadStart, arg);


text:
Q: PHP Strict Standards: Creating default object from empty value I have following setup.
index.php
   require_once "common.php";
   ...

common.php
   ...
   $obj = new MyClass;
   require_once "config.php"
   ...

config.php
   ...
   require_once "settings.php";
   ...

settings.php
   $obj->dostuff = true;
   ...

When i open index.php i get: Strict Standards: Creating default object from empty value in settings.php on 3
If i put $obj->dostuff = true; inside config.php it does not produce error message.
Can someone explain why i get this error? I am not asking how to fix it just understand why.
EDIT: My bad i had 2 config.php classes for each part of site and i only changed something in one of them leaving old include order in another now it works fine after it all loads in correct order.

A: It looks a scope issue. In settings.php, the $obj is not accessible. PHP is creating new one from standard class, and giving you a warning. You can confirm it by putting
echo get_class($obj);

in Your settings.php, just after the line that is producing the error. If it echos "StdClass", then that is the case.
Are You sure the $obj is not created within a function/method ?

A: If $obj is meant to be a system wide globally accessible object, you can you use the singleton pattern to access from anywhere:
class MyClass
{
    protected static $_instance;

    static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

You can then create your methods in this class.  To get the object itself simply call:
$obj = MyClass::getInstance();

Additionally, if you just want to call one of its methods but theres no need to return anything:
MyClass::getInstance()->objectMethod();

I find this to be a very efficient way to organize integral singleton based system wide operations.
In practice, my project uses this to get configuration from anywhere in the system:
class syConfig
{
    protected static $_instance;

    private $_config;

    static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function load($xmlString)
    {
        $xml = simplexml_load_string($xmlString);
        $this->_config = $xml;
    }

    public function getConfig()
    {
        return $this->_config;
    }
}


text:
Q: String was not recognized as a valid DateTime in vb.NET I've got this error that said String was not recognized as a valid DateTime, can anyone help me what's wrong here?
Dim Br As New BL.Bridge
    Me.DataSource = Br.List(DateTime.ParseExact(Me.txtTempo.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture)) 'error  is right here
    Me.ReportPath = "~/report/JaTem.rpt"
    Me.HasPrintButton = True
    Me.ShowGroupTree = False
    If DataSource.Rows.Count > 0 Then
        Me.HasPrintButton = True
        Server.Transfer("~/report/rpt.aspx")
    Else
        lblMessage.Text = "No Data!"
    End If

if txtTempo is filled with date it's work, but when txtTempo is empty, it's getting error

A: The DateTime.ParseExact method that you are using will give an error when it runs into data that it can't handle. You need to do one of 3 things,

*

*validate the data before using the ParseExact method

*use exception handling to catch the error and notify your user

*or you can use the DateTime.TryParseExact which will give you a Boolean result to indicate if the method succeeded. You would use it something like this.:

Imports System.Globalization

Module Module1
    Sub Main()
        Dim Date1Data As String = ""
        Dim Date2Data As String = "25-09-2015"
        Dim result As DateTime
        If DateTime.TryParseExact(Date1Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
            'handle it here
        Else
            Console.WriteLine("Format Error")
        End If

        If DateTime.TryParseExact(Date2Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
            Console.WriteLine(result) 'handle it here
        Else
            Console.WriteLine("Format Error")
        End If
        Console.ReadLine()
    End Sub

End Module

or modifying your code something like this should work.
Dim Br As New BL.Bridge
Dim result as Date

If DateTime.TryParseExact(Me.txtJatem.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
    Me.DataSource = Br.List(result) 'error  is right here
    Me.ReportPath = "~/report/JaTem.rpt"
    Me.HasPrintButton = True
    Me.ShowGroupTree = False
    If DataSource.Rows.Count > 0 Then
        Me.HasPrintButton = True
        Server.Transfer("~/report/rpt.aspx")
    Else
        lblMessage.Text = "No Data!"
    End If
Else
    lblMessage.Text = "Format Error, please check input and try again"
End If


text:
Q: Optimal class weight for SVC? Hello I am working with sklearn to perform a classifier, I have the following distribution of labels:
label : 0 frecuency :  119
label : 1 frecuency :  1615
label : 2 frecuency :  197
label : 3 frecuency :  70
label : 4 frecuency :  203
label : 5 frecuency :  137
label : 6 frecuency :  18
label : 7 frecuency :  142
label : 8 frecuency :  15
label : 9 frecuency :  182
label : 10 frecuency :  986
label : 12 frecuency :  73
label : 13 frecuency :  27
label : 14 frecuency :  81
label : 15 frecuency :  168
label : 18 frecuency :  107
label : 21 frecuency :  125
label : 22 frecuency :  172
label : 23 frecuency :  3870
label : 25 frecuency :  2321
label : 26 frecuency :  25
label : 27 frecuency :  314
label : 28 frecuency :  76
label : 29 frecuency :  116

One thing that clearly stands out is that I am working with a unbalanced data set I have many labels for the class 25,23,1,10, I am getting bad results after the training as follows:
             precision    recall  f1-score   support

          0       0.00      0.00      0.00        31
          1       0.61      0.23      0.34       528
          2       0.00      0.00      0.00        70
          3       0.67      0.06      0.11        32
          4       0.00      0.00      0.00        62
          5       0.78      0.82      0.80        39
          6       0.00      0.00      0.00         3
          7       0.00      0.00      0.00        46
          8       0.00      0.00      0.00         5
          9       0.00      0.00      0.00        62
         10       0.14      0.01      0.02       313
         12       0.00      0.00      0.00        30
         13       0.31      0.57      0.40         7
         14       0.00      0.00      0.00        35
         15       0.00      0.00      0.00        56
         18       0.00      0.00      0.00        35
         21       0.00      0.00      0.00        39
         22       0.00      0.00      0.00        66
         23       0.41      0.74      0.53      1278
         25       0.28      0.39      0.33       758
         26       0.50      0.25      0.33         8
         27       0.29      0.02      0.03       115
         28       1.00      0.61      0.76        23
         29       0.00      0.00      0.00        42

avg / total       0.33      0.39      0.32      3683

I am getting many zeros and the SVC is not able to learn from several class, the hyperparameters that I am using are the followings:
from sklearn import svm
clf2= svm.SVC(kernel='linear')

I order to overcome this issue I builded one dictionary with weights for each class as follows:
weight={}
for i,v in enumerate(uniqLabels):
        weight[v]=labels_cluster.count(uniqLabels[i])/len(labels_cluster)

for i,v in weight.items():
        print(i,v)
print(weight)

these are the numbers and output, I am just taking the numbers of element of determinated label divided by the total of elements in the labels set, the sum of these numbers is 1:
0 0.010664037996236221
1 0.14472622994892015
2 0.01765391164082803
3 0.006272963527197778
4 0.018191594228873554
5 0.012277085760372793
6 0.0016130477641365713
7 0.012725154583744062
8 0.0013442064701138096
9 0.01630970517071422
10 0.0883591719688144
12 0.0065418048212205395
13 0.002419571646204857
14 0.007258714938614571
15 0.015055112465274667
18 0.009588672820145173
21 0.011201720584281746
22 0.015413567523971682
23 0.34680526928936284
25 0.20799354780894344
26 0.0022403441168563493
27 0.028138722107715744
28 0.006810646115243301
29 0.01039519670221346

trying again with this dictionary of weights as follows:
from sklearn import svm
clf2= svm.SVC(kernel='linear',class_weight=weight)

I got:
             precision    recall  f1-score   support

          0       0.00      0.00      0.00        31
          1       0.90      0.19      0.31       528
          2       0.00      0.00      0.00        70
          3       0.00      0.00      0.00        32
          4       0.00      0.00      0.00        62
          5       0.00      0.00      0.00        39
          6       0.00      0.00      0.00         3
          7       0.00      0.00      0.00        46
          8       0.00      0.00      0.00         5
          9       0.00      0.00      0.00        62
         10       0.00      0.00      0.00       313
         12       0.00      0.00      0.00        30
         13       0.00      0.00      0.00         7
         14       0.00      0.00      0.00        35
         15       0.00      0.00      0.00        56
         18       0.00      0.00      0.00        35
         21       0.00      0.00      0.00        39
         22       0.00      0.00      0.00        66
         23       0.36      0.99      0.52      1278
         25       0.46      0.01      0.02       758
         26       0.00      0.00      0.00         8
         27       0.00      0.00      0.00       115
         28       0.00      0.00      0.00        23
         29       0.00      0.00      0.00        42

avg / total       0.35      0.37      0.23      3683

Since I am not getting good results I really appreciate suggestions to automatically adjust the weight of each class and express that in the SVC, I don have many expierience dealing with unbalanced data.

A: A possible solution to your question is answered here: A priori selection of SVM class weights , which suggest a weight inverse proportional to the class size.
Whereas I do not know how to determine the best possible weights unless repeatedly trying out several possible combinations, I still want to answer the underlying question: How to improve the performance in this problem?
Firstly, it seems that you are not determining the parameters of the classifer by crossvalidation (see "model selection" in scikit-learn). This could account for a terrible result already. Tweaking parameters is crucial. For example you could use SVC with rbf kernel and compare results.
Secondly, you might want to use other classifiers before you start optimizing. Unless you have specific research interest in SVC with linear kernel, you should look at other classifiers as well.
Thirdly, I recommend to look into boosting. Using boosting means repeatedly building a classifier, where those datapoints which are wrongly classified get a high weight regarding the loss function.

A: If you are not getting good results, you should first check that you are using the right classification algorithm (is your data well fit to be classified by a linear SVM?) and that you have enough training data.
Practically, that means you might consider visualizing your dataset through PCA or t-SNE to see how "clustered" your classes are, and checking how your classification metrics evolve with the amount of data your classifier is given.
If you then confirm that investing in tweaking your linear SVM is the right way to approach your problem, you can look at modifying the class weights. Note then that what you suggest as weights is probably the opposite of what you want to do: you are giving more weights to less frequent classes, marginalizing them further - said differently, you typically want to use weights that are inversely proportional to class frequencies. You can calculate these manually, or you can let sklearn do it automatically for you by specificing class_weight='balanced'.

A: I recommend you to use RBF kernel, followed by hyperparameter tuning of C and gamma. Linear kernel is not recommended when you have many labels.


text:
Q: How can I return the data inside html using json encode and ajax I'm trying to display data from my database using JSON and ajax, but i'm having difficult on how perform that. Help please, Thanks.
//my js function
function show_messages(){
     $.ajax({
         url: "display_table.php",
         cache: false,
         success: function(html){
             $("#table_content").html(html);
         }
     });
 }

 <?php

$query="SELECT * FROM comments ORDER BY id ASC";
$result = mysql_query($query);
if(isset($_REQUEST['AnswerId'])){ $AnswerId = $_REQUEST['AnswerId']; }
else {$AnswerId = 0; }

$i=0;
while ($mytablerow = mysql_fetch_row($result)){
$mytable[$i] = $mytablerow;
$i++;
}

function tree($treeArray, $level, $pid = 0) {
global $AnswerId;
if (! $treeArray)
{ return; }
     foreach($treeArray as $item){
    if ($item[1] == $pid){
        ?>
        <div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">

<?php echo($item[2]) ; ?>

<?php echo($item[3]) ; ?>

<?php echo($item[4]) ; ?>

        <?php
if ($level<=10)
{ echo 'Reply'; }
echo 'Delete';
        ?>
 <?php

        if ($AnswerId == $item[0]){
            ?>
<?php
            ShowForm($AnswerId);
            ?>
<?php
        }

        ?>
 <?php
        echo ('
');
        tree($treeArray, $level+1, $item[0]);
    }
} }
tree($mytable, 0);
?>


text:
Q: How to imperatively assign a prop to a React component? How do I imperatively add a prop to a component (without using the component tag?)
When I try this:
component.props.onChange = onChange;

I get the following error.

TypeError: Cannot assign to read only property 'onChange' of object '#'

Here is some more of my code for context.

FormTemplate.js

const getComponent = ( onChange, component, ) => {
  component.props.onChange = onChange; // this line throws the error
  return component;
}

const FormTemplate = ({ fields, onChange, }) => {
  // ...
  return (

      {
        fields.map( ({ component, ...rest, }) =>
          ( component && (rest.type === 'component') )
          ?
          getComponent(onChange, component,)
          :
          getTextField(onChange, rest,)
        )
      }

  );
}

AppConfig.js

const formFieldConfig = {
  zip: {
    type: 'component',
    label: 'Zip code',
    icon: 'place',
    component: <ZipCodeInput />,
  },
}

A: Just like the error says, you can't mutate the props you get directly.
The only way to update the props of a component is to clone the element and add/update props to the cloned element.
const getComponent = ( onChange, component, ) =>
  React.cloneElement(component, { onChange })

A: There's another way you can approach this that will keep your code in the context of components (instead of creating the getComponent helper function, which adds some indirection), and will probably be clearer to other developers working with this code in the future:
const formFieldConfig = {
  zip: {
    type: 'component',
    label: 'Zip code',
    icon: 'place',
    component: ZipCodeInput, // <-- Don't create an element yet
  },
}

const FormTemplate = ({ fields, onChange, }) => {
  // ...
  return (

      {
        fields.map(({ component, ...rest, }) => {
          const Component = (component && (rest.type === 'component'))
            ? component
            : textField // <-- Assuming this is also a React component

          return <Component onChange={onChange} {...rest} />
        })
      }

  );
}

It's hard to know for sure that this will work with TextField without seeing the code, but it shouldn't be hard to get it working with getTextField as well.


text:
Q: mysql create federated all table in database or federated database I want to federated all tables from database or federated database.
Can I do that in mysql?
The thing is, I have mysql events at night in server A but for some reason that events weren't finished yet in the morning (It should finished).
So, to make the events faster I want to split the events into other server and that will process some events in server A and some events in server B.
Since, my data is only updated in server A (primary), then I should federated the table from server A to Server B so the server B can process some of the events and give the data back to the server A.
I've tried one federated table and it works, but can I just federated the database or all the tables in a fast or easier way beside create federated table one by one?
Anyone can help me?
Thanks I really appreciate that.

A: You are probably looking for MySQL Clustering: http://www.mysql.com/products/cluster/


text:
Q: Hago click en 'Submit' y el item se incluye en el array, pero no aparece en pantalla (React JS) Estoy realizando una ToDo app, la cual lleva incluido el feature Drag and Drop.
La cuestión es que la aplicación en sí funciona bien, y cada vez que en la barra de input introduzco una tarea y le doy Submit, puedo ver en la Consola que se está añadiendo al Array correspondiente (el de Todo)
Sin embargo, aunque se añade al array, no llego a verlo en pantalla y no sé bien cómo solucionarlo.
Os dejo una captura de cómo lo veo, y debajo el código de la App (y el código del componente que lleva incluido):

Código de la aplicación:
import React from 'react';
import { useState } from 'react';

import nextId from 'react-id-generator';
import { DragDropContext, Droppable, Draggable } from '@hello-pangea/dnd';
import _ from 'lodash';

import TodosList from '../todo/todos-list';

export default function Todos() {

    const [title, setTitle] = useState("");
    const [todos, setTodos] = useState([]);
    const [state, setState] = useState({
        "todo": {
            title: "Todo",
            items: []
          },
          "in-progress": {
            title: "In Progress",
            items: []
          },
          "done": {
            title: "Completed",
            items: []
          }
        })

    function handleChange(e) {
        const value = e.target.value;

        setTitle(value)
    }

    function handleSubmit(e) {
        e.preventDefault();

        setState(prev => {
            return {
                ...prev,
                todo: {
                    title: "Todo",
                    items: [
                        {
                            id: nextId(),
                            title: title
                        },
                        ...prev.todo.items
                    ]
                }
            }
        })

        setTitle("");
    }

    function handleUpdate(id, value){
        const temp = [...todos];
        const item = temp.find((item) => item.id === id);
        item.title = value;
        setTodos(temp);
    }

    function handleDelete(id){
        const temp = todos.filter(item => item.id !== id );

        setTodos(temp);
    }

    function handleOnDragEnd() {
        (result) => {
            const { source, destination } = result;
            if (!destination) {
              return;
            }
            if (
              source.index === destination.index &&
              source.droppableId === destination.droppableId
            ) {
              return;
            }

            const itemCopy = {...state[source.droppableId].items[source.index]}

            setState(prev => {
            prev = {...prev}

            prev[source.droppableId].items.splice(source.index, 1)

            prev[destination.droppableId].items.splice(destination.index, 0, itemCopy)

            return prev
            });

        };
    };

    return (

Welcome to your To-Do App

            <form className='todo-form' onSubmit={handleSubmit}>
                <input
                    onChange={handleChange}
                    className='todo-input'
                    value={title}
                />
                <input
                    onClick={handleSubmit}
                    type="submit"
                    value= "Add"
                    className='btn-add'
                />
            </form>

            <DragDropContext onDragEnd={handleOnDragEnd}>
                {_.map(state, (data, item) => {
                    return (

{data.title}

                            <Droppable droppableId='todos'>
                                {(droppableProvided) => (

                                        {todos.map((item, index) => (
                                            <Draggable
                                            key={item.id}
                                            draggableId={item.id}
                                            index={index}>
                                                {(draggableProvided) => (

                                                        <TodosList
                                                        item={item}
                                                        onUpdate={handleUpdate}
                                                        onDelete={handleDelete}/>

                                                )}
                                            </Draggable>
                                        ))}
                                    {droppableProvided.placeholder}

                                )}
                            </Droppable>

                    )
                })}
            </DragDropContext>

    );
}

Y el código del componente TodoList:
import React from 'react';
import { useState } from 'react';

export default function TodosList({item, onUpdate, onDelete}) {

    const [isEdit, setIsEdit] = useState(false);

    function FormEdit() {

        const [newValue, setNewValue] = useState(item.title);

        function handleSubmit(e) {
            e.preventDefault();
        }

        function handleChange(e) {
            const value = e.target.value;
            setNewValue(value);
        }

        function handleClickUpdate() {
            onUpdate(item.id, newValue);
            setIsEdit(false);
        }

        return  <form className='form-edit' onSubmit={handleSubmit}>
                    <input type="text" className='todo-input' onChange={handleChange} value={newValue}/>
                    <button className='btn-update' onClick={handleClickUpdate}>Update</button>
                </form>
    };

    function TodoElement() {
        return

                    {item.title}

                    <button className='btn-edit' onClick={() => setIsEdit(true)}> Edit </button>
                    <button className='btn-delete' onClick={(e) => onDelete(item.id)}> Delete </button>

    }

    return (

            {isEdit ? <FormEdit /> : <TodoElement />}

    );
}

A: Te falta envolver el componente <Draggable> que devuelve el map todos.map((item, index) => (
con un return()
Ya que no estas retornando el resultado de la funcion map
{todos.map((item, index) => (
return( // agrego esto
 <Draggable
   key={item.id}
   draggableId={item.id}
   index={index}>
    {(draggableProvided) => (

        <TodosList
          item={item}
          onUpdate={handleUpdate}
          onDelete={handleDelete}/>

    )}
  </Draggable>
 ) // y agrego esto
))}


text:
Q: Mongodb assertion 28616 "Runner killed during find" I am running a NodeJS script that connects to my Mongo Oplog to watch the deltas.  Periodically, I get the following Mongo error:
assertion 28616 Runner killed during find ns:local.oplog.rs query:{ orderby: { $natural: 1 }, $query: { ns: "Foo", ts: { $gt: Timestamp 1467969843000|2841 } } }

I have looked around in the documentation and such and have not found anything to direct me on how to resolve the issue, and avoid getting this error from time to time.  Anyone else out there seen this?


text:
Q: Kotlin - generate toString() for a non-data class Situation:
I have a class with lateinit fields, so they are not present in the constructor:
class ConfirmRequest() {
    lateinit var playerId: String
}

I'd like to have a toString() method with all fields and don't want to write it manually, to avoid boiler print. In Java I'd use the Lombok @ToString annotation for this problem.
Question:
Is there any way to implement it in Kotlin?

A: This is what I endup doing.
Create extension function on Any class
fun Any.toStringByReflection(exclude: List<String> = listOf(), mask: List<String> = listOf()): String {
    val propsString = this::class.memberProperties
            .filter { exclude.isEmpty() || !exclude.contains(it.name) }
            .joinToString(", ") {
                val value = if (!mask.isEmpty() && mask.contains(it.name)) "****" else it.getter.call(this).toString()
                "${it.name}=${value}"
            };

    return "${this::class.simpleName} [${propsString}]"
}

Then you can call this method from individual type.
override fun toString(): String {
    return this.toStringByReflection()
}

It generates string below
Table [colums=[], name=pg_aggregate_fnoid_index, schema=pg_catalog, type=SYSTEM INDEX]

With name field masked:
override fun toString(): String {
    return this.toStringByReflection(mask= listOf("name"))
}

It generates,
Table [colums=[], name=****, schema=pg_catalog, type=SYSTEM INDEX]

A: The recommended way is to write toString manually (or generate by IDE) and hope that you don't have too many of such classes.
The purpose of data class is to accommodate the most common cases of 85%, which leaves 15% to other solutions.

A: I find Apache Commons Lang's ToStringBuilder with reflection useful, but it calls hashCode() and other methods when I don't need that (and one called hashCode() from a 3rd-party lib generates an NPE).
So I just go with:
// class myClass
    override fun toString() = MiscUtils.reflectionToString(this)

// class MiscUTils
fun reflectionToString(obj: Any): String {
    val s = LinkedList<String>()
    var clazz: Class<in Any>? = obj.javaClass
    while (clazz != null) {
        for (prop in clazz.declaredFields.filterNot { Modifier.isStatic(it.modifiers) }) {
            prop.isAccessible = true
            s += "${prop.name}=" + prop.get(obj)?.toString()?.trim()
        }
        clazz = clazz.superclass
    }
    return "${obj.javaClass.simpleName}=[${s.joinToString(", ")}]"
}

A: Like you, I was used to using lombok for toString() and equals() in Java, so was a bit disappointed that non-data classes in Kotlin required all of the standard boilerplate.
So I created Kassava, an open source library that lets you implement toString() and equals() without any boilerplate - just supply the list of properties and you're done!
e.g.
// 1. Import extension functions
import au.com.console.kassava.kotlinEquals
import au.com.console.kassava.kotlinToString

import java.util.Objects

class Employee(val name: String, val age: Int? = null) {

    // 2. Optionally define your properties for equals()/toString() in a  companion
    //    object (Kotlin will generate less KProperty classes, and you won't have
    //    array creation for every method call)
    companion object {
        private val properties = arrayOf(Employee::name, Employee::age)
    }

    // 3. Implement equals() by supplying the list of properties to be included
    override fun equals(other: Any?) = kotlinEquals(
        other = other,
        properties = properties
    )

    // 4. Implement toString() by supplying the list of properties to be included
    override fun toString() = kotlinToString(properties = properties)

    // 5. Implement hashCode() because you're awesome and know what you're doing ;)
    override fun hashCode() = Objects.hash(name, age)
}

A: You can define a data class that contains the data that you want to use and implement methods by delegating to that.
https://stackoverflow.com/a/46247234/97777

A: What about using Kotlin reflection? I am into Kotlin for a few days, so apologies, if I misunderstood question, or wrote "Kotlin inefficient" example.
override fun toString() : String{
    var ret : String = ""
    for (memberProperty in this.javaClass.kotlin.memberProperties){
        ret += ("Property:${memberProperty.name} value:${memberProperty.get(this).toString()}\n");
    }
    return ret
}

This can also could be implemented in newly created interface for example ToString2Interface as fun toString2. Then all classes which implements ToString2Interface would have toString2()


text:
Q: ValueError: The file could not be found with  I'm trying to compile SASS and compress CSS files with django pipeline on Django 1.6.3, but I get the following error after visiting my site:

ValueError: The file 'css/test2.css' could not be found with <pipeline.storage.PipelineCachedStorage object at 0x0585DF50>.

I configured pipeline following the guide on readthedocs.org: I added pipeline to INSTALLED_APPS then I defined STATIC_URL and STATIC_ROOT:
STATIC_URL = '/test/forum/skins/default/media/'
STATIC_ROOT = '/test/forum/skins/default/media/'

Folders tree:

*

*test

*

*forum

*

*skins

*

*default

*

*media (static files)

*

*css

*js

*images

*site1

*site2

*site3

*views

*utils

*settings.py

I added SASSCompiler to PIPELINE_COMPILERS and then I added the path to the file to be compressed:
# pipeline settings
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
PIPELINE_COMPILERS = (
  'pipeline.compilers.sass.SASSCompiler',
)
PIPELINE_CSS = {
    'main': {
        'source_filenames': (
          'css/test.scss',
        ),
        'output_filename': 'css/test2.css',
    },
}

Finally I linked the css to my XHTML index:
{% load compressed %}
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        {% compressed_css 'main' %}
    </head>

I do not understand what I did wrong.
Thanks for any help!

UPDATE:
When I run collectstatic this copy the files from django and not from my project
F:\DEV\DJANGO\apps\test>python manage.py collectstatic

You have requested to collect static files at the destination
location as specified in your settings:

    F:\test\forum\skins\default\media

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\base.
css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\chang
elists.css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\dashb
oard.css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\forms
.css'
Copying 'F:\DEV\DJANGO\apps\django\django\contrib\admin\static\admin\css\ie.cs
s'
[etc .... ]

But the path F:\test\forum\skins\default\media is wrong, my project is located
in F:\DEV\DJANGO\apps\test\forum\skins\default\media.
Then I tried to find the static file:
F:\DEV\DJANGO\apps\test> python manage.py findstatic css/main.css

No matching file found for 'css/main.css'.

But the file exists.

A: In Django's settings.py, the STATIC_ROOT variable tells Django where to move your static files, whereas STATIC_URL is the URL path that users will see and from where you can access the files within the browser. See the Django documentation on static files:
https://docs.djangoproject.com/en/dev/ref/settings/#static-files
For example, lets's say you have the following in your settings.py file:
STATIC_ROOT = "/var/www/example.com/static/"
STATIC_URL = "/static/"

Now, let's you are doing your software development on the same machine within /home/fuiba/git/your-django-project/. Within your Django project you have a sub-directory called static, and within that directory you have a file called custom.css. The full path to this file is:
`/home/fuiba/git/your-django-project/static/custom.css`

Now, after running python manage.py collectstatic your style sheet is moved to your STATIC_ROOT directory. Now you start the web server and you can access the static file via the project's STATIC_URL. So, let's assume you run the web server on the localhost on port 8000, you can access the stylesheet from your browser at the following location:
http://localhost:8000/static/custom.css

Ok, that's the foundation for how it works. In your case, you appear to be developing under Windows, so there's a few caveats. First, don't use backslashes ('\') in your paths, use only forward slashes. However, you still must specify the drive letter and colon. So, let's set your STATIC_ROOT to:
STATIC_ROOT = "F:/DEV/DJANGO/apps/test-static-root/"

I'm choosing this so you don't pollute your test project directory, and a sibling directory should be created in the above location with your static files within.
Let me know how you get along, and I'll try to provide more details.
Good luck!


text:
Q: jQuery / JavaScript incrementing value on click I want to make multiple divs appear in a defined time and when I click it, gives 300 Points (value), it starts with a value of 0 (punctuation) and triggers a function when the page is ready

var puntuacion = 0;
$(document).ready(function() {
  FadeDiv();

  function FadeDiv() {
    var posx = Math.floor(Math.random() * 300);
    var posy = Math.floor(Math.random() * 300);
    $newdiv = $("

").css({
      'left': posx + 'px',
      'top': posy + 'px'
    });
    $newdiv.appendTo('body').fadeIn(1000).delay(1000).fadeOut(1000, function() {
      FadeDiv();
    });
  }
  $("#Points").text(puntuacion);
  $("#circle-green").click(function() {
    $(this).remove();
    puntuacion+=300;
    $("#Points").text(puntuacion);
  });

  setTimeout(FadeDiv, 1000);
  setTimeout(FadeDiv, 500);
  setTimeout(FadeDiv, 100);
});
body {
  background-color: #000;
  color: #FFF;
  font-family: Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-size: 14px;
}
#circle-green {
  width: 50px;
  height: 50px;
  position: absolute;
  display: none;
  background-color: #00ff00;
  -webkit-border-radius: 25px;
  -moz-border-radius: 25px;
  border-radius: 25px;
  cursor: pointer;
  box-shadow: 1px 1px 5px 5px #00ff00;
}

https://jsfiddle.net/k6shp80d/
but I can just click the first div, why? maybe because I'm new on JavaScript and jQuery, ask me any question or any doubt you have!, sorry for my bad english.

A: You are creating many #circle-green divs that don't get removed, and you are calling $("#circle-green").click. Change the #circle-green to a class, not and id. Also, change the click handler and the CSS.
Fixed!

$(document).ready(function() {
 var puntuacion = 0;
  FadeDiv();

  function FadeDiv() {
    var posx = Math.floor(Math.random() * 300);
    var posy = Math.floor(Math.random() * 300);
    $newdiv = $("

").css({
      'left': posx + 'px',
      'top': posy + 'px'
    }).click(function() {
  $(this).remove();
  puntuacion += 300;
  $("#Points").text(puntuacion);
 });
    $newdiv.appendTo('body').fadeIn(1000).delay(1000).fadeOut(1000, function() {
      FadeDiv();
    });
  }

  $("#Points").text(puntuacion);

  setTimeout(FadeDiv, 1000);
  setTimeout(FadeDiv, 500);
  setTimeout(FadeDiv, 100);
});
body {
  background-color: #000;
  color: #FFF;
  font-family: Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-size: 14px;
}
.circle-green {
  width: 50px;
  height: 50px;
  position: absolute;
  display: none;
  background-color: #00ff00;
  -webkit-border-radius: 25px;
  -moz-border-radius: 25px;
  border-radius: 25px;
  cursor: pointer;
  box-shadow: 1px 1px 5px 5px #00ff00;
}

A: use jquery onClick function and use Class instead of Id as below:
$(".circle-green").on('click',function(){

});
OR
$(document).on('click', '.circle-green', function () {
});

Hope that solves your query.
https://jsfiddle.net/k6shp80d/1/

A: Your error was in  puntuacion =+ 300;
The correct syntax is:
puntuacion += 300;

The final code should look like this:

var puntuacion = 0;
$(document).ready(function() {
  FadeDiv();

  function FadeDiv() {
    var posx = Math.floor(Math.random() * 300);
    var posy = Math.floor(Math.random() * 300);
$newdiv = $("

").css({
  'left': posx + 'px',
  'top': posy + 'px'
});
    $newdiv.appendTo('body').fadeIn(1000).delay(1000).fadeOut(1000, function() {
      FadeDiv();
    });
  }
  $("#Points").text(puntuacion);

  setTimeout(FadeDiv, 1000);
  setTimeout(FadeDiv, 500);
  setTimeout(FadeDiv, 100);
});

function greenFunc(element){
    $(element).remove();
    puntuacion += 300;
    $("#Points").text(puntuacion);
}
body {
  background-color: #000;
  color: #FFF;
  font-family: Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-size: 14px;
}
#circle-green {
  width: 50px;
  height: 50px;
  position: absolute;
  display: none;
  background-color: #00ff00;
  -webkit-border-radius: 25px;
  -moz-border-radius: 25px;
  border-radius: 25px;
  cursor: pointer;
  box-shadow: 1px 1px 5px 5px #00ff00;
}

DEMO: http://codepen.io/tuga/pen/zGOZrV


text:
Q: Blocking spam in a PHP site without bothering the user I'm currently working on a little chat/forum site that I roughed out in a weekend, and it has anonymous entries (i.e.: no usernames or passwords). This looks like it could be easy-cake for a spammer to ruin, but I don't want to bother the user with captchas or similar anti-spam inputs.
Are there any invisible-to-the-user alternatives to these? Thanks for your help.

A: One thing you should know about spammers is they always go for the low-hanging fruit. Same with hackers. By this I mean they'll pick the easiest to hit targets that affect the most users. This is why PHP and Windows vulnerabilities are often exploited: they affect so many users that if you find such a weakness/exploit your target "market" is huge.
It's also a big part of the reason why Linux and Mac OSs remain relatively unscathed by viruses for example: the target market is much smaller than Windows. Now I'm not equating the security and robustness of Windows with Mac/Linux but even though the security model of the latter two is much better the number of attacks against the former is still disproportionate with the deficiencies it has.
I say this because one of the best ways to avoid these kinds of problems is not to use popular softare. phpBB for example has had lots of attacks made against it just because it's so popular.
So by doing your own chat/forum system you're at a disadvantage because you have a system that doesn't have the field-testing something popular does but you also have an advantage in that it isn't worth most spammer's time to exploit it. So what you need to watch out for is what can automated systems do against you. Contact forms on Websites tend to have recognizable markers (like name, email and comment fields).
So I would advise:

*

*Ignoring responses that come within say 5-10 seconds of sending the form to the user;

*Using a honeypot (CSS/JS hidden fields as described elsewhere);

*Using Javascript where applicable to render, reorder or display the form;

*Using non-predictable form field names; and

*Throttle bad responses by IP.

A: Not a bomb-proof solution, but you can have some hidden input fields. If those are not left empty, you caught a bot.
Bots tend to fill all input fields, while users will sure leave fields they don't see empty.

A: This has worked 100% of the time for me:
<input type="text" style="display:none" name="email" value="do not fill this in it is for spam catching" />

Then server side (PHP):
if($_POST['email'] != 'do not fill this in it is for spam catching') {
    // spam
}

As mentioned earlier, most bots fill everything in, especially inputs named "email".

A: The idea of capchas is that they are very easy for humans to pass but very diffucult for bots etc. to avoid. If you don't want this kind of solution what will keep those spam-bots from posting to your site?
It's like you would like your computer to be safe but you don't want to use an antivirus and firewall.
I think you could create a session for every user that enters your site and first time they want to post something show them the capcha (don't require to log in, just pass capcha). If they pass it just store a flag in session that they are human. As long as they have their browser opened they can post and reply on your site what they want. Bots will unlikely pass this first test.

A: There are two classes of anti-spam protection.
The first is to make it difficult for automated bots to stumble data into your site. The hidden form field method is frequently mentioned for this, and is suitable for low traffic sites.  These protections can be trivially defeated by a spam bot written for your site.  However if you are too small a target, this won't happen.
The second is the "bothersome" types.  This usually involves a captcha, registration, or email confirmation of post. You can use a few approaches to make this less bothersome, but requires much more effort on the bot's side to post spam.
Note that both of these approaches can often impede disabled and mobile users.


text:
Q: Can we extend homomorphisms between submodules of finitely generated projective modules? Let $R$ be a ring with unit and $E$ and $F$ be two finitely generated projective left modules of $R$. Let $I$ and $J$ be submodules of $E$ and $F$ respectively.
If we have an $R$-homomorphism $\phi: I\to J$, could we always extend $\phi$ to an $R$-homomorphism $\widetilde{\phi}: E\to F$? If not, is there an simple counterexample?

A: I believe counterexamples exist even in abelian groups.  So, let $R=\mathbb{Z}$ so that everything is simply an abelian group.
Let $E=F=\mathbb{Z}$, $I = 4\mathbb{Z}$, and $J= 2\mathbb{Z}$.  Certainly $E=F$ is f.g. projective (free, even).  Then $\phi: I \to J$ by $\phi(x) = \frac{x}{2}$ is a group homomorphism.  However, it cannot extend to $\tilde{\phi}: \mathbb{Z} \to \mathbb{Z}$ since such a $\tilde{\phi}$ would have to map $4$ to $2$, and no group homomorphism on $\mathbb{Z}$ does that.


text:
Q: How to configure stepping-into Rails's core with Vim Exuberant Tags? While enjoying the flexibility of Vim Exuberant Tags def navigation in Rails applications, I thought why not go deeper, and have the Rails core source as a low-level reference.
How can I configure Vim to include another tag file, and what code should I map?
Thanks.

A: You should be able to simply pass your gems directory on the command line the ctags command. ctags takes a list of source files to examine on the command line. For instance if I was using rails 2.3.5 and running ctags from the root of my Rails application:
ctags -R $GEM_HOME/gems/rails-2.3.5/lib/* ./*

If you are using bundler, you could use bundle show to find the path for you. ctags will also let you exclude certain directories using the --exclude flag. Check out the options documentation for more info.

A: Vim looks for its tag files in the 'tags' option, which is a list of (absolute/relative) paths. Sou in Vim you could do
:set tags+=/path/to/ror/tags

Also see
:help 'tags'


text:
Q: remove duplicates in lists of lists of list I have a list of the type:
biglist = [[
    [77.56913757324219, 12.975883483886719], [77.5671615600586, 12.976168632507324],
    [77.5680160522461, 12.980805397033691], [77.56996154785156, 12.980448722839355],
    [77.56913757324219, 12.975883483886719]
]]

In order to remove duplicates I wrote the following in python:
templist = set(map(tuple,biglist[0]))
newlist = map(list,templist)

Although this removes the dup elements, I loose to the initial structure of lists in lists of list. Can someone help remove the duplicates?
Thank you
EDIT:
A little background on what I am trying to do:
The numbers you see are part of a polygon shape used in geographic information system. I am trying to store and index it in MongoDB. However, I'm getting an error while indexing, and one of the possible solutions is to remove  duplicate values and try indexing it again. Basically, the list what you see is in GeoJSON format and I need to preserve that order for inserting into mongoDB.
The expected output would be:
[[
        [77.56913757324219, 12.975883483886719], [77.5671615600586, 12.976168632507324],
        [77.5680160522461, 12.980805397033691], [77.56996154785156, 12.980448722839355]
    ]]

A: Right, this should get what you want:
>>> newlist = [[]]
>>> for i in range(len(biglist[0])):
...     if not test[0][i] in newlist[0]:
...         newlist[0].append(test[0][i])
...
>>> newlist
[[[77.56913757324219, 12.975883483886719], [77.5671615600586, 12.976168632507324], [77.5680160522461, 12.980805397033691], [77.56996154785156, 12.980448722839355]]]

However, you really should consider a few things:

*

*As I pointed out in the comments, comparing floats is going to cause you a lot of trouble.  Values that differ by less than 1x10^8 (or less) will cause your comparison to fail, and such differences can be caused by a lack of precision (floating point error).  You should always compare floats with a tolerance to avoid this.

*I'm not sure why you have a double nested list, but from what you've given here, it seems pretty silly, and makes everything more complicated
Also, your solution didn't work because you converted your list to a set.  Since sets are inherently unordered, when you reconverted to a list, the order changed.  In the future, if you care about the order your elements in (which form your edit, it sounds like you do), avoid using sets (or dictionaries) for this reason.

A: This solution is not the best but it might help you:
#!/usr/bin/python

biglist = [[
    [77.56913757324219, 12.975883483886719], [77.5671615600586, 12.976168632507324],
    [77.5680160522461, 12.980805397033691], [77.56996154785156, 12.980448722839355],
    [77.56913757324219, 12.975883483886719]
]]

blist = map(tuple, biglist[0])

seen = set()
result = list()
for tup in blist:
    if tup not in seen:
        seen.add(tup)
        result.append(tup)

print map(list, result)

Or you can try using order dict:
>>> import collections
>>> a = collections.OrderedDict()
>>> for big in biglist[0]:
...     a.setdefault(tuple(big), None)
...
>>> a.keys()
[(77.56913757324219, 12.975883483886719), (77.5671615600586, 12.976168632507324),     (77.5680160522461, 12.980805397033691), (77.56996154785156, 12.980448722839355)]
>>>

A: If you want to stick with your original solution, just use an OrderedSet instead of set.


text:
Q: sort a matrix using its value in python For example I have a matrix
a = [[6,8,9],[7,4,3],[1,2,5]]

now I want to sort matrix like as below
a = [[1,2,3],[4,5,6],[7,8,9]]

please help me I am new to python.

A: For list-of-list, you can clone the shape like this
>>> from itertools import chain
>>> a = [[6,8,9],[7,4,3],[1,2,5]]
>>> it = iter(sorted(chain.from_iterable(a)))
>>> [[next(it) for j in i] for i in a]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

A: Use chain.from_iterable
>>> a = [[6,8,9],[7,4,3],[1,2,5]]
>>> from itertools import chain
>>> l = sorted(chain.from_iterable(a))
>>> [l[i:i+3] for i in range(0, len(l),3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]


text:
Q: Adjust dates in R Could you tell me why the dates are coming off weird? I will insert an executable code below. You may notice that date1 and date2 have the wrong dates.
The link to download the database df: https://docs.google.com/spreadsheets/d/1Pi2cQk1Dl1UAH_vj1vY73fHNX3RLDRj2/edit?usp=sharing&ouid=102073768617937039119&rtpof=true&sd=true
df<-read_excel('C:/Users/Jose/Desktop/df.xlsx')

df<-subset(df,df$date2<df$date1)

dim_data<-dim(df)

day<-c(seq.Date(from = as.Date(df$date2[1]),
                to = as.Date(df$date2[dim_data[1]]),
                by = "1 day"))

df_grouped<-matrix(nrow = 9,ncol=6)
colnames(df_grouped)<-c("Id","date1","date2","Week","D","DR01")

for (k in 1:9) {
  df_grouped[k,]<-c(subset(df,date2==day[k])$Id[1],
                                  subset(df,date2==day[k])$date1[1],
                                  subset(df,date2==day[k])$date2[1],
                                  subset(df,date2==day[k])$Week[1],
                                  subset(df,date2==day[k])$D[1],
                                  sum(subset(df,date2==day[k])$DR01))
}
> df_grouped
      Id  date1        date2        Week       D     DR01
 [1,] "1" "1626739200" "1617321600" "Friday"   NA    "21"
 [2,] "1" "1626739200" "1617408000" "Saturday" NA    "24"
 [3,] NA  NA           NA           NA         NA    "0"
 [4,] NA  NA           NA           NA         NA    "0"
 [5,] NA  NA           NA           NA         NA    "0"
 [6,] NA  NA           NA           NA         NA    "0"
 [7,] "1" "1626739200" "1617840000" "Thursday" "Hol" "21"
 [8,] "1" "1626739200" "1617926400" "Friday"   NA    "11"
 [9,] "1" "1626739200" "1618012800" "Saturday" NA    "14

A: A way of solution!
   df_grouped <- df %>%
   mutate(across(starts_with("date"), as.Date)) %>%
   group_by(date2) %>%
   summarise(Id = first(Id),
             date1 = first(date1),
             Week = first(Week),
             D = first(D),
             DR01 = sum(DR01)) %>%
   select(Id,date1,date2,Week,D,DR01)

df_grouped
# A tibble: 6 x 6
     Id date1      date2      Week     D      DR01
  <dbl> <date>     <date>     <chr>    <chr> <dbl>
1     1 2021-07-20 2021-04-02 Friday   NA       21
2     1 2021-07-20 2021-04-03 Saturday NA       24
3     1 2021-07-20 2021-04-08 Thursday Hol      21
4     1 2021-07-20 2021-04-09 Friday   NA       11
5     1 2021-07-20 2021-04-10 Saturday NA       14
6     1 2021-07-20 2021-08-01 Thursday NA       13

df_grouped <- df_grouped %>% mutate(date1=format(date1,"%d/%m/%Y"),
                                    date2=format(date2,"%d/%m/%Y"))

df_grouped
# A tibble: 6 x 6
     Id date1      date2      Week     D      DR01
  <dbl> <chr>      <chr>      <chr>    <chr> <dbl>
1     1 20/07/2021 02/04/2021 Friday   NA       21
2     1 20/07/2021 03/04/2021 Saturday NA       24
3     1 20/07/2021 08/04/2021 Thursday Hol      21
4     1 20/07/2021 09/04/2021 Friday   NA       11
5     1 20/07/2021 10/04/2021 Saturday NA       14
6     1 20/07/2021 01/08/2021 Thursday NA       13


text:
Q: Laravel Change Booking Status automaticly Is there any way to change automatically the booking status to 'completed' order status after the service date is passed?
Basically, I want the $booking-> status to be changed to 'completed' after the end_date
will be an option to have a function
function booking_status_changer() {
Im new to Laravel and have not found anything that can help me accomplish this. Any help would be greatly appreciated.

A: I would recommend you use Background Jobs with Scheduler in Laravel
https://laravel.com/docs/9.x/queues#introduction
https://laravel.com/docs/9.x/scheduling
You can create a background job that requests the database to change the booking status to completed when a record has passed the deadline.


text:
Q: Why service restart fails with :-restart: Unknown instance: root@user-desktop:/etc# sudo /usr/sbin/service vsftpd restart
restart: Unknown instance:

A: A typical restart job will attempt to kill an old instance first. What is happening here is that there isn't an old copy to kill.

A: Try this sudo /etc/init.d/vsftpd restart


text:
Q: What would prevent DTMF tones being recognised (modem to modem)? A bit of back story: the SEGA Dreamcast had a dial up modem which was used for online play, in the absence of dialup ISPs it's now common practice to directly connect the DC to a USB dial up modem and route the connection through a PC via ppp.
Some revisions of the Dreamcast require a voltage on the line to dial out, and in this case a solution was found by inducing a voltage by wiring a 9v battery and resistor into the phone line. (http://dreamcast.onlineconsoles.com/phpBB2/guides_pcdcwin98.php#10)
However even still it appears some USB modems don't recognise the signals from the Dreamcast. For example if I connect a standard phone to the line in place of the Dreamcast, the tones are recognised by the PC, but the dialling of the DC isn't recognised at all!
What could cause this to happen? Why would one device generate DTMF codes that work, and another device not? If I connect a phone directly to the DC I can hear the tones being dialled but there must be some difference between those generated by the DC and those by the phone.
Also, it seems that even if I blindly answer the Dreamcast (by sending the ATA command to the receiving USB modem) the Dreamcast doesn't recognise the call was answered, perhaps that's related and this is more than just the DTMF tones...
I'd appreciate any suggestions that might help to get these two modems communicating!

A: DTMF tones are only required for dialing out through an exchange. When connecting directly from modem to modem you are already connected, so the phone number is redundant!
However the Dreamcast modem may expect to get various tones and voltages during the call (eg. dial tone, line voltage) while the receiving modem won't normally answer unless it gets ringing voltage (~90V at 20Hz). You can force the receiving modem to answer with ATA, then it should send carrier (which the Dreamcast modem will be listening for after it has finished dialing) and the two modems should talk to each other.
To trick the Dreamcast modem into thinking it is connected to a phone line you can connect it to an actual phone line, then quickly unplug it and plug into the other modem after it has dialed. A switch would make this easier, or you could build a 'telephone line simulator' which emulates all the essential functions of an exchange (dial tone, ringing voltage, line voltages with current regulation, linking the audio signal from one line to the other etc.). The one thing you won't need is DTMF tone recognition.
If you have followed the usual procedure for connecting a Dreamcast to a PC modem but it doesn't work then most likely the PC modem is not compatible with your crude line voltage circuit, or it has a software issue. If you have access to two phone lines then first get it to work from one line to the other through the exchange, then try the single phone line trick.


text:
Q: I am trying to use the mailjet to send messages via email, but why is the word version not recognized in it I am trying to use Mailjet to send messages via email, but why is the word version not recognized in it? I downloaded the mailgate package
I'm practicing programming using the asp.net core5.0 framework.
Are there other distinct ways to send messages via e-mail?
Any advice from you?
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.UI.Services;
using Newtonsoft.Json.Linq; ][1]

A: If you have Version = ApiVersion.V3_1, as part of your sample code, comment it out and add the appropriate BaseAdress line in the example below:
MailjetClient client = new MailjetClient("xxx-example-xxx", "xxx-example-xxx")
{
    BaseAdress = "https://api.mailjet.com",
    //BaseAdress = "https://api.us.mailjet.com",
    //Version = ApiVersion.V3_1,
};


text:
Q: JLabel too wide I wrote the following code which is a simple window with a JLabel header at the top. The code is as follows:
import java.awt.Color;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class Main extends JFrame {

private static final long serialVersionUID = 1L;

public static void main(String[] args) {
    init();
}

public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    int WIDTH = 500;
    int HEIGHT = 500;
    setBackground(Color.LIGHT_GRAY);
    setSize(WIDTH, HEIGHT);
    setTitle("New Window");
    setLocationRelativeTo(null);

    JPanel pane = new JPanel();
    pane.setOpaque(false);
    setContentPane(pane);
    pane.setLayout(null);

    JLabel title = new JLabel("New Window", SwingConstants.CENTER);
    title.setFont(new Font("Neuropol", Font.PLAIN, 22));
    title.setSize(WIDTH, 20);
    title.setBorder(BorderFactory.createLineBorder(Color.black));
    pane.add(title);
}

static void init() {
    Main frame = new Main();
    frame.setVisible(true);
}

}

I'm having a weird issue with it though. As you can see I set the width of the JLabel to the same width as the JFrame (and therefore the same width as the JPanel), but for some reason, the label goes past the right edge of the Frame. The width of the frame is 500, but I have to set the JLabel to a width of 483 in order for the border to be within the JFrame. I've been over and over this, but can't see anything wrong. Does anybody see my mistake here?

A:
I set the width of the JLabel to the same width as the JFrame

But the JFrame width includes the "decorations" of the frame, like the Border.

I have to set the JLabel to a width of 483 in order for the border to be within the JFrame.

No, 483 will make the label too big for the frame. The Borders of the frame are not 17 pixels. I think the Borders are 4 or 5 pixels each depending on the LAF.
So this is another reason why you should NOT be using a null layout as hardcoding a value for one LAF may not work on another LAF.
Also, what happens if the user resizes the frame wider? Now the label will not go to the end. Use a Layout Manager do design dynamic GUI's that adapt to changes as the user resizes the frame.
The easiest solution is to just use the default BorderLayout of content pane of the frame. Then you add your label to the PAGE_START.
add(title, BorderLayout.PAGE_START);

There is also no reason to create a content pane. The frame already has a JPanel which uses a BorderLayout.
Read the Swing tutorial on Layout Managers for more information and working examples. Download the demos code and use them as a starting point for your code. The demo code will show you how to better structure your code to follow Swing conventions.