text: Q: Best Way to Scale This Series with Outliers I have a pandas Dataframe where most series are distributed similar to X as shown below. 90% of the data points lie between a small range, for example -0.5 and 0.5 in the series below contains 96.9% of observations , but then the tails have outliers that are several orders of magnitude larger than the rest of the distribution. The problem is that I have investigated all of these outliers, and they are not bad data. Furthermore, from experience totally excluding those data points would significantly bias my analysis in a predictable way. Can anyone suggest a normalization or standardization process that could help with this situation. I have tried off the shelf scalers like StandardScaler() and RobustScaler() from sklearn and I have tried shifting the distribution to have a minimum of 1 so that I could then take the log of the distribution but none of these approaches are working to achieve my goal of a nice spread of data to be input into a neural network.


text:
Q: HealthKit KCALs not Increasing I am saving calories burned to healthKit central repository but the issue is it does not increment the total amount of KCAL in the fitness app . Saving workout works well i can see the time duration and the calories burned but its not added into the total MOVE/KCALs. I can see the MOVE are incremented.
    class func savingWorkout(duration : Double , burnedEnergy : Double , completion: @escaping (Result<Bool, Error>) -> ()) {

    let healthKitStore = HKHealthStore()
    let totalEnergyBurned = HKQuantity(unit: HKUnit.kilocalorie(), doubleValue: burnedEnergy)

    let finish = Date() // Now
    let start = finish.addingTimeInterval(-duration) // 1 hour ago

    let metadata = [
        HKMetadataKeyGroupFitness : false,
        HKMetadataKeyIndoorWorkout : true,
        HKMetadataKeyCoachedWorkout : true
    ]

    let workout = HKWorkout(
        activityType: .functionalStrengthTraining,
        start: start,
        end: finish,
        workoutEvents: nil,
        totalEnergyBurned: totalEnergyBurned,
        totalDistance: nil,
        device: nil,
        metadata: metadata
    )

    guard let energyBurnedType =
        HKObjectType.quantityType(forIdentifier:
            HKQuantityTypeIdentifier.activeEnergyBurned) else {
        fatalError("*** Unable to create an energy burned type ***")
    }

    let energyBurnedPerInterval = HKQuantity(unit: HKUnit.kilocalorie(),
                                             doubleValue: burnedEnergy)

    let energyBurnedPerIntervalSample =
        HKQuantitySample(type: energyBurnedType,
                         quantity: energyBurnedPerInterval,
                         start: start,
                         end: finish) as HKSample

    //3.  Save the same to HealthKit
     healthKitStore.save(energyBurnedPerIntervalSample) { (success, error) in

      if let error = error {
        print("Error Saving calories burned: \(error.localizedDescription)")
      } else {
        print("Calories saved")
      }
    }

        healthKitStore.save(workout) { result , error in
            if let error = error {
                completion(.failure(error))
                return
            }
           print("workout saved into HealthKit successfully ")
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: problems with bootstrap's less.min.js and ie8 I'm trying to make wordpress theme and everything was going well until I didn't test my site in ie8.
I use bootstrap 3 and less files.
When I check my site in ie8, I get this error: "Object doesnt support this property or method" and my site is broken.
Here is my code in head of my site:
 <!doctype html>
<!--[if lt IE 7 ]><html class="no-js ie6" lang="en"><![endif]-->
<!--[if IE 7 ]><html class="no-js ie7" lang="en"><![endif]-->
<!--[if IE 8 ]><html class="no-js ie8" lang="en"><![endif]-->
<!--[if IE 9 ]><html class="no-js ie9" lang="en"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>

   <meta charset="<?php bloginfo('charset'); ?>">

    <title><?php wp_title('|',true,'right'); ?><?php bloginfo('name'); ?></title>

    <meta name="author" content="">

    <!-- Mobile Specific Meta -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />

 <link rel="stylesheet/less" type="text/x-less" href="
<?php echo get_template_directory_uri() . "/less/bootstrap.less"; ?>" />

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" />

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

 <script type="text/javascript" src="<?php echo get_template_directory_uri() . '/js/less.min.js'; ?>" /></script>

 <!-- HTML5 shim for IE backwards compatibility -->
    <!--[if lt IE 9]>
      <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/polyfill.js">
      </script>
      <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/es5-shim.js">
      </script>
       <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/js/respond.js">
       </script>
      <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
   <?php wp_head(); ?>
</head>

Thanks in advance


text:
Q: WebSockets vs raw TCP sockets in Flash What WebSockets add to raw TCP connection?
Why should I use WebSockets?
I'd like to hear cons and pros like:

*

*Good: WebSockets add some useful things like autoreconnection, session ids, etc.

*Bad: WebSockets add a lot of overhead

I'll have only Flash clients, no need to support Javascript clients.

A: You can't do raw sockets from a web application in a browser. Even "raw" socket connections from Flash are not really raw because you have to answer a policy file request to get CORS security (part of the reason for the WebSockets handshake).
After the initial WebSocket handshake, WebSocket messages have two bytes of framing overhead per frame (Hixie-* has '\x00...\xff' and HyBi-07 has two byte header), so the overhead is pretty negligible compared to regular sockets.
The WebSocket handshake is an HTTP compatible Upgrade request so it is easy to integrate WebSockets support into existing web servers and to use existing Web ports (80/443) which means that WebSocket connection can also more easily integrate into existing firewall rules.
The HTTP compatible handshake also means that existing HTTP authentication mechanisms can work transparently with WebSockets. Also, WebSockets can be proxied by existing web proxies with little or no modification.
In the next revision of the WebSockets protocol rev (HyBi-07), their is protection against misbehaving web intermediaries using client to server XOR masking of the payload data.
Things like auto-reconnection, session ids, etc aren't defined in WebSockets although several Javascript frameworks built on WebSockets have this such as Socket.IO. If you are doing WebSockets from Flash applications then you would need to do your own session management or convert an existing session management library to use WebSockets rather than Flash sockets (such be pretty easy conversion).
Update:
Couple of links that might be useful to you or others who land here:

*

*AS3WebSocket: WebSockets client library for Flash applications.

*web-socket-js: WebSockets fallback/polyfill implemented in Flash for Javascript applications (to add WebSockets support to browsers with Flash but without native WebSockets).


text:
Q: Wordpress how to get a category from products that are present in another specific category I have clothes products. One product is in multiples categories, like "gender" ("men" or "women") and "type" (such as "pants", "shirts", etc.).
I want to list all categories and subcategories of "type" from products that exist in "men" category.
ID of "type" category: 1696
$args = array(
  'taxonomy' => 'product_cat',
  'orderby'  => 'title',
  'order'    => 'ASC',
  'child_of'   => 1696,
);
$categories = get_terms( $args );
print_r($categories);

That code gives me all the categories under 1696, but I would like to get only the "type" categories from products that also are in "men" category.
Am I clear?
Thanks a lot for your help.

A: Since wordpress only allows one id at a time for child_of argument, you could create a custom array and run get_terms for every parent category that you want.

From the documentation:

*

*child_of - (int) Term ID to retrieve child terms of. If multiple taxonomies are passed, $child_of is ignored. Default 0.
wp_term_query

$child_cats = array();

$parent_cats = array(1696, {the other category id});

$args = array(
  'taxonomy' => 'product_cat',
  'orderby'  => 'title',
  'order'    => 'ASC',
  'child_of'=> $parent_cat
);

foreach ($parent_cats as $parent_cat)
{
    $child_cats = array_merge($child_cats, get_terms($args));
};

print_r($child_cats);

Let me know if that's what you were looking for!

A: Thanks for your help, but it's not what I need.
I found a way to achieve what I want. There must be a better way but here's how I did:
I'm looping every products and put them in arrays if they are in the gender category ("femme" and "homme").
    $categories_femme = array(); // 1718
    $categories_homme = array(); // 1700

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1
    );
    $loop = new WP_Query( $args );
    if ( $loop->have_posts() ): while ( $loop->have_posts() ): $loop->the_post();

      global $product;

      $p_id = $product->get_id();

      // FEMME
      if( has_term( 1718, 'product_cat' ) ) {
        $categories_femme[] = wp_get_post_terms($p_id, 'product_cat');
      }
      // HOMME
      if( has_term( 1700, 'product_cat' ) ) {
        $categories_homme[] = wp_get_post_terms($p_id, 'product_cat');
      }

    endwhile; endif; wp_reset_postdata();

After that, I'm formating the array to get this structure of categories (one array per gender): array('term_id' => 'name_id', 'term_id' => 'name_id', 'term_id' => 'name_id');
    $categories_femme_formated = array();
    foreach ($categories_femme as $categorie_femme) {
      foreach ($categorie_femme as $categoriefemme) {
        $categories_femme_formated[$categoriefemme->term_id] = $categoriefemme->name;
      }
    }

    $categories_homme_formated = array();
    foreach ($categories_homme as $categorie_homme) {
      foreach ($categorie_homme as $categoriehomme) {
        $categories_homme_formated[$categoriehomme->term_id] = $categoriehomme->name;
      }
    }

After that, I'm looping through all clothes categories and looking if this category ID exist in the array created just before. If yes, I'm adding this category to the menu.
    $args = array(
      'taxonomy' => 'product_cat',
      'hide_empty' => false,
      'parent'   => 1696
    );
    $product_cat = get_terms( $args );

    // FEMME
    $count_order = 100;
    foreach ($product_cat as $parent_product_cat)
    {
      $p_id = $parent_product_cat->term_id;
      if (array_key_exists($p_id, $categories_femme_formated)) {
        $count_order++;
        $menu_items[] = _custom_nav_menu_item( $categories_femme_formated[$p_id], get_term_link($p_id), $count_order, 11407 );

        $child_args = array(
                'taxonomy' => 'product_cat',
                'hide_empty' => false,
                'parent'   => $parent_product_cat->term_id
            );
        $child_product_cats = get_terms( $child_args );
        $parent_order = $count_order;
        foreach ($child_product_cats as $child_product_cat)
        {
          $c_id = $child_product_cat->term_id;
          if (array_key_exists($c_id, $categories_femme_formated)) {
            $count_order++;
            $child_menu_id = 1000000 + $parent_order + 11407;
            $menu_items[] = _custom_nav_menu_item( $categories_femme_formated[$c_id], get_term_link($c_id), $count_order, $child_menu_id );

          }
        }
      }
    }

    // HOMME
    $count_order = 100;
    foreach ($product_cat as $parent_product_cat)
    {
      $p_id = $parent_product_cat->term_id;
      if (array_key_exists($p_id, $categories_homme_formated)) {
        $count_order++;
        $menu_items[] = _custom_nav_menu_item( $categories_homme_formated[$p_id], get_term_link($p_id), $count_order, 11408 );

        $child_args = array(
                'taxonomy' => 'product_cat',
                'hide_empty' => false,
                'parent'   => $parent_product_cat->term_id
            );
        $child_product_cats = get_terms( $child_args );
        $parent_order = $count_order;
        foreach ($child_product_cats as $child_product_cat)
        {
          $c_id = $child_product_cat->term_id;
          if (array_key_exists($c_id, $categories_homme_formated)) {
            $count_order++;
            $child_menu_id = 1000000 + $parent_order + 11408;
            $menu_items[] = _custom_nav_menu_item( $categories_homme_formated[$c_id], get_term_link($c_id), $count_order, $child_menu_id );

          }
        }
      }
    }

Just for everyone to understand, I'm calling this code inside a function called by:
add_filter( 'wp_nav_menu_objects', 'my_dynamic_menu_items' );

And here is the _custom_nav_menu_item function:
function _custom_nav_menu_item( $title, $url, $order, $parent = 0 ){
  $item = new stdClass();
  $item->ID = 1000000 + $order + $parent;
  $item->db_id = $item->ID;
  $item->title = $title;
  $item->url = $url;
  $item->menu_order = $order;
  $item->menu_item_parent = $parent;
  $item->type = '';
  $item->object = '';
  $item->object_id = '';
  $item->classes = array();
  $item->target = '';
  $item->attr_title = '';
  $item->description = '';
  $item->xfn = '';
  $item->status = '';
  $item->icon = '';
  $item->nolink = '';
  $item->hide = '';
  $item->mobile_hide = '';
  $item->cols = '';
  $item->tip_label = '';
  $item->popup_type = 'wide';
  $item->popup_pos = '';
  $item->popup_cols = 'col-4';
  $item->popup_max_width = '';
  $item->popup_bg_image = '';
  $item->popup_bg_pos = '';
  $item->popup_bg_repeat = '';
  $item->popup_bg_size = '';
  $item->popup_style = '';
  $item->block = '';
  $item->preview = '';
  $item->preview_fixed = '';
  $item->current = '';
  $item->current_item_ancestor = '';
  $item->current_item_parent = '';
  return $item;
}

Thanks again for your help.  :)


