问:
Google Maps does not load in a Bootstrap modal
I'm new on the platform. I am French, and I translate this text with google translation.

I have a problem with the initialization of Google Maps in my bootstrap modal (Bootstrap version 3.3.7)

I've already covered topics and forums, and no solution worked.

When you open the modal (click on the button), the maps appear in a gray box but do not load.

When I change the size of my browser, it loads but is not centered.

How to load the maps directly?

The map is loading with the ACF plugin, here's my code :

```<code><style type="text/css">

.acf-map {
  width: 100%;
  height: 400px;
  border: #ccc solid 1px;
  margin: 20px 0;
}

/* fixes potential theme css conflict */
.acf-map img {
   max-width: inherit !important;
}

</style>

<script src="https://maps.googleapis.com/maps/api/js?key=#####"></script>
<script type="text/javascript">

(function($) {

// popup is shown and map is not visible

/*
*  new_map
*
*  This function will render a Google Map onto the selected jQuery element
*
*  @type  function
*  @date  8/11/2013
*  @since 4.3.0
*
*  @param $el (jQuery element)
*  @return  n/a
*/

function new_map( $el ) {

  // var
  var $markers = $el.find('.marker');

  // vars
  var args = {
    zoom    : 16,
    center    : new google.maps.LatLng(0, 0),
    mapTypeId : google.maps.MapTypeId.ROADMAP
  };

  // create map
  var map = new google.maps.Map( $el[0], args);

  // add a markers reference
  map.markers = [];

  // add markers
  $markers.each(function(){

      add_marker( $(this), map );

  });

  // center map
  center_map( map );

  // return
  return map;

}

/*
*  add_marker
*
*  This function will add a marker to the selected Google Map
*
*  @type  function
*  @date  8/11/2013
*  @since 4.3.0
*
*  @param $marker (jQuery element)
*  @param map (Google Map object)
*  @return  n/a
*/

function add_marker( $marker, map ) {

  // var
  var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );

  // create marker
  var marker = new google.maps.Marker({
    position  : latlng,
    map     : map
  });

  // add to array
  map.markers.push( marker );

  // if marker contains HTML, add it to an infoWindow
  if( $marker.html() )
  {
    // create info window
    var infowindow = new google.maps.InfoWindow({
      content   : $marker.html()
    });

    // show info window when marker is clicked
    google.maps.event.addListener(marker, 'click', function() {

      infowindow.open( map, marker );

    });
  }

}

/*
*  center_map
*
*  This function will center the map, showing all markers attached to this map
*
*  @type  function
*  @date  8/11/2013
*  @since 4.3.0
*
*  @param map (Google Map object)
*  @return  n/a
*/

function center_map( map ) {

  // vars
  var bounds = new google.maps.LatLngBounds();

  // loop through all markers and create bounds
  $.each( map.markers, function( i, marker ){

    var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );

    bounds.extend( latlng );

  });

  // only 1 marker?
  if( map.markers.length == 1 )
  {
    // set center of map
      map.setCenter( bounds.getCenter() );
      map.setZoom( 16 );
  }
  else
  {
    // fit to bounds
    map.fitBounds( bounds );
  }
}

/*
*  document ready
*
*  This function will render each map when the document is ready (page has loaded)
*
*  @type  function
*  @date  8/11/2013
*  @since 5.0.0
*
*  @param n/a
*  @return  n/a
*/
// global var
var map = null;

$(document).ready(function(){

  $('.acf-map').each(function(){

    // create map
    map = new_map( $(this) );

    // popup is shown and map is not visible
    google.maps.event.trigger(map, 'resize');

  });

});

})(jQuery);

</script>
</code>```

And the integration of the modal bootstrap:

```<code><!-- MAPS -->

<div class="col-md-6 txtmap">

    <div class="animated fadeInRightShort" data-id='4'>
        <button type="button" class="button button-icon btnprogramme big" data-toggle="modal" data-target="#gmaps">
          <i class="fa fa-map-marker"></i>Google Maps</a>
        </button>
    </div>

</div>

<!-- MODAL MAPS -->

<div class="modal fade" id="gmaps" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel"><?php the_title(); ?> <span>- Google Maps</span></h4>
      </div>
      <div class="modal-body">

            <?php

            $location = get_field('programme-maps');

            if( !empty($location) ):
            ?>
            <div class="acf-map">
            <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>"></div>
            </div>
            <?php endif; ?>

      </div>
      <div class="modal-footer">
        <button type="button" class="button alt" data-dismiss="modal">Fermer</button>
      </div>
    </div>
  </div>
</div>
</code>```

Thank you for your help !
I do not know anymore or look ..

答:
Thank you for your answer.
I looked at the codepen, I tried to adapt it for my case, but I did not succeed. The result is the same.

Here is a screenshot of the result:

My problem

And the map appears (but it is not centered) if I modify the window of my browser.

When I look at the ACF documentation, he tells me to insert this code. But I do not know where ...

Solving the hidden map issue

The Google map API will not work as expected if initialized on a
  hidden element. When the element is show, the map will not display.
  This scenario is most likely when using a popup modal.

To solve this problem, simply trigger the ‘resize’ event on the map
  variable after the map element is visible.

```<code>// popup is shown and map is not visible
google.maps.event.trigger(map, 'resize');
</code>```

Thank you very much for your help !

Body:
I'm new on the platform. I am French, and I translate this text with google translation.

I have a problem with the initialization of Google Maps in my bootstrap modal (Bootstrap version 3.3.7)

I've already covered topics and forums, and no solution worked.

When you open the modal (click on the button), the maps appear in a gray box but do not load.

When I change the size of my browser, it loads but is not centered.

How to load the maps directly?

The map is loading with the ACF plugin, here's my code :

And the integration of the modal bootstrap:

        <button type="button" class="button button-icon btnprogramme big" data-toggle="modal" data-target="#gmaps">
          Google Maps
        </button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

<?php the_title(); ?> - Google Maps

            <?php

            $location = get_field('programme-maps');

            if( !empty($location) ):
            ?>

            <div class="marker" data-lat="<?php echo $location['lat']; ?>" data-lng="<?php echo $location['lng']; ?>">

            <?php endif; ?>

        <button type="button" class="button alt" data-dismiss="modal">Fermer</button>

Thank you for your help !
I do not know anymore or look ..

Body:
Thank you for your answer.
I looked at the codepen, I tried to adapt it for my case, but I did not succeed. The result is the same.

Here is a screenshot of the result:

My problem

And the map appears (but it is not centered) if I modify the window of my browser.

When I look at the ACF documentation, he tells me to insert this code. But I do not know where ...

Solving the hidden map issue

The Google map API will not work as expected if initialized on a
  hidden element. When the element is show, the map will not display.
  This scenario is most likely when using a popup modal.

To solve this problem, simply trigger the ‘resize’ event on the map
  variable after the map element is visible.

// popup is shown and map is not visible
google.maps.event.trigger(map, 'resize');

Thank you very much for your help !


来源: stackexchange

问:
What is being normalized by Keras/TensorFlow BatchNormalization
My question is what is being normalized by BatchNormalization (BN).

I am asking, does BN normalize the channels for each pixel separately or for all the pixels together. And does it do it on a per image basis or on all the channels of the entire batch.

Specifically, BN is operating on X. Say, X.shape = [m,h,w,c]. So with axis=3, it is operating on the "c" dimension which is the number of channels (for rgb) or the number of feature maps.

So lets say the X is an rgb and thus has 3 channels. Does the BN do the following: (this is a simplified version of the BN to discuss the dimensional aspects.  I understand that gamma and beta are learned but not concerned with that here.)

For each image=X in m:

For each pixel (h,w) take the mean of the associated r, g, & b values.

For each pixel (h,w) take the variance of the associated r, g, & b values

Do r = (r-mean)/var, g = (g-mean)/var, & b = (b-mean)/var, where r, g, & b are the red, green, & blue channels of X respectively.

Then repeat this process for the next image in m,

In keras, the docs for BatchNormalization says:

axis: Integer, the axis that should be normalized (typically the features axis).

For instance, after a Conv2D layer with data_format="channels_first",
  set axis=1 in BatchNormalization.

But what is it exactly doing along each dimension?

答:
First up, there are several ways to apply batch normalization, which are even mentioned in the original paper specifically for convolutional neural networks. See the discussion in this question, which outlines the difference between a usual and convolutional BN, and also the reason why both approaches make sense.

Particularly keras.layers.BatchNormalization implements the convolutional BN, which means that for an input [m,h,w,c]  it computes c means and standard deviations across m*h*w values. The shapes of the running mean, running std dev and gamma and beta variables are just (c,). The values across spatial dimensions (pixels), as well as across the batch, are shared.

So a more accurate algorithm would be: for each R, G, and B channel compute the mean/variance across all pixels and all images in this channel and apply the normalization.

ContentLicense: CC BY-SA 3.0


问:
A simple rate limiter in php and memcached
I'm trying to make a simple rate limiter, based on the comments from here:

```<code>function set_session_rate_limit($memcache, $name, $user_session, $time)
{
   $memcache->add($name . $user_session, 0, $time);

   return $memcache->increment($name . $user_session);
}

set_session_rate_limit($memcache, 'login_fail_', $user_session, 300);

function get_session_rate_limit($memcache, $name, $user_session)
{
   return $memcache->get($name . $user_session);
}

var_dump(get_session_rate_limit($memcache, 'login_fail_', $user_session));
</code>```

Why does the above code return bool(false)?

答:
this might not be appropriate but I believe a rate limiter should be as bare as possible. Below I have tried to a simple session-based limiter.</p>

