Monday, April 30, 2018

Google Charts Legend Position Top Not Working

Leave a Comment

You can use this jsfiddle for testing

Full Code:

google.load('visualization', '1.1', {     'packages': ['bar'] }); google.setOnLoadCallback(drawStuff);  function drawStuff() {     var data = new google.visualization.DataTable();     data.addColumn('string', 'Topping');     data.addColumn('number', 'Nescafe Instant');     data.addColumn('number', 'Folgers Instant');     data.addColumn('number', 'Nescafe Beans');     data.addColumn('number', 'Folgers Beans');     data.addRows([         ['2001', 500, 1200, 816, 200],         ['2002', 163, 231, 539, 594],         ['2003', 125, 819, 200, 578],         ['2004', 197, 536, 613, 500]     ]);      // Set chart options     var options = {         isStacked: true,         width: 800,         height: 600,         legend: {             position: "top",             alignment: "",             textStyle: {                     color: "#999"                 }             },         chart: {             title: 'Year-by-year coffee consumption',             subtitle: 'This data is not real'         },          series: {             2: {                 targetAxisIndex: 1             },             3: {                 targetAxisIndex: 1             }         }     };  }; 

Question :

I want to display legend above of the chart. I have used legend position : top. But it is not working. I can move legend either left side or right side without a problem changing legend position value.

But I can't move legend top or bottom. Why is that? What was the my mistake?

1 Answers

Answers 1

First, you need to use the correct library, as jsapi is out of date and should no longer be used,
according to the release notes.

The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.

This will only change the load statement:

old load statement...

google.load('visualization', '1.1', {   packages: ['bar'] }); 

new load statement...

google.charts.load('current', {   packages: ['corechart'] }); 

Next, as seen above, for classic charts, use --> packages: ['corechart']
instead of 'bar'

Google has provided a chart option, to style classic charts similar to material:

theme: 'material' 

When creating a classic chart, use the following namespace:

google.visualization.ColumnChart 

vs. material

google.charts.Bar 

See the following working snippet:

google.charts.load('current', {    packages: ['corechart']  }).then(function () {    var data = new google.visualization.DataTable();    data.addColumn('string', 'Topping');    data.addColumn('number', 'Nescafe Instant');    data.addColumn('number', 'Folgers Instant');    data.addColumn('number', 'Nescafe Beans');    data.addColumn('number', 'Folgers Beans');    data.addRows([      ['2001', 500, 1200, 816, 200],      ['2002', 163, 231, 539, 594],      ['2003', 125, 819, 200, 578],      ['2004', 197, 536, 613, 500]    ]);      var options = {      chartArea: {        height: '100%',        width: '100%',        top: 64,        left: 64,        right: 32,        bottom: 32      },      height: '100%',      width: '100%',      isStacked: true,      legend: {        position: 'top',        textStyle: {          color: '#999'        }      },      title: 'Year-by-year coffee consumption'    };      var container = document.getElementById('chart_div');    var chart = new google.visualization.ColumnChart(container);      drawChart();    window.addEventListener('resize', drawChart, false);    function drawChart() {      chart.draw(data, options);    }  });
html, body {    height: 100%;    margin: 0px 0px 0px 0px;    overflow: hidden;    padding: 0px 0px 0px 0px;  }    .chart {    height: 100%;  }
<script src="https://www.gstatic.com/charts/loader.js"></script>  <div class="chart" id="chart_div"></div>

Note: the only advantage to material is having multiple stacks,
in classic, you cannot group multiple stacks.


UPDATE

There are no options you can change to position the legend to top or bottom, it is simply not supported.

The only solution would be to manually build a custom legend; following is an example of how this could be done:

google.charts.load('current', {    packages: ['bar']  }).then(function () {    var data = new google.visualization.DataTable();    data.addColumn('string', 'Topping');    data.addColumn('number', 'Nescafe Instant');    data.addColumn('number', 'Folgers Instant');    data.addColumn('number', 'Nescafe Beans');    data.addColumn('number', 'Folgers Beans');    data.addRows([      ['2001', 500, 1200, 816, 200],      ['2002', 163, 231, 539, 594],      ['2003', 125, 819, 200, 578],      ['2004', 197, 536, 613, 500]    ]);      var options = {      chart: {        title: 'coffee consumption',        subtitle: 'This data is not real'      },      height: '100%',      isStacked: true,      legend: {        position: 'none'      },      series: {        2: {          targetAxisIndex: 1        },        3: {          targetAxisIndex: 1        }      },      width: '100%'    };      var container = document.getElementById('chart_div');    var chart = new google.charts.Bar(container);      drawChart();    window.addEventListener('resize', drawChart, false);    function drawChart() {      chart.draw(data, google.charts.Bar.convertOptions(options));    }      // add legend marker    function addLegendMarker(markerProps) {      var legendMarker = document.getElementById('template-legend-marker').innerHTML;      for (var handle in markerProps) {        if (markerProps.hasOwnProperty(handle)) {          legendMarker = legendMarker.replace('{{' + handle + '}}', markerProps[handle]);        }      }      document.getElementById('legend_div').insertAdjacentHTML('beforeEnd', legendMarker);    }      // chart ready event    google.visualization.events.addListener(chart, 'ready', function () {      var legend = document.getElementById('legend_div');        // get colors from chart      var colorPallette = [];      var colorsBottom = [];      var colorsTop = [];      var stacks = container.getElementsByTagName('*');      Array.prototype.forEach.call(stacks, function(stack) {        switch (stack.tagName) {          case 'path':            if ((stack.getAttribute('fill') !== null) && (stack.getAttribute('fill') !== '#ffffff')) {              if (colorsTop.indexOf(stack.getAttribute('fill')) === -1) {                colorsTop.push(stack.getAttribute('fill'));              }            }            break;            case 'rect':            if ((stack.getAttribute('fill') !== null) && (stack.getAttribute('fill') !== '#ffffff')) {              if (colorsBottom.indexOf(stack.getAttribute('fill')) === -1) {                colorsBottom.push(stack.getAttribute('fill'));              }            }            break;        }      });      for (var i = 0; i < colorsBottom.length; i++) {        colorPallette.push(colorsBottom[i]);        colorPallette.push(colorsTop[i]);      }        // clear previous legend      legend.innerHTML = '';        // add legend marker for each Y axis column - skip X axis --> i = 1      for (var i = 1; i < data.getNumberOfColumns(); i++) {        var markerProps = {};        markerProps.index = i;        markerProps.color = colorPallette[i - 1];        markerProps.label = data.getColumnLabel(i);        addLegendMarker(markerProps);      }        // add "hover" event to each legend marker      var currentSelection;      var markers = legend.getElementsByTagName('DIV');      Array.prototype.forEach.call(markers, function(marker) {        marker.addEventListener('mouseover', function (e) {          currentSelection = chart.getSelection();          var marker = e.target || e.srcElement;          if (marker.tagName.toUpperCase() !== 'DIV') {            marker = marker.parentNode;          }          var columnIndex = parseInt(marker.getAttribute('data-columnIndex'));          chart.setSelection([{column: columnIndex}]);        }, false);        marker.addEventListener('mouseout', function (e) {          chart.setSelection([]);        }, false);      });    });  });
html, body {    height: 100%;    margin: 0px 0px 0px 0px;    overflow: hidden;    padding: 0px 0px 0px 0px;  }    .chart {    height: 100%;  }    #legend_div {    color: #999;    font-family: Roboto;    position: absolute;    right: 0px;    text-align: right;    top: 0px;    width: 60%;    z-index: 1000;  }    .legend-marker {    display: inline-block;    padding: 6px 6px 6px 6px;  }    .legend-marker-color {    border-radius: 25%;    display: inline-block;    height: 12px;    width: 12px;  }
<script src="https://www.gstatic.com/charts/loader.js"></script>  <div id="legend_div"></div>  <div class="chart" id="chart_div"></div>    <!-- template for building marker -->  <script id="template-legend-marker" type="text/html">    <div class="legend-marker" data-columnIndex="{{index}}">      <div class="legend-marker-color" style="background-color: {{color}}"></div>      <span>{{label}}</span>    </div>  </script>

Read More

PHP soap issues

Leave a Comment

Drupal 7-soap

This is the error which iam getting in error log and when iam trying to print the test.wsdl file

SoapFault: looks like we got no XML document in SoapClient->__call() 

enter image description here

I have no clue what is the error

My project environment

PHP : 5.4.11

MySQL : 5.5.27 Apache : 2.2.3

OS : CentOS 5.8

code information

function ai_server() {   ini_set('soap.wsdl_cache_ttl', 0);   $server = new SoapServer(file_create_url(variable_get('app_integration_wsdl')), array("trace" => 1, "exceptions" => 0));   $server->addFunction('getData');   $server->addFunction('getId');   $server->addFunction('getInfo');   $server->addFunction('getrightsInfo');   $server->addFunction('updateInfo');   $server->addFunction('resetAppHistory');   //$server->addFunction('resetAppId');    $server->handle(); } 

soap client

function ai_sync_test() {   ini_set('soap.wsdl_cache_ttl', 0); // // ---------------------------------------------------------------- basic tests //    // is settings file accessible   $settings_file = variable_get('app_integration_settings');   require_once($settings_file);   $settings_output = is_readable($settings_file) ? 'Ok! Settings file is readable.' : 'Error! Not readable or accessible.';    // is wsdl file accessible   $wsdl_file = variable_get('app_integration_wsdl');   $wsdl_output = is_readable($wsdl_file) ? 'Ok! WSDL file is readable. ' . l('Open it. ', $wsdl_file, array('attributes' => array('target' => '_blank'))) : 'Error! Not readable or accessible. ';   $wsdl_output .= 'You need to define domain name in it into this sections (at the bottom of app_integration.wsdl file): ';   $wsdl_output .= htmlentities('<soap:address location="http://YOUR_DOMAIN_HERE/app_integration/server"/>');    // methods, which integration service is provide   $client = new SoapClient($wsdl_file, array("trace" => 1, "exceptions" => 0));    $methods = $client->__getFunctions();   $methods_output = '';   foreach ($methods as $method) {     $methods_output .= '<li>' . $method . '</li>';   } 

1 Answers

Answers 1

2 possible reasons -

  1. You are echoing something in the code, or whitespace characters are getting printed or trailing new line character.

  2. The server SOAP file in php has encode utf8 with BOM, causing apache send back the BOM mark (3 bytes) before the xml response. Encode your php file soap server with utf8 WITH OUT BOM mark.

function strip_bom($str){     return preg_replace( '/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/', "", $str ); } 
Read More

Facebook Graph API v2.0 deprecation

Leave a Comment

I've received this e-mail from facebook:

Souts Pay has been making recent API calls to Graph API v2.0, which will reach the end of the 2-year deprecation window on Monday, August 8, 2016. Please migrate all calls to v2.1 or higher in order to avoid potential broken experiences.

We recommend using our new Graph API Upgrade Tool to see which of your calls are affected by this change as well as any replacement calls in newer versions. You can also use our changelog to see the full list of changes.

But when I click at Graph API Upgrade Tool I got this message:

Your app hasn't made enough calls to the Graph API to show any info, or there are no changes for the methods you selected between v2.5 and v2.6

So should I worry about this facebook issue? If yes, how can I make this upgrade?

1 Answers

Answers 1

The Facebook API is aways changing, then if you received this message, you just need to use the API version in your URL:

Eg: https://graph.facebook.com/v2.12/me

If you don't specify the version

https://graph.facebook.com/me

It aways will use the oldest version possible, actually is v2.6

Some APIs can be deprecated, but login function is working fine, stay tunned about recent changeshere: https://developers.facebook.com/blog/

Read More

Swift parse JSON to Model Object

Leave a Comment

I had this method here and it returned my data exactly as I needed it:

func getTestData() -> [Any]?     {         return [GradingData(lot: "lot", andColumns: "andColumns", SLAIssuedFinalGrading: true, SLAIssuedFinalGradingDate: "SLAIssuedFinalGradingDate", CityApprovalIssued: true, CityCommentReceived: false, GradingRepair: "GradingRepair", CurbStopRepair: "CurbStopRepair", SplashPadDownSpout: "SplashPadDownSpout", RYCBOtherRepairs: "RYCBOtherRepairs", Comments: "Comments", columnCamera: "", DepositReceived: false), GradingData(lot: "lot", andColumns: "andColumns2", SLAIssuedFinalGrading: false, SLAIssuedFinalGradingDate: "SLAIssuedFinalGradingDate", CityApprovalIssued: false, CityCommentReceived: false, GradingRepair: "GradingRepair", CurbStopRepair: "CurbStopRepair", SplashPadDownSpout: "SplashPadDownSpout", RYCBOtherRepairs: "RYCBOtherRepairs", Comments: "Comments", columnCamera: "", DepositReceived: false)]     } 

Now I am trying to do a call to an API and return the exact same structure with this:

func GetLandGradingData(_ community: String, completion: @escaping (_ result: [GradingData]) -> Void)     {          let escapedCommunity = community.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)          let urlComponents = NSURLComponents(string: webservice + "?community=" + escapedCommunity!);         urlComponents?.user = appDelegate.username;         urlComponents?.password = appDelegate.password;          let url = urlComponents?.url;          let returnedData = [GradingData]()          URLSession.shared.dataTask(with: url!, completionHandler: {             (data, response, error) in              if(error != nil){                  completion(returnedData)              }else{                  do{                      let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [GradingData]                      OperationQueue.main.addOperation({                          completion(json)                      })                  }catch let error as NSError{                      print(error)                     completion(returnedData)                  }             }          }).resume()      } 

My problem is that is method is not returning the same structure as the getTestData method, attached are screenshots on what getTestData returns and what this api method call returns.

enter image description here enter image description here

Here is my whole class:

@objcMembers class GradingData : NSObject {      /**      Define lot Column String      */     var lot: String?     /**      Define Address Column String      */     var address: String?     /**      Define SLA Issued Final Grading Column String      */     var SLAIssuedFinalGrading = false     /**      Define SLA Issued Final Grading Date Column String      */     var SLAIssuedFinalGradingDate: String?     /**      Define City Approval Issued Column String      */     var CityApprovalIssued = false     /**      Define City Comment Received Column String      */     var CityCommentReceived = false     /**      Define Grading Repair Column String      */     var GradingRepair: String?     /**      Define Curb Stop Repair Column String      */     var CurbStopRepair: String?     /**      Define Splash Pad or Down Spout Column String      */     var SplashPadDownSpout: String?     /**      Define RYCB or Other Repairs Column String      */     var RYCBOtherRepairs: String?     /**      Define Comments Column String      */     var Comments: String?     /**      Define Camera Column String      */     var columnCamera: String?     /**      Define Deposit Received Column String      */     var DepositReceived = false       /**      Inital call to class      */     init(lot: String?, andColumns address: String?, SLAIssuedFinalGrading: Bool?, SLAIssuedFinalGradingDate: String?, CityApprovalIssued: Bool?, CityCommentReceived: Bool?, GradingRepair: String?, CurbStopRepair: String?, SplashPadDownSpout: String?, RYCBOtherRepairs: String?, Comments: String?, columnCamera: String?, DepositReceived: Bool?) {          super.init()          //Set lot string          self.lot = lot          //Set Address Column string          self.address = address          //Set SLA Issued Final Grading Column string          self.SLAIssuedFinalGrading = SLAIssuedFinalGrading!          //Set SLA Issued Final Grading Date Column string          self.SLAIssuedFinalGradingDate = SLAIssuedFinalGradingDate          //Set City Approval Issued Column string          self.CityApprovalIssued = CityApprovalIssued!          //Set City Comment Received Column string          self.CityCommentReceived = CityCommentReceived!          //Set Grading Repair Column string          self.GradingRepair = GradingRepair          //Set Curb Stop Repair Column string          self.CurbStopRepair = CurbStopRepair          //Set Splash Pad or Down Spout Column string          self.SplashPadDownSpout = SplashPadDownSpout          //Set RYCB or Other Repairs Column string          self.RYCBOtherRepairs = RYCBOtherRepairs          //Set Comments Column string          self.Comments = Comments          //Set Camera Column string          self.columnCamera = columnCamera          //Set Deposit Received Column string          self.DepositReceived = DepositReceived!      } } 

Here is my Data from the API:

<Reports> <CityApprovalIssued>false</CityApprovalIssued> <CityCommentReceived>false</CityCommentReceived> <Comments></Comments> <CurbStopRepair></CurbStopRepair> <DepositReceived>false</DepositReceived> <GradingRepair></GradingRepair> <RYCBOtherRepairs></RYCBOtherRepairs> <SLAIssuedFinalGrading>false</SLAIssuedFinalGrading> <SLAIssuedFinalGradingDate/> <SplashPadDownSpout></SplashPadDownSpout> <address>123 Fake Street</address> <lot>A0001</lot> </Reports> <Reports> <CityApprovalIssued>false</CityApprovalIssued> <CityCommentReceived>false</CityCommentReceived> <Comments></Comments> <CurbStopRepair></CurbStopRepair> <DepositReceived>false</DepositReceived> <GradingRepair></GradingRepair> <RYCBOtherRepairs></RYCBOtherRepairs> <SLAIssuedFinalGrading>false</SLAIssuedFinalGrading> <SLAIssuedFinalGradingDate/> <SplashPadDownSpout></SplashPadDownSpout> <address>125 Fake Street</address> <lot>A0002</lot> </Reports> 

This is from an ASP.NET MVC API Controller: <ArrayOfReports xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/App.Models">

This is what I get when I do this:

let string = String(data: data!, encoding: .utf8)  print(string as Any)  Optional("[{\"lot\":\"A0001\",\"address\”:\”123 Fake Street\”,\”SLAIssuedFinalGrading\":false,\"SLAIssuedFinalGradingDate\":\"\",\"CityApprovalIssued\":false,\"CityCommentReceived\":false,\"GradingRepair\":\"                                                                                                                                                                                                                                                               \",\"CurbStopRepair\":\"                                                                                                                                                                                                                                                               \",\"SplashPadDownSpout\":\"                                                                                                                                                                                                                                                               \",\"RYCBOtherRepairs\":\"                                                                                                                                                                                                                                                               \",\"Comments\":\"                                                                                                                                                                                                                                                               \",\"DepositReceived\":false},{\"lot\":\"A0002\",\"address\":\"125 Fake Street\",\"SLAIssuedFinalGrading\":false,\"SLAIssuedFinalGradingDate\":\"\",\"CityApprovalIssued\":false,\"CityCommentReceived\":false,\"GradingRepair\":\"                                                                                                                                                                                                                                                               \",\"CurbStopRepair\":\"                                                                                                                                                                                                                                                               \",\"SplashPadDownSpout\":\"                                                                                                                                                                                                                                                               \",\"RYCBOtherRepairs\":\"                                                                                                                                                                                                                                                               \",\"Comments\":\"                                                                                                                                                                                                                                                               \",\"DepositReceived\":false}]") 

4 Answers

Answers 1

First of all the response data is indeed JSON, the XML output is a bit confusing.

You probably don't need a class inherited from NSObject, in most cases especially in iOS a struct is sufficient.

Except the key columnCamera all keys exist in all records, so declare all properties as non-optional without a default value and columnCamera as optional, and declare all properties as constants (let) if they are not going to change.

An explicit init method is not needed.

The CodingKeys are added to translate most of the keys to lowercase.

struct GradingData : Decodable {      private enum CodingKeys : String, CodingKey {         case lot, address, SLAIssuedFinalGrading         case SLAIssuedFinalGradingDate         case cityApprovalIssued = "CityApprovalIssued"         case cityCommentReceived = "CityCommentReceived"         case gradingRepair = "GradingRepair"         case curbStopRepair = "CurbStopRepair"         case splashPadDownSpout = "SplashPadDownSpout"         case RYCBOtherRepairs, comments = "Comments"         case columnCamera, depositReceived = "DepositReceived"     }      let lot: String     let address: String     let SLAIssuedFinalGrading : Bool     let SLAIssuedFinalGradingDate: String     let cityApprovalIssued : Bool     let cityCommentReceived : Bool     let gradingRepair : String     let curbStopRepair : String     let splashPadDownSpout : String     let RYCBOtherRepairs : String     let comments : String     let columnCamera : String?     let depositReceived : Bool  } 

Then decode the JSON

....  var returnedData = [GradingData]() URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in      if error != nil {          print(error!)          completion(returnedData)      } else {          do {             returnedData = try JSONDecoder().decode([GradingData].self, from: data!)             DispatchQueue.main.async {                 completion(returnedData)             }          } catch {              print(error)              completion(returnedData)          }      }  }).resume() 

Answers 2

Just add another init into your GradingData model class like this:

convenience init(data: [String : Any]) {  init(lot: data["lot"] as? String,  andColumns: data["address"] as? String,  SLAIssuedFinalGrading: data["SLAIssuedFinalGrading"] as? Bool,  SLAIssuedFinalGradingDate: data["SLAIssuedFinalGradingDate"] as? String,   CityApprovalIssued: data["CityApprovalIssued"] as? Bool,  CityCommentReceived: data["CityCommentReceived"] as? Bool,  GradingRepair: data["GradingRepair"] as? String,  CurbStopRepair: data["CurbStopRepair"] as? String,  SplashPadDownSpout: data["SplashPadDownSpout"] as? String,  RYCBOtherRepairs: data["RYCBOtherRepairs"] as? String,  Comments: data["Comments"] as? String,  columnCamera: data["columnCamera"] as? String,  DepositReceived: data["DepositReceived"] as? Bool) } 

And in func GetLandGradingData(...) method replace inside do { } braces with these:

let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [[String : Any]]                      OperationQueue.main.addOperation({                        let gradingDatas = json.map { GradingData(data: $0) }                          completion(gradingDatas)                      }) 

Answers 3

Just because you asked for an example (but did not provide your GradingData which will make this really abstract):

struct GradingData : Codable {     // here is the meat, but you did not show ... }  ...  let grades = JSONDecoder().decode(GradingData.self, from: data) 

Swift is the first language I have come across which has nailed this. It really just boils down to implementing an interface (without actually doing anything interesting most of the time while still providing the possibility to do all the necessary things with minimal effort) and get a free JSON parser for your objects (not just some hash-junk dictionary).

(It is called "progress" :-)

Answers 4

Convert XML to dictionary by custom class or nsxmlparser. or if u have array of Grading then

var modelArr = [Grading]() 

var model = Grading.init(fromDictionary dictionary: xmlParsedDic) modelArr.append(model)

use this model class

import Foundation 

class Grading : NSObject, NSCoding {

var cityApprovalIssued : Bool! var cityCommentReceived : Bool! var comments : String! var curbStopRepair : String! var depositReceived : Bool! var gradingRepair : String! var rYCBOtherRepairs : String! var sLAIssuedFinalGrading : Bool! var sLAIssuedFinalGradingDate : String! var splashPadDownSpout : String! var address : String! var lot : String!   init(fromDictionary dictionary: [String:Any]){     cityApprovalIssued = dictionary["CityApprovalIssued"] as? Bool     cityCommentReceived = dictionary["CityCommentReceived"] as? Bool     comments = dictionary["Comments"] as? String     curbStopRepair = dictionary["CurbStopRepair"] as? String     depositReceived = dictionary["DepositReceived"] as? Bool     gradingRepair = dictionary["GradingRepair"] as? String     rYCBOtherRepairs = dictionary["RYCBOtherRepairs"] as? String     sLAIssuedFinalGrading = dictionary["SLAIssuedFinalGrading"] as? Bool     sLAIssuedFinalGradingDate = dictionary["SLAIssuedFinalGradingDate"] as? String     splashPadDownSpout = dictionary["SplashPadDownSpout"] as? String     address = dictionary["address"] as? String     lot = dictionary["lot"] as? String }  func toDictionary() -> [String:Any] {     var dictionary = [String:Any]()     if cityApprovalIssued != nil{         dictionary["CityApprovalIssued"] = cityApprovalIssued     }     if cityCommentReceived != nil{         dictionary["CityCommentReceived"] = cityCommentReceived     }     if comments != nil{         dictionary["Comments"] = comments     }     if curbStopRepair != nil{         dictionary["CurbStopRepair"] = curbStopRepair     }     if depositReceived != nil{         dictionary["DepositReceived"] = depositReceived     }     if gradingRepair != nil{         dictionary["GradingRepair"] = gradingRepair     }     if rYCBOtherRepairs != nil{         dictionary["RYCBOtherRepairs"] = rYCBOtherRepairs     }     if sLAIssuedFinalGrading != nil{         dictionary["SLAIssuedFinalGrading"] = sLAIssuedFinalGrading     }     if sLAIssuedFinalGradingDate != nil{         dictionary["SLAIssuedFinalGradingDate"] = sLAIssuedFinalGradingDate     }     if splashPadDownSpout != nil{         dictionary["SplashPadDownSpout"] = splashPadDownSpout     }     if address != nil{         dictionary["address"] = address     }     if lot != nil{         dictionary["lot"] = lot     }     return dictionary }  @objc required init(coder aDecoder: NSCoder) {      cityApprovalIssued = aDecoder.decodeObject(forKey: "CityApprovalIssued") as? Bool      cityCommentReceived = aDecoder.decodeObject(forKey: "CityCommentReceived") as? Bool      comments = aDecoder.decodeObject(forKey: "Comments") as? String      curbStopRepair = aDecoder.decodeObject(forKey: "CurbStopRepair") as? String      depositReceived = aDecoder.decodeObject(forKey: "DepositReceived") as? Bool      gradingRepair = aDecoder.decodeObject(forKey: "GradingRepair") as? String      rYCBOtherRepairs = aDecoder.decodeObject(forKey: "RYCBOtherRepairs") as? String      sLAIssuedFinalGrading = aDecoder.decodeObject(forKey: "SLAIssuedFinalGrading") as? Bool      sLAIssuedFinalGradingDate = aDecoder.decodeObject(forKey: "SLAIssuedFinalGradingDate") as? String      splashPadDownSpout = aDecoder.decodeObject(forKey: "SplashPadDownSpout") as? String      address = aDecoder.decodeObject(forKey: "address") as? String      lot = aDecoder.decodeObject(forKey: "lot") as? String  }  @objc func encode(with aCoder: NSCoder) {     if cityApprovalIssued != nil{         aCoder.encode(cityApprovalIssued, forKey: "CityApprovalIssued")     }     if cityCommentReceived != nil{         aCoder.encode(cityCommentReceived, forKey: "CityCommentReceived")     }     if comments != nil{         aCoder.encode(comments, forKey: "Comments")     }     if curbStopRepair != nil{         aCoder.encode(curbStopRepair, forKey: "CurbStopRepair")     }     if depositReceived != nil{         aCoder.encode(depositReceived, forKey: "DepositReceived")     }     if gradingRepair != nil{         aCoder.encode(gradingRepair, forKey: "GradingRepair")     }     if rYCBOtherRepairs != nil{         aCoder.encode(rYCBOtherRepairs, forKey: "RYCBOtherRepairs")     }     if sLAIssuedFinalGrading != nil{         aCoder.encode(sLAIssuedFinalGrading, forKey: "SLAIssuedFinalGrading")     }     if sLAIssuedFinalGradingDate != nil{         aCoder.encode(sLAIssuedFinalGradingDate, forKey: "SLAIssuedFinalGradingDate")     }     if splashPadDownSpout != nil{         aCoder.encode(splashPadDownSpout, forKey: "SplashPadDownSpout")     }     if address != nil{         aCoder.encode(address, forKey: "address")     }     if lot != nil{         aCoder.encode(lot, forKey: "lot")     }  }} 
Read More

OnActivityResult activity error : Failure delivering result ResultInfo

Leave a Comment

error : Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:28362 flg=0x1 }} to activity {com.projectbox.uploadfile/com.projectbox.uploadfile.MainActivity}: java.lang.NullPo

  @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     super.onActivityResult(requestCode, resultCode, data);     if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {         android.net.Uri selectedImage = data.getData();         String[] filePathColumn = {MediaStore.Images.Media.DATA};         android.database.Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);         if (cursor == null)             return;          cursor.moveToFirst();          int columnIndex = cursor.getColumnIndex(filePathColumn[0]);         String filePath = cursor.getString(columnIndex);         cursor.close();          File file = new File(filePath);          RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);         MultipartBody.Part body = MultipartBody.Part.createFormData("banner", file.getName(), reqFile);         RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "banner");          Log.d("THIS", data.getData().getPath());          retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);         req.enqueue(new Callback<ResponseBody>() {             @Override             public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {              }              @Override             public void onFailure(Call<ResponseBody> call, Throwable t) {                 Log.e("FFF", t.getMessage());                 t.printStackTrace();             }         });     } } 