text:
Q: Taxonomy Search not just primary selected fields I hope I can explain my problem.
I have custom page and custom taxonomy . I am trying search it is working but not how I wanth.
I am sending selected taxonomy filed id. And it is just giving result primary field selected.
Say taxonomy name "kiralikevler_aramakonaklamatip"
Admin panel I added field
1- Balayi Villası
2- Jakuzili villa
3- Özel Havuzlu Villa
I added test house say "Villa Nana" When I trt search and from select "özel havuzlu villa" in search result showing villa nana house.This is good.
But İf I select "balayi villasi " result showing noting. Search code is just working if I select from select box primary taxonomy filed. Other case not working. In this case search must Show in the search result if I select "Jakuzili villa" or "Balayi Villası"
I hope I can explain my problem.
Thsi is taxonomy screenshot:https://files.fm/f/fmudgh6ux
My search query is giving result like this
<form action="/villa-arama/" method="get">

 <?php //get_search_form(); ?>
  <input type="text" class="form-control search-slt" id="keyword" name="keyword" placeholder="Villa Adı" value="<?php echo esc_html($keyword); ?>">

  <div class="form-group col-md-2
   <select id="tipi" name="tipi" class="form-control search-slt">
   <option selected value=""><?php _e( 'Villa Türü', 'karakedi' ); ?></option>
   <?php
     $terms = get_terms( 'kiralikevler_aramakonaklamatip', array(
                              'hide_empty' => false,
                              'orderby' => 'name',
                              'order' => 'DESC',
                              'parent' => 0
                          ) );
                           foreach ($terms as $term) {
                      // print_r($term);
                      // $selected = = $options[$i] ? 'selected="selected"' : ''
                      $selected = ($tipi == $term->term_id) ? 'selected="selected"' : '';
                      // echo $selected;
                      echo '<option value="' . $term->term_id . '" ' . $selected . '>' . $term->name . '</option>';
                  }
                      ?>
                  </select>

   <button type="submit" class="btn btn-danger wrn-btn">Arama Yap</button>

        </form>
// Define arguments
                $args = array(
                    'post_type' => 'kiralikevler',
                    'posts_per_page' => -1,
                    's' => $keyword,
                );
                if(!$keyword){
                         array(
                            'taxonomy' => 'kiralikevler_kasabatipi',
                            'value' => $kasabatipi,
                           'compare' => '='
                       ),
                    );
                }
           $query = new WP_Query($args);?>


text:
Q: This page is having a problem. c# Webview2 I've built a C# windows forms app in VS 2019 that includes Webview2 (latest pre-release) to create a browser. The application loads a page and checks for specific content. If the content is not there, it reloads the page. If the content is there (which has yet to happen), it fills out some fields and clicks a button.
The app was working fine for a while. Now every once in a while I get the following in the Webview2 control:

This page is having a problem. Please come back to it later
You could also: Open a new tab Refresh the page
Error Code: STATUS_ACCESS_VIOLATION

I ran the app in debug mode to try to catch the error. There is no exception to catch. And if I place a breakpoint in the ContentLoading event of the Webview2 control, it never triggers before I see this error page. I'm not sure what's triggering it or how to stop it.
On Form_load I call the following:
async void checksites()
{
    await wv2Dig.EnsureCoreWebView2Async();
    wv2Dig.CoreWebView2.Navigate(strURL);
}

And ContentLoading will call the function below that tries to check the content as the page is loading so as to make a decision before the page fully loads. Right now it is only triggering the button we don't want. Here is the code:
async Task DigPageCheck()
        {
            iDigCount += 1; //count of number of checks
            txtDig.Text = iDigCount.ToString(); //display count

            string strResult = await wv2Dig.CoreWebView2.ExecuteScriptAsync("document.documentElement.innerHTML;");
            //get innerHTML
            strResult = Regex.Unescape(strResult);
            strResult = strResult.Remove(0, 1);
            strResult = strResult.Remove(strResult.Length - 1, 1);
            //check for button we want
            int loc = strResult.IndexOf("btn btn-primary btn-lg btn-block btn-leading-ficon add-to-cart-button");
            //check for button we want
            int loc2 = strResult.IndexOf("btn btn-disabled btn-lg btn-block add-to-cart-button"); x
            while (loc == -1 && loc2 == -1)
            {
                //while neither button exists wait and check again
                await Task.Delay(200);
                strResult = await wv2Dig.CoreWebView2.ExecuteScriptAsync("document.documentElement.innerHTML;");
                strResult = Regex.Unescape(strResult);
                strResult = strResult.Remove(0, 1);
                strResult = strResult.Remove(strResult.Length - 1, 1);
                loc = strResult.IndexOf("btn btn-primary btn-lg btn-block btn-leading-ficon add-to-cart-button");
                loc2 = strResult.IndexOf("btn btn-disabled btn-lg btn-block add-to-cart-button");

            }
            //the button we want has been found
            if (loc != -1)
            {
                iDig += 1;
                string mSubj = "Found";
                try
                {
                    sendSMS(mSubj, strDigURL);
                }
                catch
                {
                    label3.Text = "Email Error";
                }
                var functionString = string.Format(@"document.getElementsByClassName('btn btn-primary btn-lg btn-block btn-leading-ficon add-to-cart-button')[0].click();");
                await wv2Dig.CoreWebView2.ExecuteScriptAsync(functionString);

            }
            else //button we don't want found
            {
                if (bRun) //app is in run state, it can be paused
                    wv2Dig.CoreWebView2.Reload(); //Reload the page and check again
            }
        }

It seems at some point while reloading, the error page comes up.
The below was solved by removing WebView2 prelease 0.9.682 and installing prerelease 0.9.579

And I have a new issue that popped up randomly. The app freezes on await wv2Dig.EnsureCoreWebView2Async(); which is in a function called from Form_Load

A: I added wv2Dig.CoreWebView2.Stop() before doing a wv2Dig.CoreWebView2.Reload() and I have not seen the problem since. I think that may have solved the problem.  I say I think because the program ran without issue for quite some time and then started having the problem.
During this process I also downgraded the pre-release version of WebView2 beauce the WebView2 stopped working completely somehow.


text:
Q: css navigationbar: sub sub menu overlaps main menu in IE only the following navigation bar works perfect on firefox, IE and Chrome. However, on IE, the sub sub menu that displays when a sub menu is clicked is not correctly positioned. It seems to overlap the main menu.
HOw can I position it correctly for IE without affecting the navigation bar layout in other browsers? The problem is on the last line of navbar.css code. Margin-top:-23px works perfect in all browsers except IE. I'm facing the problem on hover:

*

*News and Events (the Sports Day LInk and Annual Day link are overlapping FAQ(main menu item)

*Admissions (Enroll Now link overlaps Admissions link itself)

By the way, i'm testing on IE9.
Thank you.
navbar.css
#menu {
border:none;
border:0px;
margin:0px;
margin-bottom:5%;
padding:0px;
    /*font: 67.5% "Lucida Sans Unicode", "Bitstream Vera Sans", "Trebuchet Unicode MS", "Lucida Grande", Verdana, Helvetica, sans-serif;*/
    font-size:18px;
    font-weight:bold;
}

#nav {
    height:25px;    /*35px;*/
    list-style-type:none;
    margin:0;
    padding:0;
    float:left;
    text-align:center;
    background:#ffcd05;
        }

#nav li {
    display:inline-block;
    position:relative;
    float:left;
/*    background: #006633;
*/  background:#f26739;

    }

#nav li a {
    display:inline-block;
    width:126px;
    line-height:25px;
    padding:0;
    text-decoration:none;
    color:#ffffff;
    }

#nav li li {float:left; #006633;}

#nav li li a {display:block;font-size:14px;}

#nav li:hover {background:#000000;}

/*--- Sublist Styles ---*/
#nav ul {
    position:absolute;
    padding:0px;
    left:0;
    display:none;
    }

/*--- Hide Sub Sublists ---*/
#nav li:hover ul ul {display:none;}

/*--- Sublevel UL's display and position on hover ---*/
#nav li:hover ul {display:block;}
#nav li li:hover ul {margin-left:110px; margin-top:-23px; display:block;}

My navigation bar:

<?php echo $this->Html->link('Our Program', '#', array()); ?>

<?php echo $this->Html->link('Preschool', '/pages/preschool', array()); ?>

<?php echo $this->Html->link('Kindergarten', '/pages/kindergarten', array()); ?>

<?php echo $this->Html->link('Summer Camp', '/pages/summer_camp', array()); ?>

<?php echo $this->Html->link('About Us','#', array()); ?>

<?php echo $this->Html->link('Merry Flowers', '/pages/about_us', array()); ?>

<?php echo $this->Html->link('Tour Our School','/pages/tour_our_school', array()); ?>

<?php echo $this->Html->link('Contact Us', '/pages/contact_us', array()); ?>

<?php echo $this->Html->link('My Child','#', array()); ?>

<?php echo $this->Html->link('Report Card', '/merry_parents/register', array()); ?>

<?php echo $this->Html->link('Events','#', array()); ?>

<?php  echo $this->Html->link('News & Events', '#', array()); ?>

<?php echo $this->Html->link('Sports Day','/pages/sports_day',array()); ?>

<?php echo $this->Html->link('Annual Day','/pages/annual_day',array()); ?>

<?php  echo $this->Html->link('List of Holidays', '/pages/list_of_holidays', array()); ?>

<?php echo $this->Html->link('FAQ','#',array()); ?>

<?php  echo $this->Html->link('FAQ', '/pages/faq', array()); ?>

<?php  echo $this->Html->link('Feedback', '/feedbacks/add', array()); ?>

<?php  echo $this->Html->link('Discussion', '/forum/home', array()); ?>

<?php echo $this->Html->link('Admissions','#',array()); ?>

<?php echo $this->Html->link('Enroll Now','/students/add', array()); ?>

