text:
Q: Do not display registration form to logged in users I'm trying to figure out a way to add if condition to the registration form. Presently logged in users can access the registration form, which isn't right. Below is the piece of code.
Note, my CMS is Wordpress.
I've tried using the:
if (is_user_logged_in())

/* MAIN CODE HERE */

    else
        return "You are already logged in!";

But it only ends up displaying the 'if (is_user...' above the registration form.
Here's the code:
<?php
if ('wwm-register.php' == basename($_SERVER['SCRIPT_FILENAME']))
     die ('
Direct File Access Prohibited
');

function wwm_register_page() {
global $wpdb, $user_ID;
?>
FUNCTION TO DISPLAY PLANS

<?php
return;
exit;
}

        if (get_option('wwm_form_validator')) {
?>
            FORM VALIDATION SCRIPT
<?php
        }

    $main_fields=get_option('wwm_main_fields');

    $use_plugin_as=get_option('use_plugin_as');

    if ($use_plugin_as!=='all')  {
        if($use_plugin_as=='membership') {
            $type='membership';
            $main_fields[0][show]='1'; //show username and pass and mail
        }elseif($use_plugin_as=='order'){
            $type='order';
            $main_fields[0][show]='0'; //don't show username and pass and mail
        }else{
            $type='membership';
        }
    }

    if (isset($_GET['type'])) {
        if($_GET['type']=='membership') {
            $type='membership';
            $main_fields[0][show]='1'; //show username and pass and mail
        }elseif($_GET['type']=='order'){
            $type='order';
            $main_fields[0][show]='0'; //don't show username and pass and mail
        }
    }

    if ($type)
        $planlist = $wpdb->get_results("SELECT id,title,price,description FROM ".WWM_PLANS_TABLE." WHERE display='1' AND plantype='".$type."'");
    else
        $planlist = $wpdb->get_results("SELECT id,title,price,description FROM ".WWM_PLANS_TABLE." WHERE display='1'");

    if (isset($_POST['preview'])) $preview=$_POST['preview']; else $preview=0;

    if (isset($_POST['username'])) $username=attribute_escape(strip_tags(stripslashes(strtolower(trim($_POST['username'])))));elseif (isset($_GET['username'])) $username=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['username'])))));

    if (isset($_POST['pass'])) $pass=attribute_escape(strip_tags(stripslashes((trim($_POST['pass'])))));
    if (isset($_POST['pass2'])) $pass2=attribute_escape(strip_tags(stripslashes((trim($_POST['pass2'])))));

    if (isset($_POST['email'])) $email=attribute_escape(strip_tags(stripslashes((trim($_POST['email'])))));elseif (isset($_GET['email'])) $email=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['email'])))));

    if (isset($_POST['companyname'])) $companyname=attribute_escape(strip_tags(stripslashes((trim($_POST['companyname'])))));

    if (isset($_POST['fname'])) $fname=attribute_escape(strip_tags(stripslashes((trim($_POST['fname'])))));elseif (isset($_GET['fname'])) $fname=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['fname'])))));

    if (isset($_POST['lname'])) $lname=attribute_escape(strip_tags(stripslashes((trim($_POST['lname'])))));elseif (isset($_GET['lname'])) $lname=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['lname'])))));

    if (isset($_POST['nname'])) $nname=attribute_escape(strip_tags(stripslashes((trim($_POST['nname'])))));
    if (isset($_POST['url'])) $url=attribute_escape(strip_tags(stripslashes((trim($_POST['url'])))));elseif (isset($_GET['url'])) $url=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['url'])))));

    if (isset($_POST['desc'])) $desc=attribute_escape(strip_tags(stripslashes((trim($_POST['desc'])))));elseif (isset($_GET['desc'])) $desc=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['desc'])))));

    if (isset($_POST['yahooim'])) $yahooim=attribute_escape(strip_tags(stripslashes((trim($_POST['yahooim'])))));
    if (isset($_POST['aolim'])) $aolim=attribute_escape(strip_tags(stripslashes((trim($_POST['aolim'])))));
    if (isset($_POST['jabberim'])) $jabberim=attribute_escape(strip_tags(stripslashes((trim($_POST['jabberim'])))));

    if (isset($_POST['countryname'])) $countryname=attribute_escape(strip_tags(stripslashes((trim($_POST['countryname'])))));elseif (isset($_GET['countryname'])) $countryname=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['countryname'])))));

    if (isset($_POST['statename'])) $statename=attribute_escape(strip_tags(stripslashes((trim($_POST['statename'])))));
    elseif (isset($_GET['statename'])) $statename=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['statename'])))));

    if (isset($_POST['cityname'])) $cityname=attribute_escape(strip_tags(stripslashes((trim($_POST['cityname'])))));
    elseif (isset($_GET['cityname'])) $cityname=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['cityname'])))));

    if (isset($_POST['adrs'])) $adrs=attribute_escape(strip_tags(stripslashes((trim($_POST['adrs'])))));
    elseif (isset($_GET['adrs'])) $adrs=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['adrs'])))));

    if (isset($_POST['adrs2'])) $adrs2=attribute_escape(strip_tags(stripslashes((trim($_POST['adrs2'])))));
    elseif (isset($_GET['adrs2'])) $adrs2=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['adrs2'])))));

    if (isset($_POST['zipcode'])) $zipcode=attribute_escape(strip_tags(stripslashes((trim($_POST['zipcode'])))));
    elseif (isset($_GET['zipcode'])) $zipcode=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['zipcode'])))));

    if (isset($_POST['telephone'])) $telephone=attribute_escape(strip_tags(stripslashes((trim($_POST['telephone'])))));
    elseif (isset($_GET['telephone'])) $telephone=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['telephone'])))));

    if (isset($_POST['birthday'])) $birthday=attribute_escape(strip_tags(stripslashes((trim($_POST['birthday'])))));
    if (isset($_POST['birthmonth'])) $birthmonth=attribute_escape(strip_tags(stripslashes((trim($_POST['birthmonth'])))));
    if (isset($_POST['birthyear'])) $birthyear=attribute_escape(strip_tags(stripslashes((trim($_POST['birthyear'])))));
    if (isset($_POST['gender'])) $gender=attribute_escape(strip_tags(stripslashes((trim($_POST['gender'])))));
    if (isset($_POST['terms'])) $terms=attribute_escape(strip_tags(stripslashes((trim($_POST['terms'])))));
    if (isset($_POST['avatar'])) $avatar=attribute_escape(strip_tags(stripslashes((trim($_POST['avatar'])))));

    if (isset($_POST['plan'])) $plan=attribute_escape(strip_tags(stripslashes((trim($_POST['plan'])))));elseif (isset($_GET['plan'])) $plan=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['plan'])))));

    if (isset($_POST['captcha'])) $captcha=attribute_escape(strip_tags(stripslashes((trim($_POST['captcha'])))));

    if (isset($_POST['promocode'])) $promocode=attribute_escape(strip_tags(stripslashes((trim($_POST['promocode'])))));elseif (isset($_GET['promocode'])) $promocode=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['promocode'])))));

    if (isset($_POST['payment_method'])) $payment_method=attribute_escape(strip_tags(stripslashes((trim($_POST['payment_method'])))));elseif (isset($_GET['payment_method'])) $payment_method=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['payment_method'])))));

    if (isset($_POST['blog_title'])) $blog_title=attribute_escape(strip_tags(stripslashes((trim($_POST['blog_title'])))));elseif (isset($_GET['blog_title'])) $blog_title=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['blog_title'])))));

    if (isset($_POST['blog_domain'])) $blog_domain=attribute_escape(strip_tags(stripslashes((trim($_POST['blog_domain'])))));elseif (isset($_GET['blog_domain'])) $blog_domain=attribute_escape(strip_tags(stripslashes(strtolower(trim($_GET['blog_domain'])))));

    $last_id=wwm_get_fields_last_id('registration');

    for ($i=1;$i<=$last_id;$i++){

        $list=$wpdb->get_row("SELECT label,regex,req FROM ".WWM_FIELDS_TABLE." WHERE id={$i};");
        if ($list) {

            if (isset($_POST['custom-'.$i])) $custom_value[$i]=attribute_escape(stripslashes(strip_tags(trim($_POST['custom-'.$i]))));
            elseif (isset($_GET['custom-'.$i])) $custom_value[$i]=attribute_escape(strip_tags(stripslashes(trim($_GET['custom-'.$i]))));                $custom_regex[$i]=$list->regex;
                    $custom_req[$i]=$list->req;
                    $custom_label[$i]=$list->label;
                    $custom[$i][label]=$list->label;
                    $custom[$i][value]=$custom_value[$i];

                    if (isset($_POST['file-'.$i])) {
                    $file_custom_fields[]=$_POST['file-'.$i];
                    }

            }

    }

    if (!get_option('wwm_users_can_register')) {
        echo '
'.__('Registration has been disabled.','wwm').'
';
        $hidden=true;

    }elseif((isset($_GET['action']))){
        $hidden=true;

        if (isset($_GET['method']) && 'twoco'==$_GET['method'])
            include('include/payment_2co.php');
        else
            include('include/payment.php');

    }elseif ( (isset($_GET['mail'])) && (isset($_GET['activate_key'])) ) {
        $hidden=true;
        $user_data = get_user_by_email($_GET['mail']);

        if ( (get_usermeta($user_data->ID,'activate_key')==$_GET['activate_key']) && (get_usermeta($user_data->ID,'status')=='incomplete') ){
            update_usermeta($user_data->ID,'status','0');
            delete_usermeta($user_data->ID,'activate_key');
            $thanksmsg=__('Your account has been successfully activated.','wwm') . '  '.__('Log In').'';

            if (get_option('free_members_welcome_mail')) {
                $to=$_GET['mail'];

                $username=$user_data->user_login;
                $fname=$user_data->first_name;
                $lname=$user_data->last_name;
                $expiredate=get_usermeta($user_data->ID,'expire');
                $plan=get_usermeta($user_data->ID,'plan_id');
                    $planinfo=get_plan_info($plan);
                $plantitle=$planinfo->title;

                $blogname=get_option('blogname');
                $subject='Welcome to '.$blogname.'!';

                $body=get_option('free_members_welcome_mail_body');
                $tags=array('{plantitle}','{expiredate}','{firstname}','{lastname}','{username}','{password}','{planid}');
                $replace=array($plantitle,$expiredate,$fname,$lname,$username,$pass,$plan);
                $body=str_replace($tags,$replace,$body);
                $body.='
';

                wwm_mail_actions('html'); //set actions

                if ( !wp_mail($to, $subject, $body, $header) )
                        $msg= __('The e-mail could not be sent.') . "
\n" . __('Possible reason: your host may have disabled the mail() function...') ;
            } //free members welcome

            echo '
'.$thanksmsg.'
';
        }elseif($user_data->ID && get_usermeta($user_data->ID,'status')!=='incomplete'){
            $errormsg=__('We think you did it before!','wwm');
        echo '
'.$errormsg.'
';
        }elseif((!$user_data->ID) ||get_usermeta($user_data->ID,'activate_key')!==$_GET['activate_key']){
            $errormsg=__('Your activation key is not valid for the plan!','wwm');
            echo '
'.$errormsg.'
';
        }

    }
    elseif ( (isset($_POST['submit'])) || (isset($_POST['submit-upload'])) ) {

        if ( !wp_verify_nonce( $_POST['wwm_form_noncename'], plugin_basename(__FILE__) ))
            return "Invalid nonce. Try agian.";

        require_once(ABSPATH.'/wp-includes/registration.php');
        //require_once(ABSPATH.'/wp-includes/pluggable.php');

        if (isset($_POST['submit-upload'])) { //avatar

        $override['test_form']=false;
        $allowed=array(jpg,jpeg,jpe,gif,png);

        $result=wwm_handle_upload($_FILES['avatarfile'],$override,100,$allowed); //100Kb means max upload size for avatars!

        if (!$result['error']) {
            require_once(ABSPATH.'/wp-admin/includes/image.php');
            $site=get_option(siteurl);
            $path=ABSPATH.'/wp-content/avatar/';
            $urlpath=$site."/wp-content/avatar/";
            if (!is_dir($path))  {
                mkdir($path);//chmod($path,777);
            }
            $avatar_size=get_option('wwm_avatar_width');
            $avatar=wwm_image_resize( $result['file'],$avatar_size, $avatar_size, $crop=false, $suffix=$username.'avatar', $dest_path= $path, $jpeg_quality=75) ;

            if (basename($avatar))
            $avatar=$urlpath.basename($avatar);
            else
            $uploaderror.=$main_fields[20][name].': '.__('Image is very little.','wwm').'.
';

        }else{
            $uploaderror.=$main_fields[20][name].': '.$result['error'].'.
';

        }
    }

    if ($file_custom_fields) {

        foreach($file_custom_fields as $field_id) {

                $override['test_form']=false;
                $allowed=unserialize($wpdb->get_var($wpdb->prepare("SELECT options FROM ".WWM_FIELDS_TABLE." WHERE id=%s;",$field_id)));
                $max_upload_size=get_site_option( 'fileupload_maxk', 1500 );
                $result=wwm_handle_upload($_FILES['custom-'.$field_id ],$override,$max_upload_size,$allowed);

                if (!$result['error']) {
                    $custom_value[$field_id]=$result['url'];

                }else{
                    if (!$_FILES['custom-'.$field_id ][error]=='4') { //error[4] means empty file
                        $msgerror.=$custom_label[$field_id].': '.$result['error'].'.
';
                        $custom_value[$field_id]='error';
                    }
                }

        }
    }

    for ($i=1;$i<=$last_id;$i++){
                    if ( ((empty($custom_value[$i])) || ($custom_value[$i]==__('-Select-','wwm'))) && ($custom_req[$i]) )
                    $msgerror.= sprintf(__('Please enter %s.', 'wwm'), $custom_label[$i])."
";

    }

    if ( ($planlist) && (strlen($plan)<1) ) $msgerror.=__('Please choose a plan.','wwm').'
';

    if ($main_fields[0][show]) {
        if ((strlen($username)>20) || (strlen($username)<4) ) $msgerror.=__('Please enter a username(at least 4 characters).','wwm').'
';
        if (username_exists($username)) $msgerror.=sprintf(__('%s already exists.', 'wwm'), $username)."
";
        if (!validate_username($username)) $msgerror.=sprintf(__('%s is not allowed.', 'wwm'), $username)."
";

        if ( (strlen($pass)>30) || (strlen($pass)<6) ) $msgerror.=__('Please enter a password(at least 6 characters).', 'wwm')."
";
        if ( (empty($pass2)) || (strlen($pass2)>30) || ($pass!==$pass2) ) $msgerror.=__('Please re-type password to confirm.', 'wwm')."
";
    }
    if ( ($main_fields[1][show]) || ($main_fields[0][show]) ) {
        if ( ($main_fields[1][req]) && (strlen($email)<6) ) $msgerror.=__('Please enter a correct email address.', 'wwm')."
";

        if ( ($main_fields[1][req]) && (email_exists($email)) && ($type!=='order') ) $msgerror.=__('That email already exists.', 'wwm')."
";
        if ( (!wwm_validate_email($email)) && (!strlen($email)<6) ) $msgerror.=__('Please enter a correct email address.', 'wwm')."
";
    }

        if ( ($main_fields[2][req]) && (strlen($fname)<1) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[2][name])."
";
        if ( ($main_fields[3][req]) && (strlen($lname)<1) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[3][name])."
";
        if ( (($main_fields[6][req]) && (strlen($url)<10)) || ( (strlen($url)>1) &&
        (!ereg('^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$',$url) )))
        $msgerror.=__('Please enter a correct URL.', 'wwm')."
";
        if ( ($main_fields[4][req]) && (strlen($nname)<5) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[4][name])."
";
        if ( ($main_fields[18][req]) && (strlen($desc)<5) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[18][name])."
";
        if ( ($main_fields[7][req]) && (strlen($yahooim)<5) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[7][name])."
";
        if ( ($main_fields[8][req]) && (strlen($aolim)<5) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[8][name])."
";
        if ( ($main_fields[9][req]) && (strlen($jabberim)<5) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[9][name])."
";

        if ( ($main_fields[5][req]) && (strlen($companyname)<2) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[5][name])."
";

        if ( ($main_fields[12][req]) && (strlen($countryname)<1) ) $msgerror.=__('Please choose your country.', 'wwm')."
";
        if ( ($main_fields[13][req]) && (strlen($statename)<1) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[13][name])."
";
        if ( ($main_fields[14][req]) && (strlen($cityname)<1) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[14][name])."
";
        if ( ($main_fields[15][req]) && (strlen($adrs)<1) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[15][name])."
";
        if ( ($main_fields[16][req]) && (strlen($zipcode)<1)  ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[16][name])."
";
        if ( ($main_fields[17][req]) && (strlen($telephone)<1) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[17][name])."
";
        if ( (($main_fields[10][req]) && (strlen($birthday)<1)) || (($main_fields[10][req]) && (strlen($birthmonth)<1)) || (($main_fields[10][req]) && (strlen($birthyear)<1)) ) $msgerror.=__('Please choose your birthdate.', 'wwm')."
";

        if ( ($main_fields[11][req]) && (strlen($gender)<1) ) $msgerror.=__('Please choose your gender.', 'wwm')."
";
        if ( ($main_fields[19][show]) && (strlen($terms)<1) && ( (!get_option('wwm_show_preview'))||($preview) && (get_option('wwm_show_preview')) ) ) $msgerror.=sprintf(__('Please accept %s.', 'wwm'), $main_fields[19][name])."
";
        if ( ($main_fields[20][req]) && (strlen($avatar)<1) ) $msgerror.=sprintf(__('Please upload a photo as %s.', 'wwm'), $main_fields[20][name])."
";
        if ( ($main_fields[22][req]) && (strlen($promocode)<1) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[22][name])."
";

        //if ( ($main_fields[100][show]) && (strlen($blog_domain)<4) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[100][name]) . ' '.__('(at least 4 characters)','wwm')."
";
        //if ( ($main_fields[100][show]) && (strlen($blog_title)<4) ) $msgerror.=sprintf(__('Please enter %s.', 'wwm'), $main_fields[101][name]). ' '.__('(at least 4 characters)','wwm')."
";

        if (!get_option('wwm_users_can_register')) $msgerror.=__('Registration has been disabled.', 'wwm')."
";

    if (($main_fields[21][show]) && ( (!get_option('wwm_show_preview'))||($preview) && (get_option('wwm_show_preview')) ) )  {
        $type=get_option('wwm_cap_type');
        if ( $type == 'simple' ){
            if (!class_exists(tam_captcha)) include('captcha/captcha.php');

            $tam_captcha=new tam_captcha;
            $check=$tam_captcha->check(attribute_escape($_POST['captcha-id']), $captcha);

            $tam_captcha->remove(attribute_escape($_POST['captcha-id']));

            if(!$check){
                $msgerror.=sprintf(__('Please enter a correct %s.', 'wwm'), $main_fields[21][name])."
";

            }
        } else if ( $type == 'recap'){
            require_once('captcha/recaptchalib.php');
            $privatekey = get_option('wwm_recap_private');
            $recap = rp_recaptcha_check_answer ($privatekey,

                $_SERVER["REMOTE_ADDR"],
                $_POST["recaptcha_challenge_field"],
                $_POST["recaptcha_response_field"]);

            if (!$recap->is_valid) {
                $msgerror.=sprintf(__('Please enter a correct %s.', 'wwm'), $main_fields[21][name])."
";

            }
        }
    } //end if requires

    } //end first if

        if ($_POST['submit']) {
            if ($planlist) {
                $theplan = $wpdb->get_row($wpdb->prepare("SELECT title,price,duration,plantype FROM ".WWM_PLANS_TABLE." WHERE display='1' AND id=%s",$plan) );
                $planprice=$theplan->price;
                $plantitle=$theplan->title;
                $planduration=$theplan->duration;
                $plantype=$theplan->plantype;
            }

            if ( (strstr(basename($_SERVER['SCRIPT_FILENAME']),'admin.php')) && (is_admin()) ){
                $planprice=0;
                $admin=true; //free for backend page
            }

            if ($promocode) {
                $promocode=strtolower($promocode);
                $codes=get_option('wwm_discount_code');
                $valid=false;
                if ($codes) {
                    for ($id=1;$id<=MAX_DISCOUNT_NUM;$id++ ) {
                        if ($codes[$id][code]==$promocode) {
                            if ( ($codes[$id][plans][0]) && ($codes[$id][plans][0]!==',')) {

                                foreach($codes[$id][plans] as $codeid=>$codeplan) {
                                    if($codeplan==$plan) {
                                        $planprice=$planprice*((100-$codes[$id][percent])*(1/100));
                                        $valid=true;
                                    }
                                }
                            }else{
                                $valid=true;
                                $planprice=$planprice*((100-$codes[$id][percent])*(1/100));
                            }
                        }
                    }
                }

                if (!$valid)
                $msgerror.=sprintf(__('%s is not valid.', 'wwm'), $main_fields[22][name])."
";
            }

        }

    if (empty($msgerror) && ($_POST['submit']) ) {

        $user_login = $username;
        $user_email = $email;
        $user_pass = $pass;
        $user_nicename=$nname;
        $user_url=$url;
        $display_name=$user_nicename;
        $first_name=$fname;
        $last_name=$lname;
        $description=$desc;
        //$role=''; leave to default userrole
        //$rich_editing=true;
        $yim=$yahooim;
        $aim=$aolim;
        $jabber=$jabberim;

        if (  ($planprice<=0)&& ($type!='order') && ($plantype!='order') ) {
            $userdata = compact('user_login', 'user_email', 'user_pass','user_nicename','user_url','display_name','first_name','last_name','description','yim','aim','jabber');

            $id=wp_insert_user($userdata);

            update_usermeta($id,'company',$companyname);
            update_usermeta($id,'country',$countryname);
            update_usermeta($id,'state',$statename);
            update_usermeta($id,'city',$cityname);
            update_usermeta($id,'address',$adrs);
            update_usermeta($id,'address2',$adrs2);
            update_usermeta($id,'zip',$zipcode);
            update_usermeta($id,'phone',$telephone);
            if (($birthyear)&&($birthmonth)&&($birthday) ) $birthdate=$birthyear.'-'.$birthmonth.'-'.$birthday.' 00:00:00';
                update_usermeta($id,'birthday',$birthdate);
            update_usermeta($id,'gender',$gender);
            update_usermeta($id,'last_ip', $_SERVER['REMOTE_ADDR']);
            update_usermeta($id,'status','');
            update_usermeta($id,'plan_id',$plan);
            update_usermeta($id,'avatar',$avatar);
            update_usermeta($id,'promocode',$promocode);

                if ($planduration)
                $expiredate = date("Y-m-d H:i:s",strtotime('+'.$planduration.'day')); else $expiredate=0;

            update_usermeta($id,'expire',$expiredate);

            for ($i=1;$i<=$last_id;$i++) {
                if  ( ($custom_label[$i]) && ($custom_value[$i]) )
                update_usermeta($id,'customfield_'.$i,$custom_value[$i]);
            }

            do_action('wwm_free_member_registered',$id);

SEND EMAIL
                wwm_mail_actions('html'); //set actions

                if ( !wp_mail($to, $subject, $body, $header) )
                        $msg= __('The e-mail could not be sent.') . "
\n" . __('Possible reason: your host may have disabled the mail() function...') ;

            } //end verify mail

            $thanksmsg=__('Thank you for your registration.','wwm')."
";

/* NOTIFY MEMBERS ON SIGN UP */
                }
            }
        }else{ //else if there is error
         if ( ($msgerror)&&(isset($_POST['submit'])) ) echo '
'.$msgerror.'
';

    if ($uploaderror) echo '
'.$uploaderror.'
';

if (!$hidden) {

    do_action('wwm_register_header');

    ?>

/REGISTRATION FORM/
    <?php

    }//end if
}//end of hidden
}
?>