Error stack:

Process: com.projectbox.uploadfile, PID: 17822 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:28362 flg=0x1 }} to activity {com.projectbox.uploadfile/com.projectbox.uploadfile.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.deliverResults(ActivityThread.java:4220) at android.app.ActivityThread.handleSendResult(ActivityThread.java:4263) at android.app.ActivityThread.-wrap20(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1601) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6349) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783) Caused by: java.lang.NullPointerException at java.io.File.<init>(File.java:262) at com.projectbox.uploadfile.MainActivity.onActivityResult(MainActivity.java:110) at android.app.Activity.dispatchActivityResult(Activity.java:7025) at android.app.ActivityThread.deliverResults(ActivityThread.java:4216) at android.app.ActivityThread.handleSendResult(ActivityThread.java:4263)  at android.app.ActivityThread.-wrap20(ActivityThread.java)                                                                 

5 Answers

Answers 1

You can do it something like this.

if (requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {              Uri uri = data.getData();              try {                 String[] filePathColumn = {MediaStore.Images.Media.DATA};                 Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);                 cursor.moveToFirst();                 int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                 //  picturePath = cursor.getString(columnIndex);                  // try to copy image 1                 File destination = new File(Environment.getExternalStorageDirectory(),                         System.currentTimeMillis() + ".jpg");                 picturePath = "" + destination;                 cursor.close();                 img_member.setTag(picturePath);                 Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);                  ByteArrayOutputStream bytes = new ByteArrayOutputStream();                 bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);                 FileOutputStream fo;                 try {                     destination.createNewFile();                     fo = new FileOutputStream(destination);                     fo.write(bytes.toByteArray());                     fo.close();                 } catch (FileNotFoundException e) {                     e.printStackTrace();                 } catch (IOException e) {                     e.printStackTrace();                 }                 img_member.setImageBitmap(bitmap);                 mBottomSheetDialog.hide();             } catch (IOException e) {                 e.printStackTrace();             }          } 

Answers 2

It seems that the filepath is null. You are trying use the mediastore DATA column to get a File from a content:// URI. This may or may not work as explained by Mark Murphy in How to Consume Content From a Uri.

The only reliable way to get the content is to use ContentResolver.openInputStream()

You can then either copy the stream to a file before uploading it or directly upload the stream as explained by this OkHttp recipe.

Answers 3

You are getting wrong image path or Relative Image Path here. I Think that must Be the problem..

Try Replacing

        String[] filePathColumn = {MediaStore.Images.Media.DATA};         android.database.Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);         if (cursor == null)             return;          cursor.moveToFirst();          int columnIndex = cursor.getColumnIndex(filePathColumn[0]);         String filePath = cursor.getString(columnIndex);         cursor.close(); 

With

Cursor cursor = null; Uri contentUri = data.getData(); String filepath = "";         try {             String[] proj = {MediaStore.Images.Media.DATA};             cursor = context.getContentResolver().query(contentUri, proj, null, null, null);             int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);             cursor.moveToFirst();             filePath = cursor.getString(column_index);         } finally {             if (cursor != null) {                 cursor.close();             }         } 