```<code><?php
    session_start();
    const cap = 3;//Max http requests a host can make
    const period = 5;//the period in which it limits,60 means 1 minuts
    $stamp_init = date("Y-m-d H:i:s");
    if( !isset( $_SESSION['FIRST_REQUEST_TIME'] ) ){
            $_SESSION['FIRST_REQUEST_TIME'] = $stamp_init;
    }
    $first_request_time = $_SESSION['FIRST_REQUEST_TIME'];
    $stamp_expire = date( "Y-m-d H:i:s", strtotime( $first_request_time )+( period ) );
    if( !isset( $_SESSION['REQ_COUNT'] ) ){
            $_SESSION['REQ_COUNT'] = 0;
    }
    $req_count = $_SESSION['REQ_COUNT'];
    $req_count++;
    if( $stamp_init > $stamp_expire ){//Expired
            $req_count = 1;
            $first_request_time = $stamp_init;
    }
    $_SESSION['REQ_COUNT'] = $req_count;
    $_SESSION['FIRST_REQUEST_TIME'] = $first_request_time;
    header('X-RateLimit-Limit: '.cap);
    header('X-RateLimit-Remaining: ' . ( cap-$req_count ) );
    if( $req_count > cap){//Too many requests
            http_response_code( 429 );
            exit();
    }
</code>```

Body:
I'm trying to make a simple rate limiter, based on the comments from here:

function set_session_rate_limit($memcache, $name, $user_session, $time)
{
   $memcache->add($name . $user_session, 0, $time);

   return $memcache->increment($name . $user_session);
}

set_session_rate_limit($memcache, 'login_fail_', $user_session, 300);

function get_session_rate_limit($memcache, $name, $user_session)
{
   return $memcache->get($name . $user_session);
}

var_dump(get_session_rate_limit($memcache, 'login_fail_', $user_session));

Why does the above code return bool(false)?

Body:
this might not be appropriate but I believe a rate limiter should be as bare as possible. Below I have tried to a simple session-based limiter.

<?php
    session_start();
    const cap = 3;//Max http requests a host can make
    const period = 5;//the period in which it limits,60 means 1 minuts
    $stamp_init = date("Y-m-d H:i:s");
    if( !isset( $_SESSION['FIRST_REQUEST_TIME'] ) ){
            $_SESSION['FIRST_REQUEST_TIME'] = $stamp_init;
    }
    $first_request_time = $_SESSION['FIRST_REQUEST_TIME'];
    $stamp_expire = date( "Y-m-d H:i:s", strtotime( $first_request_time )+( period ) );
    if( !isset( $_SESSION['REQ_COUNT'] ) ){
            $_SESSION['REQ_COUNT'] = 0;
    }
    $req_count = $_SESSION['REQ_COUNT'];
    $req_count++;
    if( $stamp_init > $stamp_expire ){//Expired
            $req_count = 1;
            $first_request_time = $stamp_init;
    }
    $_SESSION['REQ_COUNT'] = $req_count;
    $_SESSION['FIRST_REQUEST_TIME'] = $first_request_time;
    header('X-RateLimit-Limit: '.cap);
    header('X-RateLimit-Remaining: ' . ( cap-$req_count ) );
    if( $req_count > cap){//Too many requests
            http_response_code( 429 );
            exit();
    }


问:
kotlin get view from NavigationView header
I have such variant, but I believe that there is a better way to do this

```<code>val header = nav_view.getHeaderView(0) as LinearLayout
val userName = header.findViewById(R.id.user_name) as TextView
</code>```

The issue is that when I try to get it just by user_name, it is null.

答:
This might help you and i think that its better way .

```<code>nav_view.getHeaderView(0).userNameTxt.text
</code>```

This is shortest way to access from header.

ContentLicense: CC BY-SA 4.0

Body:
I have such variant, but I believe that there is a better way to do this

val header = nav_view.getHeaderView(0) as LinearLayout
val userName = header.findViewById(R.id.user_name) as TextView

The issue is that when I try to get it just by user_name, it is null.

Body:
This might help you and i think that its better way .

nav_view.getHeaderView(0).userNameTxt.text

This is shortest way to access from header.


问:
TypeError: Property is undefined | React
I am new to React so this questions is probably very basic, but I'd like some help.

All of the sudden Eslint started shouting at me because of no-restricted-globals, so I began to fix those errors. However, I got this classical error just now TypeError: Cannot read property 'location' of undefined, and here's the code:

```<code>import React from 'react'

export default props => {
  const url = ['#'].concat(props.to).join('/')
  const { location } = this.props
  return (
    <a
      href={url}
      onClick={props.onClick}
      className={location.hash.indexOf(url) === 0 ? 'active' : undefined}
    >
      {props.children}
    </a>
  )
}
</code>```

I would really appreciate if someone explained why location is undefined, I just can't get that. Thanks for reading everyone!

答:
Try to use this:

```
import React from 'react'

    export default props => {
      const url = ['#'].concat(props.to).join('/')
      const location= this.props.location?this.props.location:[]
      return (

          {props.children}

      )
    }

```

Hope This might run properly!

Body:
I am new to React so this questions is probably very basic, but I'd like some help.

All of the sudden Eslint started shouting at me because of no-restricted-globals, so I began to fix those errors. However, I got this classical error just now TypeError: Cannot read property 'location' of undefined, and here's the code:

import React from 'react'

export default props => {
  const url = ['#'].concat(props.to).join('/')
  const { location } = this.props
  return (

      {props.children}

  )
}

I would really appreciate if someone explained why location is undefined, I just can't get that. Thanks for reading everyone!

Body:
Try to use this:

import React from 'react'

    export default props => {
      const url = ['#'].concat(props.to).join('/')
      const location= this.props.location?this.props.location:[]
      return (

          {props.children}

      )
    }

Hope This might run properly!


问:
Replace values with different condition in multiple columns in Pandas
I have a dataframe something like this but much larger:

```<code>source  next1     next2     next3
  b1     {-}       b2      -,b2,b3
  b2,b3      -   {b2,b3}  {b2,b3,b4}
</code>```

Now I need to replace a lot of characters here. Every next column should contain values of previous. If the value is -, or {-} that means previous, and if it's not any of that, again, there need to be previous.
Desired output:

```<code>source  next1  next2     next3
 b1      b1      b2     b1,b2,b3
 b2,b3   b2,b3   b2,bb3 b2,b3,b4
</code>```

I have tried something like this:

```<code>for val in df['source'].values:
    if values=b1:
        df['next1'].replace('{-},', 'b1,',regex=True, inplace=True)
        df['next1'].replace('-,', 'b1,',regex=True, inplace=True)
</code>```

etc
But I have so much rows, and condiditons, so this works to long and not where precise, there are errors. Put one value (from replacing) to all rows.

答:
I don't think there is a fast solution to your question, as string operations will always be slow-ish. Still, there is a better/faster one.

A straight-forward solution would be

```<code>for i in range(1, df.shape(1)):  # here only order matters
    df.iloc[:, i].str.replace('{-}', '-', inplace=True)
    mask = df.iloc[:, i].str.contains('-')
    df.iloc[mask, i].str.replace('{-}', df.iloc[mask, i-1], inplace=True)
</code>```

with that, it is likely to be WAY faster to have all the columns as sets ({}) and operate on them as such.

Body:
I have a dataframe something like this but much larger:

source  next1     next2     next3
  b1     {-}       b2      -,b2,b3
  b2,b3      -   {b2,b3}  {b2,b3,b4}

Now I need to replace a lot of characters here. Every next column should contain values of previous. If the value is -, or {-} that means previous, and if it's not any of that, again, there need to be previous.
Desired output:

source  next1  next2     next3
 b1      b1      b2     b1,b2,b3
 b2,b3   b2,b3   b2,bb3 b2,b3,b4

I have tried something like this:

for val in df['source'].values:
    if values=b1:
        df['next1'].replace('{-},', 'b1,',regex=True, inplace=True)
        df['next1'].replace('-,', 'b1,',regex=True, inplace=True)

etc
But I have so much rows, and condiditons, so this works to long and not where precise, there are errors. Put one value (from replacing) to all rows.

Body:
I don't think there is a fast solution to your question, as string operations will always be slow-ish. Still, there is a better/faster one.

A straight-forward solution would be

for i in range(1, df.shape(1)):  # here only order matters
    df.iloc[:, i].str.replace('{-}', '-', inplace=True)
    mask = df.iloc[:, i].str.contains('-')
    df.iloc[mask, i].str.replace('{-}', df.iloc[mask, i-1], inplace=True)

with that, it is likely to be WAY faster to have all the columns as sets ({}) and operate on them as such.


问:
Server Side Confirmation Box
There are some questions on the stack about this but none helped me. This is my scenario. I have a drop down box

```<code><asp:DropDownList ID="ddl" runat="server" DataTextField="ValText" DataValueField="ValID" AutoPostBack="true"  OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
</code>```

Requirement:

When the drop down is selected or if the value is changed in the drop down I need a javascript alert asking whether the file selected in the drop down is to be downloaded. If the user clicks yes then the function for file to download should be invoked else nothing should be done. I don't have an Idea how to achieve this. Any suggestions?

答:
You can add onchange="javascript:validateSelection();" so it would look like this:
<asp:DropDownList ID="ddl" onchange="javascript:validateSelection();" runat="server" OnSelectedIndexChanged="ddl_SelectedIndexChanged">

add then a javascript function using the 'confirm' popup like below:

```<code>function validateSelection() {
            var test = confirm("Would you like to download the file selected?");
            if (test)
            {
                __doPostBack("ctl00$MainContent$ddl1", "ddlchange");
            }
        }
</code>```

Title: Server Side Confirmation Box

Body:
There are some questions on the stack about this but none helped me. This is my scenario. I have a drop down box

<asp:DropDownList ID="ddl" runat="server" DataTextField="ValText" DataValueField="ValID" AutoPostBack="true"  OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

Requirement:

When the drop down is selected or if the value is changed in the drop down I need a javascript alert asking whether the file selected in the drop down is to be downloaded. If the user clicks yes then the function for file to download should be invoked else nothing should be done. I don't have an Idea how to achieve this. Any suggestions?

Body:
You can add onchange="javascript:validateSelection();" so it would look like this:
<asp:DropDownList ID="ddl" onchange="javascript:validateSelection();" runat="server" OnSelectedIndexChanged="ddl_SelectedIndexChanged">

add then a javascript function using the 'confirm' popup like below:

function validateSelection() {
            var test = confirm("Would you like to download the file selected?");
            if (test)
            {
                __doPostBack("ctl00$MainContent$ddl1", "ddlchange");
            }
        }


问:
Unwanted box shadow appearing on website and responsive break
I am currently updating/working on this web page "https://www.emergencydentalservice.com/emergency-dentist-by-city" and their is an unwanted box shadow appearing in the body that I can not determine from where or why. On top of the unwanted shadow the site also seems to break after 768px and I can't figure out why. Any help would be greatly appreciated, thank you all. Image of the site breaking after 768px</p>

答:
You have a box shadow set to #inside-main on eds_main.css.

```<code>#inside-main {
    width: 100%;
    background: #fff;
    margin: 0 auto;
    box-shadow: 1px -2px 4px #666;
    -webkit-box-shadow: 1px -2px 4px #666;
    -moz-box-shadow: 1px -2px 4px #666;
    -o-box-shadow: 1px -2px 4px #666;
}
</code>```

becomes

```<code>#inside-main {
    width: 100%;
    background: #fff;
    margin: 0 auto;
}
</code>```

As for the layout breaking, you have #foot-de-eds, #foot-top-cites on eds_main.css set to:

```<code>#foot-de-eds, #foot-top-cites {
    margin: 1.3em auto;
    width: 100%;
    max-width: 1028px;
    padding-left: 2em;
}
</code>```

Try removing the max-width: 1028px; - so:

```<code>#foot-de-eds, #foot-top-cites {
    margin: 1.3em auto;
    width: 100%;
    padding-left: 2em;
}
</code>```

Body:
You have a box shadow set to #inside-main on eds_main.css.

#inside-main {
    width: 100%;
    background: #fff;
    margin: 0 auto;
    box-shadow: 1px -2px 4px #666;
    -webkit-box-shadow: 1px -2px 4px #666;
    -moz-box-shadow: 1px -2px 4px #666;
    -o-box-shadow: 1px -2px 4px #666;
}

becomes

#inside-main {
    width: 100%;
    background: #fff;
    margin: 0 auto;
}

As for the layout breaking, you have #foot-de-eds, #foot-top-cites on eds_main.css set to:

#foot-de-eds, #foot-top-cites {
    margin: 1.3em auto;
    width: 100%;
    max-width: 1028px;
    padding-left: 2em;
}

Try removing the max-width: 1028px; - so:

#foot-de-eds, #foot-top-cites {
    margin: 1.3em auto;
    width: 100%;
    padding-left: 2em;
}


问:
C#: Regex with digits and slash in the middle
So i have string with digits and words for example:

```<code>1283677/10, this is my string, bla bla
</code>```

And i want to take only the serial number: 1283677/10

This is what i have try:

```<code>Match match = Regex.Match(text, @"\d{8}(/\d{1,2})?");
</code>```

Currently return empty.

答:
You have 7 digits in the part before slash. So the fix is fair simple:</p>

```<code>Match match = Regex.Match(text, @"\d{7}(/\d{1,2})?");
</code>```

Body:
So i have string with digits and words for example:

1283677/10, this is my string, bla bla

And i want to take only the serial number: 1283677/10

This is what i have try:

Match match = Regex.Match(text, @"\d{8}(/\d{1,2})?");

Currently return empty.

Body:
You have 7 digits in the part before slash. So the fix is fair simple:

Match match = Regex.Match(text, @"\d{7}(/\d{1,2})?");


问:
Maximo BIRT report runtime error when ran from Maximo
I've developed a report that I'm able to run on Eclipse BIRT to preview without any issues. However, when importing it into Maximo and trying to run it I get the below error:

```<code>There was an exception on the server. Check your report parameter values, or contact your system administrator, who can find additional details in the server log.
</code>```

I checked the application server logs and there was no relevant information there. I also enabled the birt report loggers on Maximo at the DEBUG level and I'm still not getting any errors there either.

How can I pinpoint what the problem is that's stopping it from running on Maximo?

答:
The solution to using an alias in the from and to can be accomplished by changing the where that Maximo passes. For example the receiving application passes matrectrans so we just replace the object name with the alias and use myWhere.
var myWhere =  params["where"].replace("matrectrans","m");
-W</p>

Body:
I've developed a report that I'm able to run on Eclipse BIRT to preview without any issues. However, when importing it into Maximo and trying to run it I get the below error:

There was an exception on the server. Check your report parameter values, or contact your system administrator, who can find additional details in the server log.

I checked the application server logs and there was no relevant information there. I also enabled the birt report loggers on Maximo at the DEBUG level and I'm still not getting any errors there either.

How can I pinpoint what the problem is that's stopping it from running on Maximo?


问:
Calculate the value according to the dates
Good afternoon, I have a doubt on how to make a calculation, as for examples I have a face 'date' and a face 'date end' when selected these dates it will calculate a value, for example for * 38.00 reais and calculates by "end date." If you can give me strength, thank you.</p>

答:
```<code>    <!DOCTYPE html>
<html>
<head>
    <title>teste</title>
    <meta charset="UTF-8" />

      <script src="js/moment.js"></script>

    <script type="text/javascript">

    function calc{
    var date1 = new Date(document.getElementById("databegin").value);
    var date2 = new Date(document.getElementById("dataend").value);

    date1 = Moment('DD/MM/YYYY'),
    date2 = Moment('DD/MM/YYYY'),

    daysPass = final.diff(date1, 'days');

    alert('Days: ' + daysPass); // Dias passados: 13
    alert('Value: R$' + (daysPass * 38) + ',00');

    }

    </script>
</head>
<body>
  <fieldset id="c">
    <h3>Test:</h3>
      <input type="date" id="databegin"></br>
      <input type="date" id="dataend"></br>
      <button id="calc" onclick="calc();">Calc</button>
  </fieldset>
  <br>
  <fieldset>
    Result: <span id="result">0</span>
  </fieldset>
  </body>
</html>
</code>```


问:
Eclipse 3.6 Helios for Ubuntu 10.10
I have ubuntu 10.10 net book edition installed on my dell studio laptop. I downloaded helios for the eclipse site but when I am not able to run it. I have downloaded eclipse 3.5 from synaptic package manager but I am not able to update eclipse 3.5 to eclipse 3.6. Is der any other way to have updated eclipse? Eclipse 3.6 supports HTML 5. </p>

<p>Please let me know, thanks a lot in advance </p>

答:
At least, you still have the manual install, which leaves your current Eclipse3.5 untouched (allowing you to go back to it if 3.6 gives you too much troubles)

To get your 3.6 download running:

Unzip the download into a directory you have complete control of, usually a directory under your username, preserving folders.

Create a shortcut to the eclipse executable, usually in the resulting "eclipse" folder.

Run the program using the resulting shortcut.

When your new eclipse install starts, point to your existing workspace.

  You can continue with both 3.5 and 3.6 installed using the same workspace, or you can remove 3.5 by deselecting it from your software management program (one of several ways).

Alexander Pogrebnyak actually points out in the comment:

workspace cannot round trip 3.5->3.6->3.5.

  The usual solution is to keep 3.5 and 3.6 versions of workspace in different directories.

The idea to have one workspace for each version is always the safest route to take, with each of your project imported into each respective workspace.

Note, you have to make sure your java is correctly installed (which should be already good for you, but just in case):

Installing Helios 3.6 on Ubuntu 10.10 is rather simple.

  Download eclipse package from eclipse.org and extract it to a folder in your home directory.

The tricky part is setting up java6-jdk from the sun partner repository but there is a easy to follow guide:

  basically you have to enable the partner repository, then install java6 jdk with:

```<code>sudo apt-get install sun-java6-jre sun-java6-plugin
</code>```

and then if necessary update your java alternatives with:

```<code># shows a list with available java alternatives:
sudo update-java-alternatives -l

# sets the alternative
sudo update-java-alternatives -s java-6-sun
sudo update-alternatives --config java
</code>```

ContentLicense: CC BY-SA 2.5

Title: Eclipse 3.6 Helios for Ubuntu 10.10

Body:
I have ubuntu 10.10 net book edition installed on my dell studio laptop. I downloaded helios for the eclipse site but when I am not able to run it. I have downloaded eclipse 3.5 from synaptic package manager but I am not able to update eclipse 3.5 to eclipse 3.6. Is der any other way to have updated eclipse? Eclipse 3.6 supports HTML 5.

Please let me know, thanks a lot in advance

Body:
At least, you still have the manual install, which leaves your current Eclipse3.5 untouched (allowing you to go back to it if 3.6 gives you too much troubles)

To get your 3.6 download running:

Unzip the download into a directory you have complete control of, usually a directory under your username, preserving folders.

Create a shortcut to the eclipse executable, usually in the resulting "eclipse" folder.

Run the program using the resulting shortcut.

When your new eclipse install starts, point to your existing workspace.

  You can continue with both 3.5 and 3.6 installed using the same workspace, or you can remove 3.5 by deselecting it from your software management program (one of several ways).

Alexander Pogrebnyak actually points out in the comment:

workspace cannot round trip 3.5->3.6->3.5.

  The usual solution is to keep 3.5 and 3.6 versions of workspace in different directories.

The idea to have one workspace for each version is always the safest route to take, with each of your project imported into each respective workspace.

Note, you have to make sure your java is correctly installed (which should be already good for you, but just in case):

Installing Helios 3.6 on Ubuntu 10.10 is rather simple.

  Download eclipse package from eclipse.org and extract it to a folder in your home directory.

The tricky part is setting up java6-jdk from the sun partner repository but there is a easy to follow guide:

  basically you have to enable the partner repository, then install java6 jdk with:

sudo apt-get install sun-java6-jre sun-java6-plugin

and then if necessary update your java alternatives with:

# shows a list with available java alternatives:
sudo update-java-alternatives -l

# sets the alternative
sudo update-java-alternatives -s java-6-sun
sudo update-alternatives --config java


问:
Update existing entity with inline options doesn't work
Consider this code:

```<code> [TestMethod]
    public void AssertAutoMapper()
    {
        Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Entity, EntityModel>()
                    .ReverseMap();

                cfg.CreateMap<Message, MessageModel>()
                    .ReverseMap();
            }
        );

        Mapper.Configuration.AssertConfigurationIsValid();

        var model = new EntityModel() { Messages = new List<MessageModel>() {  } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity, opt => opt. ConfigureMap().ForMember(x => x.Messages, o => o.UseDestinationValue()));

        Assert.IsTrue(entity.Messages.Count == 1);
    }
</code>```

My first assert is Ok, but the second fails.
I tried with Ignore() but I have the same problem.

答:
I'm not sure why it's not working in the way you did, but configuring during initialization works.

```<code>        Mapper.Initialize(cfg =>
                {
                    cfg.CreateMap<Entity, EntityModel>()
                        .ReverseMap().ForMember(x => x.Messages, o => o.Ignore());
                    cfg.CreateMap<Message, MessageModel>()
                        .ReverseMap();
                });

        Mapper.Configuration.AssertConfigurationIsValid();

        var model = new EntityModel() { Messages = new List<MessageModel>() { } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity);
        Assert.IsTrue(entity.Messages.Count == 1);
</code>```

EDIT:

Inline configuration has no effect if you have provided configuration already in Initialize method. So to get it working you must do:

```<code>        Mapper.Initialize(cfg => { });
        Mapper.Configuration.AssertConfigurationIsValid();
        var model = new EntityModel() { Messages = new List<MessageModel>() { } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity, opt => opt.ConfigureMap().ForMember(x => x.Messages, o => o.Ignore()));
</code>```

Body:
Consider this code:

 [TestMethod]
    public void AssertAutoMapper()
    {
        Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Entity, EntityModel>()
                    .ReverseMap();

                cfg.CreateMap<Message, MessageModel>()
                    .ReverseMap();
            }
        );

        Mapper.Configuration.AssertConfigurationIsValid();

        var model = new EntityModel() { Messages = new List<MessageModel>() {  } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity, opt => opt. ConfigureMap().ForMember(x => x.Messages, o => o.UseDestinationValue()));

        Assert.IsTrue(entity.Messages.Count == 1);
    }

My first assert is Ok, but the second fails.
I tried with Ignore() but I have the same problem.

Body:
I'm not sure why it's not working in the way you did, but configuring during initialization works.

        Mapper.Initialize(cfg =>
                {
                    cfg.CreateMap<Entity, EntityModel>()
                        .ReverseMap().ForMember(x => x.Messages, o => o.Ignore());
                    cfg.CreateMap<Message, MessageModel>()
                        .ReverseMap();
                });

        Mapper.Configuration.AssertConfigurationIsValid();

        var model = new EntityModel() { Messages = new List<MessageModel>() { } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity);
        Assert.IsTrue(entity.Messages.Count == 1);

EDIT:

Inline configuration has no effect if you have provided configuration already in Initialize method. So to get it working you must do:

        Mapper.Initialize(cfg => { });
        Mapper.Configuration.AssertConfigurationIsValid();
        var model = new EntityModel() { Messages = new List<MessageModel>() { } };
        var entity = new Entity() { Messages = new List<Message>() { new Message() { Content = "Test" } } };
        Mapper.Map(model, entity, opt => opt.ConfigureMap().ForMember(x => x.Messages, o => o.Ignore()));


问:
How to loop through a JSON array and put data in variables
I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:

Notice: Trying to get property of non-object

My JSON data looks like this:

```<code>{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
</code>```

I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?

```<code><?php

    //Get content
    $url = "https://eftelingapi.herokuapp.com/attractions";
    $data = json_decode(file_get_contents($url));

    //Fetch data
    $attractieId = $data->AttractionInfo[0]->Id;
    $attractieType = $data->AttractionInfo[0]->Type;
    $attractieStatus = $data->AttractionInfo[0]->State;
    $attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
    $attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
    $attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;

?>
</code>```

I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.

Update code:

```<code>require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));

//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);

$sql =  "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
    echo "success";
} else {
    echo "Error: " . $sql . "<br>" . $db->error;
}
</code>```

It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.

答:
I think you need something like this:

```<code>    $json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
    $arr = json_decode($json);

     foreach ($arr->AttractionInfo as $key => $attraction) {
       foreach($attraction as $key=> $value) {
          print_r($key.' - '.$value.'<br>');
          $$key = $value;
       }
    }

echo '<br>';
echo $Id; // it will be last item/attraction id.
</code>```

We can improve this code. Just say where and how do you want to use it

Body:
I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:

Notice: Trying to get property of non-object

My JSON data looks like this:

{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},

I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?

<?php

    //Get content
    $url = "https://eftelingapi.herokuapp.com/attractions";
    $data = json_decode(file_get_contents($url));

    //Fetch data
    $attractieId = $data->AttractionInfo[0]->Id;
    $attractieType = $data->AttractionInfo[0]->Type;
    $attractieStatus = $data->AttractionInfo[0]->State;
    $attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
    $attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
    $attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;

?>

I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.

Update code:

require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));

//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);

$sql =  "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
    echo "success";
} else {
    echo "Error: " . $sql . "
" . $db->error;
}

It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.

Body:
I think you need something like this:

    $json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
    $arr = json_decode($json);

     foreach ($arr->AttractionInfo as $key => $attraction) {
       foreach($attraction as $key=> $value) {
          print_r($key.' - '.$value.'<br>');
          $$key = $value;
       }
    }

echo '<br>';
echo $Id; // it will be last item/attraction id.

We can improve this code. Just say where and how do you want to use it


问:
Traversing an object in javascript and convert it in specific format
I have the following object structure:

```<code>{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}
</code>```

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

```<code>const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");
</code>```

My expected output should be

```<code>[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]
</code>```

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output

答:
You mostly just needed to pass an array through and give a little adjustment to the path you're building.

The inclusion of the last item in the final path is a little surprising, and took some extra tweaking, but I think it's what you're looking for in the result.

const getFinalNode = function(data, path, result){
  result = result || [];

  // This check isn't needed if the initial call will always be an object.
  if (typeof data === 'object'){
    for (let [key, val] of Object.entries(data)) {
      if (typeof val === 'object'){
        getFinalNode(val, path ? (path + "/" + key) : key, result);

      }else{
        const notNum = isNaN(key);
        result.push({
          name: notNum ? key : path.slice(path.lastIndexOf("/") + 1),
          value: val,
          path:path + (notNum ? "/" + key : "")
        });
      }
    }
  }
  return result;
}

const data = {
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
};