A: Ok, i got it working. Once I added top:23px for the sublists style, sports day and annual day submenus did not overlap news and events. Thanks you.
#menu {
padding:0;
margin:0;
border:none;
margin-bottom:5%;

 /*font: 67.5% "Lucida Sans Unicode", "Bitstream Vera Sans", "Trebuchet Unicode MS", "Lucida Grande", Verdana, Helvetica, sans-serif;*/
    font-size:18px;
    font-weight:bold;
    position:relative;
    z-index:1;
}
#nav{
  padding:0;
    margin:0;
    border:none;
  list-style-type:none;
  float:left;
  height:25px;
  text-align:center;
  background:#ffcd05;
}

#nav li{ /*our program, about us, my child, event, etc..*/
     float:left;
     display:block;
     text-align:center;
     background:#f26739;
      width:126px;
      position:relative;  /*very important for good layout of submenus*/
     }
#nav li a{
    text-decoration:none;
    display:block;
    color:#ffffff;
    padding:0;
}
#nav li ul li{font-size:14px;}

#nav li:hover{
      background:#000000;
}
/* sublists style */
#nav ul{  /*lists that come under our program, event, etc...*/
position:absolute; /* very impt for good layout of submenus*/
left:0px;
top:23px;  /*sports day and annual day submenus will not overlap news and events*/
display:none;
padding:0;
}

/*--- Hide Sub Sublists ---*/
#nav li:hover ul ul {display:none;}

/*--- Sublevel UL's display and position on hover ---*/
#nav li:hover ul{display:block;}

#nav li li:hover ul {margin-left:110px; margin-top:-23px;display:block;}


text:
Q: CRUD with angular js and jquery mobile I've been trying to make a CRUD application with angular JS and jquery mobile, but I have some problems with the collapsibles, the information is correctly obtained by angular js but I can't expand the collapsibles.
I delcared a directive to make the collepsible refresh
The error I get is the following:
https://gyazo.com/c35800051e3cdd6d9200a9955c382558
I leave here the code:
index.html
<!DOCTYPE html>

    <title>Probando jQuery Mobile</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />

Lista de productos

{{elemento.nombre}}

                    <form>
                        Tipo:<input type='text' id='tipo' value='{{elemento.tipo}}' disabled>
                        Categoria::<input type='text' id='categoria' value='{{elemento.categoria}}' disabled>
                        UDM:<input type='text' id='udm' value='elemento.udm' disabled>
                        Precio Venta:<input type='text' id='p_venta' value='{{elemento.p_venta}}' disabled>
                        Precio Compra:<input type='text' id='p_compra' value='{{elemento.p_compra}}' disabled>
                        Modificar
                        Eliminar
                    </form>

logica.js --> file with angular js
//creacion del modulo mi_app
var app = angular.module('miapp',[]);
app.controller('controlador',function($scope){
    $scope.lista_productos = [];        //Array con la lista de productos
    //Constructora del objeto producto
    $scope.Producto = function (nombre, tipo, consumible, categoria, udm, p_venta, p_compra, m_coste, pos_comp, pos_vent){
        this.nombre = nombre;
        this.tipo = tipo;
        this.consumible = consumible;
        this.categoria = categoria;
        this.udm = udm;
        this.p_venta = p_venta;
        this.p_compra = p_compra;
        this.m_coste = m_coste;
        this.pos_comp = pos_comp;
        this.pos_vent = pos_vent;
    };
    //Creación e inserción de los productos
    $scope.producto1 = new $scope.Producto("cartulina", "papel", true, "categoria1", "Unidades", 2.50, 1, "Fijo", true, false);
    $scope.producto2 = new $scope.Producto("boligraf bic", "papel", true, "categoria1", "Unidades", 2.50, 1, "Fijo", true, false);
    $scope.producto3 = new $scope.Producto("grapadora", "papel", true, "categoria1", "Unidades", 2.50, 1, "Fijo", true, false);
    $scope.lista_productos.push($scope.producto1);
    $scope.lista_productos.push($scope.producto2);
    $scope.lista_productos.push($scope.producto3);

});

app.directive("actualizaLista", function() {
    return function(scope) {
        if (scope.$last){
            $('#sitio_lista').collapsibleset('refresh');
            //$('#sitio_lista').trigger('create').collapsibleset('refresh');
        }
    };
});

Thanks in advance

A: Try this:
$('#sitio_lista').collapsible().trigger( "create" );

for jquery mobile 1.3.2


text:
Q: Изменение стилей элемента через setInterval на Vue Хочу понять, как работает Vue: читал документацию, много гуглил, но не могу понять, как мне нужно написать функцию, чтобы получить желаемый результат.
Есть четыре блока, в которых есть тег h3. Мне нужно каждые несколько секунд убирать стиль у одного элемента, и добавлять этот стиль к следующему. Всего их четыре. Идея была такая: сделать массив из идентификаторов, а потом с помощью setInterval переключаться между ними. Но поле el, как я понял, менять нельзя.
Моя попытка:

Web & App Design

Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim.

new Vue({
  el: '#service__title__1',
  data: {
    isActive: false,
    id: ['#service__title__1', '#service__title__2', '#service__title__3', '#service__title__4'],
  },

  methods: {
    titleChanger: function() {
      var a = this;
      var n = 0;
      var element = document.getElementById(a.id[n]);
      setInterval(function() {
        a.el = element;
        a.isActive = true;
        n++;
        if (n > 3) {
          n = 0;
        }
        element = document.getElementById(a.id[n]);

      }, 1000)
    }

  },
  mounted() {
    this.titleChanger();
  }

})

Как правильно воплотить эту задумку в реальность?

A: Вот пример

Web & App Design

Web & App Design

Web & App Design

Web & App Design

.active {
  background-color:red;
}

new Vue({
  el: '#app',
  data: {
   currentIndex: 1,
   elementsCount:4
  },
  mounted(){
  let self = this;
  setInterval(function(){
  self.nextEl();
  },2000)
  },
  methods:{
  isActive(val){
  return this.currentIndex === val ?  "active" :'' ;
  },
  nextEl(){
  console.log(this.currentIndex);
  this.currentIndex = this.currentIndex === this.elementsCount ? 1 : ++this.currentIndex;
  }
  }
})

Можно доработать под Ваш функционал.
"#el" менять нельзя, потому что это указатель на элемент который надо отрендерить как экземпляр Vue

A: Для выполнения этой задачи подойдет следующая схема:

*

*создать индекс активной услуги;

*с помощью метода setInterval менять этот индекс;

*добавить вычисляемое свойство стиля, которое будет зависеть от этого индекса.

Ниже демонстрация данного подхода.

// Отключим ненужные для примера
// сообщения в консоли.
Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',

  data: {
    // Индекс текущей активной услуги.
    currentIndex: 0,

    // Модель нашего таймера.
    timing: null,

    // Модель с услугами (массив услуг).
    services: [{
      title: 'Voluptatem enim optio',
      description: 'Maiores adipisci et ut ipsam quo voluptas. Nulla atque et cupiditate odit.',
      image: 'https://via.placeholder.com/180x80'
    }, {
      title: 'Eum praesentium autem',
      description: 'Sint sapiente error eum. Et eveniet omnis deserunt sunt.',
      image: 'https://via.placeholder.com/180x80'
    }, {
      title: 'Voluptatem nihil voluptate',
      description: 'Odit consequatur accusantium excepturi minima velit. Et molestiae maiores ea.',
      image: 'https://via.placeholder.com/180x80'
    }, {
      title: 'Debitis illum ex eum',
      description: 'Commodi quia asperiores dignissimos sint quo tempore. Neque magni aut.',
      image: 'https://via.placeholder.com/180x80'
    }]
  },

  computed: {
    /**
     * Вычисляемое свойство:
     * указывает является ли переданный index
     * равнозначным индексу текущей активной услуги.
     */
    isActive() {
      return index => this.currentIndex === index
    },

    // Задаем стили (класс) для активной услуги.
    activeStyle() {
      return index => {
        return {
          'service__title-active': this.isActive(index)
        }
      }
    }
  },

  /**
   * Используем хук `mounted` для запуска таймера.
   */
  mounted() {
    this.runTiming()
  },

  methods: {
    // Запускаем наш таймер.
    runTiming() {
      this.timing = setInterval(this.changeCurrentIndex, 1000)
    },

    // Изменяем индекс текущей активной услуги.
    changeCurrentIndex() {
      // services.length - количество услуг.
      // ++ - увеличиваем активную услугу на единицу.
      // a % b – это остаток от деления a на b.
      this.currentIndex = ++this.currentIndex % this.services.length;
    }
  },

  beforeDestroy() {
    // При использовании компонентного подхода
    // обязательно удаляем наш таймер.
    clearInterval(this.timing)
  }
});
.services {
  display: flex;
  flex-wrap: wrap;
  max-width: 600px;
  margin: 0 auto;
}

.service {
  width: 50%;
  box-sizing: border-box;
}

.service__title-active {
  color: #08c;
}

  {{ currentIndex }}

    <template v-for="(service, index) in services">

{{ service.title }}

{{ service.description }}

    </template>


text:
Q: Having two using static directives that has property with same name I have pre C#6 code that code like this:
Guid guid = Guid.Empty;
string value = string.Empty;

I wanted to start using using static directive and change it to something like
using static System.Guid;
using static System.String;
// ...
Guid guid = Empty;
string value = Empty;

But this simply ends up with two errors

Error CS0229  Ambiguity between 'Guid.Empty' and 'string.Empty'

Why can't compiler decide with Empty I want to use?

A: Because that's not how the C# compiler is designed. Trying to guess what you mean looks simple in simple cases like what you have shown, but becomes problematic in other cases.
For example:
var value = Empty;
string s = Empty.ToString();
F(Empty.SomeMethod());


text:
Q: Actual effect of using WAI ARIA? I'm trying to dig into ARIA and make my websites more accessible.
I understood using ARIA attributes is a good start but I'd like to understand the actual effects of doing so.
If, for instance, I add a role="navigation" on my nav tag used as a menu, what effect will this have for the user?
What will its screenreader (or any app helping him) do?
Is it really useful to add this if I'm already using a nav tag, which obviously is already telling the user that this is a navigation item?
Thanks!

A: The way I understand it is that adding ARIA roles will create a taxonomy of semantics (called landmarks) on your site that a user can navigate to using keyboard shortcuts (key bindings) defined by screen readers with ARIA support.
For example, instead of jumping through actionable elements like buttons/links, the user can use a different key binding to jump to ARIA landmarks instead.
Semantic tags such as "nav" should be handled by the screen reader client by default (and have a specific key binding to do so - usually "tab"). ARIA roles - in this scenario - just add another level of semantics and, by extension, an alternate method for navigating through the page.
A link to the WAI-ARIA Roles Model W3C spec.

A: In simple terms WAI-ARIA allows developers to talk to the platform accessibility API through HTML mark-up. Platform accessibility API is the way how operating systems expose information about objects on the screen to the assistive technologies.
When you set role="navigation" on an HTML element what happens in the background is, user-agent maps this information to the correct accessibility API on user's operating system. As a result, the assistive technology receives the right semantics about your HTML element.
For example for the "navigation" role user-agent maps this to "AXLandmarkNavigation" on Mac OS X. You can find the full list of mapping of ARAI roles to accessibility APIs on WAI-ARIA 1.0 User Agent Implementation Guide.