Hope this will Solve your problem.

Answers 4

Try enabling keep activities from developer options ...that may be one of the cause I have faced earlier

Answers 5

if(!cursor.moveToFirst()) or if(TextUtils.isEmpty(filePath)) you should return from method:

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {     super.onActivityResult(requestCode, resultCode, data);     if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {         android.net.Uri selectedImage = data.getData();         String[] filePathColumn = {MediaStore.Images.Media.DATA};         android.database.Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);         if (cursor == null)             return;          if(!cursor.moveToFirst()){             cursor.close();             return;          }            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);         String filePath = cursor.getString(columnIndex);         cursor.close();         if(TextUtils.isEmpty(filePath))           return;          File file = new File(filePath);          RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);         MultipartBody.Part body = MultipartBody.Part.createFormData("banner", file.getName(), reqFile);         RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "banner");          Log.d("THIS", data.getData().getPath());          retrofit2.Call<okhttp3.ResponseBody> req = service.postImage(body, name);         req.enqueue(new Callback<ResponseBody>() {             @Override             public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {              }              @Override             public void onFailure(Call<ResponseBody> call, Throwable t) {                 Log.e("FFF", t.getMessage());                 t.printStackTrace();             }         });     } } 
Read More

Sunday, April 29, 2018

Two way data binding issue in a MVVM