console.log(getFinalNode(data, ""));```

I used Object.entries() with destructuring assignment in a for-of just for the convenience of having the key and value assigned to variables. Your original for-in loop was fine too.

Body:
I have the following object structure:

{
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
}

Now I want to convert these structure in specific format that are shown in expected output.

I'm trying to traverse above structure but the constructed path not correct
Here is what I'm doing

const getFinalNode = function(data, path){
  if (typeof data === 'object'){
    for (let key in data) {
      // console.log(key);
      if (typeof data[key] === 'object'){
        path += key+'/'
        getFinalNode(data[key], path)
        // console.log(true);
      }else{
        console.log({
          value: data[key],
          key: key,
          path:path
        })
      }
    }
  }
}
getFinalNode(data, "");

My expected output should be

[
    {
        name: "b",
        value: "abc",
        path: "a/b"
    },
    {
        name: "d",
        value: "pqr",
        path: "a/c/0/d"
    },
    {
        name: "e",
        value: true,
        path: "a/c/0/e"
    },
    {
        name: "f",
        value: 1,
        path: "a/c/1/f"
    },
    {
        name: "e",
        value: 'xyz',
        path: "a/c/1/e"
    },
    {
        name: "e",
        value: 1,
        path: "a/c/1/e"
    }
]

So how can I traverse above structure and convert it in expected output or is there any solution that can I use in my existing code.

Now I getting following output

Body:
You mostly just needed to pass an array through and give a little adjustment to the path you're building.

The inclusion of the last item in the final path is a little surprising, and took some extra tweaking, but I think it's what you're looking for in the result.

const getFinalNode = function(data, path, result){
  result = result || [];

  // This check isn't needed if the initial call will always be an object.
  if (typeof data === 'object'){
    for (let [key, val] of Object.entries(data)) {
      if (typeof val === 'object'){
        getFinalNode(val, path ? (path + "/" + key) : key, result);

      }else{
        const notNum = isNaN(key);
        result.push({
          name: notNum ? key : path.slice(path.lastIndexOf("/") + 1),
          value: val,
          path:path + (notNum ? "/" + key : "")
        });
      }
    }
  }
  return result;
}

const data = {
    a: {
        b: "abc",
        c: [
            {
                d: "pqr",
                e: true
            },
            {
                f: 1,
                e: ["xyz", 1]
            }
        ]
    }
};

console.log(getFinalNode(data, ""));

I used Object.entries() with destructuring assignment in a for-of just for the convenience of having the key and value assigned to variables. Your original for-in loop was fine too.


问:
Is there a C# version of CTypeDynamic?
From the documentation:

The CTypeDynamic method applies dynamic conversions in accordance with the conversion semantics defined by the object itself. If a dynamic object inherits from DynamicObject, the CTypeDynamic method first attempts to perform the conversion by using a user-defined, static conversion. If the user-defined, static conversion fails, the CTypeDynamic method attempts to perform the conversion by using dynamic conversions. If a dynamic object implements IDynamicMetaObjectProvider, the CTypeDynamic method gives precedence to dynamic conversions over user-defined, static conversions.

Is there something in C# that does this? Or do I just have to import the VB library that has it.

答:
The C# equivalent function to VB's CTypeDynamic() is Convert.ChangeType().

The change in name helps distinguish the C# function as being about setting a type conversion at runtime according to a type variable, rather than being about the dynamic type mechanism.

Convert.ChangeType

Returns an object of a specified type whose value is equivalent to a specified object.

Conversion.CTypeDynamic

Converts an object to the specified type.

...

The CTypeDynamic method converts the object passed as the Expression parameter to the type specified by the TargetType parameter. If the object is a dynamic object, the CTypeDynamic method applies available dynamic conversions.

...

CTypeDynamic method first attempts to perform the conversion by using
  a user-defined, static conversion

Title: Is there a C# version of CTypeDynamic?


问:
Show the data of JSON response using jQuery
I am using an API, which returns a JSON whenever you search something. It is basically a auto complete search API. Whenever you start typing in the box, it hits the API endpoint with a GET request and returns a JSON. Suppose, you start typing "lucky" , then request is https://autocomplete.clearbit.com/v1/companies/suggest?query=lucky and JSON response is

```<code>[{"name":"Lucky Brand","domain":"luckybrand.com","logo":"https://logo.clearbit.com/luckybrand.com"},{"name":"LuckyVitamin.com","domain":"luckyvitamin.com","logo":"https://logo.clearbit.com/luckyvitamin.com"},{"name":"Lucky Gunner Ammo","domain":"luckygunner.com","logo":"https://logo.clearbit.com/luckygunner.com"},{"name":"Lucky Orange","domain":"luckyorange.com","logo":"https://logo.clearbit.com/luckyorange.com"},{"name":"Lucky's Market","domain":"luckysmarket.com","logo":"https://logo.clearbit.com/luckysmarket.com"}]
</code>```

It returns name, domain and logo. I have a html search box so, whenever you start typing, I want to show the logo image, name and domain in a row of each item. But it is not properly showing. This is my code,

html :-

```<code><input type="text" placeholder="type something ..." id="suggest" />
</code>```

css :-

```<code>body{
    padding: 30px;
}
</code>```

JS :- (I am using jQuery)

```<code>$(document).ready(function () {

    $("#suggest").autocomplete({
        delay: 100,
        source: function (request, response) {

            // Suggest URL
            var suggestURL = "https://autocomplete.clearbit.com/v1/companies/suggest?query=%QUERY";
            suggestURL = suggestURL.replace('%QUERY', request.term);

            // JSON Request
            $.ajax({
                method: 'GET',
                dataType: 'json',
                jsonCallback: 'jsonCallback',
                url: suggestURL
            })
            .success(function(data){
                response(data[]); //Here I want to pass all the return
                                  //items. I can show only one item,
                                  //like data[1].name but not sure how
                                  //to go through each item.

            });
        }
    });

});
</code>```

答:
You can use the forEach() Method to go through your Response e.g.

```<code>data.forEach(function(item) {
    console.log(item.name, item.logo, item.domain);
});
</code>```

more about forEach here

Body:
I am using an API, which returns a JSON whenever you search something. It is basically a auto complete search API. Whenever you start typing in the box, it hits the API endpoint with a GET request and returns a JSON. Suppose, you start typing "lucky" , then request is https://autocomplete.clearbit.com/v1/companies/suggest?query=lucky and JSON response is

[{"name":"Lucky Brand","domain":"luckybrand.com","logo":"https://logo.clearbit.com/luckybrand.com"},{"name":"LuckyVitamin.com","domain":"luckyvitamin.com","logo":"https://logo.clearbit.com/luckyvitamin.com"},{"name":"Lucky Gunner Ammo","domain":"luckygunner.com","logo":"https://logo.clearbit.com/luckygunner.com"},{"name":"Lucky Orange","domain":"luckyorange.com","logo":"https://logo.clearbit.com/luckyorange.com"},{"name":"Lucky's Market","domain":"luckysmarket.com","logo":"https://logo.clearbit.com/luckysmarket.com"}]

It returns name, domain and logo. I have a html search box so, whenever you start typing, I want to show the logo image, name and domain in a row of each item. But it is not properly showing. This is my code,

html :-

<input type="text" placeholder="type something ..." id="suggest" />

css :-

body{
    padding: 30px;
}

JS :- (I am using jQuery)

$(document).ready(function () {

    $("#suggest").autocomplete({
        delay: 100,
        source: function (request, response) {

            // Suggest URL
            var suggestURL = "https://autocomplete.clearbit.com/v1/companies/suggest?query=%QUERY";
            suggestURL = suggestURL.replace('%QUERY', request.term);

            // JSON Request
            $.ajax({
                method: 'GET',
                dataType: 'json',
                jsonCallback: 'jsonCallback',
                url: suggestURL
            })
            .success(function(data){
                response(data[]); //Here I want to pass all the return
                                  //items. I can show only one item,
                                  //like data[1].name but not sure how
                                  //to go through each item.

            });
        }
    });

});

Body:
You can use the forEach() Method to go through your Response e.g.

data.forEach(function(item) {
    console.log(item.name, item.logo, item.domain);
});

more about forEach here


问:
babel-plugin-react-css-modules is not matching styles with styleName
Issue

I am trying to use babel-plugin-react-css-modules in my React project for better performance as opposed to React CSS Modules.

However, the styles are being not applied correctly.

Cause

The version in

答:
Found the solution myself after some struggling.

Cause

This is due to a quirk of css-loader: if there are double quotes around localIdentName option, it will wrap the generated class name with hyphens.

Working Examples

So instead of doing this in webpack config:

```<code>{
    test: /\.(scss|sass)$/,
    use: [
        'style-loader?sourceMap',
        'css-loader?modules="true"&importLoaders="1"&localIdentName="[path]___[name]__[local]___[hash:base64:5]"',
        'sass-loader?sourceMap',
    ],
},
</code>```

Do this:

```<code>{
    test: /\.(scss|sass)$/,
    use: [
        'style-loader?sourceMap',
        'css-loader?modules="true"&importLoaders="1"&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
        'sass-loader?sourceMap',
    ],
},
</code>```

Or event better if you are using Webpack 2+

```<code>{
        test: /\.(scss|sass$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              sourceMap: true,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
            }
          },
          'sass-loader'
        ]
}
</code>```

Body:
Found the solution myself after some struggling.

Cause

This is due to a quirk of css-loader: if there are double quotes around localIdentName option, it will wrap the generated class name with hyphens.

Working Examples

So instead of doing this in webpack config:

{
    test: /\.(scss|sass)$/,
    use: [
        'style-loader?sourceMap',
        'css-loader?modules="true"&importLoaders="1"&localIdentName="[path]___[name]__[local]___[hash:base64:5]"',
        'sass-loader?sourceMap',
    ],
},

Do this:

{
    test: /\.(scss|sass)$/,
    use: [
        'style-loader?sourceMap',
        'css-loader?modules="true"&importLoaders="1"&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
        'sass-loader?sourceMap',
    ],
},

Or event better if you are using Webpack 2+

{
        test: /\.(scss|sass$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: true,
              sourceMap: true,
              localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
            }
          },
          'sass-loader'
        ]
}


问:
DUnit test - Cannot create form. No MDI forms are currently active
I'm starting with DUnit tests so sorry in advance for any newbie mistakes. When I tried to run simple tests and the compiler runs the SetUp of my test class, it stops returning the message 'Cannot create form. No MDI forms are currently active'.

After some research, I found some explanations but none related to my problem.

The problem appears to be when I call the Create method of my child origin class - by origin I mean the class where I have all the procedures and functions to be tested, lets call it by TfrmFoo. And my test class should be the TestTfrmFoo. The TFrmFoo has a parent with some basic codes, the TfrmParentFoo.

I'm calling the Create method like this:

```<code>...

implementation

procedure TestTfrmFoo.SetUp;
begin

    FfrmParentFoo := TfrmParentFoo.Create(nil);

    FfrmFoo := TfrmFoo.Create(FfrmParentFoo);

end;

procedure TestTfrmFoo.TearDown;
begin
    FfrmFoo.Free;
    FfrmFoo := nil;
end;

...
</code>```

After that, the Create method of the TfrmFoo class is called and the following error occurs: 'Cannot create form. No MDI forms are currently active'.

I already tried to override the Create of my child class TfrmFoo setting the FormStyle property to 'fsNormal' instead 'fsMDIChild' and nothing. I also found some ideas about using a sleep(500) but the problem continues.

Edited:
After the Remy Lebeau contribution, I changed the SetUp test to create the parent form before calling the child, and using it as a parameter to the Create child. Same error message. Did I change something wrong?

Any other tips? tks!

答:
After a few tries, I removed only the child Create method

FfrmFoo := TfrmFoo.Create(FfrmParentFoo); and worked like a charm :D.

The problem was because I was trying to create a new child instance even after create a parent new one. The final code became like following:

```<code>...

implementation

procedure TestTfrmFoo.SetUp;
begin

  FfrmParentFoo := TfrmParentFoo.Create(nil);

end;

procedure TestTfrmFoo.TearDown;
begin
  FfrmFoo.Free;
  FfrmFoo := nil;
end;