text:
Q: Number of Zeros of a Complex Function I need help solving this problem.  I think it involves Rouche's Theorem but I am not sure.
Determine the number of zeros of the function in the upper half plane. $f(z)=z^4+3iz^2+z-2+i$

A: so in you case  we have
$f(z)=z^4+i(3*z^2+1)+z-2$
upper half plane as i said is that iamginary part  is positive,but  first let say  that we can conclude   we  may have two function  like first  $f(z)=z^4+z-2$ and $g(z)=i(3*z^2+1)$
or we  could  say  that we have tree function
$f(z)=z^4$
$f_1(z)=i(3*z^2+1)$
$f_2(z)=z-2$
if we  measure  this inside simple controur for example when    $|z|=1$  then  we may have
$|f(z)|=1$
$f_1(z)=4$
$|f_2(z)|=-1$
so we are taking positive and minimum right  because of this pdf file
http://fbhs.snnu.edu.cn/kcwz/all/dianzijiaoan/chn7/7.9.pdf
so it should be $1$
or in case of two function  if we concatenate   first  two function we will get  $5$,so i think it should be for two function $5$


text:
Q: Forcing nls to fit a curve passing through a specified point I'm trying to fit a Boltzmann sigmoid 1/(1+exp((x-p1)/p2)) to this small experimental dataset:
xdata <- c(-60,-50,-40,-30,-20,-10,-0,10)
ydata <- c(0.04, 0.09, 0.38, 0.63, 0.79, 1, 0.83, 0.56)

I know that it is pretty simple to do it. For example, using nls:
fit <-nls(ydata ~ 1/(1+exp((xdata-p1)/p2)),start=list(p1=mean(xdata),p2=-5))

I get the following results:
Formula: ydata ~ 1/(1 + exp((xdata - p1)/p2))

Parameters:
   Estimate Std. Error t value Pr(>|t|)
p1  -33.671      4.755  -7.081 0.000398 ***
p2  -10.336      4.312  -2.397 0.053490 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1904 on 6 degrees of freedom

Number of iterations to convergence: 13
Achieved convergence tolerance: 7.079e-06

However, I need (due to theoretical reasons) the fitted curve to pass precisely through the point (-70, 0). Although the value of the fitted expression showed above passes near zero at x = -70, it is not exactly zero, which is not what I want.
So, the question is: Is there a way to tell nls (or some other function) to fit the same expression but forcing it to pass through a specified point?
Update:
As it has been mentioned in the comments, it is mathematically impossible to force the fit to go through the point (-70,0) using the function I provided (the Boltzmann sigmoid). On the other hand, @Cleb and @BenBolker have explained how to force the fit to go through any other point, for instance (-50, 0.09).

A: It is not possible to force the fit to go through 0 using the function you provide (without an off-set) as we discussed in the comments below your question.
However, you can force the curve to go through other data points by setting weights for individual data points. So e.g. if you give a data point A a weight equals 1 and a data point B a weight equals 1000, the data point B is much more important (in terms of the contribution to the sum of residuals which is going to be minimized) for the fit than A and the fit will therefore be forced to go through B.
Here is the entire code and I explain it in more detail below:
# your data
xdata <- c(-60, -50, -40, -30, -20, -10, -0, 10)
ydata <- c(0.04, 0.09, 0.38, 0.63, 0.79, 1, 0.83, 0.56)
plot(xdata, ydata, ylim=c(0, 1.1))
fit <-nls(ydata ~ 1 / (1 + exp((xdata - p1) / p2)), start=list(p1=mean(xdata), p2=-5))

# plot the fit
xr = data.frame(xdata = seq(min(xdata), max(xdata), len=200))
lines(xr$xdata, predict(fit, newdata=xr))

# set all weights to 1, do the fit again; the plot looks identical to the previous one
we = rep(1, length(xdata))
fit2 = nls(ydata ~ 1 / (1 + exp((xdata - p1) / p2)), weights=we, start=list(p1=mean(xdata) ,p2=-5))
lines(xr$xdata, predict(fit2, newdata=xr), col='blue')

# set weight for the data point -30,0.38, and fit again
we[3] = 1000
fit3 = nls(ydata ~ 1 / (1 + exp((xdata - p1) / p2)), weights=we, start=list(p1=mean(xdata), p2=-5))
lines(xr$xdata, predict(fit3, newdata=xr), col='red')
legend('topleft', c('fit without weights', 'fit with weights 1', 'weighted fit for -40,0.38'),
       lty=c(1, 1, 1),
       lwd=c(2.5, 2.5, 2.5),
       col=c('black', 'blue', 'red'))

The output looks as follows; as you can see the fit now goes through the desired data point (red line):

So what is going on: I first fit as you did, then I fit with weights whereby all weights are set to 1; therefore, the plot looks identical to the one before and the blue line hides the black line. Then - for fit3 - I change the weight for the third data point to 1000 which means that it is now much more "important" for the least square fit than the other points and the new fit goes through this data point (the red line).
Here is also a second example where I changed the line
we[3] = 1000

to
we[2] = 1000

which forces the fit to go through the second data point:

If you want to get more information about the weights argument you can read here: documentation

A: Building on @Cleb's answer, here's a way to pick a specified point the function must pass through and solve the resulting equation for one of the parameters:
dd <- data.frame(x=c(-60,-50,-40,-30,-20,-10,-0,10),
                 y=c(0.04, 0.09, 0.38, 0.63, 0.79, 1, 0.83, 0.56))

Initial fit (using plogis() rather than 1/(1+exp(-...)) for convenience):
fit <- nls(y ~ plogis(-(x-p1)/p2),
           data=dd,
           start=list(p1=mean(dd$x),p2=-5))

Now plug in (x3,y3) and solve for p2:
y3 = 1/(1+exp((x-p1)/p2))
logit(x) = qlogis(-x) = log(x/(1-x))
e.g. plogis(2)=0.88 -> qlogis(0.88)=2
qlogis(y3) = -(x-p1)/p2
p2 = -(x3-p1)/qlogis(y3)

Set up a function and plug it in for p2:
p2 <- function(p1,x,y) {
    -(x-p1)/qlogis(y)
}
fit2 <- nls(y ~ plogis(-(x-p1)/p2(p1,dd$x[3],dd$y[3])),
    data=dd,
    start=list(p1=mean(dd$x)))

Plot the results:
plot(y~x,data=dd,ylim=c(0,1.1))
xr <- data.frame(x = seq(min(dd$x),max(dd$x),len=200))
lines(xr$x,predict(fit,newdata=xr))
lines(xr$x,predict(fit2,newdata=xr),col=2)


text: Q: Is There a Smooth Approximation to Classifying Spaces $BG\,?$ If you look at https://en.wikipedia.org/wiki/Chern%E2%80%93Weil_homomorphism, right above contents the claim is made that we can approximate the classifying space by smooth manifolds. I am aware of at least two constructions of the classifying space of a Lie group $G:$ one is Milnor's join construction, the other is via the geometric realization of the nerve of $G\,.$ Both of these involve taking a direct limit, therefore one can perform analogous constructions for a finite number $j\,,$ and I assume this gives $B_jG\,.$ Is there a reference for this?


text:
Q: After subscribe save value into array or variable I want to save the data after http request and subscribing like below but I cant see the data at the first index. It looks like this within the browser. With this.mySet[0] I have not access to this. What it wrong?

[]0: "test"length: 1__proto__: Array(0)

api.service.ts:409
myComponent.ts
     mySet = [];
     getLageSub()  {

       this.apiService.getLage().subscribe(data => {this.mySet.push(data)});
console.log(this.mySet)<------here is my output but I will need it elsewhere

      }

myService.ts
getLage()  {
    let url = 'rest/getData-pool';

    try {
      return this.http.post(url, {}, this.getPutHeaders()).map((res) =>res.json())

    } catch (error) {

      console.log(error);
    }
  }

A: Try this case :
mySet : any;Constructor(){this.mySet = [];}
getLageSub() { this.apiService.getLage().subscribe(data => {this.mySet.push(data)}); console.log(this.mySet)<------here is my output but I will need it elsewhere }

A: I hope it will help:
mySet : any;Constructor(){this.mySet = [];}
getLageSub() { this.apiService.getLage().subscribe(data => {this.mySet.push(JSON.parse(JSON.stringify(data)))}); console.log(this.mySet)<------here is my output but I will need it elsewhere }


text:
Q: The sides of a triangle are in the ratio $1:\sqrt 3: 2$, then the angles are in the ration- Using the sine rule
$$\sin A:\sin B:\sin C=1:\sqrt 3: 2$$
This is small question, so I could only do one step. How should finish it?

A: The best answer is in comment. In any case it is simpler to find the angles themselves and use the result to find the ratio.
In general case  use the cosine theorem to find the angles in a triangle:
$$
\cos A=\frac{b^2+c^2-a^2}{2bc}.
$$
In your case one obtains:
$$
\cos A=\frac{\sqrt3}2,\;\cos B=\frac12,\; \cos C=0.
$$
I assume the angles with these cosines are well-known to you.

A: In a triangle, given that $$a=k, b=\sqrt{3} k, c=2k \implies c^2=a^2+b^2, ~\text{so}~ C=\pi/2$$
Next, bt sin-law:
$$\frac{\sin A}{1}=\frac{\sin B}{\sqrt{3}}=\frac{\sin C}{2} \implies \frac{\sin A}{1/2}=\frac{\sin B}{\sqrt{3}/2}=\frac{\sin C}{1} \implies A=\pi/6, B=\pi/3, C=\pi/2.$$ Also check that $A+B+C=\pi.$
So $$A:B:C:=1:2:3$$


text:
Q: Yii2 - finfo_file(/tmp/phpqE6gyD): failed to open stream: No such file or directory on save after file upload I am getting following error, when I try to save data into db after file upload:
finfo_file(/tmp/phpqE6gyD): failed to open stream: No such file or directory

This is the code:
$userFolderPath = \Yii::getAlias('@webroot') . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . \Yii::$app->user->getIdentity()->iduser;
        $model = new CsFile();
        $files = UploadedFile::getInstances($model, 'files');
        $errors = [];

        if (!file_exists($userFolderPath))
            mkdir($userFolderPath, 0777, true);

        foreach($files as $file):
            $fileModel = new CsFile();
            $fileModel->files = $file;

            if($fileModel->validate()):

                $filename = str_replace(' ', '_', $file->baseName);

                if(file_exists($userFolderPath . DIRECTORY_SEPARATOR . $filename . "." . $file->extension)):
                     $filename .= "-" .uniqid();
                endif;

                $fileModel->files
                    ->saveAs($userFolderPath .DIRECTORY_SEPARATOR. $filename . '.' . $fileModel->files->extension);

                $fileModel->iduser    = Yii::$app->user->getIdentity()->iduser;
                $fileModel->name      = $filename;
                $fileModel->extension = $file->extension;
                $fileModel->add_date  = date('Y-m-d H:i:s');
                $fileModel->save();

            else:

            endif;

        endforeach;

        var_dump('<pre>', $errors, '</pre>');

A: I had the same problem a few weeks ago. Turns out, when we rename the file before upload and try to save the model, this error will appear.
If that attribute it's only for handle your upload and have no field in your table, you can just unset this fields before saving: $files Model->files = null.
Let me know if your scenario is different than mine.

A: Yii2 use UploadFile class through function $model->upload() to save upload file
To fix this use inside your $model->upload function :
return copy($this->YourAttribute->tempName, $newFileName);
instead
return $model->attribute->saveAs($newFileName)