Leave a Comment

I am trying to build a simple C#/WinFoms project that uses the Model-View-ViewModel design pattern according to the structure:

enter image description here

The data binding between the two UserControls and the associated ViewModels does not work well.

The MainForm contains two UserControls (UC): Uc_Create, Uc_Iteration. Each UC contains a combobox that is connected to the associated property in the ViewModel_xxx, namely

Uc_Create has:

this.comboBox1ComplexCreate.DataSource = oVM_Create.VM_Create_ListOfStringsInModel;  

Uc_Iteration has:

this.comboBox1ComplexIteration.DataSource = oVM_Iteration.VM_Iteration_ListOfStringsInModel; 

The problem:

When I add elements to VM_Iteration_ListOfStringsInModel the combobox in the corresponding UC (comboBox1ComplexCreate) and the list in the Model are correctly changed but the other combobox (comboBox1ComplexIteration) in Uc_Iteration is not!

Why????

If I change the List in the Model to a BindingList, everything works fine. What am I doing wrong?

Thanks in advance!


Model:

namespace Small_MVVM {      public class Model      {         private static readonly object m_oLock = new object();          private static Model instance;           public List<string> simplelistOfStrings;           private Model()         {             simplelistOfStrings = new List<string>();         }          public static Model GetInstance()         {             if (instance == null)             {                 lock (m_oLock)                 {                     if (instance == null)                     {                         instance = new Model();                     }                 }             }             return instance;         }     } } 

ModelView_Create:

namespace Small_MVVM {     class ViewModel_Create : NotifyPropertyChangedBase     {         private static Model oModel = Model.GetInstance();          private BindingList<string> _VM_Create_ListOfStringsInModel = new BindingList<string>(oModel.simplelistOfStrings);         public BindingList<string> VM_Create_ListOfStringsInModel         {             get             {                  return _VM_Create_ListOfStringsInModel;             }             set             {                 _VM_Create_ListOfStringsInModel = value;                 this.FirePropertyChanged(nameof(VM_Create_ListOfStringsInModel));             }         }     } } 

ModelView_Iteration:

namespace Small_MVVM {      class ViewModel_Iteration : NotifyPropertyChangedBase     {         private static Model oModel = Model.GetInstance();          public ViewModel_Iteration()         {          }          BindingList<string> _VM_Iteration_ListOfStringsInModel = new BindingList<string>(oModel.simplelistOfStrings);         public BindingList<string> VM_Iteration_ListOfStringsInModel         {             get             {                 return _VM_Iteration_ListOfStringsInModel;             }             set             {                 _VM_Iteration_ListOfStringsInModel = value;                 this.FirePropertyChanged(nameof(VM_Iteration_ListOfStringsInModel));             }         }     } } 

This is the abstract class NotifyPropertyChangedBase that implements the INotifyPropertyChange interface:

public abstract class NotifyPropertyChangedBase : INotifyPropertyChanged {      public event PropertyChangedEventHandler PropertyChanged;      protected bool CheckPropertyChanged<T>(string propertyName, ref T oldValue, ref T newValue)     {             if (oldValue == null && newValue == null)         {                 return false;         }          if ((oldValue == null && newValue != null) || !oldValue.Equals((T)newValue))         {             oldValue = newValue;             return true;         }          return false;     }      private delegate void PropertyChangedCallback(string propertyName);      protected void FirePropertyChanged(string propertyName)     {          if (this.PropertyChanged != null)         {             this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));         }     } } 

3 Answers

Answers 1

If you are following MVVM pattern , then you should make use of ObservableCollection for collections like as below

   private ObservableCollection<int> _intList;    public ObservableCollection<int> IntList      {         get         {           return _intList;         }         set         {            _intList= value;            _intList.CollectionChanged +=                          new System.Collections.Specialized.NotifyCollectionChangedEventHandler                                             (MyProperty_CollectionChanged);             }         }   void MyProperty_CollectionChanged(object sender,                                  System.Collections.Specialized.NotifyCollectionChangedEventArgs e)   {      NotifyPropertyChanged("IntList");  } 

ObservableCollection - Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

you can also check this : MVVM (Model-View-ViewModel) Pattern For Windows Form Applications, using C#

Answers 2

I think your problem is that there is no link between your two BindingLists.

When you add items to VM_Iteration_ListOfStringsInModel the changes are propagated to the bound combobox and the underlying List in your model. But the list in your model cannot further propagate these changes to VM_Create_ListOfStringsInModel as it does not support this feature. VM_Create_ListOfStringsInModel will contain the item you added to VM_Iteration_ListOfStringsInModel but it won't raise a ListChanged event as List in you model breaks the event chain. A List cannot raise an ListChanged event. That is what BindingList exists for.

And as you already tried, when you replace the list in your model by a BindingList it works.

So one solution you have already mentioned, the other would be to use only one shared BindingList for both comboboxes if this is an option for you.

    private void ListDemo()     {          var l = new List<string>();         l.Add("A");          BindingList<string> blist1 = new BindingList<string>(l);         BindingList<string> blist2 =new BindingList<string>(l);         blist1.ListChanged += Blist1_ListChanged;         blist2.ListChanged += Blist2_ListChanged;           blist1.Add("B");         // at this point blist1 and blist2 items count is 2 but only blist1 raised ListChanged     }      private void Blist2_ListChanged(object sender, ListChangedEventArgs e)     {         //No event fired here when adding B     }      private void Blist1_ListChanged(object sender, ListChangedEventArgs e)     {        // event fired when adding B     } 

Answers 3

Both ViewModel_Iteration and ViewModel_Create defines their property (VM_Iteration_ListOfStringsInModel and VM_Create_ListOfStringsInModel) by initializing a new object of BindingList which uses the model.simplelistOfStrings as specified source list. So both ViewModels have different object of ListOfStringsInModel --- They don't point to same object.

Definitely you should define the simplelistOfStrings property as BindingList so that a two-way data-binding mechanism can be established in your View and code behind. However, instead of defining a new member variable in both ViewModel_Iteration and ViewModel_Create ViewModels, I would suggest that you should change the property definition as follows :

        public BindingList<string> VM_Iteration_ListOfStringsInModel         {             get             {                 return oModel.simplelistOfStrings;             }             set             {                 oModel.simplelistOfStrings = value;                 this.FirePropertyChanged(nameof(VM_Iteration_ListOfStringsInModel));             }         } 

And

        public BindingList<string> VM_Create_ListOfStringsInModel         {             get             {                  return oModel.simplelistOfStrings;             }             set             {                 oModel.simplelistOfStrings = value;                 this.FirePropertyChanged(nameof(VM_Create_ListOfStringsInModel));             }         } 

Another improvement in above approach can be done is that don't use the set at all property definition at all. The Notification is required as reference of property will change when assigned with a new List. So instead of allowing to set a new list, use a approach to Clear and Add new items in the list. That's way the reference of property will remain the same and Two way binding would work without pluming the explicit notification.

ViewModel_Iteration

            public BindingList<string> VM_Iteration_ListOfStringsInModel             {                 get                 {                     return oModel.simplelistOfStrings;                 }             } 

ViewModel_Create

            public BindingList<string> VM_Create_ListOfStringsInModel             {                 get                 {                      return oModel.simplelistOfStrings;                 }             } 

Usage

VM_Create_ListOfStringsInModel.Clear(); VM_Create_ListOfStringsInModel.Add(item); // Or use AddRange to add Range. 
Read More

How to get to Facebook User Page by a known app scoped User ID

Leave a Comment

Till today there have been methods to get to Facebook User Page by user id. I mean ID, that facebook API returns to our app: https://graph.facebook.com/10152384781676191?fields=link

{   "link": "https://www.facebook.com/app_scoped_user_id/10152384781676191/",   "id": "10152384781676191" } 

But none of the methods works any more:


UPDATE: It seems the following happened: according to TechCrunch, malicious sites pulled data form public user profiles.

After TechCrunch article Facebook immediately blocked the URLs that Graph API returns: graph.facebook.com/v2.11/{user-id}/?fields=link&access_token={access-token} . They "...are working on instituting additional authentication and rate limiting...".


Any 1) quick workarounds and/or 2) permanent solution?