A: You mention:

But it only ends up displaying the 'if
  (is_user...' above the registration
  form.

This indicates that your PHP code is showing up as HTML instead. Make sure you enclose your PHP code properly with the ... tag.


text:
Q: Is Dark Magic in Harry Potter evil? In Harry Potter, there is a lot of talk of "Dark Magic", "Dark Witches," and "Dark Wizards". But are they evil?
I know that if you're an evil sod, then you're more likely to take any advantage you can get and go right for the kill. But is there any reasoning behind "dark magic" being considered "dark" other than being unsportsmanlike, for lack of a better word?
A lot of stories and games have a trend of an evil act or spell being undeniably and even quantifiable evil, Evil is a force in the world that one can measure and detect. Does the HP universe have any such reasoning behind it's "dark side" beyond being the easy path?

A: I don't think so.
Dark Magic does not corrupt
Using Dark Magic does not supernaturally lead to using more Dark magic, or engaging in other evil actions. Harry uses the Imperius Curse twice in Deathly Hallows, and the Cruciatus Curse once. McGonagall also employs the Imperius Curse. Neither of them shows any temptation toward evil, nor do they start escalating their malicious actions thereafter. On the contrary, Harry arguably grows more noble.
Doing Dark Magic does not require being evil
Harry, McGonagall, and various others employ curses or hexes at various points, as mentioned in the previous answer.
Dark Magic does not come from a source of evil
There's no supernatural entity granting wizards their magic, whether benign or malign. So far as the series shows us, anyway, wizarding power comes from some innate quality (as does the magical power of other magical species, which many witches and wizards would rather pretend didn't exist). There's no Morgoth to grant knowledge of necromancy, no Satan to beg for charms.
These are really the three main ways in which something might be said to be "supernaturally" evil, and the Dark Arts fit none of them.
That said, while there may be no metaphysical component to Dark Magic, there is good reason to classify many such spells as evil, particularly thinking from the point of view of someone in peacetime.
Dark Magic is nonetheless unethical
Dark Magic is a rather broad field. Many spells are considered Dark, not merely
the Unforgivable Curses. We can see good reason for many of them:

*

*The only purpose of the Avada Kedavra curse is to kill. When you have many other spells that can subdue people, using a spell that can only kill them is somewhat evil.

*Crucio does nothing but cause someone pain. Again, there is little use for this spell (in-universe) besides torture, which is a pretty evil thing to do.

*The Imperius Curse removes someone's free will, which many people would consider quite an unethical thing in itself.

*Similarly, Sectumsempra is a particularly painful way of killing someone.

Note that none of these is inherently evil; if Stupefy etc. did not exist, and Avada Kedavra was the only way to stop someone, it might not be wrong. But under the circumstances that prevail for most of the Harry Potter series, the main reasons to use these spells would be negative ones.
More minor types of Dark Magic exist as well. According to JKR:

[Hex h]as a connotation of dark magic, as do jinxes, but of a minor sort. I
  see 'hex' as slightly worse. I usually use 'jinx' for spells whose
  effects are irritating but amusing.

The key is that such spells are harmful. Also, these minor types of Dark Magic, or at least things "affiliated with" Dark Magic,  appear to be taught in school. There's not any particular reason to think that Stunning Spells aren't technically a type of hex, and thus strictly speaking Dark Magic.
Note: Despite this, I would argue that a supernatural morality unconnected to magic itself does exist in the Potterverse. Magic may not be supernaturally evil, but evil is. For example, murder is known to split the soul, and there is no reason to think this works differently for non-magical individuals as for witches or wizards. Love is a powerful force that can be magically harnessed. Nonetheless, "Dark Magic" is a human label.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to repeat a certain piece of code When I declared an if statement to check if the user types in a number instead of a direct word or letter, it will say "Not a valid input, please enter your response as a number." But then once you click ok on the alert box when it says that message the message you typed in the prompt that was wrong or not a number will still get put in the object.
How can I make it so if you type something else but a number, it will keep on saying, "Not a valid input, please enter your response as a number" until you type in a number?
var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
    var askFirstName = prompt("What is your first name?");
    var askLastName = prompt("What is your last name" + " " +     titleCase(askFirstName) + "?");
    var askAge = prompt("How old are you" + " " + titleCase(askFirstName) +  " " + titleCase(askLastName) + "?");

if(!Number.isInteger(Number.parseInt(askAge))) {
    alert("Not a valid input, please enter your response as a number.");
};

    return {
        firstName: titleCase(askFirstName),
        lastName: titleCase(askLastName),
        age: askAge
    };
};
function titleCase(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
};

for(var i = 0; i < amountOfUsers; i++) {
    storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);

A: Instead show an alert call again to your function recursively.
if(!Number.isInteger(Number.parseInt(askAge))) {
    returnUserInput()
};

It will prompt again and again until response is ok.

A: Put the prompt, check and alert in a loop:
function returnUserInput() {
    var askFirstName = prompt("What is your first name?");
    var askLastName = prompt("What is your last name" + " " +     titleCase(askFirstName) + "?");
    while (true) {
        var askAge = prompt("How old are you" + " " + titleCase(askFirstName)
                            +  " " + titleCase(askLastName) + "?");
        if(Number.isInteger(Number.parseInt(askAge))) break; // OK, exit loop
        alert("Not a valid input, please enter your response as a number.");
    };
    return {
        firstName: titleCase(askFirstName),
        lastName: titleCase(askLastName),
        age: askAge
    };
};


text:
Q: How to iterate over a tf.tensor in eager mode I'm trying to iterate over a tensor in eager mode but I can't.
Naturally, you would do something like:
probs = tf.convert_to_tensor(np.array([[1,2,3], [4,5,6], [7,8,9]]))
indexs = tf.convert_to_tensor(np.array([1, 2, 3]))

@tf.function
def iterate_tensor(probs, indexs):
    return [output[label] for output, label in zip(probs, indexs)]
iterate_tensor(probs, indexs)

But this gives the error OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed:
Another thing that I tried was:
probs = tf.convert_to_tensor(np.array([[1,2,3], [4,5,6], [7,8,9]]))
indexs = tf.convert_to_tensor(np.array([1, 2, 3]))

@tf.function
def iterate_tensor(probs, indexs):
    return tf.map_fn(lambda i: i[0][i[1]], (probs, indexs), dtype=(tf.int64, tf.int64))

iterate_tensor(probs, indexs)

Gives the error ValueError: The two structures don't have the same nested structure.

A: This seems to work:
probs = tf.convert_to_tensor(np.array([[1,2,3], [4,5,6], [7,8,9]]))
indexs = tf.convert_to_tensor(np.array([1,1,1]))

@tf.function
def iterate_tensor(probs, indexs):
    return tf.linalg.diag_part(tf.gather(probs, indexs, axis=1))
iterate_tensor(probs, indexs)

Output: <tf.Tensor: shape=(3,), dtype=int64, numpy=array([2, 5, 8])>


text:
Q: Removing subarray from array with splice I am using splice method to remove a subarray from an array with the following code:

    for(let i = 0; i < cid.length; i++)
    {
      if(coinsValue[cid[i][0]] < troco && cid[i][1] > 0)
          available += cid[i][1]
      if(coinsValue[cid[i][0]] > troco)
          cid[i].splice(0)
    }