A: Clyff is right. But in case you are saving the path of the file in database to read later, setting the attribute to null is not going to work.
The problem is when you try to save the model still with result of UploadedFile::getInstance($model, 'file') in the file field which is already used by $model->file->saveAs();
$model->save() cannot save the path of the saved and already removed temporary files path directly.
So after successful $model->file->saveAs($path) you need to do something like:
$model->file = $path;
It was quite unclear to me and spent a bit of time after fileinfo , so hope the answer helps.

A: I was having same problem, I solved it with this:
$model->file->saveAs($filepath , false)

then...
$model->save(false)

Important: In the saveAs function pass false parameter.

A: Using false parameter in $model->save(false) that means you are ignoring model validation, which is not right.
But using false as a second parameter in $file->saveAs($path,false) means you are trying to keep the file in the temp folder after being uploaded and allow the model to access the file during validation when trying to save to the database.
If the model fails to access the file (i.e removed from the temp folder after being uploaded), you will getting an ERROR Fail to open a stream, No such file/folder


text:
Q: Vue JS Main.js failed to compile Keep getting this error. Tried uninstalling and reinstalling node and vue but does not seem to work

ERROR  Failed to compile with 1 errors                               7:03:46 PM
error  in ./src/main.js

main.js code below:
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

A: If you are using eslint, try removing comma.
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),   //please remove the comma
    }).$mount('#app')


text:
Q: Python - pandas: create a separate row for each recurrence of a record I have date-interval-data with a "periodicity"-column representing how frequent the date interval occurs:

*

*Weekly: same weekdays every week

*Biweekly: same weekdays every other week

*Monthly: Same DATES every month

Moreover I have a "recurring_until"-column specifying when the recurrence should stop.
What I need to accomplish is:

*

*creating a separate row for each recurring record until the "recurring_until" has been reached.

What I have:

What I need:

I have been trying with various for loops without much success. Here is the sample data:
import pandas as pd

data = {'id':['1','2','3','4'],'from':['5/31/2020','6/3/2020','6/18/2020','6/10/2020'],'to':['6/5/2020','6/3/2020','6/19/2020','6/10/2020'],'periodicity':['weekly','weekly','biweekly','monthly'],'recurring_until':['7/25/2020','6/9/2020','12/30/2020','7/9/2020']}

df = pd.DataFrame(data)

A: First of all preprocess:
df.set_index("id", inplace=True)
df["from"], df["to"], df["recurring_until"] = pd.to_datetime(df["from"]), pd.to_datetime(df.to), pd.to_datetime(df.recurring_until)

Next compute all the periodic from:
new_from = df.apply(lambda x: pd.date_range(x["from"], x.recurring_until), axis=1) #generate all days between from and recurring_until
new_from[df.periodicity=="weekly"] = new_from[df.periodicity=="weekly"].apply(lambda x:x[::7]) #slicing by week
new_from[df.periodicity=="biweekly"] = new_from[df.periodicity=="biweekly"].apply(lambda x:x[::14]) #slicing by biweek
new_from[df.periodicity=="monthly"] = new_from[df.periodicity=="monthly"].apply(lambda x:x[x.day==x.day[0]]) #selectiong only days equal to the first day
new_from = new_from.explode() #explode to obtain a series
new_from.name = "from" #naming the series

after this we have new_from like this:
id
1   2020-05-31
1   2020-06-07
1   2020-06-14
1   2020-06-21
1   2020-06-28
1   2020-07-05
1   2020-07-12
1   2020-07-19
2   2020-06-03
3   2020-06-18
3   2020-07-02
3   2020-07-16
3   2020-07-30
3   2020-08-13
3   2020-08-27
3   2020-09-10
3   2020-09-24
3   2020-10-08
3   2020-10-22
3   2020-11-05
3   2020-11-19
3   2020-12-03
3   2020-12-17
4   2020-06-10
Name: from, dtype: datetime64[ns]

Now lets compute all the periodic to as:
new_to = new_from+(df.to-df["from"]).loc[new_from.index]
new_to.name = "to"

and we have new_to like this:
id
1   2020-06-05
1   2020-06-12
1   2020-06-19
1   2020-06-26
1   2020-07-03
1   2020-07-10
1   2020-07-17
1   2020-07-24
2   2020-06-03
3   2020-06-19
3   2020-07-03
3   2020-07-17
3   2020-07-31
3   2020-08-14
3   2020-08-28
3   2020-09-11
3   2020-09-25
3   2020-10-09
3   2020-10-23
3   2020-11-06
3   2020-11-20
3   2020-12-04
3   2020-12-18
4   2020-06-10
Name: to, dtype: datetime64[ns]

We can finally concatenate this two series and join them to the initial dataframe:
periodic_df = pd.concat([new_from, new_to], axis=1).join(df[["periodicity", "recurring_until"]]).reset_index()

result:


text:
Q: How to enable the debug mode in TestExecute tool I am executing tests through TestExecute and I want to enable the debug mode, i.e. I want it to pause at all the breakpoints which are set in the TestComplete project suite that is being executed using TestExecute.
I have searched a lot and unable to find a solution...Hopefully I'll get help here :)

A: Sorry for my bad news but this feature (debug mode) is not supported by TestExecute.
TestExecute its a tool only to execute the testcases. In order to debug the code, make new implementations and everything else, you must buy a TestComplete license.
This is the reason of the prices between them (TestExecute its 2x cheaper than TestComplete).
In fact TestExecute its a part of TestComplete.


text:
Q: How to parse error parameter in request callback? I'm deliberately triggering an error in a stored procedure under certain conditions which I want to catch in my Node.js API which uses the Tedious package.
Code Snippet from API:
        let request = new Request(sql, (err)=>{
            if (err) {
                sqlerr = err;
                console.log(typeof(err));
                console.log("**RQ-ERROR**", err);
            }
        });

In the callback of the "Request" object above there is an "err" parameter. The "typeof()" returns "object"; however, when I dump it to the console it looks like this:
**RQ-ERROR** { RequestError: Duplicate entry for specified period
    at RequestError (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\errors.js:32:12)
    at Parser.tokenStreamParser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\connection.js:723:34)
    at emitOne (events.js:96:13)
    at Parser.emit (events.js:188:7)
    at Parser.parser.on.token (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
    at emitOne (events.js:96:13)
    at Parser.emit (events.js:188:7)
    at addChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:297:12)
    at readableAddChunk (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:279:11)
    at Parser.Readable.push (C:\inetpub\wwwroot\PersonnelApps\kudosapi\node_modules\readable-stream\lib\_stream_readable.js:240:10)
  message: 'Duplicate entry for specified period',
  code: 'EREQUEST',
  number: 50000,
  state: 1,
  class: 16,
  serverName: 'PERSODG2LNN52\\SQLEXPRESS',
  procName: 'CreateStatusReport',
  lineNumber: 44 }

This almost looks like a JavaScript object but, as you can see, the "RequestError" data isn't quoted nor is there a comma after the text "240:10)" just before the "message" member. I'm not sure if this is a bug in TDS or if I'm just missing something but I cannot access any of the members as it is. I'd have to convert it to a string and parse it which is fine but isn't very elegant.
Suggestions?

A:
as you can see, the "RequestError" data isn't quoted nor is there a comma after the text "240:10)"

These are artifacts of the console logging out the error message. You can try it out for yourself with something like the following:
$ node
> console.log(new Error('this is an error object!'));
Error: this is an error object!
    at repl:1:13
    at Script.runInThisContext (vm.js:119:20)
    at REPLServer.defaultEval (repl.js:332:29)
    at bound (domain.js:395:14)
    at REPLServer.runBound [as eval] (domain.js:408:12)
    at REPLServer.onLine (repl.js:639:10)
    at REPLServer.emit (events.js:194:15)
    at REPLServer.EventEmitter.emit (domain.js:441:20)
    at REPLServer.Interface._onLine (readline.js:290:10)
    at REPLServer.Interface._line (readline.js:638:8)

I'm not exactly sure what the desired outcome of this question is, but try inspecting the err.message property rather than using the typeof operator.