...
</code>```

Thanks Remy Lebeau for the insight.

Body:
I'm starting with DUnit tests so sorry in advance for any newbie mistakes. When I tried to run simple tests and the compiler runs the SetUp of my test class, it stops returning the message 'Cannot create form. No MDI forms are currently active'.

After some research, I found some explanations but none related to my problem.

The problem appears to be when I call the Create method of my child origin class - by origin I mean the class where I have all the procedures and functions to be tested, lets call it by TfrmFoo. And my test class should be the TestTfrmFoo. The TFrmFoo has a parent with some basic codes, the TfrmParentFoo.

I'm calling the Create method like this:

...

implementation

procedure TestTfrmFoo.SetUp;
begin

    FfrmParentFoo := TfrmParentFoo.Create(nil);

    FfrmFoo := TfrmFoo.Create(FfrmParentFoo);

end;

procedure TestTfrmFoo.TearDown;
begin
    FfrmFoo.Free;
    FfrmFoo := nil;
end;

...

After that, the Create method of the TfrmFoo class is called and the following error occurs: 'Cannot create form. No MDI forms are currently active'.

I already tried to override the Create of my child class TfrmFoo setting the FormStyle property to 'fsNormal' instead 'fsMDIChild' and nothing. I also found some ideas about using a sleep(500) but the problem continues.

Edited:
After the Remy Lebeau contribution, I changed the SetUp test to create the parent form before calling the child, and using it as a parameter to the Create child. Same error message. Did I change something wrong?

Any other tips? tks!

Body:
After a few tries, I removed only the child Create method

FfrmFoo := TfrmFoo.Create(FfrmParentFoo); and worked like a charm :D.

The problem was because I was trying to create a new child instance even after create a parent new one. The final code became like following:

...

implementation

procedure TestTfrmFoo.SetUp;
begin

  FfrmParentFoo := TfrmParentFoo.Create(nil);

end;

procedure TestTfrmFoo.TearDown;
begin
  FfrmFoo.Free;
  FfrmFoo := nil;
end;

...

Thanks Remy Lebeau for the insight.


问:
uDeploy secure component property remains encrypted in shell script
I'm trying to configure a uDeploy property in a script. Have a "pass" variable, which I'm trying to either write to a file or use in a script.

Have tried the following:

echo ${p:pass} >> /tmp/variable.txt
echo "${p:pass}" >> /tmp/variable.txt
echo '${p:pass}' >> /tmp/variable.txt

which all give **** in '/tmp/variable.txt.
Same thing happens in the command.

答: This is happening since you have configured pass as Secure , use a non secure variable for this


问:
Can VBA attempt to assign to a cell a formula that is too long?
I am on Windows, if that matters. This code seems to attempt to assign a formula that is too long:

```<code>ActiveSheet.ListObjects("SegmentValues_1").ListColumns("Change").DataBodyRange.Formula = "=IFERROR(IF(INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([@Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0))=0,""Last total was ZERO"",([@CODE_ZONE]-INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([@Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0)))/INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([@Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0)))),""Did not exist previously"")"
</code>```

Is such a thing possible? If so, how to solve it?

Body:
I am on Windows, if that matters. This code seems to attempt to assign a formula that is too long:

ActiveSheet.ListObjects("SegmentValues_1").ListColumns("Change").DataBodyRange.Formula = "=IFERROR(IF(INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([@Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0))=0,""Last total was ZERO"",([@CODE_ZONE]-INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([@Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0)))/INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([@Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0)))),""Did not exist previously"")"

Is such a thing possible? If so, how to solve it?

Body:
The long formulas work in Excel VBA quite well. Take a look at this 24 nested IF():

Sub TestMe()

    Range("A1").Formula = "=IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
            "IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
            "IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
            "IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
            "IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
            "IF(1=1,2))))))))))))))))))))))))))))))))))))))))))))))"

End Sub

It is translated really well into Excel. Thus, take a good look at your formula, the problem should be there.


问:
Overload operator<< for a vector struct of pointer?
I am currently trying to make a overload operator<<  to my  vector of structs, such that I will print the content of the vector in a matrix format..

this is what I've tried so far

```<code>// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

struct element
{
    std::vector<int> keys;
    std::string item;

    element(std::vector <int> key, std::string item)
    {
        keys = key;
        this->item = item;
    }

};

inline std::stream operator << (std::ostream &stream, const std::vector<element*> _element)
{
    for (auto elements: _element)
    {
        for(auto item : elements)
        {
            std::stream << item.key << " "
        }
    }

}

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    std::vector<element> storage;
    std::vector<int> test(10);
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    std::string name = "test";
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));

    std::vector<element*> copy_of_storage;
    for(auto elements: storage)
    {
        copy_of_storage.push_back(&(elements));
    }

    std::cout << copy_of_storage << std::endl;

}
</code>```

but for some reason it is not working, and can't seem to understand what is going wrong?

https://wandbox.org/permlink/BQpqmz0HwoXgyS7t

答:
There are quite a few things you can do to fix your code example - better naming conventions would be an important start.

The reason your code doesn't work is because of your operator << function. The following will work:

```<code>std::ostream& operator << (std::ostream &stream, std::vector<element*> _elements)
{
    for (auto element : _elements)
    {
        for(auto item : element->keys)
        {
            stream << item << " ";
        }
    }
    return stream;
}
</code>```

Your working example: https://wandbox.org/permlink/FVXbLlXEAJpVbfAx

Furthermore:

Refactor your code - better variable names.

Try to use the member initialisation list in the element constructor.
And might be worth changing the ctor params to const &.

operator << should return a std::ostream&.

remove the inline keyword

in the operators << param list, you can remove the const from the std::vector<element*> since it is a copy of a vector that contains non-const pointers.

Body:
I am currently trying to make a overload operator<<  to my  vector of structs, such that I will print the content of the vector in a matrix format..

this is what I've tried so far

// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

struct element
{
    std::vector<int> keys;
    std::string item;

    element(std::vector <int> key, std::string item)
    {
        keys = key;
        this->item = item;
    }

};

inline std::stream operator << (std::ostream &stream, const std::vector<element*> _element)
{
    for (auto elements: _element)
    {
        for(auto item : elements)
        {
            std::stream << item.key << " "
        }
    }

}

int main()
{
    std::cout << "Hello, Wandbox!" << std::endl;
    std::vector<element> storage;
    std::vector<int> test(10);
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    std::string name = "test";
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));
    std::generate(test.begin(), test.end(), []() {
    return rand() % 100;
});
    storage.push_back(element(test,name));

    std::vector<element*> copy_of_storage;
    for(auto elements: storage)
    {
        copy_of_storage.push_back(&(elements));
    }

    std::cout << copy_of_storage << std::endl;

}

but for some reason it is not working, and can't seem to understand what is going wrong?

https://wandbox.org/permlink/BQpqmz0HwoXgyS7t

Body:
There are quite a few things you can do to fix your code example - better naming conventions would be an important start.

The reason your code doesn't work is because of your operator << function. The following will work:

std::ostream& operator << (std::ostream &stream, std::vector<element*> _elements)
{
    for (auto element : _elements)
    {
        for(auto item : element->keys)
        {
            stream << item << " ";
        }
    }
    return stream;
}

Your working example: https://wandbox.org/permlink/FVXbLlXEAJpVbfAx

Furthermore:

Refactor your code - better variable names.

Try to use the member initialisation list in the element constructor.
And might be worth changing the ctor params to const &.

operator << should return a std::ostream&.

remove the inline keyword

in the operators << param list, you can remove the const from the std::vector<element*> since it is a copy of a vector that contains non-const pointers.


问:
Error with reformatting the way data has been passed into a function
I have the following code :

```<code>var games = ["game_1", "game_2","game_3"]

var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]

var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]

//change format as shown below:

reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]

 incomingData.map(incomingData=>{

       games.map((game,i)=>{
               players[i].game= incomingData.game

     })
    })

console.log(players) //[ { name: 'steve', game: undefined },  { name: sparrow', game: undefined },  { name: 'captain', game: undefined } ]
</code>```

I am trying to learn about how to handle objects. I am getting undefined for the list of game inside the object. I understand this approach is wrong and would like to get some suggestions regarding how to go about changing the format to the required format.

答:
This is what you need:

```<code> incomingData.map(data=>{
     games.map((game,i)=>{
         players[i].game=incomingData[i][games[i]]
     })
 })