1 Answers

Answers 1

Facebook banned the link property in their Graph API intentionally. Now they propose to fill out a from in order to review each case individually.

The form: https://go.fb.com/2018-FB4D-platform-review-form.html

News update from April 20th: Facebook Login Changes to Address Abuse

It came to our attention yesterday that some third-party tracking scripts on websites were directly accessing Facebook public profiles. While investigating this issue, we have taken immediate action by:

  • Disabling the ability to resolve the app-scoped user ID (ASID) returned by Facebook Login to a Facebook profile page, even for logged-in users.
  • Instituting rate limiting of profile picture requests, to further prevent any third parties from trying to link people's activity across different websites using the application-specific identifiers issued by Facebook Login.

We don’t take breaking changes lightly, but we believe that these updates will help protect people’s privacy and increase trust across the ecosystem. If you have an urgent issue in need of resolution, please fill out this form and someone from our team will get in touch with you.

Thank you for your patience while we work to resolve this issue as soon as possible.

Read More

Getting same predicted values for all inputs in trained tensor flow network

Leave a Comment

I have created a tensorflow network designed to read data from this dataset (note: the information in this dataset is designed purely for test purposes and is not real):enter image description here and am trying to build a tensorflow network designed to essentially predict values in the 'Exited' column. My network is structured to take 11 inputs, pass through 2 hidden layers (6 neurons each) with relu activation, and output a single binary value using a sigmoid activation function in order to produce a probability distribution. I am using a gradient descent optimizer and a mean squared error cost function. However, after training the network on my training data and predicting off my testing data, all my predicted values are greater than 0.5 meaning likely to be true and I'm not sure what the problem is:

X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.2, random_state=101) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.fit_transform(X_test)  training_epochs = 200 n_input = 11 n_hidden_1 = 6 n_hidden_2 = 6 n_output = 1  def neuralNetwork(x, weights):      layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])      layer_1 = tf.nn.relu(layer_1)      layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])      layer_2 = tf.nn.relu(layer_2)      output_layer = tf.add(tf.matmul(layer_2, weights['output']), biases['output'])      output_layer = tf.nn.sigmoid(output_layer)      return output_layer  weights = {     'h1': tf.Variable(tf.random_uniform([n_input, n_hidden_1])),     'h2': tf.Variable(tf.random_uniform([n_hidden_1, n_hidden_2])),     'output': tf.Variable(tf.random_uniform([n_hidden_2, n_output])) }  biases = {     'b1': tf.Variable(tf.random_uniform([n_hidden_1])),     'b2': tf.Variable(tf.random_uniform([n_hidden_2])),     'output': tf.Variable(tf.random_uniform([n_output])) }  x = tf.placeholder('float', [None, n_input]) # [?, 11] y = tf.placeholder('float', [None, n_output]) # [?, 1]  output = neuralNetwork(x, weights) cost = tf.reduce_mean(tf.square(output - y)) optimizer = tf.train.AdamOptimizer().minimize(cost)  with tf.Session() as session:     session.run(tf.global_variables_initializer())     for epoch in range(training_epochs):         session.run(optimizer, feed_dict={x:X_train, y:y_train.reshape((-1,1))})     print('Model has completed training.')     test = session.run(output, feed_dict={x:X_test})     predictions = (test>0.5).astype(int)     print(predictions) 

All help is appreciated! I have been looking through questions related to my problem but none of the suggestions have seemed to help.

1 Answers

Answers 1

Initial assumption: I won't access data from a personal link for security reasons. It's your responsibility to create a reproducible code snippet based solely on secure/persistent artifacts.
However, I can confirm your problem happens when your code is ran against keras.datasets.mnist, with a small change: each sample is associated with a label 0: odd or 1: even.

Short answer: you messed up the initialization. Change tf.random_uniform to tf.random_normal and set biases to a deterministic 0.

Actual answer: ideally, you want the model to start predicting randomly, close to the 0.5. This will prevent the saturation of the sigmoid's output and result in large gradients in early stages of training.

The sigmoid's eq. is s(y) = 1/(1 + e**-y), and s(y) = 0.5 <=> y = 0. Therefore, the layer's output y = w * x + b must be 0.

If you used StandardScaler, then your input data follows a Gaussian distribution, mean = 0.5, std = 1.0. Your parameters must sustain this distribution! However, you've initialized your biases with tf.random_uniform, which uniformly draws values from the [0, 1) interval.

By starting your biases at 0, y will be close to 0:

y = w * x + b = sum(.1 * -1, .9 * -.9, ..., .1 * 1, .9 * .9) + 0 = 0 

So your biases should be:

biases = {     'b1': tf.Variable(tf.zeros([n_hidden_1])),     'b2': tf.Variable(tf.zeros([n_hidden_2])),     'output': tf.Variable(tf.zeros([n_output])) } 

This is sufficient to output numbers smaller than 0.5:

[1.        0.4492423 0.4492423 ... 0.4492423 0.4492423 1.       ] predictions mean: 0.7023628 confusion matrix: [[4370 1727]  [1932 3971]] accuracy: 0.6950833333333334 

Further corrections:

  • Your neuralNetwork function does not take a biases parameter. It instead uses the one defined in the other scope, which seems like a mistake.

  • You should not fit the scaler to the test data, because you will lose the statistics from train and because it violates the principle that that chunk of data is purely observational. Do this:

    scaler = StandardScaler() x_train = scaler.fit_transform(x_train) x_test = scaler.transform(x_test) 
  • It's very uncommon to use MSE with sigmoid output. Use binary cross-entropy instead:

    logits = tf.add(tf.matmul(layer_2, weights['output']), biases['output']) output = tf.nn.sigmoid(logits) cost = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits) 
  • It's more reliable to initialize the weights from a normal distribution:

    weights = {     'h1': tf.Variable(tf.random_uniform([n_input, n_hidden_1])),     'h2': tf.Variable(tf.random_uniform([n_hidden_1, n_hidden_2])),     'output': tf.Variable(tf.random_uniform([n_hidden_2, n_output])) } 
  • You are feeding the entire train dataset at each epoch, instead of batching it, which is the default in Keras. Therefore, it's reasonable to assume Keras implementation will converge faster and the results might differ.

By making a few teaks, I manage to achieve this results:

import tensorflow as tf from keras.datasets.mnist import load_data from sacred import Experiment from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler  ex = Experiment('test-16')   @ex.config def my_config():     training_epochs = 200     n_input = 784     n_hidden_1 = 32     n_hidden_2 = 32     n_output = 1   def neuralNetwork(x, weights, biases):     layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])     layer_1 = tf.nn.relu(layer_1)     layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])     layer_2 = tf.nn.relu(layer_2)     logits = tf.add(tf.matmul(layer_2, weights['output']), biases['output'])     predictions = tf.nn.sigmoid(logits)     return logits, predictions   @ex.automain def main(training_epochs, n_input, n_hidden_1, n_hidden_2, n_output):     (x_train, y_train), _ = load_data()     x_train = x_train.reshape(x_train.shape[0], -1).astype(float)     y_train = (y_train % 2 == 0).reshape(-1, 1).astype(float)      x_train, x_test, y_train, y_test = train_test_split(x_train, y_train, test_size=0.2, random_state=101)     print('y samples:', y_train, y_test, sep='\n')      scaler = StandardScaler()     x_train = scaler.fit_transform(x_train)     x_test = scaler.transform(x_test)      weights = {         'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),         'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),         'output': tf.Variable(tf.random_normal([n_hidden_2, n_output]))     }      biases = {         'b1': tf.Variable(tf.zeros([n_hidden_1])),         'b2': tf.Variable(tf.zeros([n_hidden_2])),         'output': tf.Variable(tf.zeros([n_output]))     }      x = tf.placeholder('float', [None, n_input])  # [?, 11]     y = tf.placeholder('float', [None, n_output])  # [?, 1]      logits, output = neuralNetwork(x, weights, biases)     # cost = tf.reduce_mean(tf.square(output - y))     cost = tf.nn.sigmoid_cross_entropy_with_logits(labels=y, logits=logits)     optimizer = tf.train.AdamOptimizer().minimize(cost)      with tf.Session() as session:         session.run(tf.global_variables_initializer())         try:             for epoch in range(training_epochs):                 print('epoch #%i' % epoch)                 session.run(optimizer, feed_dict={x: x_train, y: y_train})          except KeyboardInterrupt:             print('interrupted')          print('Model has completed training.')         p = session.run(output, feed_dict={x: x_test})         p_labels = (p > 0.5).astype(int)          print(p.ravel())         print('predictions mean:', p.mean())          print('confusion matrix:', confusion_matrix(y_test, p_labels), sep='\n')         print('accuracy:', accuracy_score(y_test, p_labels)) 
[0.        1.        0.        ... 0.0302309 0.        1.       ] predictions mean: 0.48261687 confusion matrix: [[5212  885]  [ 994 4909]] accuracy: 0.8434166666666667 
Read More

Calculate input field based on expiry date

Leave a Comment

A form with 50 entries: each with P1-48, E1-48, and X1-48. I want to calculate the Entry Fee "E1" based on the expires date X1. The js date format for the expires date is YYYY.MM.DD, ex. 2018.04.21 and a player pays $3 if his expires date is greater or equal to today's date. He pays $5 if his expires date is older or less than today's date. But if the expires date is blank and the player pays a membership fee, the Entry Fee is waived to zero.

JS:

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

I also have this as a "template" starting guide. I think it could be modified and piggyback the target result onto it.