The output is :
[ [ 'PENNY', 1.01 ],
  [ 'NICKEL', 2.05 ],
  [ 'DIME', 3.1 ],
  [ 'QUARTER', 4.25 ],
  [ 'ONE', 90 ],
  [ 'FIVE', 55 ],
  [ 'TEN', 20 ],
  [ 'TWENTY', 60 ],
  [] /// removed elements from this array, but not the array itself ]

As you can see the elements that fit the condition are removed and I'm still left with an empty array. However I want to remove it completely!
Any help?

A: You're removing items from a sub array, not from the array itself.
To remove item from the top array you should do like this:
cid.splice(i, 1) instead of cid[i].splice(0)
for(let i = 0; i < cid.length; i++) {
    if (coinsValue[cid[i][0]] < troco && cid[i][1] > 0) {
        available += cid[i][1];
    } else if (coinsValue[cid[i][0]] > troco) {
        cid.splice(i, 1);
    }
}


text:
Q: Control console font & layout used by C# .NET console application How can I set Windows (or Visual Studio, or my application) so that when I run a console app by hitting F5 from Visual Studio 2010, I can get a 120x50 layout with my choice of font, instead of the 80x25 standard CMD/DOS window?
(even better - anyone know how I can get VS to run console apps in something like Console2 or bash instead of cmd.exe ?)

A: Run a program from VS as normal (ctrl-f5, or f5, or whatever) and then from the system menu (click the icon in the upper-left corner of the window), choose "Defaults". Alter your settings as you like, and save them. From then on, new windows should be launched according to those settings.
As for running your program in something other than "cmd.exe", you should be aware that "cmd.exe" is not involved at all in the window. The window is a normal console window, and "cmd.exe" didn't create it. In the same vein, "bash" wouldn't be involved, because that's a command shell, not a windowing program.
Cmd.exe and bash (and a whole host of others, including 4nt, command.com, and everything along those lines) are not windowing programs, and they don't create windows. They're console-mode programs, and Windows automatically creates special "console" windows for them to run in. Windows knows they're console-mode programs because there's a flag in the .exe file (which is a file format called PE) that specifies what type of application it is.
Console2 is a program that hosts console applications, and in theory could be used, if Console2 allows you to start it and an external program at the same time. In your project properties, under the "Debug" tab, change the "Start Action" option to "Start external program:" and type in the command line that will start Console2 and your program together.


text:
Q: Cannot connect Heroku to custom Google Domain In Heroku, my domain name for www.[somesite].com shows an ACM Status of "OK".
I also am using automatically managed SSL.
On Google Domains, I have a CNAME for www pointing to the DNS target.
I also have a synthetic record forwarding @ for .[somesite].com to https://www.[somesite].com, with Temporary Redirect, Do not forward path, and Disable SSL.
If I use "Enable SSL" I get an error saying that:
The SSL Certificate for this domain hasn't been created yet.This process may take up to 24 hours to complete.

However, the site does not work. I do not know why Heroku shows that it does nor why it gives a ACM Status of OK.
I have been beating my head against this for several hours and have no idea what to do. Anyone have an idea?

A: Updated 2021
The following guide will help you to set up a website with SSL and forward all versions of your site to the appropriately secured site (https).

*

*(Heroku) Deploy the site on Heroku (either with CLI or Github integration)

*(Heroku) Upgrade to the "Hobby" Dyno (for $7).

*(Heroku) Add SSL by going to Settings -> Configure SSL. Choose "Automatically".

*(Heroku) Add a domain (on heroku.com) by clicking "Add domain". Be sure to use www in the domain name. So the Domain Name text field would be "www.example.com".

*(Google Domains) Add a Custom Resource Record

*

*Name: www

*Type: CNAME

*TTL: 600

*Data: URL from Heroku

*

*For example, behavior-apple-eh2cfqgjkiop23q1wvd4372b.herokudns.com.

*(Google Domains) Add a Synthetic Record

*

*Subdomaine Forward

*Subdomain: @

*Destination URL: https://www.example.com

*Permanent Redirect (301)

*Forward path

*Enable SSL

*(Google Domains) If you are using a domain that requires DNSSEC (such as a .dev domain), enable DNSSEC in the DNSSEC section.

You will have to wait about 15 minutes for everything to propagate. At the conclusion of the 15 minutes, you will be able to go to every combination of your site, and it will redirect to https://www.example.com.

Some of the errors you may see along the way are as follows:
ACM Issue
On Heroku:

ACM is failing for 1 domain name

www.example.com Unable to resolve DNS for www.exampe.com

Solution: the reason you are seeing this is because your CNAME is not set up on Google Domains. Complete step (5) above to resolve this issue.
Extra Period Issue
(On Google Domains) "A period keeps getting added to the end of the "Data" section of the URL when I put it in."
Solution: This is expected.

Helpful images
Final Heroku Page

Final Google Domains Page

Resources

*

*Other StackOverflow answer

*My root domain isn't working, what's wrong?

*Heroku Devcenter: Add a Custom Root Domain


text:
Q: How can I submit div data to MySQL I was wondering how can I submit div data to MySQL. Im not used to javascript so I dont really know whats happening on the javascript part but how can I get or input the action="" part and method="" part and can I or should I add value="" to the hidden input???
Form html code:
<form onsubmit="document.getElementById('hidden_data').value=document.getElementById('showing_data').innerHTML;">
        <input id="hidden_data" name="data" type="hidden"/>

        <input type="submit" Value="Enter" id="submitthis">
</form>

A: Use the hidden field inside the form tag and use the JavaScript to put the value inside it. You can get the hidden field in the $_POST['hydName'].Put the data on the click of the submit button into the hidden field. Keep your action and method of the form same as required. After the click event is fired, it will submit the form to its action URL
<input type="submit" onclick="document.getElememtById('hidden').value = document.getElementById('div').innerHtml;" />


text:
Q: cancel a SynchronousRequest in iPhone SDK. (TIMEOUT Interval not working) I've queried this forum for hours looking for an idea/answer/solution for my problem, but came up empty every time.
i have created a SynchronousRequest using the following:
    NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [params length]];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setTimeoutInterval:3.0];
    [theRequest setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    [theRequest setHTTPBody: [params dataUsingEncoding:NSUTF8StringEncoding]];
    NSData  *aData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];

the connection is established, and the data is retrieved successfully to aData.
but, when there is a connection problem, or the server is not available, the request is attempting to connect for 75 seconds which is tooooo much time for the timeout interval,
i have added the setTimeoutInterval parameter (with 3 seconds) but it does not affect the connection,
i saw some answers from people saying that i should use NSTimer, and runLoop,
but it's not clear to me how this should be implemented.
PLEASE HELP!
the users are waiting 75 seconds before they get a timeout error message! it's ridiculous
appreciate your help.

A: On the iPhone a minimum timeout interval is hard-coded into the framework, you can't set the timeout below 75 seconds. Apple did this because there's frequently a significant amount of lag when you're dealing with cellular data connections.
What you want to do in most situations use an asynchronous network connection (so that your GUI doesn't freeze) and allow the request to go the full 75 seconds before timing out.
Read Apple's instructions for how to set up an asynchronous connection, it's a great start.
If you really do want to set a very short timeout, you can use an NSTimer like this:
- (void)loadURL:(NSURL *)url {
    /* Set up the NSURLConnection here */

    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(cancelURLConnection:) userInfo:nil repeats:NO];
}

- (void)cancelURLConnection:(NSTimer)timer {
    [self.connection cancel]
}

I'm not at my desktop, so that code may be buggy and it's definitely incomplete. Also note that you can't easily use a timer to kill a synchronous web requset, since the synchronous request blocks the runloop and the timer won't fire until the request is done.

A: may I suggest having a look at the sample code from simpleURLconnections?
From that code, the NSMutableURLRequest is sent using
 self.connection = [NSURLConnection connectionWithRequest:request delegate:self];

for both retrieving and sending data (but have a look at the rest of the code). Maybe the problem lies in the sendSynchronousRequest and you can avoid using that ?
Regards

A: You could use some code like the following (taken from an app I'm working on) - isFinished is a global variable:
- (void)someMethod {
    [[WSXMLRPCController sharedInstance] validateLicenseWithServiceURL:serviceUrl username:username password:password delegate:self];

    isFinished = NO;
    NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:10]; // break the loop after 10 seconds and not finished with the request from the call above ...
    while(!isFinished && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:endDate]){
        if([endDate compare:[NSDate date]] == NSOrderedAscending){
            [self connection:nil didFailWithError:nil forMethod:nil];
        }
    }
}

- (void)connection: (XMLRPCConnection *)connection didFailWithError: (NSError *)error forMethod: (NSString *)method {
   isFinished = YES;
}

- (void)connection: (XMLRPCConnection *)connection didReceiveResponse: (XMLRPCResponse *)response forMethod: (NSString *)method {
   isFinished = YES;
}

Probably not the cleanest solution, but it works. BTW this code is making use of the WordPress XMLRPCConnection class and delegate methods, but the same if possible with the NSURLConnection class and delegate methods.


text:
Q: wicket:link and pages with @AuthorizeInstantiation I have a navigation bar like:

        <wicket:link>

Page1

Page2

Page3

        </wicket:link>

This panel works really well (with the matching css).
But, Page3 is only accessible for users logged in.
@AuthorizeInstantiation("SIGNED_IN")
public class Page3 extends MyPage {
    // ...
}

When a user is logged in, everything is as expected.
Navigation: Page1 Page2 Page3

But when the user is not logged in, I expect Page3 not to be part of the navigation bar (because it is not accessible).
Navigation: Page1 Page2

How can I do this? TIA!

A: Add your links using wicket. Then use IAuthorizationStrategy to check if you can instantiate the page the link refers to. Hide the link if not:
IAuthorizationStrategy strategy = getApplication().getSecuritySettings().getAuthorizationStrategy();
Link<?> page1link = new Link<Void>("page1") {
    @Override
    public void onClick() {
        setResponsPage(Page1.class);
    }
}
page1link.add(new Label("page1linklabel","Page 1"));
page1link.setVisible(strategy.isInstantiationAuthorized(Page1.class));
add(page1link);

The html for your link then looks like this:


text:
Q: Why Apple allow to create multiple HMHomeManager instances I'll like to know why Apple allow to create more than one instance of HMHomeManager and what is the purpose of it?
I would expect the instance of HMHomeManager to be a singleton.

A: I can't speak for Apple but I see no cases where HMHomeManager would benefit from being a singleton and several clear disadvantages.

*

*HMHomeManager has a delegate property. The delegate pattern works well when you want a delegator to send messages to a single delegate or when many delegators might share a delegate. It is however not useful when one delegator might produce messages of interest to many delegates which would be the case if HMHomeManager were a singleton.

*Singletons are not easily deallocated. Any app using a HMHomeManager as a singleton would keep that object in memory monitoring for changes to the home database even if it was no longer needed.

*The assumption that there should only ever be one HMHomeManager may not hold true forever. While one HMHomeManager can contain many homes they all share a common user. Designing this class as a singleton would preclude an app from acting on behalf of multiple users at once. Even if there's never a need for such behavior developers might be wise to avoid selecting an interface which cannot support it early in the design process.

A: Don't create multiple instances of HMHomeManager.May be below code will be helpful. If you want to made any changes to the existing home try to execute the code after made the changes like add room,zone...
for(HMHome *home in appDelegate.homeManager.homes)
{
    if([home.name isEqualToString:appDel.selectedHome.name])
    {
        appDel.selectedHome = home;
    }
}

A: I would expect internally there is a singleton client that communicates with the home daemon, the same way CLLocationManager has a singleton CLLocationInternalClient.sharedServiceClient which allows us to scatter location managers throughout our app without having to worry about forwarding notifications or multicasting delegate methods around ourselves. I haven't examined HMHomeManager as closely and it does seem quite a rushed API so maybe not as well designed. It's concerning the documentation mentions "the manager for your app" as if we are only supposed to have one. Furthermore when you receive the home changed delegate call it tells us to "invalidate your own app's objects that cache the home's data". One thing I have noticed is when you init a HMHomeManager it inits all the rooms, services and accessory objects which in my case is about 400KB (calculated by initing 10 home managers and comparing the RAM difference) for my 301 characteristics, 68 services, 19 accessories home (I used Allocations in Instruments searching for 'HM' to learn this). So we probably should stick to one manager per app but there is a serious design problem with the API that when we toggle a characteristic the delegate method isn't called so we need to reach out to our app's object and invalidate it rather than it happening automatically for us like any other API would.