text:
Q: Monge and Kantorovich problem in optimal transport It is well-known that in optimal transport, Kantorovich problem is a relaxation of the Monge problem, which always admits a solution. Let's write
$$ M(\mu,\nu)=\inf_{T: T_\#\mu=\nu} \int c(x,T(x))d\mu $$
$$K(\mu,\nu)=\inf_{\pi: \pi \; \text{has marginals}\;\mu\;\text{and}\;\nu} \int c(x,y)d\pi $$
I am interested in understanding what happens when the optimal value functions of these two problem are the same: $M(\mu,\nu)=K(\mu,\nu)<\infty$. In this case, does the Monge problem admit a solution? If not, what would be a counterexample? In addition, when the Monge problem has a solution, is it necessarily true that $M(\mu,\nu)=K(\mu,\nu)<\infty$?
Thanks in advance!

A: I have found a paper with the example I am looking for:
On the equality between Monge's infimum
and Kantorovich's minimum in optimal mass transportation
by Aldo Pratelli


text:
Q: DRY Strategy for looping over unknown levels of nested objects My scenario is based on Gmail API.
I've learned that email messages can have their message parts deeply or shallowly nested based upon varying factors, but mostly the presence of attachments.
I'm using the Google API Ruby Client gem, so I'm not working with JSON, I'm getting objects with all the same information, but I think the JSON representation makes it easier to understand my issue.
A simple message JSON response looks like this (one parts array with 2 hashes inside it):
{
  "id": "175b418b1ff69896",
  "snippet": "COVID-19: Resources to help your business manage through uncertainty 20 Liters 500 PEOPLE FOUND YOU ON GOOGLE Here are the top search queries used to find you: 20 liters used by 146 people volunteer",
  "payload": {
    "parts": [
      {
        "mimeType": "text/plain",
        "body": {
          "data": "Hey, you found the body of the email! I want this!"
        }
      },
      {
        "mimeType": "text/html",
        "body": {
          "data": "
I actually don't want this
"
        }
      }
    ]
  }
}

The value I want is not that hard to get:
response.payload.parts.each do |part|
  @body_data = part.body.data if part.mime_type == 'text/plain'
end

BUT The JSON response of a more complex email message with attachments looks something like this (now parts nests itself 3 levels deep):
{
  "id": "175aee26de8209d2",
  "snippet": "snippet text...",
  "payload": {
    "parts": [
      {
        "mimeType": "multipart/related",
        "parts": [
          {
            "mimeType": "multipart/alternative",
            "parts": [
              {
                "mimeType": "text/plain",
                "body": {
                  "data": "hey, you found me! This is what I want!!"
                }
              },
              {
                "mimeType": "text/html",
                "body": {
                  "data": "
I actually don't want this one.
"
                }
              }
            ]
          },
          {
            "mimeType": "image/jpeg"
          },
          {
            "mimeType": "image/png"
          },
          {
            "mimeType": "image/png"
          },
          {
            "mimeType": "image/jpeg"
          },
          {
            "mimeType": "image/png"
          },
          {
            "mimeType": "image/png"
          }
        ]
      },
      {
        "mimeType": "application/pdf"
      }
    ]
  }
}

And looking at a few other messages, the object can vary from 1 to 5 levels (maybe more) of parts
I need to loop over an unknown number of parts and then loop over an unknown number of nested parts and the repeat this again until I reach the bottom, hopefully finding the thing I want.
Here's my best attempt:
def trim_response(response)
  # remove headers I don't care about
  response.payload.headers.keep_if { |header| @valuable_headers.include? header.name }

  # remove parts I don't care about
  response.payload.parts.each do |part|
    # parts can be nested within parts, within parts, within...
    if part.mime_type == @valuable_mime_part && part.body.present?
      @body_data = part.body.data
      break
    elsif part.parts.present?
      # there are more layers down
      find_body(part)
    end
  end
end

def find_body(part)
  part.parts.each do |sub_part|
    if sub_part.mime_type == @valuable_mime_part && sub_part.body.present?
      @body_data = sub_part.body.data
      break
    elsif sub_part.parts.present?
      # there are more layers down
      ######### THIS FEELS BAD!!! ###########
      find_body(sub_part)
    end
  end
end

Yep, there's a method calling itself. I know, that's why I'm here.
This does work, I've tested it on a few dozen messages, but... there has to be a better, DRY-er way to do this.
How do I recursively loop and then move down a level and loop again in a DRY fashion when I don't know how deep the nesting goes?

A: No need to go through all this pain. Just keep diving in the parts dictionary until you find the first value where there is no parts anymore. At this moment you have the final parts in your parts variable.
Code:
reponse = {"id" => "175aee26de8209d2","snippet" => "snippet text...","payload" => {"parts" => [{"mimeType" => "multipart/related","parts" => [{"mimeType" => "multipart/alternative","parts" => [{"mimeType" => "text/plain","body" => {"data" => "hey, you found me! This is what I want!!"}},{"mimeType" => "text/html","body" => {"data" => "
I actually don't want this one.
"}}]},{"mimeType" => "image/jpeg"}]},{"mimeType" => "application/pdf"}]}}
parts   = reponse["payload"]
parts   = (parts["parts"].send("first") || parts["parts"]) while parts["parts"]
data    = parts["body"]["data"]
puts data

Output:
hey, you found me! This is what I want!!

A: You can compute the desired result using recursion.
def find_it(h, top_key, k1, k2, k3)
  return nil unless h.key?(top_key)
  recurse(h[top_key], k1, k2, k3)
end

def recurse(h, k1, k2, k3)
  return nil unless h.key?(k1)
  h[k1].each do |g|
    v = g.dig(k2,k3) || recurse(g, k1 , k2, k3)
    return v unless v.nil?
  end
  nil
end

See Hash#dig.
Let h1 and h2 equal the two hashes given in the example1. Then:
find_it(h1, :payload, :parts, :body, :data)
  #=> "Hey, you found the body of the email! I want this!"

find_it(h2, :payload, :parts, :body, :data)
  #=> "hey, you found me! This is what I want!!"

1. The hash h[:payload][:parts].last #=> { "mimeType": "application/pdf" } appears to contain hidden characters that are causing a problem. I therefore removed that hash from h2.


text:
Q: Javascript string->int injective function I want to create a unique ID to a given string while the same ID should be received for that string every time i'm trying to do that, and two different strings should get different IDs.
Let say the size of the strings is limited to x chars, and therefor this injective function is possible.
Are you familiar with a javascript function or a suitable algorithm that would be good fot it?
Thanks in advance.


text:
Q: How to echo a string of html from one page to another in PHP For instance, when the user submits a form, code from another .php file is executed and then the focus comes back to the previous page (the one with the form on it). Is it possible to send markup back to the first page from the .php file that handles the action?
I would like to send a message back to the user if there was a problem with their login, preferably without using JavaScript.
I'm assuming there's a simple solution for this that doesn't require assigning a string to $_SESSION, and then printing that on the other page, but I can't think of one.

A: Basically this is handled with html attribute in tags or with javascript but they are not secure and can be edited best way is handled with all of them
Example :

// For Not Null
<input name="test" require>

// Minimum Value Must Be Bigger Than 5 or equal 5
<input name="test" min="5">

// Maximum Value Must Be lowee Than 5 or equal 5
<input name="test" max="5">
<button type="submit">Submit</button>

After this form submitted check it into php

A: I would suggest this.
form.php post a value to calc.php
calc.php redirect user to form.php with the input value and the output value
form.php
if(isset($_GET['output_value'])){
    $input_value = $_GET['input_value'];    // get back some value from calc.php
    $output_value = $_GET['output_value'];  // get back some value from calc.php
    echo "Input value: " . $input_value . "
";
    echo "Output value: " . $output_value. "
";
}

calc.php
$input_value = $_POST['input_value'];
$output_value = $input_value * $input_value;
header("Location: http://www.example.com/form.php?input_value=" . $input_value . "&output_value=" . $output_value); // redirect user to the first page with some values


text:
Q: String comparison in JQuery I have this registration form
    <form method="post" action="Register">
        <input type="text" name="name" placeholder="Name"/>

        <input type="email" name="email" placeholder="Email" id="email"/>

        This email is already taken!
        <input type="password" name="password" placeholder="Password" />

        <input type="submit" value="Sumbit" id="button"/>
    </form>

And this JS code is supposed to check whether the email exists in the database or not by calling a servlet using AJAX when focus leaves the email textarea.

$(document).ready(function(){
var field = $("#email");
        $(field).focusout(function(){
              var email = $(field).val();

                $.get("Verify",{"email":email},function(data){
                 alert(data);
                    if(data=="true")
                        $("#taken").css("display","block");

                    if(data=="false")
                        $("#taken").css("display","none");

                });
         }); });

The servlet is returning the correct result (the code works until alert(data)) which is a String that's either "true" or "false", I checked that it's a String by alerting "typeof data".
What I want is to display the span $("#taken") if the AJAX response (data) was equal to "true" and hide it otherwise.
My problem is that the comparison is not working!
I've tried using "===" instead of "==" and I have also tried converting data to boolean by using

var existed = Boolean(data);

to use to use "if(existed)" and "if(!existed)" instead of comparing strings
Nothing worked! I know the answer must be silly but I have truly spent the last two hours looking into it and nothing I have tried worked out. Please help.

A: Use $.getJSON instead of $.get
And then change your code to
 if(data)
       $("#taken").css("display","block");
 } else {
       $("#taken").css("display","none");
 }

You also better add Content-type: application/json; charset=utf-8 header to the response from the server
The reason it doesn't work for you is that data is boolean and when comparing it against a string,  the string is also converted to boolean,  and both"true" and "false" are converted to TRUE as they are non empty strings
=== won't work as well becausedata and the strings differ in type so the comparison is always falsy


text:
Q: Why does a Convencience Constructor or Object Factory have to care about releasing the Object? Actually, if you use a method with "new", "create", "alloc" or "copy" in it's name, then you are responsible for releasing the object that is returned to you. BUT: Why do these methods make an call to -autorelease? Wouldn't this result in "over-releasing" the object?
Lets say I get that object from such a method, and then I call -release on that. The object is in the Autorelease Pool and has a reference count of 0. What would happen next, when the Autorelease Pool is released?

A: Convenience constructors don't have any of those words in their names (e.g., [NSMutableArray array]), so by convention they return autoreleased objects. Methods that do have one of the words that indicate they return a retained object don't call autorelease, so that part of the premise of your question is incorrect.
If you release objects returned from a convenience constructor yourself (without having explicitly retained them) then they will be over-released, and your application will probably crash.

A: Sorry @all! I've been sitting too long in the bright sun, I think. Of course these convenience methods have ownership of the objects they create, because they call -alloc at some point at the beginning. And the -alloc Method itself doesn't call -alloc, since it's -alloc already. That's it.
Thought about deleting the question, but maybe someone else was sitting in the sun for too long, too, just like me. So this might help.


text:
Q: What would be the formula to get the position of a combination, instead of a permutation ,given an index in this example Let be an array $A = \{a,b,c,d,e,f\}$ of six elements and we want three elements at the time, so the total number of permutations with repetitions will be: $6^3$.
Now to get the position of those permutations, given an index $i$, we use the following formula:
word[0] = i % 6
word[1] = (i / 6) % 6
word[2] = (i / 6 / 6) % 6

So for index = 0, we will get:
word[0] = 0 % 6                =  0
word[1] = (0 / 6) % 6          =  0
word[2] = (0 / 6 / 6) % 6      =  0

Which gives the permutation: a a a
But, what would be the formula to get the position of combinations (combinations have no repetitions) instead of permutations with repetitions of this example?

A: This is an old confusingly phrased question brought to the front page by a small edit. Perhaps the OP is no longer interested in the answer. But I think I know what he's asking.
He imagines a list of the three character words built from the six letter alphabet $\{a,b,c,d,e,f\}$ and wants to know the position of a particular word in this list when the list is ordered lexicographically.
That's easy. Just imagine that each word is a number in base $6$ using the digits $a=0$, $b=1 ,\ldots$ . Then each word is its position (indexing starting from $0$, of course).


text:
Q: WebEngine loadContent() не загружаются картинки Я имею html-файл и много картинок от от него:

*

*Html-файл является зашифрованным.

*Картинки не зашифрованы.

В своей программе я считываю, расшифровываю и вывожу текст на экран: webEngine.loadContent(htmlCode).
Цель: вывести полноценный html-файл с картинками.
Проблема: не отображаются картинки.
PS: Html-файл и его картинки находятся за пределами программы.

Моё решение, которое не работает как надо:
Я нашёл библиотеку Jsoup, она парсит html-файлы. С помощью неё, я, в каждый атрибут src="" тега img вставлял разные пути, но что-то не получается:

*

*C:\Users\Gomas\Desktop\Новая папка (2)\Lectures\Lectures1\imageXXX.png

*file:\C:\Users\Gomas\Desktop\Новая папка (2)\Lectures\Lectures1\imageXXX.png

Код:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

...
String url = getUrl();
...

String htmlCode = getHtmlCode();
Document document = new Document(htmlCode);

Elements tagsImg = document.getElementsByTag("img");

tagsImg.forEach(tagImg ->{
    String nameImg = tagImg.attr("src");
    tagImg.attr("src", url + nameImg);
});

webEngine.loadContent(String.valueOf(document));

PS:
Почему не получается? Путь точный, но работать не хочет. Есть идеи?

A: При условии что в html используются абсолютные пути, ни каких проблем не обнаружено (работает и через load и через loadContent). Попробуйте соответствовать данному примеру (если это возможно):
C:/Test/Page.html
<!DOCTYPE html>

    <meta charset="utf-8">

Ниже картинка

Main.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        WebView webView = new WebView();

        primaryStage.setScene(new Scene(webView, 300, 300));
        primaryStage.show();

        Path pathToPage = Paths.get("C:/Test/Page.html");

        // test load
//        webView.getEngine().load(pathToPage.toUri().toString());

        // test load content
        String content = Files.lines(pathToPage).
                peek(System.out::print).
                collect(Collectors.joining());
        webView.getEngine().loadContent(content);
    }

}

P.S.: контент после дешифровки, так же должен работать.


text:
Q: How to retry a consumed Observable? I am trying to re-execute a defined observable that failed. Using Retrofit2 and RxJava2 together i want to retry a specific request with its subscription and behavior when clicking a button. is that possible?
service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(....)

A: An option is to create Publisher, which emission is controlled by your button.
final PublishSubject<Object> retrySubject = PublishSubject.create();

service.excecuteLoginService(url,
            tokenModel,
            RetrofitManager.apiKey)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnError(throwable -> showButton())
            .retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))
            .subscribeWith(result -> {}, error -> {});

Your button will just emit an item from the Subject:
retrySubject.onNext(EMPTY);


text:
Q: Rescaling image to get values between 0 and 255 A piece of code taken from here is trying to plot the intermediate outputs of a convolutional neural network. The outputs are taken and rescaled in this way:
if channel_image.sum()!=0:
    channel_image -= channel_image.mean()
    channel_image /= channel_image.std()
    channel_image *= 64
    channel_image += 128

channel_image = np.clip(channel_image, 0, 255).astype("uint8")

Everything in this transformation is pretty clear, except the multiplication by 64: what is that for? Is that an empirical value?

A: After subtracting the mean and dividing by the standard deviation, you have calculated the Z-Score for the channel image values.
It looks like they have chosen +/- 2 for the values to show as the number of standard deviations from the mean as:
2*64 + 128 = 256
-2*64 + 128 = 0

So multiplying by 64 scales the values to between -128 and +128, then shifting by 128 moves the values to between 0 and 256.
Any values outside the +/-2 standard deviations are then clipped by the line:
np.clip(channel_image, 0, 255).astype("uint8")

Really the 64 value should be calculated as something like:
def multiplier(num_std_deviations):
    return 256/(num_std_deviations*2)

A: After division by the standard deviation, the values are in a small range (virtually all of them in [-3,3] for a normal distribution). They are rescaled to better fill the [-128,127] range.


text:
Q: Compiling PHP 5.1.6 from source - php -v and phpinfo() version discrepancy I have just bought a VPS running Ubuntu and I need to install the LAMP stack with PHP 5.1.6. The VPS came with no PHP installed (checked this from the shell with php -v) and with Apache/2.2.12 installed. I installed PHP 5.1.6 from source and compiled it with Apache 2.2 (using libapache2-mod-php5), tried a phpinfo() test which worked fine, however, phpinfo() shows the PHP version as 5.2.1 (with JSON enabled), whereas running php-v in the shell shows as 5.1.6. Anyone any ideas what might be happening here? I need to ensure I am running PHP 5.1.6.
Thanks in advance for any help!

A: php -v gives you the version of the cli installation of php, while phpinfo will give you the version which got installed as apache module.
If you are not using cli php anywhere, you should be fine with running php scripts off apache.
But ideally you should fix this.


text:
Q: Custom stock options doesn't show up in bulk edit (Woocommerce 3.2.1) I used code from these posts (1,2) to create custom stock options:
function add_custom_stock_type() {
?>

<?php

woocommerce_wp_select( array( 'id' => '_stock_status', 'wrapper_class' =>
'hide_if_variable custom-stock-status', 'label' => __( 'Stock status',
'woocommerce' ), 'options' => array(
    'instock' => __( 'In stock', 'woocommerce' ),
    'outofstock' => __( 'Out of stock', 'woocommerce' ),
    '1to3' => __( 'Διαθέσιμο! Παράδοση σε: 1-3 ημέρες', 'woocommerce' ),
    '3to5' => __( 'Διαθέσιμο! Παράδοση σε: 3-5 ημέρες', 'woocommerce' ),
    '7to10' => __( 'Διαθέσιμο! Παράδοση σε: 7-10 ημέρες', 'woocommerce' ),
    'onrequest' => __( 'Διαθέσιμο κατόπιν παραγγελίας', 'woocommerce' ),//
    The new option !!!
), 'desc_tip' => true, 'description' => __( 'Controls whether or not the
product is listed as "in stock" or "out of stock" on the frontend.',
'woocommerce' ) ) );
}
add_action('woocommerce_product_options_stock_status',
'add_custom_stock_type');

function save_custom_stock_status( $product_id ) {
update_post_meta( $product_id, '_stock_status', wc_clean(
$_POST['_stock_status'] ) );
}
add_action('woocommerce_process_product_meta',
'save_custom_stock_status',99,1);

function woocommerce_get_custom_availability( $data, $product ) {
$stock_status = get_post_meta($product->id , '_stock_status' , true );
switch( $stock_status  ) {
    case 'instock':
        $data = array( 'availability' => __( 'In stock', 'woocommerce' ),
'class' => 'in-stock' );
    break;
    case 'outofstock':
        $data = array( 'availability' => __( 'Out of stock', 'woocommerce'
), 'class' => 'out-of-stock' );
    break;
    case '1to3':
        $data = array( 'availability' => __( 'Διαθέσιμο! Παράδοση σε: 1-3
ημέρες', 'woocommerce' ), 'class' => '1to3' );
    break;
    case '3to5':
        $data = array( 'availability' => __( 'Διαθέσιμο! Παράδοση σε: 3-5
ημέρες', 'woocommerce' ), 'class' => '3to5' );
    break;
    case '7to10':
        $data = array( 'availability' => __( 'Διαθέσιμο! Παράδοση σε: 7-10
ημέρες', 'woocommerce' ), 'class' => '7to10' );
    break;
    case 'onrequest':
        $data = array( 'availability' => __( 'Διαθέσιμο κατόπιν
παραγγελίας', 'woocommerce' ), 'class' => 'on-request' );
    break;
}
return $data;
}
add_action('woocommerce_get_availability',
'woocommerce_get_custom_availability', 10, 2);

The new stock options show up correctly in the single product edit page, but they won't show up when I try to bulk edit some products. Only "In stock" and "Out of stock" option are shown.
Product page:

Bulk Edit:

How can I bulk edit the products with the new custom stock options? It's a bit frustrating to edit the products one-by-one.

A: Yes it's possible I have done this, code is below for saving an example custom field.
/**
 * Add a custom column to WooCommerce products quick edit.
 *
 */
function es_display_custom_quickedit_product() {
    ?>

Custom Fields

        <?php _e( 'Member Price', 'woocommerce' ); ?>

            <input type="text" name="member_price" class="text wc_input_price" value="">

    <?php
}

add_action( 'woocommerce_product_quick_edit_end', 'es_display_custom_quickedit_product' );

/**
 * Save the quick edit custom WooCommerce fields
 *
 */
function es_save_custom_quickedit_product( $product ) {
    if ( isset( $_REQUEST['member_price'] ) AND ! empty( $_REQUEST['member_price'] ) ) {
        update_post_meta( $product->id, 'member_price', wc_clean( $_REQUEST['member_price'] ) );
    }
    else
        delete_post_meta( $product->id, 'member_price' );
}

add_action( 'woocommerce_product_quick_edit_save', 'es_save_custom_quickedit_product' );

A: You can add the custom stock status in the quick edit by using the following filter in theme's functions.php
function add_custom_stock_type_in_quick_edit( $status ) {
    return array(
        'instock' => __( 'In stock', 'woocommerce' ),
        'exhibited' => __( 'Exhibited', 'woocommerce' ),
        'sold' => __( 'Sold', 'woocommerce' ),
    );
}
add_filter( 'woocommerce_product_stock_status_options', 'add_custom_stock_type_in_quick_edit' );


text:
Q: Debug Multi-Dimensional Arrays C# Is there a way to display the matrix as a table in debug mode? I think that how VS 2019 show it isn't relevant to see how the matrix changes.

A: You can add a simple extension method to a project you are debugging:
public static class DebugExtensions
{
    public static string Test2D(this Array source, int pad = 10)
    {
        var result = "";
        for (int i = source.GetLowerBound(0); i <= source.GetUpperBound(0); i++)
        {
            for (int j = source.GetLowerBound(1); j <= source.GetUpperBound(1); j++)
                result += source.GetValue(i, j).ToString().PadLeft(pad);
            result += "\n";
        }
        return result;
    }
}

This method is iterating through 2 dimensional array adding each array item to a multi-line string.
While debugging you can use it in Watch window. Open Watch window, type new expression, click on magnifier icon and choose "Text Visualizer":


text:
Q: Mysql 8.0 installation error in windows 10 Can anyone help me in installing mysql server and workbench on  windows 10(64 bit architecture).
Steps:

*

*Download Windows (x86, 32-bit), MSI Installer from https://dev.mysql.com/downloads/mysql/5.7.html#downloads

*unzip and run mysql-installer-web-community-5.7.25.0.msi

*Select standalone mYSQL server in Group Replication

*Type and Networking--> config type: development computer, TCP/IP , PORT 3306

*Authentication method: Use strong password encrytpion.

*Accounts and Roles: type the password.

*Apply configuration: when I click on execute it fails with below error.

Beginning configuration step: Writing configuration file
  Invalid server template
  Ended configuration step: Writing configuration file

Thanks in advance

A: XAMPP includes MySQL server
you can download from this link XAMPP download

A: There may be 2 solutions here:

*

*Try to run as admin

*change installation path

*and why do you unzip .msi installer?


text:
Q: The field in this expression has an invalid table in this context i'm trying to do following query:
@NamedQuery(name="Grade.findGradeByClassGroup",
            query= "SELECT gr From Grades gr join DeterminateTable d on gr.DeterminateTableId = d.DeterminateTableId join SchoolYears sy on gr.GradeId = sy.GradeId join ClassGroups cg on cg.schoolYear = sy.YearInt where cg.groupId = :classGroup")

And I get this exception:
Caused by: Exception [EclipseLink-6069] (Eclipse Persistence Services - 2.6.0.v20141202-3914740): org.eclipse.persistence.exceptions.QueryException
Exception Description: The field [Grades.GradeId] in this expression has an invalid table in this context.
Query: ReadAllQuery(name="Grade.findGradeByClassGroup" referenceClass=Grade jpql="SELECT gr From Grades gr join DeterminateTable d on gr.DeterminateTableId = d.DeterminateTableId join SchoolYears sy on gr.GradeId = sy.GradeId join ClassGroups cg on cg.schoolYear = sy.YearInt where cg.groupId = :classGroup")
    at org.eclipse.persistence.exceptions.QueryException.invalidTableForFieldInExpression(QueryException.java:755)
    at org.eclipse.persistence.internal.expressions.FieldExpression.validateNode(FieldExpression.java:325)
    at org.eclipse.persistence.expressions.Expression.normalize(Expression.java:3291)
    at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:369)
    at org.eclipse.persistence.internal.expressions.FieldExpression.normalize(FieldExpression.java:225)
    at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:224)
    at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:574)
    at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:865)
    at org.eclipse.persistence.expressions.ExpressionBuilder.normalize(ExpressionBuilder.java:267)
    at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:363)
    at org.eclipse.persistence.internal.expressions.FieldExpression.normalize(FieldExpression.java:225)
    at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:232)
    at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:574)
    at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:865)
    at org.eclipse.persistence.expressions.ExpressionBuilder.normalize(ExpressionBuilder.java:267)
    at org.eclipse.persistence.internal.expressions.DataExpression.normalize(DataExpression.java:363)
    at org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:758)
    at org.eclipse.persistence.internal.expressions.QueryKeyExpression.normalize(QueryKeyExpression.java:671)
    at org.eclipse.persistence.internal.expressions.CompoundExpression.normalize(CompoundExpression.java:224)
    at org.eclipse.persistence.internal.expressions.RelationExpression.normalize(RelationExpression.java:574)
    at org.eclipse.persistence.internal.expressions.SQLSelectStatement.normalize(SQLSelectStatement.java:1474)
    at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.buildNormalSelectStatement(ExpressionQueryMechanism.java:550)
    at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.prepareSelectAllRows(ExpressionQueryMechanism.java:1722)
    at org.eclipse.persistence.queries.ReadAllQuery.prepareSelectAllRows(ReadAllQuery.java:867)
    at org.eclipse.persistence.queries.ReadAllQuery.prepare(ReadAllQuery.java:798)
    at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:666)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:909)
    at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:615)
    at org.eclipse.persistence.internal.jpa.QueryImpl.getDatabaseQueryInternal(QueryImpl.java:342)
    ... 65 more

I can't figure out whats wrong, tried to google but couldn't get any answers...
What could be causing this?


text:
Q: How to split up the_title and insert a span tag My titles, site wide, will follow this theme all within a h1 tag:
Main title heading / Sub-title text
I'm trying to wrap a span tag around all text after and including the '/' so my markup will look like this:

Main title heading / Sub-title text

How do I accomplish this? I'm not great with PHP but I've tried playing with explode but can't get the end result all I end up doing is hiding everything after the '/'
EDIT:
Code removed & Pastebin created, this is my whole page for index.php: http://pastebin.com/0T9mt7Fu

A: This comes a bit late, but I don't know where else it would make sense. I had a similar problem and created a solution.
As toscho has pointed out, the_title is used in nav menus, too. He has created a filter to switch the title filter on/off for nav menus—which I personally think is Einsteinesque. (Thanks a bunch!)
So I've just modified his filter a little to make it work here. Then added the actual filtering function. Wherever you use space-pipe-space (" | ") in a post title field, the part after it gets wrapped up in a  tag (including the slash the original post author asked for).
/**
 * Append a sub-heading to WordPress post titles
 */

add_filter( 'wp_nav_menu_args', 'gp121028_title_filter_switch' );
add_filter( 'wp_nav_menu', 'gp121028_title_filter_switch' );
/**
 * Switch title filter off when menu class starts and on when it ends.
 *
 * @param  mixed $input Array or string, we just pass it through.
 * @return mixed
 */
function gp121028_title_filter_switch( $input ) {
    $func = 'wp_nav_menu_args' == current_filter() ? 'remove_filter' : 'add_filter';
    $func( 'the_title', 'gp121028_filter_title' );
    return $input;
}

/**
 * The actual filter function for the_title()
 */
function gp121028_filter_title( $title ) {
    $substrings = explode( ' | ', $title );
    $title = ( ! empty( $substrings[0] ) ) ? $substrings[0] . '/' . $substrings[1] . '' : $title;
    return $title;
}

Hope it helps somebody!

A: its best if you just use custom field type to create a sub title...
That way you leave the title un-touched and just add a field where
you can insert a value like so (calling field sub title):

Then you can fetch your subtitle easily:
<?php
$sub_title=get_post_meta($post->ID,'subtitle',true);
if($sub_title != '') {
echo '
'. the_title() .''. $sub_title .'
';
} else {
echo '
'. the_title() .'
';
}
?>

.
i hope this a suitable solution for you... i use it on occasions
Cheers, Sagive

HOW TO:
Replace (i hope it looks the same in your theme) with the code above..:

<?php the_title(); ?>

A: I think the answer @Sagive SEO gave seems like the best approach from a semantic perspective. But if you prefer to keep both "titles" in the title field, a simple explode should work for you.
Try something like this:
add_filter( 'the_title', 'wpse45589_split_title', 10, 2 );

function wpse45589_split_title( $title, $post_id = null ) {
    if ( !$post_id )
        return $title;
    $post = get_post( $post_id );
    if ( $post->post_type !== 'page' )
        return $title;
    $parts = explode( '/', $title, 2 );
    $title_to_return = $parts[0];
    if ( !empty( $parts[1] ) )
        $title_to_return .= '/'.$parts[1].'';
    return $title_to_return;
}

ETA: following @toscho's suggestion below, I added a couple lines to check the post type before filtering the title. This function should now only add the 's to the title on pages, not in nav menus, etc.


text:
Q: Method to fill forms across many sites - jQuery? After working in good ole' c++ all day, I like to have a few javascript/jQuery side projects that are purely for fun. One of most intriguing things about jQuery is the ease of filling forms. All you need is a selector and the .val() method and you are golden. However, what would be the most efficient way to fill forms across multiple sites? The form elements would have different selectors obviously. So is there a way to have a script inspect a page and determine the selectors needed, then hand those selectors to jQuery for filling?
Just an intriguing thought, probably not possible, but I thought I'd ask anyway, if only to satisfy my curiosity. So is something like I described above possible? Dynamically getting the selectors off of a page?
Thanks!!

A: Assuming you're doing something like making an extension and not trying to do some cross-domain scripting (which won't work btw), the HTML should still be the same across sites.
You can select $('textarea'), $('select'), $('textfield'), $('input') etc, without worrying about things like classes and IDs.