<script> // change expiration date color function getExpireDate(ele) { var i = null; for (i = 0; members.length > i; i++) {     if (members[i].Name == ele.value) {         var exDate = moment(members[i].Expires, 'YYYY.MM.DD');         if (moment().isAfter(exDate)) {         $(ele).closest('.universal').find('.expDate').css('color', "#A3005B");         } else {         $(ele).closest('.universal').find('.expDate').css('color', "#275052");         }         return members[i].Expires;      } } return ''; } </script>  <script>  for (let i = 0; i <= 48; i++) {     $("#P" + i).on("blur", function(){     $("#X" +i).val(getExpireDate(this));     }); } </script>  <script>      var members [     {"Name": "Jones, David", "Expires": "2017.05.03" },     {"Name": "Roth, Bill", "Expires": "2017.03.08" },     {"Name": "Scullin, Kenn", "Expires": "2019.02.20" }     ]  <script> 

HTML:

<div>     <input type = "text" id = "P1"> <!--Player-->     <input type = "text" id = "E1"> <!--Entry Fee-->      <input type = "text" id = "M1"> <!--Membership Fee-->  <input type = "text" id = "X1" onblur="getExpireDate()" class="expDate"> <!--expires--> <div> 

Funny thing is:

<input type = "text" onblur="getClass()" class="text" id="Y1" maxlength = "4" size = "4" disabled /> <!--works even with input disabled -->  <input type = "text" onblur="calcEntryFee(this);" class="expDate" name = "exp" id="X1" maxlength = "10" size = "10" disabled /><!--new code doesn't work -->  <script> // Lookup class or rating  function getClass(ele) { var i = null; for (i = 0; members.length > i; i++) { if (members[i].Name == ele.value) { return members[i].Rating;  } } return; }   for (let i = 0; i <= 48; i++) { $("#P" + i).on("blur", function(){ $("#Y" +i).val(getClass(this)); }); } </script> 

3 Answers

Answers 1

How about this:

(The main function is calcEntryFee().)