text:
Q: Cisco anyconnect keeps disconnecting and reconnecting For some reason every few minutes Cisco anyconnect VPN client keeps disconnecting and reconnecting.
Example log:
  4:28:43 PM    Connected to myaccess.oraclevpn.com.
     4:34:10 PM    Reconnecting to myaccess.oraclevpn.com...
     4:34:10 PM    Establishing VPN - Examining system...
     4:34:10 PM    Establishing VPN - Activating VPN adapter...
     4:34:10 PM    Establishing VPN - Configuring system...
     4:34:10 PM    Establishing VPN...
     4:34:10 PM    Connected to myaccess.oraclevpn.com.
     4:35:30 PM    Reconnecting to myaccess.oraclevpn.com...
     4:35:30 PM    Establishing VPN - Examining system...
     4:35:30 PM    Establishing VPN - Activating VPN adapter...
     4:35:30 PM    Establishing VPN - Configuring system...
     4:35:30 PM    Establishing VPN...
     4:35:30 PM    Connected to myaccess.oraclevpn.com.
     4:49:35 PM    Reconnecting to myaccess.oraclevpn.com...
     4:49:36 PM    Establishing VPN - Examining system...
     4:49:36 PM    Establishing VPN - Activating VPN adapter...
     4:49:36 PM    Establishing VPN - Configuring system...
     4:49:36 PM    Establishing VPN...
     4:49:36 PM    Connected to myaccess.oraclevpn.com.
     5:19:20 PM    Reconnecting to myaccess.oraclevpn.com...
     5:19:20 PM    Establishing VPN - Examining system...
     5:19:20 PM    Establishing VPN - Activating VPN adapter...
     5:19:20 PM    Establishing VPN - Configuring system...
     5:19:20 PM    Establishing VPN...
     5:19:20 PM    Connected to myaccess.oraclevpn.com.
     5:21:46 PM    Reconnecting to myaccess.oraclevpn.com...
     5:21:46 PM    Establishing VPN - Examining system...
     5:21:46 PM    Establishing VPN - Activating VPN adapter...
     5:21:46 PM    Establishing VPN - Configuring system...
     5:21:46 PM    Establishing VPN...
     5:21:46 PM    Connected to myaccess.oraclevpn.com.
     5:27:31 PM    Reconnecting to myaccess.oraclevpn.com...
     5:27:31 PM    Establishing VPN - Examining system...
     5:27:31 PM    Establishing VPN - Activating VPN adapter...
     5:27:31 PM    Establishing VPN - Configuring system...
     5:27:31 PM    Establishing VPN...

I am on latest 4.6.01103

A: For me what solved this is to work only on wifi or only on wired ethernet connection (I disabled the wifi adapter (in Control Panel\All Control Panel Items\Network Connections in win10)
Now everything is stable!

A: I had the same issue and inspired by thedrs answer, I disabled all network adapters I didn't need for the VPN connection.
It turned out that the Hyper-V machine (and the corresponding virtual Ethernet adapter) I had running were causing it. After shutting down the virtual machine, no more reconnects occurred.

A: I know this thread is old but I just ran into this problem (it would reconnect at least several times/hour - sometimes several times within a 60 second span). The above two solutions didn't work for me (disabling unused network connections, shutting down hyper-v machine) but what DID work for me was disabling IPV-6 under network connections:
Open up network connections, right click on wi-fi or ethernet, go to properties and uncheck the box corresponding to Internet Protocol Version 6.
I thought I saw that suggestion in this thread, but I can't find it anymore. Good luck!

A: There are 3 parties involved in this problem. Cisco, your IT dept, and ISP. They can fix it by either changing group policy and moving the port, etc. Apparently, your ISP is limiting and disconnecting people using VPN to watch overseas TV. That's why your company VPN keeps reconnecting. But when you call them, they will point to the other two parties. So the ONLY and easiest way for you to do YOURSELF is to disable all other connections, including Bluetooth, Virtual Machine, Wired (if you're on wireless). And for the remaining wireless AND AnyConnect connection, UNCHECK IP6 from the network properties! Easy fix by yourself and work and uptime 100% for those WFH and Covid Lockdown folks.


text:
Q: Web api authentication schema I'm implementing a rest api to using the new web api framework. This api will be consumed by other companies so we'll be adding an authentication method.
In relation to authentication, I'm thinking to implement something based on tokens. Something like this

*

*client provide credentials to login method

*system authenticate client and send a token

*client uses this token on following api calls

I wonder if this schema is useful for my scenario. Operations will be mainly atomic, basically clients will periodically ping this api to get some specific data, so not sure if make sense having a session token (at some point the token should expire and not sure how to manage this).
How would you recommend to implement authentication schema for this scenario?

A: When you generate a token I would store it in a database with a foreign key back to the authenticated login's primary key. I would also (with the token) store the date and time it was established, and a timeout period (you could set this per token, or store it in a config).  Check the token/time everytime the service is pinged by that user, then force them to reauthenticate after that time expires (by checking it against the created date stored with the token).
This would make sure that the login information is only getting transmitted after the token expires, when a new token is generated it would delete the old token record.
Am I understanding your requirements right?

A: Making a token based authentication scheme like this is not easy.
I don't really have an answer for how you could implement it in a good and secure way. But will offer some thoughts off the top of my head about issues you will have to deal with:

*

*The token generation need to be well randomized and the tokens need to be "sufficiently" (for some definition of sufficient) long in order to prevent someone from simply sending a bunch of different tokens to see if he "gets a hit"

The above issues should not be too difficult to implement. But the more tricky thing to figure out is:

*

*How you can you reliably verify that the token has not been "kidnapped".

If the token is simply some random string, then anyone who happens to "see" it in tranfer (use SSL) will be able to assume the identity of the use for which the token was generated.
The token, when received by your service will let you know that:

*

*Your application issued the token to user/application/entity X

*The token is intact (has not been changed)

*Any other thing you store with the token (is it expired etc)

But it will not without further effort let you know for sure that it was sent by user/application/entity X. It could be Y who has managed to get hold of the token.
That is the case for many authentication schemes of course, so depending on just how sensitive your data is, and also on what kind of operations can be done via you service, it may not be a huge issue for you.


text:
Q: How to automatically precompile css.erb file on every request In custom_colors.css.erb file is:
<%
  WebsiteSetting.last.link_color.present? ? (link_color = WebsiteSetting.last.link_color) : (link_color = '#0088cc')
%>
$custom_link: <%= link_color %>;

and in many css files i'm using $custom_link variable, but when i update WebsiteSetting.last by setting link_color field by colorpicker (hex), nothing changes in views. I suppose the problem is with precompiling custom_colors.css.erb file after request.

A: Dynamic assets precompilation (on each request) is normally done in development environment only for debugging reasons.
If you want to be able to use some request-dependent styles consider moving that code to the application layout:
application.html.erb:
<!DOCTYPE html>
<html lang="en">
  <head>
    ...
    <style type="text/css">
      #my_div {
        color: <% WebsiteSetting.last.link_color.present? ? WebsiteSetting.last.link_color : '#0088cc' %>;
      }
    </style>
    ...
  </head>
  <body>
    ...
  </body>
</html>


text:
Q: CoreData, Magical Record and mogenerator I've just installed mogenerator to create the Managed Objects in my project.
I was working without mogenerator before.
I'm also using MagicalRecord.
I have an entity Message and I am trying to run the line...
return [Message countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"user == 123"]];

but I'm getting an unrecognized selector error on this line.
If I change it to...
return [_Message countOfEntitiesWithPredicate:[NSPredicate predicateWithFormat:@"user == 123"]];

It works fine. But the stupid thing is that I do this same function a couple of lines later with a different predicate and it works fine without the fix. I have tried without the predicate but get the same result.
EDIT
I just tried commenting this line out and putting...
return 0;

Now I get the unrecognized selector on the second use of this line. It's almost like I have to "initialise" the CoreData by calling it on _Message first?!?!
Any ideas?
EDIT 2
I'm also getting this when trying to run...
[Message createEntity];

Same unrecognised selector. This is very annoying if it's going to do this to all my Core Data stuff.

A: I had a similar problem. What I realized is Core Data does not like entities named "Message" and "Connection". Prefixing these with my custom prefix solved the issue for me.

A: I don't know 100% that this was the answer but when I ran the project using AppCode in the iPhone simulator I saw an odd debug message that said the class Message was implemented twice.
It must have been implemented in another framework I was using or something.
When I changed the name of the core data entity back to something more unique it worked fine.
I'm surprised this compiled at all TBH.


text:
Q: Counting total number of points within polygon (Buffer) layer using ArcGIS Pro I'm trying to count the total number of points contained within a polygon layer.
I have a series of buffer layers, each getting progressively larger and encompassing more points.
I have used the "summarize within" / "spatial join" tool as suggested by Esri: https://support.esri.com/en/technical-article/000023531
However, these tools provide the count of points for each polygon, rather than the count of unique points for the entire layer.
I could add up the point count for each polygon but, as some points sit within two or more overlapping polygons, this would result in some points being counted more than once.
How can I ensure I am counting each individual point within a polygon LAYER only once?

A: You could join your polygon layer into a single polygon feature. Or more straightforward, when you create your polygon Buffer, you can set the dissolve type to "Dissolve all output features into a single feature", which you can then follow up by using the summarize within tool.


text:
Q: How include precision and scale patrs to decimal column defintion in liquibase? Let say that I want to create some Number with 10 precision digit and 2 fratcion digits like that 0123456789.12. Is there a way to define such type and keep column definition dabase agnostic? E.g. define type that converted by liquibase automaticy to DECIMAL(10, 2) for Mysql and NUMERIC(10, 2) for postgres (or any other database).

A: we use this column definition and it works:
<column name="lat" type="DECIMAL(12, 2)">


text:
Q: Android custom Arrayadapter not showing data in list view I want a page with highscores. I made a row.xml for the layout and I made a custom ArrayAdapter. When I print out my objects, I get the right info but it does not come into my list view. It shows nothing at all.
Here is my row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/txtNumber"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:text="@string/txtNumber" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtName"
        android:id="@+id/txtName"
        android:layout_gravity="top|bottom"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txtScore"
        android:id="@+id/txtScore"
        android:layout_weight="1" />

</LinearLayout>

My custom arrayAdapter
Package be.ehb.dt.multiscreen_highscores;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

// ** * Created by Naomi on 17/12/15. */

public  class PersonAdapter extends ArrayAdapter<Person> {