</code>```

You can play with it on jsfiddle.

So how does it work? Inside innermost function you already see all necessary data. All you need is to properly assing game attribute of i-th player. So you need to take i-th object from incomingData and then read attribute that is i-th element of games. So for instance for 0 element you want incomingData[0].game_1 that is equivalent to incomingData[0]["game_1"] and since "game_1" is dynamic you replace it with games[i] which leads to final incomingData[i][games[i]].
Note also that you have used formal parameter name of outer map with the same name as variable in scop effectively hiding it.  You could access that hidden variable but simpler and cleaner is to give different name, hence renamed to data.

Surely it can be simplified as other users shown, my goal here was to simply fix assignment leading to undefined. Enough for learning fundamentals, for optimal code however see one loop receipt.

Body:
I have the following code :

var games = ["game_1", "game_2","game_3"]

var players= [{name:"steve"},{name:"sparrow"},{name:"captain"}]

var incomingData= [{game_1:"basketball"},{game_2:"badminton"},{game_3:"pingpong"}]

//change format as shown below:

reformat=[ {name:"steve",game:"basketball"},{name:"steve",game:"badminton"},{name:"steve",game:"pingpong"}]

 incomingData.map(incomingData=>{

       games.map((game,i)=>{
               players[i].game= incomingData.game

     })
    })

console.log(players) //[ { name: 'steve', game: undefined },  { name: sparrow', game: undefined },  { name: 'captain', game: undefined } ]

I am trying to learn about how to handle objects. I am getting undefined for the list of game inside the object. I understand this approach is wrong and would like to get some suggestions regarding how to go about changing the format to the required format.

Body:
This is what you need:

 incomingData.map(data=>{
     games.map((game,i)=>{
         players[i].game=incomingData[i][games[i]]
     })
 })

You can play with it on jsfiddle.

So how does it work? Inside innermost function you already see all necessary data. All you need is to properly assing game attribute of i-th player. So you need to take i-th object from incomingData and then read attribute that is i-th element of games. So for instance for 0 element you want incomingData[0].game_1 that is equivalent to incomingData[0]["game_1"] and since "game_1" is dynamic you replace it with games[i] which leads to final incomingData[i][games[i]].
Note also that you have used formal parameter name of outer map with the same name as variable in scop effectively hiding it.  You could access that hidden variable but simpler and cleaner is to give different name, hence renamed to data.

Surely it can be simplified as other users shown, my goal here was to simply fix assignment leading to undefined. Enough for learning fundamentals, for optimal code however see one loop receipt.


问:
How do I open the "front camera" on the Android platform?
More generally, if a device has more than one embedded camera,
is there a way to initialize one of them in particular?

I didn't find it in Android reference documentation:

https://developer.android.com/reference/android/hardware/Camera.html

https://developer.android.com/reference/android/hardware/camera2/package-summary.html

https://developer.android.com/reference/android/hardware/camera2/CameraManager.html

Samsung SHW-M100S has two cameras. If there is no reference to use two cameras, any idea how Samsung did...?

答:
```<code>private Camera openFrontFacingCameraGingerbread() {
    int cameraCount = 0;
    Camera cam = null;
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    cameraCount = Camera.getNumberOfCameras();
    for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
        Camera.getCameraInfo(camIdx, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                cam = Camera.open(camIdx);
            } catch (RuntimeException e) {
                Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;
}
</code>```

Add the following permissions in the AndroidManifest.xml file:

```<code><uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
</code>```

Note: This feature is available in Gingerbread(2.3) and Up Android Version.

Body:
private Camera openFrontFacingCameraGingerbread() {
    int cameraCount = 0;
    Camera cam = null;
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    cameraCount = Camera.getNumberOfCameras();
    for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
        Camera.getCameraInfo(camIdx, cameraInfo);
        if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            try {
                cam = Camera.open(camIdx);
            } catch (RuntimeException e) {
                Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
            }
        }
    }

    return cam;
}

Add the following permissions in the AndroidManifest.xml file:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />

Note: This feature is available in Gingerbread(2.3) and Up Android Version.


问:
Delete keys using regex in memcache
Can i delete multiple keys in one go having similar key name in memcache using regex?

e.g. keys are:

```<code>key1
key2
key3

command [key.]
</code>```

What "command" to use which should delete all of key1, key2, and key3?

答:
Memcached does not have an option to delete keys with regex. You can delete cached data per key, or flush the whole cache.

If you have similar keys, you might look at official wiki for Memcached namspacing.

e.g. instead of having your keys in Memcached saved in like this:

```<code>key1
key2
key3
</code>```

you could organize keys in namespaces, they would now look like this:

```<code>key:<namespace_value>:1
key:<namespace_value>:2
key:<namespace_value>:3
</code>```

where namespace_value is some random integer, which you would keep in Memcached as well, per cache region (with prefix "key" ) For example, if your cache data looks like this:

```<code><key>            <value>
namespace:key       1234
key:1234:1        value1
key:1234:2        value2
key:1234:3        value3
</code>```

Now before you access your key, you will fetch the namespace_value first, and append it to your key.

Fetch value for namespace:key (results in 1234)

Fetch the value for key1 within namespace; your actual lookup key would be key:<namespace_value>:1 => key:1234:1

Now to evict all keys with prefix "key" it is sufficient to increment namespace_value, and save it back in your cache. Now your namespace value would be 1235, and cache data will be:

```<code><key>            <value>
namespace:key      1235
key:1234:1        value1
key:1234:2        value2
key:1234:3        value3
</code>```

The next fetch for key1 with the new namespace value will search for key:1235:1, and will give you a miss. Therefore, you have evicted the cache for all your keys.

Title: Delete keys using regex in memcache

Body:
Can i delete multiple keys in one go having similar key name in memcache using regex?

e.g. keys are:

key1
key2
key3

command [key.]

What "command" to use which should delete all of key1, key2, and key3?

Body:
Memcached does not have an option to delete keys with regex. You can delete cached data per key, or flush the whole cache.

If you have similar keys, you might look at official wiki for Memcached namspacing.

e.g. instead of having your keys in Memcached saved in like this:

key1
key2
key3

you could organize keys in namespaces, they would now look like this:

key:<namespace_value>:1
key:<namespace_value>:2
key:<namespace_value>:3

where namespace_value is some random integer, which you would keep in Memcached as well, per cache region (with prefix "key" ) For example, if your cache data looks like this:

<key>            <value>
namespace:key       1234
key:1234:1        value1
key:1234:2        value2
key:1234:3        value3

Now before you access your key, you will fetch the namespace_value first, and append it to your key.

Fetch value for namespace:key (results in 1234)

Fetch the value for key1 within namespace; your actual lookup key would be key:<namespace_value>:1 => key:1234:1

Now to evict all keys with prefix "key" it is sufficient to increment namespace_value, and save it back in your cache. Now your namespace value would be 1235, and cache data will be:

<key>            <value>
namespace:key      1235
key:1234:1        value1
key:1234:2        value2
key:1234:3        value3

The next fetch for key1 with the new namespace value will search for key:1235:1, and will give you a miss. Therefore, you have evicted the cache for all your keys.


问:
Smarty HTML Escape doesnt work
I try to escape the variable output to escape HTML in an XML Export. I dont know what i'm doing wrong. The Export is used in xt:commerce 5 online shop.

Smarty should be v. 3.1

Template:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<orders>
    {assign var=foo value='<b>baaa& ü ä ß ö <> aaa</b>'}{$foo|escape:'htmlall'}
</orders>
</code>```

Output

```<code><?xml version="1.0" encoding="UTF-8" ?>
<orders>
    <b>baaa& ü ä ß ö <> aaa</b>
</orders>
</code>```

答:
Escaping html makes sure your browser does not use the content as html, for example if you remove the escape then the text will be bold.
To actually remove the tags from the string, you must use strip_tags (https://www.smarty.net/docs/en/language.modifier.strip.tags.tpl):

```<code><?xml version="1.0" encoding="UTF-8" ?>
<orders>
    {assign var=foo value='<b>baaa& ü ä ß ö <> aaa</b>'}{$foo|strip_tags:}
</orders>
</code>```

Output:

```<code><xml version="1.0" encoding="UTF-8" ?="">
<orders>
     baaa& ü ä ß ö   aaa
</orders>
</code>```

Title: Smarty HTML Escape doesnt work

Body:
I try to escape the variable output to escape HTML in an XML Export. I dont know what i'm doing wrong. The Export is used in xt:commerce 5 online shop.

Smarty should be v. 3.1

Template:

<?xml version="1.0" encoding="UTF-8" ?>
<orders>
    {assign var=foo value='baaa& ü ä ß ö <> aaa'}{$foo|escape:'htmlall'}
</orders>

Output

<?xml version="1.0" encoding="UTF-8" ?>
<orders>
    baaa& ü ä ß ö <> aaa
</orders>

Body:
Escaping html makes sure your browser does not use the content as html, for example if you remove the escape then the text will be bold.
To actually remove the tags from the string, you must use strip_tags (https://www.smarty.net/docs/en/language.modifier.strip.tags.tpl):

<?xml version="1.0" encoding="UTF-8" ?>
<orders>
    {assign var=foo value='<b>baaa& ü ä ß ö <> aaa</b>'}{$foo|strip_tags:}
</orders>

Output:

<xml version="1.0" encoding="UTF-8" ?="">
<orders>
     baaa&amp; ü ä ß ö   aaa
</orders>


问:
How to initialize a static variable in a multithreaded context?
I thought up a good use of the static keyword inside a function to be something like this:

```<code>void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}
</code>```

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).

答:
Won't work because the initializer of a static variable must be a constant in C. A function call is not a constant. This is different from C++, where you can make a static perform work before main is entered. For example, this won't compile:

```<code>int deepthought()
{
    return 42;
}

void ask()
{
    static int answer = deepthought();
}
</code>```

The simplest option is to make your locks global and initialize them before going into MT mode. A better option is to pass them along with the data they guard.

P.S.: I advise against using a void * to get an opaque pointer. Instead, implement a platform-specific, one-element struct Lock for type-safety.

Body:
I thought up a good use of the static keyword inside a function to be something like this:

void threadSafeWrite(int *array, int writeIndex, int writeData){
    static void *threadLock = Lock_create(); //in my code locks are void* to be cross-platform compatable
    Lock_aquire(threadLock);
    array[writeIndex] = writeData;
    Lock_release(threadLock);
}

In short it seems like a good way to make a critical section. My question is though, how do I initialize the threadLock in a threadsafe manner? The problem with the example I fear is that the lock will get allocated multiple times and each thread will use a different lock. Any ideas on how to fix this? Seems like a chicken and egg problem. I want a solution (or solutions) which work with both pthreads and windows threads.

EDIT: the reason I want this functionality is because it provides a non-intrusive way to test whether there is a difference when running a piece of code single-threaded or multithreaded (meant for debug purposes).

Body:
Won't work because the initializer of a static variable must be a constant in C. A function call is not a constant. This is different from C++, where you can make a static perform work before main is entered. For example, this won't compile:

int deepthought()
{
    return 42;
}

void ask()
{
    static int answer = deepthought();
}

The simplest option is to make your locks global and initialize them before going into MT mode. A better option is to pass them along with the data they guard.

P.S.: I advise against using a void * to get an opaque pointer. Instead, implement a platform-specific, one-element struct Lock for type-safety.


问:
Microsoft Access 2016: Conditional Inner Join Multiple Cases
I hope what I'm asking for makes sense. I would like to have a query that chooses a specific type of Inner Join based on a user input.

This is what I have.

Queries:

qryFiltered (Main Query)

qryLand (sub)

qrySea (sub)

qryAllOrder (sub)

Tables:

tblLowPriority

Forms:

EnterWork (which has a option group called ogLandSea)

In my main query "qryFiltered", I have the following SQL code:

SELECT qryAllOrder.*

FROM
SWITCH
(Forms!EnterWork!ogLandSea = 1, (qryAllOrder LEFT JOIN tblLowPriority ON qryAllOrder.[WORK_ORDER_NBR] = tblLowPriority.[WO]) INNER JOIN qrySea ON qryAllOrder.WORK_ORDER_NBR = qrySea.WORK_ORDER_NBR,

Forms!EnterWork!ogLandSea = 2, (qryAllOrder LEFT JOIN tblLowPriority ON qryAllOrder.[WORK_ORDER_NBR] = tblLowPriority.[WO]) INNER JOIN qryLand ON qryAllOrder.WORK_ORDER_NBR = qryLand.WORK_ORDER_NBR)

WHERE tblLowPriority.WO Is Null```

Basically, what I'm looking for is to choose the join based on what the user selects on the form. The inner join would choose either qrySea or qryLand based on this input. The error I'm getting is: "Syntax error in FROM clause."

What am I doing wrong here? It's the Switch function that's not working. I tried the two Land and Sea options separately without the Switch function and it works. I just can't seem to figure out a way to have the Inner Join change based on user input.

Appreciate all your responses!

答:
I was able to get this to work by doing a Left Join from the main query to the two subqueries. And then I put a Switch criteria in the WHERE Clause:

WHERE (Switch([Forms]![EnterWork]![ogLandSea]=1,[qrySea]![WORK_ORDER_NBR] Is Not Null Or [qrySea]![WORK_ORDER_NBR] Is Null Or [qryLand]![WORK_ORDER_NBR] Is Not Null,[Forms]![EnterWork]![ogLandSea]=2,[qrySea]![WORK_ORDER_NBR] Is Not Null,[Forms]![EnterWork]![ogLandSea]=3,[qryLand]![WORK_ORDER_NBR] Is Not Null,[Forms]![EnterWork]![ogFN]=4,[qrySea]![WORK_ORDER_NBR] Is Null And [qryLand]![WORK_ORDER_NBR] Is Null))<>False)```

Basically, this is what it does:

Option 1: Display all records from the Main Query

Option 2: Display only records that are in qrySea

Option 3: Display only records that are in qryLand

Option 4: Display only records that are NOT in qrySea nor qryLand

Body:
I hope what I'm asking for makes sense. I would like to have a query that chooses a specific type of Inner Join based on a user input.

This is what I have.

Queries:

qryFiltered (Main Query)

qryLand (sub)

qrySea (sub)

qryAllOrder (sub)

Tables:

tblLowPriority

Forms:

EnterWork (which has a option group called ogLandSea)

In my main query "qryFiltered", I have the following SQL code:

SELECT qryAllOrder.*

FROM
SWITCH
(Forms!EnterWork!ogLandSea = 1, (qryAllOrder LEFT JOIN tblLowPriority ON qryAllOrder.[WORK_ORDER_NBR] = tblLowPriority.[WO]) INNER JOIN qrySea ON qryAllOrder.WORK_ORDER_NBR = qrySea.WORK_ORDER_NBR,

Forms!EnterWork!ogLandSea = 2, (qryAllOrder LEFT JOIN tblLowPriority ON qryAllOrder.[WORK_ORDER_NBR] = tblLowPriority.[WO]) INNER JOIN qryLand ON qryAllOrder.WORK_ORDER_NBR = qryLand.WORK_ORDER_NBR)

WHERE tblLowPriority.WO Is Null

Basically, what I'm looking for is to choose the join based on what the user selects on the form. The inner join would choose either qrySea or qryLand based on this input. The error I'm getting is: "Syntax error in FROM clause."

What am I doing wrong here? It's the Switch function that's not working. I tried the two Land and Sea options separately without the Switch function and it works. I just can't seem to figure out a way to have the Inner Join change based on user input.

Appreciate all your responses!

Body:
I was able to get this to work by doing a Left Join from the main query to the two subqueries. And then I put a Switch criteria in the WHERE Clause:

WHERE (Switch([Forms]![EnterWork]![ogLandSea]=1,[qrySea]![WORK_ORDER_NBR] Is Not Null Or [qrySea]![WORK_ORDER_NBR] Is Null Or [qryLand]![WORK_ORDER_NBR] Is Not Null,[Forms]![EnterWork]![ogLandSea]=2,[qrySea]![WORK_ORDER_NBR] Is Not Null,[Forms]![EnterWork]![ogLandSea]=3,[qryLand]![WORK_ORDER_NBR] Is Not Null,[Forms]![EnterWork]![ogFN]=4,[qrySea]![WORK_ORDER_NBR] Is Null And [qryLand]![WORK_ORDER_NBR] Is Null))<>False)

Basically, this is what it does:

Option 1: Display all records from the Main Query

Option 2: Display only records that are in qrySea

Option 3: Display only records that are in qryLand

Option 4: Display only records that are NOT in qrySea nor qryLand


问:
Access Class properties inside callback
I'm using this plugin: https://github.com/blinkmobile/cordova-plugin-sketch with Ionic 3.

My last important step is to get the result outside the callback functions to work further with it.

This is my Code:

```<code>anhangArray: Array<{ name: string, value: string }>=[];

  takePhoto() {
  const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.FILE_URI,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true,
  allowEdit: false,
}

this.camera.getPicture(options).then((imageData) => {

  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData);

}, (err) => {
  // Handle error
});
}

getSketch(src: string) {
window.navigator.sketch.getSketch(this.onSuccess, this.onFail, {
  destinationType: window.navigator.sketch.DestinationType.DATA_URL,
  encodingType: window.navigator.sketch.EncodingType.JPEG,
  inputType: window.navigator.sketch.InputType.FILE_URI,
  inputData: src
});
}

onSuccess(imageData) {
var _mythis = this;
if (imageData == null) { return; }

// do your thing here!
setTimeout(function () {
  if (imageData.indexOf("data:image") >= 0) {
  } else {
    imageData = "data:image/jpeg;base64," + imageData;
  }
  _mythis.anhangArray.push({ name: "anhang_" + parseInt(_mythis.user._kunnr), value: imageData });
  console.log(this.anhang);

}, 0);
}
</code>```

Error: Uncaught TypeError: Cannot read property 'anhangArray' of undefined

答:
you can solve in this way too:

this.camera.getPicture(options).then((imageData) => {

  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData).bind(this);```

where .bind(this) pass the scope to your caller one.

Title: Access Class properties inside callback

Body:
I'm using this plugin: https://github.com/blinkmobile/cordova-plugin-sketch with Ionic 3.

My last important step is to get the result outside the callback functions to work further with it.

This is my Code:

anhangArray: Array<{ name: string, value: string }>=[];

  takePhoto() {
  const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.FILE_URI,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true,
  allowEdit: false,
}

this.camera.getPicture(options).then((imageData) => {

  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData);

}, (err) => {
  // Handle error
});
}

getSketch(src: string) {
window.navigator.sketch.getSketch(this.onSuccess, this.onFail, {
  destinationType: window.navigator.sketch.DestinationType.DATA_URL,
  encodingType: window.navigator.sketch.EncodingType.JPEG,
  inputType: window.navigator.sketch.InputType.FILE_URI,
  inputData: src
});
}

onSuccess(imageData) {
var _mythis = this;
if (imageData == null) { return; }

// do your thing here!
setTimeout(function () {
  if (imageData.indexOf("data:image") >= 0) {
  } else {
    imageData = "data:image/jpeg;base64," + imageData;
  }
  _mythis.anhangArray.push({ name: "anhang_" + parseInt(_mythis.user._kunnr), value: imageData });
  console.log(this.anhang);

}, 0);
}

Error: Uncaught TypeError: Cannot read property 'anhangArray' of undefined

Body:
you can solve in this way too:

this.camera.getPicture(options).then((imageData) => {

  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData).bind(this);

where .bind(this) pass the scope to your caller one.


问:
Adding content/text in rectangle WPF
This is my code for rectangle :

```<code> <Rectangle x:Name="rect1" Grid.Column="1"  Fill="#FF5C626C" HorizontalAlignment="Left" Height="50" Margin="36,171,0,0" StrokeThickness="2" VerticalAlignment="Top" Width="358" RadiusX="30" RadiusY="50">
        <Rectangle.Triggers>
        </Rectangle.Triggers>
        <Rectangle.Style>

            <Style TargetType="Rectangle">
                <Style.Triggers>

                    <EventTrigger RoutedEvent="Rectangle.MouseEnter">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF767C84" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="Rectangle.MouseLeave">
                        <BeginStoryboard>
                            <Storyboard>
                                <ParallelTimeline  >
                                    <ColorAnimation Storyboard.TargetProperty="Fill.Color" To="#FF5C626C" />
                                </ParallelTimeline>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
    </Rectangle>
</code>```

My question is how do i add a text/content in the rectangle ?

One might suggest using a code block, but if u go through my code, youu'll notice that the rectangle changes it's color on mouseover.So if i put a textblock over the rectangle,the mouseover doesn't work properly(as the textblock covers the entire rectangle).

Another suggestion would be to use a border.But i am not sure about this as i need to find the code to apply mouse over effect on a border.

The next suggestion might be to use a button instead.I would've but my rectangle has corner radius and is a bit round-shaped which, if i use a button, would be hard to achieve.

So how do i add content/text inside the rectangle?

答:
If you feel you definitely have to use a rectangle, put it in a grid and add a TextBlock element above it.

By setting the TextBlock's IsHitTestVisible property to False all hit-testing (mouse events) will be ignored on it and fall through to your rectangle.

```<code><Grid>
    <Rectangle (...your attributes here...)>
        (...your rectangle code here...)
    </Rectangle>
    <TextBlock Text="Hello World!" IsHitTestVisible="False" />
</Grid>
</code>```

Title: Adding content/text in rectangle WPF

Body:
This is my code for rectangle :

 <Rectangle x:Name="rect1" Grid.Column="1"  Fill="#FF5C626C" HorizontalAlignment="Left" Height="50" Margin="36,171,0,0" StrokeThickness="2" VerticalAlignment="Top" Width="358" RadiusX="30" RadiusY="50">
        <Rectangle.Triggers>
        </Rectangle.Triggers>
        <Rectangle.Style>

            </Style>
        </Rectangle.Style>
    </Rectangle>

My question is how do i add a text/content in the rectangle ?

One might suggest using a code block, but if u go through my code, youu'll notice that the rectangle changes it's color on mouseover.So if i put a textblock over the rectangle,the mouseover doesn't work properly(as the textblock covers the entire rectangle).

Another suggestion would be to use a border.But i am not sure about this as i need to find the code to apply mouse over effect on a border.

The next suggestion might be to use a button instead.I would've but my rectangle has corner radius and is a bit round-shaped which, if i use a button, would be hard to achieve.

So how do i add content/text inside the rectangle?

Body:
If you feel you definitely have to use a rectangle, put it in a grid and add a TextBlock element above it.

By setting the TextBlock's IsHitTestVisible property to False all hit-testing (mouse events) will be ignored on it and fall through to your rectangle.

<Grid>
    <Rectangle (...your attributes here...)>
        (...your rectangle code here...)
    </Rectangle>
    <TextBlock Text="Hello World!" IsHitTestVisible="False" />
</Grid>