text:
Q: R- vector argument matching and perform corresponding calculation Let's say I want to create a function that takes arguments of value x, y, and type, like
myfun <- function(x, y, type=c("all", "add", "multiply", "mean")){
    method <- match.arg(type, several.ok = TRUE)
    * body of the function
}

When I call the function by myfun(10,20, type = "all"), it will return a table that performs all types of metrics like this
method    value
sum         30
multiply    200
mean        15

When I call the function by myfun(10,20, type = c("sum", "multiply")), it will return a table like this
method    value
sum         30
multiply    200

I am wondering how to write a function that can take vector argument, and match the argument to a corresponding calculation, then put the method name and value in a table?
I was thinking about creating a table like the first table above, and then perform subset by matching the first column to the name of the argument. Is is feasible?

A: One can have an attempt using eval and parse as below. We have to define a custom function for multiply as such function is not available.
multiply <- function(x, y){
  x*y
}

myfun <- function(x, y, type=c("all", "sum", "multiply", "mean")){
  if("all" %in% type)
  {
    type=c("sum", "multiply", "mean")
  }
  method <- match.arg(type, several.ok = TRUE)
  df<- data.frame(method = character(0), value = double(0))
  #body of the function
  for(m in seq_along(method)){
    df<-rbind(df, data.frame(method=method[m],
              value=eval(parse(text = sprintf("%s(%f,%f)",method[m],x,y)))))
  }

  df
}