    public PersonAdapter(Context context, ArrayList<Person> personen) {
        super(context,0, personen);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        Person person = getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, parent, false);
        }

        TextView txtNumber = (TextView) convertView.findViewById(R.id.txtNumber);
        TextView txtName = (TextView) convertView.findViewById(R.id.txtName);
        TextView txtScore = (TextView) convertView.findViewById(R.id.txtScore);

        txtNumber.setText(""+person.number);
        txtName.setText(person.name);
        txtScore.setText(""+person.score);
    return convertView;
    }
}

And my mainActivity
package be.ehb.dt.multiscreen_highscores;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity{
    private ArrayList<Person> personen;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<Person> arrayOfPersons = new ArrayList<Person>();
        PersonAdapter adapter = new PersonAdapter(this,arrayOfPersons);
        ListView v = (ListView) findViewById(R.id.listHighscores);

        personen=new ArrayList<>();
        personen.add(new Person(1,"Naomi",3454));
        personen.add(new Person(2,"Steven",2394));
        personen.add(new Person(3, "Lieven", 2254));
        Log.d("print",personen.get(1).toString());
        v.setAdapter(adapter);

    }

}

A: You should modify your adapter code like ,
ArrayList<Person> personen;
public class PersonAdapter extends ArrayAdapter<Person> {

public PersonAdapter(Context context, ArrayList<Person> personen) {
    super(context,0, personen);
    this.personen = personen;

}

@Override
public int getCount() {
    return personen.size();
}

Now get here Person person = personen.get(position);
Edit:
    ListView v = (ListView) findViewById(R.id.listHighscores);
    personen=new ArrayList<>();
    personen.add(new Person(1,"Naomi",3454));
    personen.add(new Person(2,"Steven",2394));
    personen.add(new Person(3, "Lieven", 2254));
    Log.d("print",personen.get(1).toString());
    PersonAdapter adapter = new PersonAdapter(this,personen)
    v.setAdapter(adapter);


text:
Q: Partitioning array index out of bounds I am trying to implement a randomized selection algorithm where an array is filled with random numbers and the user selects a location and the program returns the value coinciding with the location in the sorted version of the array without actually sorting the array.
The problem is that the program is giving an Array Index Out of Bounds error and I believe I wrote the randomized partition and swap functions correctly.
import java.util.*;

public class RandomizedSelection {

    public static void main(String[] args) {
        int[] arr = new int[10];

        // fill array with random numbers between the range of 0-200
        for (int i = 0; i < 10; i++) {
            int n = (int)(java.lang.Math.random()*199);
            arr[i] = n;
        }

        System.out.println("There is an array of 10 elements in the range" +
                            " of 0 - 200. Select a location to view" +
                            " the value.");

        int loc = randomizedSelect(arr, 0, arr.length-1, 5);

        System.out.println(loc);

        System.out.println("The array was:\n" + Arrays.toString(arr));
    }

    public static int randomizedSelect(int[] array, int start, int end, int i) {
        if (start==end)
            return array[start];

        int q = randomizedPartition(array, start, end);
        int k = q - start + 1;

        if (i == k)
            return array[q];

        else if (i < k)
            return randomizedSelect(array, start, q-1, i);
        else
            return randomizedSelect(array, q+1, end, i-k);
    }

    public static int randomizedPartition(int[] array, int start, int end) {
        Random rand = new Random(System.currentTimeMillis());
        int pivotIdx = rand.nextInt(end - start + 1) + start;
        int pivot = array[pivotIdx];

        swap(array, array[pivotIdx], array[end]);

        System.out.println(Arrays.toString(array));
        pivotIdx = end;

        int i = start - 1;

        for (int j = start; j <= end-1; j++) {
            if (array[j] <= pivot) {
                i = i + 1;
                swap(array, array[i], array[j]);
            }
        }
        swap(array, array[i+1], array[pivotIdx]);
        return i+1;
    }