var members = [   // ... fill data here. ];  function getMemberData( name ) {     var a = jQuery.trim( name ).toLowerCase(),         i, b, member;      for ( i = 0; i < members.length; i++ ) {         b = jQuery.trim( members[ i ].Name ).toLowerCase();         if ( a === b ) {             member = members[ i ];             break;         }     }      return member || {}; }  function calcEntryFee( elem ) {     var idx, member, exDate, today, fee;      elem = elem || {};     if ( /^[PEMX](\d+)$/.test( elem.id ) ) {         idx = RegExp.$1;     } else {         return false;     }      member = getMemberData( jQuery( '#P' + idx ).val() );     mmfee = parseFloat( jQuery( '#M' + idx ).val() );     exDate = moment( member.Expires, 'YYYY.MM.DD' );     today = moment();     fee = '';      if ( exDate.isBefore( today ) ) {         fee = 5;     } else if ( exDate.isSameOrAfter( today ) ) {         fee = 3;     } else if ( ! member.Expires && mmfee > 0 ) {         fee = 0;     }      // Updates the entry fee input value.     jQuery( '#E' + idx ).val( fee );      return fee; } 

You'd use calcEntryFee() like this:

<input id="X1" placeholder="X" size="10" onblur="calcEntryFee( this );" /> 

See the full code and try a live demo on https://codepen.io/anon/pen/WJRNVY.

Answers 2

Had to re-read your question a few times. I'm still not sure a fully understand what you're trying to achieve, but I believe this is pretty close:

let getMember = {   index: function(name) {     let index = -1;       $.each(members, function(i, player) {       if (player.Name === name) { index = i; }     });     return index;   },   entryFee: function(memberIndex) {     if (memberIndex === -1) {       return 'waived';     } else {}       let today = new Date();       let expires = new Date(members[memberIndex].Expires.replace(/\./g, '-'));       return today <= expires ? '$3' : '$5';         } };  let members = [   {"Name": "Jones, David", "Expires": "2017.05.03" },   {"Name": "Roth, Bill", "Expires": "2017.03.08" },   {"Name": "Scullin, Kenn", "Expires": "2019.02.20" } ];   let tableHTML = '';  for (let i=0; i < 50; i++) {     tableHTML += `   <div class="row">     <input type="text" class="player" placeholder="player">     <input type="text" class="entryFee" placeholder="entry fee">     <input type="text" class="membershipFee" placeholder="membership fee">     <input type="text" class="expDate" placeholder="expire date">   <div>`; }  $(`<div class="table">${tableHTML}</div>`)   .appendTo('body')   .on('blur', '.player', function() {     if (!this.value) { return false; }     let memberIndex = getMember.index(this.value);     let entryFee = getMember.entryFee(memberIndex);      $(this)       .next().val(entryFee)       .next().val(entryFee === 'waived' ? 'yes' : 'no')       .next()         .val(memberIndex >= 0 ? members[memberIndex].Expires : 'non-member')         .addClass(entryFee === '$3' ? 'currentMember' : 'nonCurrentMember');      $('.player').eq($('.player').index(this) + 1).focus(); }); 

https://jsfiddle.net/ypzjfkxk/

Without an external library to boot! Can't say I have any experience with moment.js, but all of the questions I've come across seem to be solvable in plain javascript. Also, it would be just as fast and easy to generate an alphabetical table for this. Then you wouldn't have to worry about typos in the player input. Unless you're trying to create a log or something?

Answers 3

This works for me:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <!DOCTYPE html>  <html lang="en">    <head>      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>            <script type="application/javascript">        var members = [          {"Name": "Jones, David", "Expires": "2017.05.03" },          {"Name": "Scullin, Kenn", "Expires": "2019.02.20" },          {"Name": "Peter, Kenn", "Expires": "2018.04.24" },          {"Name": "Chris, Kennx", "Expires": "" }        ];          $(document).ready(function(){          var nUsers = 4; // Number os users            // Fill inputs (tmp: visual purpose)          for (count=1; count<=nUsers; count++){            $("#P"+count).val(members[count-1].Name);            $("#X"+count).val(members[count-1].Expires);          }          $("#M4").val("$20");            /* Get current date. For security purpose you should            get this from the server and not the client side.*/          var date = moment().toDate();            // Go through every input row          for (count=1; count<=nUsers; count++){            var exDate = $("#X"+count).val(); // Get the exire date              // Confirm that date is has the right format            if (moment(exDate, 'YYYY.MM.DD').isValid()){              exDate = moment(exDate, 'YYYY.MM.DD').toDate();              var diff = new Date(exDate - date);              var nDays = parseInt(diff/1000/60/60/24);                console.log(nDays);                if (nDays >= 0){ // If his expires date is greater or equal to today's date                $("#E"+count).val("$3");                $("#X"+count).css('color', "#275052");              }              if (nDays < 0){                $("#E"+count).val("$5"); // If his expires date is older or less than today's date                $("#X"+count).css('color', "#A3005B");              }            }            else{ // If expire date is empty              var mFee = parseFloat($("#M"+count).val().replace(/\$/, ''));              if ((exDate.length == 0) && (mFee > 0 )){ // If the expires date is blank and the player pays a membership fee                $("#E"+count).val("$0");              }            }          }        });      </script>      </head>    <body>        <!-- visual purpose -->      <div>        <input type = "text" id = "P1"> <!--Player-->        <input type = "text" id = "E1"> <!--Entry Fee-->        <input type = "text" id = "M1"> <!--Membership Fee-->        <input type = "text" id = "X1" class="expDate"> <!--expires-->          <br>          <input type = "text" id = "P2"> <!--Player-->        <input type = "text" id = "E2"> <!--Entry Fee-->        <input type = "text" id = "M2"> <!--Membership Fee-->        <input type = "text" id = "X2" class="expDate"> <!--expires-->          <br>          <input type = "text" id = "P3"> <!--Player-->        <input type = "text" id = "E3"> <!--Entry Fee-->        <input type = "text" id = "M3"> <!--Membership Fee-->        <input type = "text" id = "X3" class="expDate"> <!--expires-->          <br>          <input type = "text" id = "P4"> <!--Player-->        <input type = "text" id = "E4"> <!--Entry Fee-->        <input type = "text" id = "M4"> <!--Membership Fee-->        <input type = "text" id = "X4" class="expDate"> <!--expires-->        <div>      </body>  </html>

And a recommendation that I gave to you in the code is you should get the current time from the server side and not from the client side.

I hope that works for you. :)

Read More

AWS SNS subscription keeps deleting the subscription itself

Leave a Comment

I subscribed to a SNS topic with an endpoint of an email address.

I have received notice of unsubscribing from the topic lastnight, I asked all who had access to the inbox, nobody clicked the unsubscribe link.

I recreated the subscription and this morning it unsub itself again.

How could that be? And how can I prevent this from happening again? I looked up in CloudTrail but unsubscribe action is not logged unless they are made with in the console or via the API.

Any indicator would be helpful , thanks.

1 Answers

Answers 1

It might indeed be the gmail automatic spam filter, but since there are no logs available this is hard to verify.

From the AWS Documentation I see that you can enable authentication for deletion. This should prevent it being deleted by gmail.

Deletes a subscription. If the subscription requires authentication for deletion, only the owner of the subscription or the topic's owner can unsubscribe, and an AWS signature is required. If the Unsubscribe call does not require authentication and the requester is not the subscription owner, a final cancellation message is delivered to the endpoint, so that the endpoint owner can easily resubscribe to the topic if the Unsubscribe request was unintended.

Read More

What does algebraic effects mean in FP?

Leave a Comment

Ref:

I have searched a lot of links, but it seems that no one could explain it specifically. Could anyone give some code(use javaScript) to explain it? Thanks a lot!

0 Answers

Read More

Saturday, April 28, 2018

recreating a ggplot plot in d3.js plot

Leave a Comment

With a data frame dft below I'm plotting the data using R's ggplot. I need to recreate this plot in D3 for using in a Angular (2+) web app.

Data

text <- " MODEL,ENGINE,var,value,label,var2 ABCD A1601 F1S - QU1234,QUOINOK,varA_XX_Xxxx,11989,11989,varA_XX_Xxxx ABCD A1601 F1S - QU1234,QUOINOK,varB_XX_xxxXx,1.87,1.87,varB_XX_xxxXx ABCD A1601 F1S - QU1234,QUOINOK,varC,1.61,1.61,varC ABCD A1601 F1S - QU1234,QUOINOK,varD_XXX_YYYYYYY_Zzz,0,0,VAR DEFH Xxxxxxx (%) ABCD A1601 F1S - QU1234,QUOINOK,varE_XXX_YYYYYYY_Zzz,42.4,42.4,VAR DEFH Xxxxxxx (%) ABCD A1601 F1S - QU1234,QUOINOK,varF_XXX_YYYYYYY_Zzz,26.6,26.6,VAR DEFH Xxxxxxx (%) ABCD A1601 F1S - QU1234,QUOINOK,varH_XXX_YYYY_Zzz,31,31,VAR DEFH Xxxxxxx (%) ABCD A1601 F1S - QU1234,QUOINOK,varG_XXX_YY_ZZZZ,3.4,3.4,VAR GIJK Xxxx (%) ABCD A1601 F1S - QU1234,QUOINOK,varI_XXXX_YY_ZZZZZ,9.3,9.3,VAR GIJK Xxxx (%) ABCD A1601 F1S - QU1234,QUOINOK,varJ_XXXX_Yyyy_ZZ_ZZZZZ,12.5,12.5,VAR GIJK Xxxx (%) ABCD A1601 F1S - QU1234,QUOINOK,varK_Xxxx_YY_ZZZZZ,0,0,VAR GIJK Xxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varA_XX_Xxxx,10357,10357,varA_XX_Xxxx ABCD CPH1609 F3 - QU1234T,QUOINOK,varB_XX_xxxXx,1.71,1.71,varB_XX_xxxXx ABCD CPH1609 F3 - QU1234T,QUOINOK,varC,1.62,1.62,varC ABCD CPH1609 F3 - QU1234T,QUOINOK,varD_XXX_YYYYYYY_Zzz,0,0,VAR DEFH Xxxxxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varE_XXX_YYYYYYY_Zzz,36.3,36.3,VAR DEFH Xxxxxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varF_XXX_YYYYYYY_Zzz,34,34,VAR DEFH Xxxxxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varH_XXX_YYYY_Zzz,29.7,29.7,VAR DEFH Xxxxxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varG_XXX_YY_ZZZZ,3.4,3.4,VAR GIJK Xxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varI_XXXX_YY_ZZZZZ,9.3,9.3,VAR GIJK Xxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varJ_XXXX_Yyyy_ZZ_ZZZZZ,13.6,13.6,VAR GIJK Xxxx (%) ABCD CPH1609 F3 - QU1234T,QUOINOK,varK_Xxxx_YY_ZZZZZ,0,0,VAR GIJK Xxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varA_XX_Xxxx,12688.5,12688,varA_XX_Xxxx ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varB_XX_xxxXx,1.87,1.87,varB_XX_xxxXx ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varC,1.7,1.7,varC ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varD_XXX_YYYYYYY_Zzz,0,0,VAR DEFH Xxxxxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varE_XXX_YYYYYYY_Zzz,32.3,32.3,VAR DEFH Xxxxxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varF_XXX_YYYYYYY_Zzz,29.8,29.8,VAR DEFH Xxxxxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varH_XXX_YYYY_Zzz,37.9,37.9,VAR DEFH Xxxxxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varG_XXX_YY_ZZZZ,3.4,3.4,VAR GIJK Xxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varI_XXXX_YY_ZZZZZ,9.7,9.7,VAR GIJK Xxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varJ_XXXX_Yyyy_ZZ_ZZZZZ,11,11,VAR GIJK Xxxx (%) ABCD CPH1613 F3 - MOL2345,MOLTOVAST,varK_Xxxx_YY_ZZZZZ,0,0,VAR GIJK Xxxx (%) " dft <- read.table(textConnection(text), sep=",", header = T) 

Set order of attributes in the plot

varOrder <- c("varA_XX_Xxxx", "varB_XX_xxxXx","varC",                     "varG_XXX_YY_ZZZZ", "varI_XXXX_YY_ZZZZZ",                     "varJ_XXXX_Yyyy_ZZ_ZZZZZ", "varK_Xxxx_YY_ZZZZZ",                     "varD_XXX_YYYYYYY_Zzz", "varE_XXX_YYYYYYY_Zzz",                     "varF_XXX_YYYYYYY_Zzz", "varH_XXX_YYYY_Zzz") var2Order <- c("varA_XX_Xxxx", "varB_XX_xxxXx", "varC",                "VAR GIJK Xxxx (%)", "VAR DEFH Xxxxxxx (%)" ) dft$var <- factor(dft$var, levels=varOrder) dft$var2 <- factor(dft$var2, levels=var2Order) 

Plot

library(ggplot2) library(ggthemes) library(RColorBrewer) library(scales)  p <-  ggplot(dft, aes(x=MODEL, y=value, fill=var, label=label)) +       geom_col(aes(col = ENGINE), position=position_dodge(width = 0.9),                    size=1.2) +     geom_text(position = position_dodge(width = 1),                show.legend = FALSE,               size = 3.5,               vjust=1               ) +     facet_wrap( ~ var2, scales = "free_y", ncol = 1, drop = T) +     theme_custom_col +     scale_fill_brewer(palette = "Set3") +      scale_color_brewer(palette = "Paired") +     theme(       text = element_text(size=ggplotAxesLabelSize),       legend.position="top",       axis.text.x=element_text(angle = 20),       axis.text.y=element_blank()       ) +     labs(y = "") p 

Output enter image description here

How should I go about recreating this in D3 using the same data ?

1 Answers

Answers 1

In short, ggplot is more like a chart library in R and D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS.(definition from d3 document).

In order to implement your ggplot result using d3.js, there will be some knowledge gap and things you need to think. Because ggplot create plot directly on device concept in R, and d3.js create visualization by binding the data to the html element.

There will be two rough suggestions to reach your goals under different considerations.

One: You want to leverage the ggplot2 power and your effect on crafting R codes. and you will directly use it on your web app without adding new interactive effect or other modification. Besides, the data used to plot is static.

you should consider to use the Rshiny or Rmarkdown along to wrap your plot into html element and bind to your web app. You only have to workout how to integrate the html element to your web app and the view or size show on the web.

Second: You just use ggplot2 to prototype the viz effect and there still lots of improvements you want to add-on.

You can consider use d3.js to craft the viz effect, which mean you need to get some basic html knowledge to begin with. Then, you have to recreate all vis effect on binding the html element to data with d3.js . After that, you have to workout the way to integrate your d3.js code into web app such as Angular. Since all web framework have some design to bind the html element on its own way, which also may be a issue during intergration the d3.js code into your web app.

Hope these suggestions work for you. Your question is big and need a development decision first under your own consideration. I'm also R user and learn d3.js after ggplot/grid cannot satisfy my viz goal. So, I can understand your situation. And taking second approach you may spend much more time than you think.

Read More

Uncaught TypeError: Cannot read property 'bool' of undefined after upgrade reactjs

Leave a Comment

I have just upgraded my reactjs project from 15.4.2 to 16.3.2 , the project compiles fine however, in the browser, I get this error:

Uncaught TypeError: Cannot read property 'bool' of undefined     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.exports.__esModule (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3) 

but I could know where is the line causing the error.. maybe I have to upgrade other packages too?

here is what I have currently:

"devDependencies": {     "axios": "^0.17",     "babel-preset-react": "^6.24.1",     "bootstrap-sass": "^3.3.7",     "create-react-class": "^15.6.3",     "cross-env": "^5.1",     "laravel-mix": "^1.0",     "lodash": "^4.17.4",     "react": "16.3.2",     "react-dom": "16.3.2"   },   "dependencies": {     "ajv": "^6.4.0",     "animate.css": "^3.1.1",     "bootstrap": "^3.3.7",     "dom-tools": "^0.1.4",     "font-awesome": "^4.7.0",     "history": "^4.7.2",     "jquery": "^3.1.1",     "jquery-slimscroll": "^1.3.6",     "metismenu": "^2.5.0",     "prop-types": "^15.6.0",     "react-bootstrap": "^0.28.3",     "react-bootstrap-sweetalert": "^4.3.1",     "react-infinite-grid": "^0.4.0",     "react-infinite-scroller": "^1.1.4",     "react-metismenu": "^1.4.0-alpha.2",     "react-pace": "^1.0.0",     "react-redux": "^5.0.6",     "react-router": "^4.2.0",     "react-router-dom": "^4.2.2",     "react-table": "^6.8.0",     "redux": "^3.7.2",     "redux-logger": "^3.0.6",     "redux-persist": "^4.9.1",     "redux-thunk": "^2.2.0",     "ree-validate": "^1.0.15",     "rndoam": "^0.1.0",     "semantic-ui-react": "^0.76.0"   } 

EDIT

Full error:

Uncaught TypeError: Cannot read property 'bool' of undefined     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.exports.__esModule (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3)     at Object.<anonymous> (propTypes.js:3)     at __webpack_require__ (propTypes.js:3) (anonymous) @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 (anonymous) @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 exports.__esModule @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 (anonymous) @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 (anonymous) @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 (anonymous) @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 (anonymous) @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 (anonymous) @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 Object.defineProperty.value @ propTypes.js:3 __webpack_require__ @ propTypes.js:3 (anonymous) @ propTypes.js:63 (anonymous) @ propTypes.js:66 

2 Answers

Answers 1

but I could know where is the line causing the error.

You need to use the tools provided by your browser to see where the error happens. Otherwise it's easy to spend hours on simple errors.

Specifically, if you use Chrome, open the DevTools on the Sources tab. Click the pause button (blue on the image) to "Pause on Exceptions":

pause on exceptions button

Now if you reload the page with Sources pane open, you will see where exactly the code is breaking. It might be in a third party dependency that needs updating.

Finally, your sourcemap setup looks broken. It's odd that almost every call frame has the same line number. If you're not sure how to configure webpack correctly for development, I suggest using an officially supported tool like Create React App that configures it for you.

Answers 2

https://reactjs.org/docs/typechecking-with-proptypes.html

From the link above

React.PropTypes has moved into a different package since React v15.5. Please use the prop-types library instead.

You have to import PropTypes from 'prop-types'; instead of relying on React.PropTypes

Read More

std::locale/std::facet Critical section

Leave a Comment

Out of curiosity. In the past I've seen performance degradation in function like boost::to_lower because of the CriticalSection employed in std::use_facet when the lazy facet is allocated. As far as I remember there was a bug with global lock on locale but according to Stephan Lavavej it was fixed in VS2013. And voila, I saw this lock on facet killing server performance yesterday so I guess I'm confusing two different issues.
But in the first place, why there is a CriticalSection around the lazy facet? Obviously it will ruin the performance. Why they didnt resolve to some kind of upgradable lock or atomic operations on pointers?

1 Answers

Answers 1

MSVC++'s std::locale is implemented in terms of the underlying C function setlocale. That touches global state, and must therefore be protected by a lock.

Changing the locking semantics of a data structure is unfortunately an ABI breaking change, so not much we'll be able to do about it for a while.

Read More

d3js scroll visibility - series animation for bar chart

Leave a Comment

enter image description here

I am working on a d3 application and I am interested in taking the following jsfiddle -- and onload or on an action -- revoking an animation where the bar charts animate one by one.

So the first bar animates to its height, then the second and so forth. Also a reversal of the animation would be good too -- so maybe something that is invoked automatically on scroll visibility?

http://jsfiddle.net/pg886/201/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://d3js.org/d3.v4.min.js"></script>  <div      class="barchart"      data-role="barchart"      data-width=300     data-height=400      data-data="x"     data-configurations="" > </div>  <style>     .barchart{         /*width:100%;         border: 1px solid red;*/     }      .barchart svg{         width:100%;         /*border: 1px solid green;*/     }      .barchartg{      }      .barchart .axis path{         fill: none;         stroke: #000;         shape-rendering: crispEdges;     }      .barchart .axis line {         fill: none;         stroke: none;         shape-rendering: crispEdges;     }      .barchart .x.axis path {         display: none;     }      .barchart .axis text{         fill: #005a70;     }      .barchart.dark .axis text{         fill: #ffffff;     }     .barchart.dark .axis path{           stroke: #ffffff;     }      .barchart .bar:hover {         fill: #e9168a;     }  </style>   <script>      $(document).ready(function() {         console.log("test")          var $this = $(".barchart");          var w = $this.data("width");         var h = $this.data("height");         var data = $this.data("data");          var data = [{             "label": "Apples",             "value": 100         },         {             "label": "Pears",             "value": 120         },         {             "label": "Bananas",             "value": 20         }];          var configurations = $this.data("configurations");          function colores_google(n) {             var colores_g = ["#f7b363", "#448875", "#2b2d39", "#c12f39", "#f8dd2f", "#1b91dc"];             return colores_g[n % colores_g.length];         }          //asess the margin bottom for the chart based on the max char label         var charLabelCount = [];         data.map(function(d) {              var labelStr =  d.label.toString();             charLabelCount.push(labelStr.length);          })         var maxChars = charLabelCount.reduce(function(a, b) {             return Math.max(a, b);         });          var bottomMarg = 60;         if(maxChars > 15){             bottomMarg = 170;         }         //bottom margin calculation          var margin = {top: 15, right: 20, bottom: bottomMarg, left: 40},             width = w - margin.left - margin.right,             height = h - margin.top - margin.bottom;          var x = d3.scaleBand()             .rangeRound([0, width]).padding(0.1);          var y = d3.scaleLinear()             .range([height, 0]);          var xAxis = d3.axisBottom(x);         var yAxis = d3.axisLeft(y);          var svg = d3.select($this[0])             .append("svg")             .attr("width", w)             .attr("height", h)             .attr("viewBox", "0 0 "+w+" "+h)             .attr("preserveAspectRatio", "xMidYMid meet")           .append("g")             .attr("transform", "translate(" + margin.left + "," + margin.top + ")")             .attr("class", "barchartg");          function sortBy(array,key){             var sorted = array.sort(function(a, b) {                 return parseFloat(b[key]) - parseFloat(a[key]);             });             return sorted;         }          var sortedMax = 45;//45 as an initial value          //if there is a configuration file - it acts as an overide -- this is so there could be just one chart -- or a set of charts next to each other         if(configurations){             //if its a comparison chart -- use a max value that will be shared amongst a stack of sibling charts             if(configurations[0]["maxValue"]){                 sortedMax = configurations[0]["maxValue"] + 5;//add 5 value buffer             }         }         else{             //if its a stand alone chart - adjust the max val by this chart's own values             sortedMax = sortBy(data, "value")[0]["value"] + 5;//add 5 value buffer         }          x.domain(data.map(function(d) {              return d.label;          }));          y.domain([0, sortedMax]);          svg.append("g")           .attr("class", "x axis")           .attr("transform", "translate(0," + height + ")")           .call(xAxis);          svg.selectAll(".x.axis text")                   .attr("transform", "rotate(-60) translate(-5,-5)")                 .style("text-anchor", "end");          svg.append("g")           .attr("class", "y axis")           .call(yAxis)         .append("text")           .attr("transform", "rotate(-90)")           .attr("y", 6)           .attr("dy", ".71em")           .style("text-anchor", "end")           .text("");          svg.selectAll(".bar")           .data(data)         .enter().append("rect")           .attr("class", "bar")                      .attr("fill", function(d, i) {              return colores_google(i);           })           .attr("x", function(d) {              return x(d.label);            })           .attr("width", x.bandwidth())           .attr("y", function(d) {              return y(d.value);            })           .attr("height", function(d) {              return height - y(d.value);            });     });  </script> 

2 Answers

Answers 1

Use .transition() to trigger animation to each rect.

But you have to start each rect with a height of zero and y of zero as well, so that you have something to work with in the animation.

$(document).ready(function() {    console.log("test")      var $this = $(".barchart");      var w = $this.data("width");    var h = $this.data("height");    var data = $this.data("data");      var data = [{        "label": "Apples",        "value": 100      },      {        "label": "Pears",        "value": 120      },      {        "label": "Bananas",        "value": 20      }    ];      var configurations = $this.data("configurations");      function colores_google(n) {      var colores_g = ["#f7b363", "#448875", "#2b2d39", "#c12f39", "#f8dd2f", "#1b91dc"];      return colores_g[n % colores_g.length];    }      //asess the margin bottom for the chart based on the max char label    var charLabelCount = [];    data.map(function(d) {      var labelStr = d.label.toString();      charLabelCount.push(labelStr.length);    })    var maxChars = charLabelCount.reduce(function(a, b) {      return Math.max(a, b);    });      var bottomMarg = 60;    if (maxChars > 15) {      bottomMarg = 170;    }    //bottom margin calculation      var margin = {        top: 15,        right: 20,        bottom: bottomMarg,        left: 40      },      width = w - margin.left - margin.right,      height = h - margin.top - margin.bottom;      var x = d3.scaleBand()      .rangeRound([0, width]).padding(0.1);      var y = d3.scaleLinear()      .range([height, 0]);      var xAxis = d3.axisBottom(x);    var yAxis = d3.axisLeft(y);      var svg = d3.select($this[0])      .append("svg")      .attr("width", w)      .attr("height", h)      .attr("viewBox", "0 0 " + w + " " + h)      .attr("preserveAspectRatio", "xMidYMid meet")      .append("g")      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")      .attr("class", "barchartg");      function sortBy(array, key) {      var sorted = array.sort(function(a, b) {        return parseFloat(b[key]) - parseFloat(a[key]);      });      return sorted;    }      var sortedMax = 45;         if (configurations) {          if (configurations[0]["maxValue"]) {        sortedMax = configurations[0]["maxValue"] + 5;       }    } else {            sortedMax = sortBy(data, "value")[0]["value"] + 5;     }      x.domain(data.map(function(d) {      return d.label;    }));      y.domain([0, sortedMax]);      svg.append("g")      .attr("class", "x axis")      .attr("transform", "translate(0," + height + ")")      .call(xAxis);      svg.selectAll(".x.axis text")      .attr("transform", "rotate(-60) translate(-5,-5)")      .style("text-anchor", "end");      svg.append("g")      .attr("class", "y axis")      .call(yAxis)      .append("text")      .attr("transform", "rotate(-90)")      .attr("y", 6)      .attr("dy", ".71em")      .style("text-anchor", "end")      .text("");      svg.selectAll(".bar")      .data(data)      .enter().append("rect")      .attr("class", "bar")      .attr("fill", function(d, i) {        return colores_google(i);      })      .attr("x", function(d) {        return x(d.label);      })      .attr("width", x.bandwidth())      .attr("y", function(d) {        return y(0);      })      .attr("height", function(d) {        return 0      });            d3.selectAll("rect").transition()      .duration(500)      .delay(function(d,i){ return 500*i;})      .attr("height",function(d){ return height - y(d.value);})      .attr("y",function(d){return y(d.value);});            setTimeout(function(){      d3.selectAll("rect").transition()      .duration(500)      .delay(function(d,i){ return 600*(3-i);})      .attr("height",function(d){ return 0;})      .attr("y",function(d){return y(0);});      },2000);        });
.barchart {    /*width:100%;  		border: 1px solid red;*/  }    .barchart svg {    width: 100%;    /*border: 1px solid green;*/  }    .barchartg {}    .barchart .axis path {    fill: none;    stroke: #000;    shape-rendering: crispEdges;  }    .barchart .axis line {    fill: none;    stroke: none;    shape-rendering: crispEdges;  }    .barchart .x.axis path {    display: none;  }    .barchart .axis text {    fill: #005a70;  }    .barchart.dark .axis text {    fill: #ffffff;  }    .barchart.dark .axis path {    stroke: #ffffff;  }    .barchart .bar:hover {    fill: #e9168a;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <script src="https://d3js.org/d3.v4.min.js"></script>        <div class="barchart" data-role="barchart" data-width=300 data-height=400 data-data="x" data-configurations="">  </div>

Answers 2

you need to add transition for each bar while generating and delay the transion according to your wish.the code is as.

.transition()   .delay(function (d,i){ return i * 300;})           .duration(250) 

the updated code with your code block is as follows

svg.selectAll(".bar")       .data(data)     .enter().append("rect")       .attr("class", "bar")    .transition()   .delay(function (d,i){ return i * 300;})           .duration(250)       .attr("fill", function(d, i) {          return colores_google(i);       })       .attr("x", function(d) {          return x(d.label);        })       .attr("width", x.bandwidth())       .attr("y", function(d) {          return y(d.value);        })       .attr("height", function(d) {          return height - y(d.value);        }) 
Read More