Tests
myfun(2,3)   #like "All"
#    method value
#1      sum     5
#2 multiply     6
#3     mean     2

myfun(12,4, "mean")
#  method value
#1   mean     8

> myfun(12,4, "multiply")
#    method value
#1 multiply    48


text:
Q: Dynamically allocating 2D int array Can someone please point out what I am doing wrong in the following code?
int* a = NULL;
int* b = NULL;
a = new int[map->mapSize.width];
b = new int[map->mapSize.height];

layer->tileGids = new int[a][b];

Here's what the code uses:
typedef struct _size {
    int width, height;
} size;

class Map {
    size mapSize;
}

class Layer {
    int * tileGids;
}

EDIT: Compiler-Errors (in line 6 of the first bit of code):

*

*error: expression in new-declarator must have integral or enumeration type|

*error: 'b' cannot appear in a constant-expression|

Solution:
I have decided to accept lightalchemist's answer. In essence, what works for me is use a vector instead of the array. Vector manages the memory for you and hence is a lot easier to deal with.

A: You can't pass a pointer for initializing the size of an array. Others have now mentioned this.
This post (it's not mine) seems like it might help you: http://eli.thegreenplace.net/2003/07/23/allocating-multi-dimensional-arrays-in-c/
You should also consider doing the allocation in the class Layer's constructor and then deleting the memory in it's destructor (i.e. RAII - resource acquisition is initialization). This is considered good style.
Finally, you might consider using continuous memory and a custom indexing scheme, which you could easily use Layer to encapsulate. This of course depends upon how big things will get. The bigger they get the better the case for continuous memory becomes.
This should give you a flavor.
#include <iostream>
#include <cstdlib>

int main()
{
   const size_t ROWS = 5;
   const size_t COLS = 2;
   const size_t size = ROWS*COLS;

   int* arr = new int[size];

   int i = 0;
   for ( size_t r = 0 ; r < ROWS; ++r )
   {
      for (size_t c = 0; c < COLS; ++c )
      {
         arr[r*COLS+c] = i++;
      }
   }

   for ( int j = 0; j < i; ++j)
   {
      std::cout << arr[j] << std::endl;
   }

   delete [] arr;
}

A:
Can someone please point out what I am doing wrong in the following code?

A lot. You're allocating two single arrays (a "row array" and a "column array", not what you need), and then you try to do something strange.

Generally you can't (strictly speaking) dynamically allocate a 2D array in C++ (because the type system would still need the type, along with the dimensions, to be known at compile time). You can emulate it with an array of arrays or so, but the best way is to allocate an 1D array:
int width=5;

std::vector<int> tab(width*height);

and then access the element by calculating the coordinates manually:
// access the element (1,2)
tab[1 + 2*width] = 10;

This way you're essentially interpreting a 1D array as a 2D array (with performance equal to static 2D arrays).
Then it's best to wrap the indexing with a class for convenience; boost::multi_array also has this done for you already.

A: Firstly, your variables "a" and "b" are pointers. Your code:
layer->tileGids = new int[a][b]
is the root cause of the problem.
I'm trying to guess your intention here and I think what you are trying to do is make layer.tileGids a 2 dimension array to reference a "grid" of size (mapSize.Width, mapSize.height) so that you can refer to each "cell" in the grid using layer.tileGids[x][y].
If you are indeed trying to create a 2 dimension array, there are 2 methods to do it.
Method 1:
class Layer {
int ** tileGids; // NOTE the "**" to indicate tileGids is a pointer to pointer i.e. 2D array.
}

To initialize it:
int width = map->mapSize.width;
int height = map->mapSize.height;
layer.tileGids = new int*[width]; // NOTE the "int*" to indicate tileGids is a new array of pointers to int.
for (int i = 0; i < width; i++) // Initialize each element in layer.tileGids[] to be a pointer to int.
{
  layer.tileGids[i] = new int[height];
}

Now you can access the items in layer.tileGids using:
int value = layer.tileGids[x][y] // where 0 <= x < width and 0 <= y < height

To deallocate this data structure, similar to how you allocate it, you need to deallocate each dynamically allocated array in each "row":
for (int i = 0; i < width; i++)
    {
      delete [] layer.tileGids[i]; // Deallocate each row.
    }

delete [] layer.tileGids; // Deallocate "array" to the pointers itself.

Method 2:
Now another easier, less messy method (avoid pointers) is to use the C++ vector class. You need to make the following changes:
#include <vector>
class Layer {
  vector<vector<int> > tileGids; // Note the space at "<int> >".
}

To initialize:
int width = map->mapSize.width;
int height = map->mapSize.height;
layer.tileGids = vector<vector<int> >(width, vector<int>(height, 0));  // Initialize all entries to 0.

To access the elements:
int value = layer.tileGids[x][y]; // Where 0 <= x < width and 0 <= y < height

Note that for the second method using vectors, you do not have to do any memory cleanup as is required in the first method because the vector will automatically take care of it.  However, because a vector can grow dynamically i.e. you can add items to it, you lose the safety of having a fixed size array i.e. someone could accidentally increase the size of your grid if you use the vector method but if he tries to do that when you intialized it using the first method above an error will occur and you will immediately know that something is wrong.

A: a and b are int* here:
layer->tileGids = new int[a][b];

Perhaps you meant to say this?
layer->tileGids = new int[*a][*b];