    private static void swap(int[] array, int i, int j) {
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

I am not sure why the index is out of bounds. My assumption is that when it reaches the last element in the array, there is no element to swap it with. Is this the issue? How can I fix this? I was thinking of just partitioning it into two arrays, but I'd prefer avoiding that.

A: Your call to swap() is passing the contents of the array at the given index position rather than the index position itself for both i and j. To find this all I needed to do was put print statements in swap()

A: You need to replace
swap(array, array[pivotIdx], array[end]);
swap(array, array[i], array[j]);
swap(array, array[i+1], array[pivotIdx]);

with
swap(array, pivotIdx, end);
swap(array, i, j);
swap(array, i+1, pivotIdx);

Because, when you ask for a swap, you use the index and not the value


text:
Q: How do I build and link external cross platform libraries in C? I am relatively new to C and I'm making a project that I wish to be cross platform. I want to use an external library that has sworn to be cross platform as well. I am wondering how I should include this within my project?
From what I can understand, I have two options. Build the libraries before hand on every platform I wish to use, then handle which library is linked within my build process (not very platform independent). Or I can include the entire source of the library and build it along with my project.
Are these my only options for handling cross platform libraries? Maybe I am not understanding how the process completely works yet, so any help would be awesome!
(PS I'm using CMake to build my project.)
Thanks!

A: There are several factors and their combinations that may affect the answer.

*

*The external library can be either static or shared.

*The build is intended for internal testing or for release.

*The application source code with autoconf stuff is distributed or binary application is distributed.

*The external library source code with own autoconf stuff is distributed or binary shared library is distributed.

When you want to distribute binary application then it is better to use the static external library. In this case you only have the options written above. You can either build the library before hand for each platform or incorporate the library build to your building process.
If the external library and the application are open source and they are distributed with own autoconf stuff then you do not need to distribute the external library and you can just add an autoconf dependency.


text:
Q: mfc c++ strange block characters after text written to file my program has two edit control boxes that display text from a text file, and they both have buttons associated with them that update the text files associated with them if anything is written or deleted in the edit control boxes. i have this code to read from a text file
    try
{
    CStdioFile file(_T("1.txt"), CFile::modeRead);
    CString str,mainstr = _T("");
    while(file.ReadString(str))
    {

        mainstr += str;
        mainstr += _T("\r\n");
    }

    CWnd *editwindow = this->GetDlgItem(IDC_EDIT2);
    editwindow->SetWindowText(mainstr);

}
catch(CException* e)
{
    MessageBox(_T("no such file"));
    e->Delete();

}

and then this code to write to the text file
    m_addtext.GetWindowText(m_adtxt);
if ( IsDlgButtonChecked(IDC_RADIO1) == BST_CHECKED )
{
    CStdioFile file;
    file.Open (_T("1.txt"), CFile::modeCreate | CFile::modeWrite);
    file.WriteString (m_adtxt);
    file.Close ();
}

it all works pretty much fine and dandy for what i want, but the problem is is that it adds a block character after a word if i delete a character in the edit box, and then click the update button. sometimes it even adds a block after every word and one block on every empty line. it works fine as long as it creates a new file and nothing is deleted. i've tried null terminating, i've tried ccs="encoding". can anyone point me in the right direction?

A: As MSDN says about CStdioFile in its default of text mode:

Text mode provides special processing for carriage return–linefeed
  pairs. When you write a newline character (0x0A) to a text-mode
  CStdioFile object, the byte pair (0x0D, 0x0A) is sent to the file.
  When you read, the byte pair (0x0D, 0x0A) is translated to a single
  0x0A byte.

So, although your reading looks ok, because the \n will be stripped off by the overload of ReadString that you use, then you have manually appended \r\n to display correctly in an edit control, however when you save the contents, every \r\n will be explanded to \r\r\n as described in the quote above.
The solution is either to remove all of the \r characters from the string before writing to CStdioFile, leaving just the \n characters, and let CStdioFile insert the \r for you. Or, much easier, just open the file in binary mode rather than text mode to suppress this conversion:
CStdioFile file;
file.Open (_T("1.txt"), CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
file.WriteString(m_adtxt);
file.Close ();


text:
Q: Rewriting URLs from http:// to https:// in IIS8 Goal : I would like to redirect multiple sub domains (e.g.http://xxx.domain.com) to https://xxx.domain.com
I have the following binding in IIS
Hostname : domain.com
Port : 80
Ip Address: *
Hostname : domain.com
Port : 443
Ip Address: *
I have the following rewrite rule in my web.config
  <rules>
    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="http://(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
    </rule>

for some reason http://xxx.domain.com gives a 404 instead of being redirected.  https://xxx.domain.com works fine.
Any clue why http://xxx.domain.com gives a 404 ?

A: My web.config contains:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <system.webServer>
      <rewrite>
         <rules>
            <rule name="Redirect to HTTPS" enabled="true" stopProcessing="true">
               <match url="(.*)" />
               <conditions>
                  <add input="{HTTPS}" pattern="^OFF$" />
               </conditions>
               <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
            </rule>
         </rules>
      </rewrite>
   </system.webServer>
</configuration>

And this is working for me.  The differences I see between mine and yours are:
My rule has "enabled="true" in it and my initial match does not have "http://" in the pattern, just the "(.*)" .

A: The URL in your match tag is wrong, it should be:
<match url=".*" />

And in the action URL, replace {R:1} with {R:0}.


text:
Q: How to calculate gl_FragCoord in glsl Ok, in my GLSL fragment shader I want to be able to calculate the distance of the fragment from a particular line in space.
The result of this is that I am first trying to use a varying vec2 set in my vertex shader to mirror what ends up in gl_FragCoord:
varying vec2 fake_frag_coord;
//in vertex shader:
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
fake_frag_coord=(gl_ModelViewProjectionMatrix * gl_Vertex).xy;

Now in the fragment shader I expect:
gl_FragCoord.xy==fake_frag_coord

But it does not. What operation does the pipeline do on gl_Position to turn it into gl_FragCoord that I am neglecting to do on fake_frag_coord?

A: gl_FragCoord is screen coordinates, so you'd need to have information about the screen size and such to produce it based on the Position. The fake_frag_coord you've produced will correspond to a point in the screen in normalized device coordinates I think (-1 to 1). So if you were to multiply by half the screen's size in a particular dimension, and then add that size, you'd get actual screen pixels.

A: The problem you have is that gl_ModelViewProjectionMatrix * gl_Vertex computed in a shader is not always what the fixed function pipeline yields. To get identical results, do fake_frag_coord = ftransform().
Edit:
And then scale it with your screen dimensions.

A: I wish I had more rep so I could nitpick too.
Here's what I know.
OpenGL performs the Divide-By-W automatically for you, so by the time a position arrives in a fragment shader, it's already in NDC coordinates, and by then W will be 1.0, the only time you need to divide by W is if you want to do the same math on the CPU side, and get the same results, OR, if you for some odd reason, wanted to get NDC coordinates within your vertex shader.

A: varying vec2 fake_frag_coord;
//in vertex shader:

fake_frag_coord=(gl_ModelViewMatrix * gl_Vertex).xy


text:
Q: What is Div if not division size.total = size.width * size.height;
y = yuv[position.y * size.width + position.x];
u = yuv[(position.y / 2) * (size.width / 2) + (position.x / 2) + size.total];
v = yuv[(position.y / 2) * (size.width / 2) + (position.x / 2) + size.total + (size.total / 4)];
rgb = YUV444toRGB888(y, u, v);

Here / is Div not division.

The above formula is taken from the wikipedia link .
The one thing I want to know is that the statement mentioned

Here / is Div not division.

What is Div here then, it is not dividing then what?

A: What the page means by Div is integer division.  In C, if both operands to the / operator are of an integral type, the result is also of an integral type and any fractional part is truncated.
For example, 5 / 2 evaluates to 2.


text:
Q: How to create a java object that gets values from users? So i am working on a java project in which i have very little experience.I have to create 2 objects,x and y.Object x which contains given values using a constructor.Object y ,which i am stuck, requires values given by the user from the keyboard and i cant find a way to do that.Later on i have to compare these to objects for another question that is being asked.Can anyone help me out with object y?
I am being taught java for not over a month and i am struggling to finish this project before the deadline.Thanks in advance!

A: You can find here how to read values from a user :
https://www.w3schools.com/java/java_user_input.asp
 The w3schools.com site has a full Java tutorial(and not only) that's gonna help you a lot! Good luck finishing that project!


text:
Q: Text Field Not Updating I'm trying to get the log on my program to update with every button press *see picture below, however it will only display the data on the first time it has been pressed. I'm not sure if that's because it's in a for loop.
Initialise button
stop();
import flash.events.MouseEvent;
var MAX_ORGANISMS: int = 12;
var MAX_GENES: int = 2;
var genotype: Array = new Array();
var MAX_PARENTS: int = 2; // number of parents organisms to select
var MAX_CHILDREN: int = 2; // number offspring per selected parent
var generation: int = 0; // to count the generation being shown
var list_selected: Array = new Array(); // list of selected org.
var number_selected: int;
var geno_text: String = "";

function random_genotype_initialisation(): void {
generation = 0;
number_selected = 0;
var org: int;
for (org = 0; org < MAX_ORGANISMS; org++) {
    list_selected[org] = 0;
    var genotype_1organism: Array = new Array();
    genotype_1organism[0] = randomRangeInteger(1, 4);
    // gene1 = head colour (4 types)
    genotype_1organism[1] = randomRangeInteger(46, 49);
    // gene2 = head width (44 - 48)
    genotype_1organism[2] = randomRangeInteger(50, 55);
    // gene3 = head legnth
    genotype_1organism[3] = randomRangeInteger(1, 4);
    // gene4 = eye type (4 types)
    genotype_1organism[4] = randomRangeInteger(30, 35);
    // gene5 = eye width (30 - 35)

    genotype_1organism[5] = randomRangeInteger(1, 4);
    // gene6 = nose type (4 types)
    genotype_1organism[6] = randomRangeInteger(10, 18);
    // gene7 = nose height (10 - 18)

    genotype[org] = genotype_1organism.slice();

}
}

function randomRangeInteger(min: int, max: int): int {
    var randomNum: int = Math.floor(Math.random() * (max - min + 1)) + min;
    return randomNum;
}

function show_phenotype(): void {
var org: int;
var org_property: String;
for (org = 0; org < MAX_ORGANISMS; org++) {

    org_property = "o" + org + "_head";
    this[org_property].gotoAndStop(genotype[org][0]);
    this[org_property].width = genotype[org][1];
    this[org_property].height = genotype[org][2];

    org_property = "o" + org + "_eyes";
    this[org_property].gotoAndStop(genotype[org][3]);
    this[org_property].width = genotype[org][4];

    org_property = "o" + org + "_nose";
    this[org_property].gotoAndStop(genotype[org][5]);
    this[org_property].height = genotype[org][6];

    geno_text += "Geno" + org + " has initialised." + "This Geno has a " + genotype[org][1] + " by " + genotype[org][2] + " face" + "\n" ;
    geno_log.text = geno_text;

}
}

function initialise(event: MouseEvent) {
random_genotype_initialisation();
show_phenotype();
}

initialise_btn.addEventListener(MouseEvent.MOUSE_UP, initialise);

The program has some faces, which change features randomly, each time the user presses the initialise button. Which by my knowledge shows that the button handler works, and the program is performing correctly, however, the text does not follow suit and only changes once.


text:
Q: React-Native: Android Webview very slow with AngularJS-Website I threw together an example project with the webview in it. What perplexes me is that loading the Angular-page with Android is ca. 3x slower than loading it with iOS. Am I missing something?
I tried turning on hardware acceleration bc I read it somewhere but hardly does anything. I'm aware this is a vague question, still hope I could get some hints.
The code is just the sample:
  <View style={styles.container}>
    <WebView
        source={{uri: 'https://AngularSite'}} />
   </View>


text:
Q: How to extract all numbers ending in a certain string from cell, and sum them together So in a table form, here is what I want to achieve (fill in the Total column automatically summing up all numbers that have exactly h behind them, preferably with arrayformula.

Stuff
Total

Apples 1,5h, Banana 2x, Oranges 3h
4,5h

5 Pears 1h, 2 Kiwis 1x, Melon 4h, 2h
7,0h

Stuff 1g, Stuff 2 1,5h, Stuff 3 2j
1,5h

I've tried everything I can come up with, and I'm outta luck. I can get to a point where I have just the correct numbers as a split with
=arrayformula( if( len( A2:A );
      substitute( substitute(
        iferror(
          if(
            regexmatch( iferror( split(A2:A; " ") ); "[0-9]*[,]?[0-9]h+" );
            iferror( split(A2:A; " ") );
          )
        );
      "h," ;"" ); "h"; "" )
; "") )

But I don't know where to go from there. I've tried summing the numbers up in a million ways with mmult but always end up short somehow.
Oh, note that I'm using ; to separate commands and , as a decimal separator, regional things and shouldn't matter in your answers.
Doing this thing in script was quite trivial, but usage of it is slow and it updates all the cells every time you add a row. I'm sure it's doable as a cell formula too so just eager to know how. Thanks in advance.

A: try:
=ARRAYFORMULA(IF(A1:A10="",,TEXT(MMULT(IFERROR(SUBSTITUTE(
 REGEXEXTRACT(SPLIT(A1:A10, ", ", ), "(\d+(?:.\d+)?)h"), ",", "."))*1,
 SEQUENCE(COLUMNS(SPLIT(A1:A10, ", ", )), 1, 1, 0)), "0.0\h")))

for non-english sheets go for:
=ARRAYFORMULA(IF(A1:A10="";;TEXT(MMULT(IFERROR(
 REGEXEXTRACT(SPLIT(A1:A10; ", "; ); "(\d+(?:.\d+)?)h"))*1;
 SEQUENCE(COLUMNS(SPLIT(A1:A10; ", "; )); 1; 1; 0)); "0.0\h")))


text:
Q: ios detect a false change in wireless - Reachability Example My Application use Wifi network and I am using Reachability example code to detect the Wifi network.
Application works well when app is connected to any normal Wifi Access Point but my app detects false network change when app is connected to Ad-hoc network.
When App is connected to ad-hoc network, after some time (around every 15 to 20 minutes) current reachability status goes to Not Reachable for few seconds and comeback again to Reachable state (FYI, Similar Android App is working fine on same Ad-hoc network).
Debug Information
Reachability Flag Status: -- -------
After 1 or 2 seconds Wifi return to normal status
Reachability Flag Status: -R ------d
Code
    - (NetworkStatus) currentReachabilityStatus{
        NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef");
        NetworkStatus retVal = NotReachable;
        SCNetworkReachabilityFlags flags;
        if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
        {
            if(localWiFiRef)
            {
                retVal = [self localWiFiStatusForFlags: flags];
            }
            else
            {
                retVal = [self networkStatusForFlags: flags];
            }
        }
        if(NotReachable == retVal){
            printf("\nNetwork not reachable.");
        }
        return retVal;
    }


text:
Q: boost::geometry::within for a point in a geographic coordinate system fails --- why? Code:
I am using boost_1_61_0.  I am using the geometry part of the library for a GIS application.  The idea is to find points within defined regions (a rectangle in this case).  This works sometimes but not always.  Here is an example where the point should be within the rectangle but isn't...
I have the following test case:
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/multi/geometries/multi_polygon.hpp>
#include <boost/geometry/geometries/register/point.hpp>
#include <iostream>
#include <boost/geometry/io/wkt/wkt.hpp>

class wxPoint
{
public :
    double  getx() const
    {
        return m_x;
    }
    double gety() const
    {
        return m_y;
    }
    void setx( double in)
    {
        m_x = in;
    }
    void sety(double in)
    {
        m_y = in;
    }
private:
    double m_x;
    double m_y;
};

BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET(
    wxPoint,
    double,
    boost::geometry::cs::geographic<boost::geometry::degree>,
    wxPoint::getx,
    wxPoint::gety,
    wxPoint::setx,
    wxPoint::sety )

int main()
{
    boost::geometry::model::polygon< wxPoint > poly;

    boost::geometry::read_wkt( "POLYGON((0 89, 180 89, 180 0, 0 0, 0 89 ))", poly );

    wxPoint point;
    point.setx( 150 );
    point.sety( 88 );

    bool within = boost::geometry::within( point, poly );

    return 0;
}

I expect within to be true but it is false.   Why is it false?

A: If you don't put the points in clockwise order the boost::geometry::within may be undefined.
Try boost::geometry::read_wkt( "POLYGON((0 89, 0 0, 180 0, 180 89, 0 89 ))", poly );  instead

A: On further investigation, see my comments on the other answer, it appears that this is a difference in how boost geometry builds the polygon that you give it.
When we give a point as 0 0 to 180 0 this in boost land actually wraps the world to the west in this case and not the east as I and I'm sure you were expecting.
To prevent this from happening I would suggest inserting an extra point to break up any single vertex that has a longitude component greater than or equal to 180 degrees.  This forces boost to plot in the direction you intended rather than the shortest distance.


text:
Q: Why do some sites not load if cookies are blocked? As a rule I only allow cookies from sites that require one to logon, and my browsers(Palemoon and Chromium) are set to reject cookies by default, except for a whitelist.
Some sites simply don't load unless you let them set cookies, all I get is a blank page.
Is there a reason why?
Was looking at it from a browser compatibility angle. My question is adequately answered now.

A: In many cases, unfortunately, this is just bad development. I've seen a lot of pieces of code related to cookies with no error handling whatsoever regarding disabled cookies. There are 3 cases: websites that need cookies and that will print a page if you have them disabled (that's good), websites that need them but just seem to print an unclear error when you try, and websites that need or don't even need them but fails to handle the case where there are disabled. Depending on the language used for development, it will raise an exception that, if not caught, will lead to a blank page, as debug information is disabled in production mode (if they at least did this).


text:
Q: What does the word "sideways" mean here? Here is a sentence from an instruction passage of a game:

A sideways swipe will see the main character change direction or pull
  off a speedy mid-air dash

I am not sure if the word sideways means oblique or on one side here.

A: "Sideways" means travelling in a relative direction of left-right or right-left.
In your example, a "sideways swipe" seems to mean a touch-screen gesture with your finger moving from one side of the screen to the other.
From the details you give, I'm not sure if you may be confusing the word "swipe" with the word "slash". For clarity, this is not talking about the symbol /


text:
Q: Proving the inverse image of a subalgebra under a homomorphism is a subalgebra Let $h : \mathbf{A} \rightarrow \mathbf{B}$ be a homomorphism of $\Sigma$-algebras. Given any subalgebra $\mathbf{Y}$ of $\mathbf{B}$, prove that $h^{-1}(Y)$ is a subalgebra of $\mathbf{A}$ (denoted by $h^{-1}(\mathbf{Y}))$.
I think I have most of it, but I get stuck in showing that each function in the subalgebra $h^{-1}(\mathbf{Y})$ is a restriction of the corresponding function in $\mathbf{A}$.


text:
Q: What is wrong with my oneToMany/manyToOne relation in Doctrine? I implemented a manyToMany relationship in Symfony2/Doctrine, where the relation is an Entity itself (that was necessary because I needed to add additional columns - notice that these additional columns are not mentioned below).
There are a couple of Q&As around here that recommend to take the relationship as an entity (e.g. here, here, here or here).
I have automatically generated all getter and setter methods via doctrine:generate:entities (this explains why it is called addCompanie instead of addCompany), so I would have thought that this covers my oneToMany/ManyToOne relationship.
And creating a User and a Company work fine so far. But as soon as I try to assign a user to a company I get the following error message:

Found entity of type Acme\MyBundle\Entity\User on
  association Acme\MyBundle\Entity\Company#employees,
  but expecting Acme\MyBundle\Entity\CompanyHasUser

These are my Doctrine definitions (yml):
# User
Acme\MyBundle\Entity\User:
  type: entity
  fields:
    id:
      id: true
      type: integer
      generator:
        strategy: AUTO
  oneToMany:
    companies:
      targetEntity: Acme\MyBundle\Entity\CompanyHasUser
      mappedBy: employees

# Company
Acme\MyBundle\Entity\Company:
  type: entity
  fields:
    id:
      id: true
      type: integer
      generator:
        strategy: AUTO
  oneToMany:
    employees:
      targetEntity: Acme\MyBundle\Entity\CompanyHasUser
      mappedBy: companies

# CompanyHasUser
Acme\MyBundle\Entity\CompanyHasUser:
  type: entity
  fields:
    id:
      id: true
      type: integer
      generator:
        strategy: AUTO
  manyToOne:
    companies:
      targetEntity: Acme\MyBundle\Entity\Company
      inversedBy: employees
      joinColumns:
        company_id:
          referencedColumnName: id
          nullable: false
    employees:
      targetEntity: Acme\MyBundle\Entity\User
      inversedBy: companies
      joinColumns:
        user_id:
          referencedColumnName: id
          nullable: false

This is what my Entity class User look like
namespace Acme\MyBundle\Entity;

class User
{
    private $id;
    private $companies;

    public function __construct()
    {
        $this->companies = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function addCompany(\Acme\MyBundle\Entity\CompanyHasUser $companies)
    {
        $this->companies[] = $companies;

        return $this;
    }

    public function removeCompany(\Acme\MyBundle\Entity\CompanyHasUser $companies)
    {
        $this->companies->removeElement($companies);
    }

    public function getCompanies()
    {
        return $this->companies;
    }
}

This is what my Entity class Company look like
namespace Acme\MyBundle\Entity;

class Company
{
    private $id;
    private $employees;

    public function __construct($name, $companyAdmin)
    {
        $this->employees = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function addEmployee(\Acme\MyBundle\Entity\CompanyHasUser $employees)
    {
        $this->employees[] = $employees;

        return $this;
    }

    public function removeEmployee(\Acme\MyBundle\Entity\CompanyHasUser $employees)
    {
        $this->employees->removeElement($employees);
    }

    public function getEmployees()
    {
        return $this->employees;
    }
}

And this is what my Entity class CompanyHasUser looks like (relation between User and Company, but as far as this relation contains further columns - not mentioned in these code snippets - I had to create it as an Entity):
namespace Acme\MyBundle\Entity;

class CompanyHasUser
{
    private $companies;
    private $employees;

    public function setCompanies(\Acme\MyBundle\Entity\Company $companies)
    {
        $this->companies = $companies;

        return $this;
    }

    public function getCompanies()
    {
        return $this->companies;
    }

    public function setEmployees(\Acme\MyBundle\Entity\User $employees)
    {
        $this->employees = $employees;

        return $this;
    }

    public function getEmployees()
    {
        return $this->employees;
    }
}

My Controller logic is:
// Create new User (employee)
$user = new User();
$em = $this->getDoctrine()->getManager();
$em->persist($user);

// Create new Company (employer)
$company = new Company();

// Create relationship
$company->addEmployee($user);
$em->persist($company);

// Flush
$em->flush();

A: I found it out with huge thanks to Bronchas answer here. Controller logic can be implemented as follows:
// Create new User (employee)
$user = new User();
$em = $this->getDoctrine()->getManager();
$em->persist($user);

// Create new Company (employer)
$company = new Company();
$em->persist($company);

// Employ User at Company
$employment = new CompanyHasUser();
$employment->setEmployees($user);
$employment->setCompanies($company);
$em->persist($employment);

// Flush
$em->flush();


text:
Q: mysql-binlog-connector-java - Could not find first log file name in binary log index file I am doing a POC on this library, and I am having some difficulties setting it up. I have an extremly simple MySQL setup:
- a single VM (no master-slaves)
- centos 7
- MySQL version 5.7
Here is the code I have until now:
public static void main(String[] args) throws IOException {

    BinaryLogClient client = new BinaryLogClient("***.***.***.***", 3306, "****", "******");
    client.setBinlogFilename("/var/log/mysql/mysql-bin");

    client.registerLifecycleListener(new BinaryLogClient.LifecycleListener() {
        @Override
        public void onConnect(BinaryLogClient binaryLogClient) {
            System.out.println("OnConnect()");
        }
        @Override
        public void onCommunicationFailure(BinaryLogClient binaryLogClient, Exception e) {
            System.out.println("OnCommunicationFailure()");
            e.printStackTrace();
        }
        @Override
        public void onEventDeserializationFailure(BinaryLogClient binaryLogClient, Exception e) {
            System.out.println("OnEventDeserialize()");
        }
        @Override
        public void onDisconnect(BinaryLogClient binaryLogClient) {
            System.out.println("OnDisconnect()");
        }
    });

    client.registerEventListener(new EventListener() {
        @Override
        public void onEvent(Event event) {
            System.out.println(event.toString());
        }
    });
    client.connect();
}

When running this code I get the following output:

OnCommunicationFailure()
  com.github.shyiko.mysql.binlog.network.ServerException: Could not find first log file name in binary log index file
      at com.github.shyiko.mysql.binlog.BinaryLogClient.listenForEventPackets(BinaryLogClient.java:882)
      at com.github.shyiko.mysql.binlog.BinaryLogClient.connect(BinaryLogClient.java:559)
      at Main.main(Main.java:40)

My MySQL configuration file content:

[mysqld]
datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock
symbolic-links=0
log-error=/var/log/mysql/mysqld.log
server_id=1
log-bin=/var/log/mysql/mysql-bin
pid-file=/var/run/mysqld/mysqld.pid
bind-address=...

The contents of my log directory is as follows:
[mysql]# ls
error.log  mysql-bin.000001  mysql-bin.index  mysqld.log

and the contents of mysql-bin.index is of course:
/var/log/mysql/mysql-bin.000001

All of the online solutions for this problem refer to a master slave configurations and the solutions are accordingly - help anyone?:)


text:
Q: How to make distance between two views variable in autolayout I have a view which is 50 px down from the top layout.
I want the distance to vary based on the device size for example it should become 30 px in 4s while it should become 50px in iphone se while 60 in iPhone 6s.
I tried giving aspect ratio instead of vertical spacing but it not working.
If I just give vertical spacing its 50px in all devices.. Kindly help me out

A: AutoLayout does allow you to have different constraints based on screen, but it's only limited to orientation changes, and iPad vs iPhones. You'll have to do it programmatically.
This link will show you how to get the device, and then once you have that, you need to make an @IBOutlet to your constraint, and then you can change its .constant property to either 40, 50, or 60
public extension UIDevice {

    var modelName: String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machineMirror = Mirror(reflecting: systemInfo.machine)
        let identifier = machineMirror.children.reduce("") { identifier, element in
            guard let value = element.value as? Int8, value != 0 else { return identifier }
            return identifier + String(UnicodeScalar(UInt8(value)))
        }

        switch identifier {
        case "iPhone4,1":                               return "iPhone 4s"
        case "iPhone8,1":                               return "iPhone 6s"
        case "iPhone8,4":                               return "iPhone SE"
        default:                                        return identifier
        }
    }

}

Now you can use it like so:
@IBOutlet weak var myConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()
    if UIDevice.current.modelName == "iPhone 4s" {
        myConstraint.constant = 30
    }
    else if UIDevice.current.modelName == "iPhone SE" {
        myConstraint.constant = 50
    }
    else if UIDevice.current.modelName == "iPhone 6s" {
        myConstraint.constant = 60
    }
}

A: @Aziz Javed propsed the correct solution depending on what you really want. If you want a specific constant values for each device the only way is to do it by code as Aziz Suggested.

The storyboard constrant does not have an aspect ratio property for
  (Top,Bottom,Left,Right,Leading,Trailing) constraints.

The work around solution in storyboard is to add a view on top of your view. Add a spacing constraints equal to zero to top and bottom to your view. On the added view that will play the spacing role add a height constraint with the aspect ratio set to screen view.


text:
Q: Share object between actors in Ray How to read and write data to the same object from multiple actors?
Docs say:
https://docs.ray.io/en/master/memory-management.html
import numpy as np
a = ray.put(np.zeros(1))
b = ray.get(a)

but this makes new copy.

A: The right way to use global variables among actors (that you can read/write) is to use an actor that holds an object. https://docs.google.com/document/d/167rnnDFIVRhHhK4mznEIemOtj63IOhtIPvSYaPgI4Fg/edit#heading=h.eg7m6lz2y48u
Plasma objects are immutable, and you can only modify the object after you copy them to worker's heap memory (meaning it is not global anymore at that point).
Also note that for your example, it doesn't create a new copy! It uses something called zero-copy read (https://www.python.org/dev/peps/pep-0574/), meaning only the in-band data (metadata for numpy object) is copied, and the out of band data (buffer) is not copied to your python's heap memory (it resides in the shared memory, and your ray program directly pointes to that memory region).