Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Thursday, December 29, 2016

Any advice for a developer given the task of enhancing & refactoring a business critical application?

Any advice for a developer given the task of enhancing & refactoring a business critical application?


Recently I inherited a business critical project at work to "enhance". The code has been worked on and passed through many hands over the past five years. Consultants and full-time employees who are no longer with the company have butchered this very delicate and overly sensitive application. Most of us have to deal with legacy code or this type of project... its part of being a developer... but...

There are zero units and zero system tests. Logic is inter-mingled (and sometimes duplicated for no reason) between stored procedures, views (yes, I said views) and code. Documentation? Yeah, right. I am scared. Yes, very sacred to make even the most minimal of "tweak" or refactor. One little mishap, and there would be major income loss and potential legal issues for my employer.

So, any advice? My first thought would be to begin writing assertions/unit tests against the existing code. However, that can only go so far because there is a lot of logic embedded in stored procedures. (I know its possible to test stored procedures, but historically its much more difficult compared to unit testing source code logic). Another or additional approach would be to compare the database state before and after the application has performed a function, make some code changes, then do database state compare.

Answer by Larry Watanabe for Any advice for a developer given the task of enhancing & refactoring a business critical application?


  1. Get a very firm list of requirements.

  2. Make sure you have implicit requirements as well as explicit ones - i.e. what programs it has to work with, and how.

  3. Write all scenarios and use cases for how it is currently being used.

  4. Write a lot of unit tests.

  5. Write a lot of integration tests to test the integration of the program with existing programs it has to work with.

  6. Talk to everyone who uses the program to find out more implicit requirements.

  7. Test, test, test changes before moving into production.

  8. CYA :)

Answer by cletus for Any advice for a developer given the task of enhancing & refactoring a business critical application?


Ask yourself this: what are you trying to achieve? What is your mission? How much time do you have? What is the measurement for success? What risks are there? How do you mitigate and deal with them?

Don't touch anything unless you know what it is you're trying to achieve.

The code might be "bad" but what does that mean? The code works right? So if you rewrite the code so it does the same thing you'll have spent a lot of time rewriting something introducing bugs along the way so the code does the same thing? To what end?

The simplest thing you can do is document what the system does. And I don't mean write mind-numbing Word documents no one will ever read. I mean writing tests on key functionality, refactoring the code if necessary to allow such tests to be written.

Answer by fupsduck for Any advice for a developer given the task of enhancing & refactoring a business critical application?


You said you are scared to touch the code because of legal, income loss and that there is zero documentation. So do you understand the code? The first thing you should do is document it and make sure you understand it before you even think about refactoring. Once you have done that and identified the problem areas make a list of your refactoring proposals in the order of maximum benefit with minimum changes and attack it incrementally. Refactoring makes additional sense if: the expected lifespan of the code will be long, new features will be added, bug fixes are numerous. As for testing the database state - I worked on a project recently where that is exactly what we did with success.

Answer by Sudhanshu for Any advice for a developer given the task of enhancing & refactoring a business critical application?


I just rewrote thousands of lines of the most complex subsystem of an enterprise filesystem to make it multi-threaded, so all of this comes from experience. If the rewrite is justified (it is if the rewrite is being done to significantly enhance capabilities, or if existing code is coming in the way of putting in more enhancements), then here are the pointers:

  1. You need to be confident in your own abilities first of all to do this. That comes only if you have enough prior experience with the technologies involved.

  2. Communicate, communicate, communicate. Let all involved stake-holders know, this is a mess, this is risky, this cannot be done in a hurry, this will need to be done piece-meal - attack one area at a time.

  3. Understand the system inside out. Document every nuance, trick and hack. Document the overall design. Ask any old-timers about historical reasons for the existence of any code you cannot justify. These are the mines you don't want to step on - you might think those are useless pieces of code and then regret later after getting rid of them.

  4. Unit test. Work the system through any test-suite which already exists, otherwise first write the tests for existing code, if they don't exist.

  5. Spew debugging code all over the place during the rewrite - asserts, logging, console prints (you should have the ability to turn them on and off, as well specify different levels of output i.e. control verbosity). This is a must in my experience, and helps tremendously during a rewrite.

  6. When going through the code, make a list of all things that need to be done - things you need to find out, things you need to write tests for, things you need to ask questions about, notes to remind you how to refactor some piece of code, anything that can affect your rewrite... you cannot afford to forget anything! I do this using Outlook Tasks (just make sure whatever you use is always in front of you - this is the first app I open as soon as I sit down on the desk). If I get interrupted, I write down anything that I have been thinking about and hints about where to continue after coming back to the task.

  7. Try avoiding hacks in your rewrite (that's one of the reasons you are rewriting it). Think about tough problems you encounter. Discuss them with other people and bounce off your ideas against them (nothing beats this), and put in clean solutions. Look at all the tasks you put into the todo list - make a 10,000 feet picture of existing design, then decide how the new rewrite would look like (in terms of modules, sub-modules, how they fit together etc.).

  8. Tackle the toughest problems before any other. That'll save you from running into problems you cannot solve near the end of tunnel, and save you from taking any steps backward. Of course, you need to know what the toughest problems will be - so again, better document everything first during your forays into existing code.

Answer by Carl Manaster for Any advice for a developer given the task of enhancing & refactoring a business critical application?


Two things, beyond @Sudhanshu's great list (and, to some extent, disagreeing with his #8):

First, be aware that untested code is buggy code - what you are starting with almost certainly does not work correctly, for any definition of "correct" other than "works just like the unmodified code". That is, be prepared to find unexpected behavior in the system, to ask experts in the system about that behavior, and for them to conclude that it's not working the way it should. Prepare them for it to - warn them that without tests or other documentation, there's no reason to think it works they way they think it's working.

Next: Refactor The Low-Hanging Fruit Take it easy, take it slow, take it very careful. Notice something easy in the code - duplication, say - and test the hell out of whatever methods contain the duplication, then eliminate it. Lather, rinse, repeat. Don't write tests for everything before making changes, but write tests for whatever you're changing. This way, it stays releasable at every stage and you are continuously adding value, continuously improving the code base.

I said "two things", but I guess I'll add a third: Manage expectations. Let your customer know how scared you are of this task; let them know how bad what they've got is. Let them know how slow progress will be, and let them know you'll keep them informed of that progress (and, of course, do it). Your customer may think s/he's asking for "just a little fix" - and the functionality may indeed change only a little - but that doesn't mean it's not going to be a lot of work and a lot of time. You understand that; your customer needs to, too.

Answer by Noufal Ibrahim for Any advice for a developer given the task of enhancing & refactoring a business critical application?


I've had this problem before and I've asked around (before the days of stack overflow) and this book has always been recommended to me. http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052

Answer by JB King for Any advice for a developer given the task of enhancing & refactoring a business critical application?


Is it possible to get a separation of the DB and non-DB parts, so that a DBA can take on the challenge of the stored procedures and databases themselves freeing you up to work on the other parts of the system? This also presumes that there is a DBA who can step up and take that part of the application.

If that isn't possible, then I'd make the suggestion of seeing how big is the codebase and if it is possible to get some assistance so it isn't all on you. While this could be seen as side-stepping responsibility, the point would be that things shouldn't be in just one person's hands usually as they can disappear at times.

Good luck!


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

C++ is it possible to NOT inherit a member?

C++ is it possible to NOT inherit a member?


I am pretty sure it isn't but I am going to ask anyway...
Here's an example: let's say I have a class called Elipse:

class Elipse  {  private:    double d_m_lAxis; // the length of the large Axis of the elipse    double d_m_sAxis; // short axis  //Point is a struct of 2 doubles (x and y)    Point P_m_focal1; //focal point 1    Point P_m_focal2; //focal point 2  protected:    Point P_m_center;     public:    Elipse(Point _P_lowerLeft,Point _L_upperRight)    {      //draw elipse in a rectangle, just like in paint    }  }  

Now I want to inherit Circle from Elipse (because Circle is an Elipse with both Axis of the same length):

class Circle : public Elipse     {  private:    double d_m_radius;  public:    Circle(Point _P_lowerLeft,double _d_diameter) :      Elipse(_P_lowerLeft,/*get the upper ight*/        Point(_P_lowerLeft.x + _d_diameter,_P_lowerLeft.y + _d_diameter))        {          // draw a circle in a square, just like in paint        }  }  

So now I got the class I wanted and it doesn't have the access to any of the private members of the Elipse which would become redundant in Circle.
However, as far as I know these members are still inherited and the child class simply does not have access to them. This makes the class unnecessarily large in size and it is also possible to access those members via functions inherited from Elipse, unless they are overriden.

Is there a way to not inherit a member at all?

Answer by Maciej Baranowski for C++ is it possible to NOT inherit a member?


What you're trying to achive with this inheritance violates Liskov Substitution principle. In fact in your case Ellipse should not be a base for Circle. See more details e.g. on wikipedia:

https://en.wikipedia.org/wiki/Liskov_substitution_principle#A_typical_violation - here it is explained based on very similar example (rectangle and square)

Answer by Webert S. Lima for C++ is it possible to NOT inherit a member?


A circle is a particular case of elipse, not a subtype of it, so you wouldn't need to do this. Instead, just initialize your elipse with same value for any axis.

About the inheritance, private, protected members are there for this purpose. They like private that will be inherited. The class won't be large because of the base class private members. The compiler will optimize the final code.

Answer by WhiZTiM for C++ is it possible to NOT inherit a member?


This makes the class unnecessarily large in size and it is also possible to access those members via functions inherited from Elipse, unless they are overriden. Is there a way to NOT inherit a member at all?

Though, you may want to rethink your design, You could take advantage of EBO (empty base class optimization), there will be no size overhead.

Have an empty type like:

class EllipticalType {};  

Then define your Ellipse like

class Elipse : public EllipticalType  {  private:    double d_m_lAxis; // the length of the large Axis of the elipse    double d_m_sAxis; // short axis  //Point is a struct of 2 doubles (x and y)    Point P_m_focal1; //focal point 1    Point P_m_focal2; //focal point 2  protected:    Point P_m_center;     public:    Elipse(Point _P_lowerLeft,Point _L_upperRight)    {      //draw elipse in a rectangle, just like in paint    }  }  

Then you do:

class Circle : public EllipticalType  {            private:              double d_m_radius;            public:      Circle(Point _P_lowerLeft,double _d_diameter) : Elipse(_P_lowerLeft,/*get the upper right*/Point(_P_lowerLeft.x + _d_diameter,_P_lowerLeft.y + _d_diameter))          {          // draw a circle in a square, just like in paint          }    }  

You can also extract common members and put them into EllipticalType

Answer by Yakk for C++ is it possible to NOT inherit a member?


No. You cannot. Inheritance in C++ implies a certain level of binary compatibility in practice.

A workaround follows. But first:

A circle is not an ellipse.

To be more precise, a mutable circle is not a mutable ellipse in many useful ways. There are operations you can perform on a mutable ellipse whose postconditions do not align with the same operations on a mutable circle.

For example, suppose there is get/set major/minor axis. A reasonable postcondition on set major axis is that get minor axis remains unchanges on a mutable ellipse. While you can have set major/minor axis on a circle, that postcondition cannot hold!

Now, an immutable circle is an immutable ellipse. It is only once you start editing it does the covariant/contravariant problem occur. This problem is not limited to rectangle/square, ellipse/circle, automobile/truck style "toy" OO; an editable list of Derived is not an editable list of Base either in the same way. An editable list of Base accepts any Base type; the same is not true of a list of Derived.

On the other hand, an immitable list of Derived is an immutable list of Base.


Going back to your original question, inheriting the implementations like that may be unwise. However, you could split data from logic from interface.

Then inherit interface and logic while leaving data unassociated.

In C++ this can be done with templates and CRTP. If you do not know CRTP the following will be arcane and unreadable. I do not guarantee the countrapositive.

template  struct ellipse_math {    Self* self(){ return static_cast(this);}    Self const* self() const { return static_cast(this);}      double get_area() const { /* math using self()->get_major() and self()->get_minor(); */ }  };  struct circle_state {    double m_radius;    double get_major() const;    double get_minor() const;    double get_radius() const;  };  struct ellipse_state {    double m_major, m_minor;    double get_major() const;    double get_minor() const;  };  struct I_ellipse {    virtual double major()const=0;    virtual double minor()const=0;    cirtual double area()const=0;    virtual ~I_ellipse(){};  };  struct I_circle:I_ellipse {    virtual double radius()const=0;  };  template  struct impl_I_ellipse : I  {    Self* self(){ return static_cast(this);}    Self const* self() const { return static_cast(this);}    virtual double major()const final override { return self()->get_major(); }    virtual double minor()const final override { return self()->get_minor(); }    virtual double area()const final override { return self()->get_area(); }  };  template  struct impl_I_circle : impl_I_ellipse {    Self* self(){ return static_cast(this);}    Self const* self() const { return static_cast(this);}    virtual double radius()const final override { return self()->get_radius(); }  };    struct ellipse :    ellipse_state,    impl_I_ellpise,    ellpise_math  {};  struct circle  :    circle_state,    impl_I_circle,    ellpise_math  {};  

This is pretty ridiculous in this simple case, but I did avoid having unused ellipse fields in my circle implementation, and got to reuse the ellpise logic.

The above was typed on a phone, so probably contains tpyos.

Honestly if I was going this far, I'd go all the way to SBO type erasure of ellipse-like and circle-like objects using free functions for dispatch. Because the inheritance above and vtable are getting in the way more than they are helpimg.

Answer by StoryTeller for C++ is it possible to NOT inherit a member?


The mathematical phrasing "a circle is an ellipse where [...]" should be rephrased to the more type aware "For every circle, there exists an ellipse where [...], that describes the same set of points".

With that in mind, your implementation should allow the creation of Ellipse objects from Circle objects, but not polymorphic substitution.
One such possibility, is an explicit conversion operator:

class Elipse  {    // as you defined  };    class Circle  {    // As you defined    explicit operator Ellipse()    {      Point lower_left, upper_right;      // calculate the two points      return Ellipse(lower_left, upper_right);    }  };  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Saturday, December 24, 2016

AngularJS - Directive template dynamic

AngularJS - Directive template dynamic


How can I create a directive with a dynamic template?

'use strict';    app.directive('ngFormField', function($compile) {  return {      transclude: true,      scope: {          label: '@'      },      template: '',      // append      replace: true,      // attribute restriction      restrict: 'E',      // linking method      link: function($scope, element, attrs) {          switch (attrs['type']) {              case "text":                  // append input field to "template"              case "select":                  // append select dropdown to "template"          }      }    }  });  
  

This is what I have right now, and it is displaying the label correctly. However, I'm not sure on how to append additional HTML to the template. Or combining 2 templates into 1.

Answer by kwon for AngularJS - Directive template dynamic


Had a similar need. $compile does the job. (Not completely sure if this is "THE" way to do it, still working my way through angular)

http://jsbin.com/ebuhuv/7/edit - my exploration test.

One thing to note (per my example), one of my requirements was that the template would change based on a type attribute once you clicked save, and the templates were very different. So though, you get the data binding, if need a new template in there, you will have to recompile.

Answer by zim for AngularJS - Directive template dynamic


i've used the $templateCache to accomplish something similar. i put several ng-templates in a single html file, which i reference using the directive's templateUrl. that ensures the html is available to the template cache. then i can simply select by id to get the ng-template i want.

template.html:

      

directive:

myapp.directive(?foobardirective?, ['$compile', '$templateCache', function ($compile, $templateCache) {        var getTemplate = function(data) {          // use data to determine which template to use          var templateid = 'foo';          var template = $templateCache.get(templateid);          return template;      }        return {          templateUrl: 'views/partials/template.html',          scope: {data: '='},          restrict: 'E',          link: function(scope, element) {              var template = getTemplate(scope.data);                element.html(template);              $compile(element.contents())(scope);          }      };  }]);  

Answer by nakosung for AngularJS - Directive template dynamic


I managed to deal with this problem. Below is the link :

https://github.com/nakosung/ng-dynamic-template-example

with the specific file being:

https://github.com/nakosung/ng-dynamic-template-example/blob/master/src/main.coffee

dynamicTemplate directive hosts dynamic template which is passed within scope and hosted element acts like other native angular elements.

scope.template = '< div ng-controller="SomeUberCtrl">rocks< /div>'  

Answer by Aquajet for AngularJS - Directive template dynamic


You should move your switch into the template by using the 'ng-switch' directive:

module.directive('testForm', function() {      return {          restrict: 'E',          controllerAs: 'form',          controller: function ($scope) {              console.log("Form controller initialization");              var self = this;              this.fields = {};              this.addField = function(field) {                  console.log("New field: ", field);                  self.fields[field.name] = field;              };          }      }  });    module.directive('formField', function () {      return {          require: "^testForm",          template:              '
' + ' {{title}}:' + ' ' + ' ' + ' ' + ' ' + '
', restrict: 'E', replace: true, scope: { fieldType: "@", title: "@", name: "@", value: "@", options: "=", }, link: function($scope, $element, $attrs, form) { $scope.field = $scope; form.addField($scope); } }; });

It can be use like this:

      
User '{{!form.fields.email.value}}' will be a {{!form.fields.role.value}}

Answer by Hazarapet Tunanyan for AngularJS - Directive template dynamic


If you want to use AngularJs Directive with dynamic template, you can use those answers,But here is more professional and legal syntax of it.You can use templateUrl not only with single value.You can use it as a function,which returns a value as url.That function has some arguments,which you can use.

http://www.w3docs.com/snippets/angularjs/dynamically-change-template-url-in-angularjs-directives.html

Answer by felix at housecat for AngularJS - Directive template dynamic


I have been in the same situation, my complete solution has been posted here

Basically I load a template in the directive in this way

var tpl = '' +       
' + '
';

then according to the value of maxLength and required I can dynamically load one of the 2 templates, only one of them at a time is shown if necessary.

I heope it helps.

Answer by user2173353 for AngularJS - Directive template dynamic


One way is using a template function in your directive:

...  template: function(tElem, tAttrs){      return '
'; } ...


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

How to test a prop update on React component

How to test a prop update on React component


What is the correct way of unit testing a React component prop update.

Here is my test fixture;

describe('updating the value', function(){          var component;          beforeEach(function(){              component = TestUtils.renderIntoDocument();          });            it('should update the state of the component when the value prop is changed', function(){              // Act              component.props.value = false;              component.forceUpdate();              // Assert              expect(component.state.value).toBe(false);          });  });  

This works fine and the test passes, however this displays a react warning message

'Warning: Dont set .props.value of the React component . Instead specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.'  

All i want to test is the update of a property, not to create a new instance of the element with a different property. Is there a better way to do this property update?

Answer by arkoak for How to test a prop update on React component


props are basically meant to be static values which are constant. That does not mean that properties will remain static and do not effect state indirectly

However SetState is preffered to be used for variable values that also impact the way how and when the component renders . The component itself does not re-render and thus does not update if prop is changed in normal conditions.

Instead you should use

this.setState({value: false});  

This will trigger all sub-actions including render as would a user-interaction would in a live environment.

Answer by Alexandre Kirszenberg for How to test a prop update on React component


If you re-render the element with different props in the same container node, it will be updated instead of re-mounted. See React.render.

In your case, you should use ReactDOM.render directly instead of TestUtils.renderIntoDocument. The later creates a new container node every time it is called, and thus a new component too.

var node, component;  beforeEach(function(){      node = document.createElement('div');      component = ReactDOM.render(, node);  });    it('should update the state of the component when the value prop is changed', function(){      // `component` will be updated instead of remounted      ReactDOM.render(, node);      // Assert that `component` has updated its state in response to a prop change      expect(component.state.value).toBe(false);  });  

Answer by David Gilbertson for How to test a prop update on React component


Caveat: this won't actually change props.

But for me, all I wanted was to test my logic in componentWillReceiveProps. So I'm calling myComponent.componentWillReceiveProps(/*new props*/) directly.

I didn't need/want to test that React calls the method when props change, or that React sets props when props change, just that some animation is triggered if the props differ to what was passed in.

Answer by user1095118 for How to test a prop update on React component


AirBnB's Enzyme library provides and elegant solution to this question.

it provides a setProps method, that can be called on either a shallow or jsdom wrapper.

    it("Component should call componentWillReceiveProps on update", () => {          const spy = sinon.spy(Component.prototype, "componentWillReceiveProps");          const wrapper = shallow();            expect(spy.calledOnce).to.equal(false);          wrapper.setProps({ prop: 2 });          expect(spy.calledOnce).to.equal(true);      });  

Answer by kidney for How to test a prop update on React component


This is an older question, but in case anyone else stumbles upon this, the following setup has worked for me nicely:

it('updates component on property update', () => {      let TestParent = React.createClass({          getInitialState() {              return {value: true};          },          render() {              return ;          }      });      component = TestUtils.renderIntoDocument();      component.setState({value: false});      // Verification code follows  });  

This makes React run the usual component update.

Answer by Yaniv Efraim for How to test a prop update on React component


Both TestUtils.renderIntoDocument and ReactDOM.render uses the returned value from ReactDOM.render. According to React docs:

ReactDOM.render() currently returns a reference to the root ReactComponent instance. However, using this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root ReactComponent instance, the preferred solution is to attach a callback ref to the root element

What if we take this advise and do something like this:

let component, node;    const renderComponent = (props = {}) => {    ReactDOM.render( component = r} {...props} />, node);  }    beforeEach(function(){      node = document.createElement('div');      renderComponent({value: true}, node);   });    it('should update the state of the component when the value prop is changed', function(){      // `component` will be updated instead of remounted      renderComponent({value: false}, node);       // Assert that `component` has updated its state in response to a prop change      expect(component.state.value).toBe(false);  });  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

JSON reply converted to Array shows no output when printed in PHP

JSON reply converted to Array shows no output when printed in PHP


This is the JSON reply I get for a query I make with an API for Flipkart. I wanted to print the productId and title from the API reply in search listing page I'm designing.

{     "productInfoList":[        {           "productBaseInfo":{              "productIdentifier":{                 "productId":"MOBE89M7BPKYHZGX",                 "categoryPaths":{                    "categoryPath":[                       [                          {                             "title":"Mobiles>Handsets"                          }                       ]                    ]                 }              },              "productAttributes":{                 "title":"Sony Xperia C4 Dual",                 "productDescription":"Are you a selfie fan? If yes, then grab this exceptional Sony Xperia C4 Dual smartphone which has been designed to click the best PROselfies. Apart from an amazing front and rear camera, this Full HD smartphone offers maximum performance and speed. All You Need For PROselfies For all selfie lovers, the 5 MP front camera of this Sony device is equipped with a soft LED flash, 25 mm wide-angle lens and other features to click the best PROselfies. Exmor R sensor ensures sharp pictures with low noise. HDR balances bright background lights for clearer results. SteadyShot lets you shoot amazing selfie videos. Unique Soft LED Flash The unique soft LED flash automatically adjusts according to the lighting conditions, illuminates the scene and gives you the perfect shot. Whether there is a bright backlight or you are taking photos at night, the Superior Auto feature ensures that your selfies and group selfies are of professional quality. 25 mm Wide View Thanks to the 25 mm wide-angle lens with an 80-degree field of view, you can fit in more of your friends or more of the view in a single shot. Main Camera This Sony Xperia smartphone is equipped with a 13 MP primary shooter. Exmor RS For Mobile This image sensor technology assures sharp photos and videos with fine detailing, amazing picture clarity and rich colors, even while shooting in challenging light conditions. Superior Auto The Superior Auto feature recognises up to 52 different scenarios such as illuminated night shots and close-up macros. This intelligent feature adjusts the settings according to the scene, so you get noteworthy photos always. HDR For Photo & Video HDR mode shoots the same image multiple times under different exposures and layers them, so that you get clear and bright photos and videos. This feature is extremely useful while capturing photos or videos in strong backlight or high-contrast situations. SteadyShot Thanks to SteadyShot, every video you shoot with this Xperia smartphone is smooth, steady and perfect. Sound Photo Relive you favourite moments with sound and visuals. Capture up to 10 seconds of audio with your photos using Sound Photo app and share it via PlayMemories Online. AR Mask Replace your own face or other people's faces with a different face using the AR Mask app. You can choose from the pre-loaded faces or create your own collection. Style Portrait This app lets you select from different styles to enhance your photos or add fun effects to them. These effects can be applied in real-time or after taking the photo or video. Download More Apps Apart from the pre-installed apps, you can download more camera apps directly from the camera interface of this Xperia smartphone. Display The large 13.97 cm (5.5) Full HD display and Mobile Bravia Engine 2 make the Xperia C4 an ideal device for watching movies and playing games. The IPS technology allows excellent viewing from all angles, so you and your friends can enjoy a movie on this device while chilling out in the college cafeteria. Sound Equipped with a speaker capable of up to 97 decibels and ClearAudio+ technologies for crystal clear audio, you can pump up your home get-togethers with loud music. This Xperia device delivers rich bass, thanks to the xLoud loudness enhancement engine. Design Despite the large screen size, the Xperia C4 is sleek, lightweight and easily slides into your jeans pocket or wallet. The device is 7.9 mm thin and weighs just 147 grams. Processor Play games lag-free, run multiple apps simultaneously, surf the web seamlessly and stream HD videos without glitches. The competent 1.7 GHz Octa Core processor and 2 GB RAM offers maximum performance in everything you do on your Xperia smartphone. The phone also comes with a built-in LTE/4G modem for extremely fast internet connectivity. Battery An incredibly powerful yet efficient 2600 mAh battery powers this Xperia phone. To further extend the already long battery life, this device offers four power management modes - Battery STAMINA mode, Extended standby mode, Extended usage mode and Ultra STAMINA mode.",                 "imageUrls":{                    "400x400":"http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-400x400-imae8dsymwzxb6u2.jpeg",                    "200x200":"http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-200x200-imae8dsymwzxb6u2.jpeg",                    "unknown":"http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-original-imae8dsymwzxb6u2.jpeg",                    "800x800":"http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-800x800-imae8dsymwzxb6u2.jpeg"                 },                 "maximumRetailPrice":{                    "amount":29490.0,                    "currency":"INR"                 },                 "sellingPrice":{                    "amount":19699.0,                    "currency":"INR"                 },                 "productUrl":"http://dl.flipkart.com/dl/sony-xperia-c4-dual/p/itme9gw2xxxgd9wy?pid=MOBE89M7BPKYHZGX&affid=admintechz",                 "productBrand":"Sony",                 "inStock":true,                 "isAvailable":true,                 "codAvailable":true,                 "emiAvailable":null,                 "discountPercentage":33.0,                 "cashBack":null,                 "offers":[                   ],                 "size":null,                 "color":"Black",                 "sizeUnit":"",                 "sizeVariants":"[MOBE89M8BXKKYMBP, MOBE89M8Y4RN9NHT, MOBE89M7BPKYHZGX]",                 "colorVariants":"[MOBE89M8BXKKYMBP, MOBE89M8Y4RN9NHT]",                 "styleCode":null              }           },           "productShippingBaseInfo":{              "shippingOptions":null           },           "offset":null        }     ]  }  

This is the php code I use to print the elements in the Array. But I don't seem to get any output.

$response is the reply I get from the API.

$array = json_decode($response, true);  $test1 = $array['productAttributes']['title'];  $test2 = $array['productInfoList']['productBaseInfo']['productIdentifier']['productId'];        echo $test1;      echo test2;  

debug -

Array ( [productInfoList] => Array ( [0] => Array ( [productBaseInfo] => Array ( [productIdentifier] => Array ( [productId] => MOBE89M7BPKYHZGX [categoryPaths] => Array ( [categoryPath] => Array ( [0] => Array ( [0] => Array ( [title] => Mobiles>Handsets ) ) ) ) ) [productAttributes] => Array ( [title] => Sony Xperia C4 Dual [productDescription] => Are you a selfie fan? If yes, then grab this exceptional Sony Xperia C4 Dual smartphone which has been designed to click the best PROselfies. Apart from an amazing front and rear camera, this Full HD smartphone offers maximum performance and speed. All You Need For PROselfies For all selfie lovers, the 5 MP front camera of this Sony device is equipped with a soft LED flash, 25 mm wide-angle lens and other features to click the best PROselfies. Exmor R sensor ensures sharp pictures with low noise. HDR balances bright background lights for clearer results. SteadyShot lets you shoot amazing selfie videos. Unique Soft LED Flash The unique soft LED flash automatically adjusts according to the lighting conditions, illuminates the scene and gives you the perfect shot. Whether there is a bright backlight or you are taking photos at night, the Superior Auto feature ensures that your selfies and group selfies are of professional quality. 25 mm Wide View Thanks to the 25 mm wide-angle lens with an 80-degree field of view, you can fit in more of your friends or more of the view in a single shot. Main Camera This Sony Xperia smartphone is equipped with a 13 MP primary shooter. Exmor RS For Mobile This image sensor technology assures sharp photos and videos with fine detailing, amazing picture clarity and rich colors, even while shooting in challenging light conditions. Superior Auto The Superior Auto feature recognises up to 52 different scenarios such as illuminated night shots and close-up macros. This intelligent feature adjusts the settings according to the scene, so you get noteworthy photos always. HDR For Photo & Video HDR mode shoots the same image multiple times under different exposures and layers them, so that you get clear and bright photos and videos. This feature is extremely useful while capturing photos or videos in strong backlight or high-contrast situations. SteadyShot Thanks to SteadyShot, every video you shoot with this Xperia smartphone is smooth, steady and perfect. Sound Photo Relive you favourite moments with sound and visuals. Capture up to 10 seconds of audio with your photos using Sound Photo app and share it via PlayMemories Online. AR Mask Replace your own face or other people's faces with a different face using the AR Mask app. You can choose from the pre-loaded faces or create your own collection. Style Portrait This app lets you select from different styles to enhance your photos or add fun effects to them. These effects can be applied in real-time or after taking the photo or video. Download More Apps Apart from the pre-installed apps, you can download more camera apps directly from the camera interface of this Xperia smartphone. Display The large 13.97 cm (5.5) Full HD display and Mobile Bravia Engine 2 make the Xperia C4 an ideal device for watching movies and playing games. The IPS technology allows excellent viewing from all angles, so you and your friends can enjoy a movie on this device while chilling out in the college cafeteria. Sound Equipped with a speaker capable of up to 97 decibels and ClearAudio+ technologies for crystal clear audio, you can pump up your home get-togethers with loud music. This Xperia device delivers rich bass, thanks to the xLoud loudness enhancement engine. Design Despite the large screen size, the Xperia C4 is sleek, lightweight and easily slides into your jeans pocket or wallet. The device is 7.9 mm thin and weighs just 147 grams. Processor Play games lag-free, run multiple apps simultaneously, surf the web seamlessly and stream HD videos without glitches. The competent 1.7 GHz Octa Core processor and 2 GB RAM offers maximum performance in everything you do on your Xperia smartphone. The phone also comes with a built-in LTE/4G modem for extremely fast internet connectivity. Battery An incredibly powerful yet efficient 2600 mAh battery powers this Xperia phone. To further extend the already long battery life, this device offers four power management modes - Battery STAMINA mode, Extended standby mode, Extended usage mode and Ultra STAMINA mode. [imageUrls] => Array ( [400x400] => http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-400x400-imae8dsymwzxb6u2.jpeg [200x200] => http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-200x200-imae8dsymwzxb6u2.jpeg [unknown] => http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-original-imae8dsymwzxb6u2.jpeg [800x800] => http://img.fkcdn.com/image/mobile/z/g/x/sony-xperia-c4-dual-na-800x800-imae8dsymwzxb6u2.jpeg ) [maximumRetailPrice] => Array ( [amount] => 29490 [currency] => INR ) [sellingPrice] => Array ( [amount] => 19699 [currency] => INR ) [productUrl] => http://dl.flipkart.com/dl/sony-xperia-c4-dual/p/itme9gw2xxxgd9wy?pid=MOBE89M7BPKYHZGX&affid=admintechz [productBrand] => Sony [inStock] => 1 [isAvailable] => 1 [codAvailable] => 1 [emiAvailable] => [discountPercentage] => 33 [cashBack] => [offers] => Array ( ) [size] => [color] => Black [sizeUnit] => [sizeVariants] => [MOBE89M8BXKKYMBP, MOBE89M8Y4RN9NHT, MOBE89M7BPKYHZGX] [colorVariants] => [MOBE89M8BXKKYMBP, MOBE89M8Y4RN9NHT] [styleCode] => ) ) [productShippingBaseInfo] => Array ( [shippingOptions] => ) [offset] => ) ) )  

Answer by T.J. Crowder for JSON reply converted to Array shows no output when printed in PHP


Look closely at the JSON, and you'll see that productInfoList is an object with a property called productBaseInfo whose value is an array of objects (e.g., [....], although it only has one entry), each of which has properties like productBaseInfo.

So to see the first (only) entry's productBaseInfo.productIdentifier.productId, you'd want:

$test2 = $array['productInfoList'][0]['productBaseInfo']['productIdentifier']['productId'];  // Note --------------------------^^^  

Answer by Kroonal for JSON reply converted to Array shows no output when printed in PHP


Use below code. It gives you title and ProductID $array = json_decode($string, true);

$test1 = $array['productInfoList'][0]['productBaseInfo']['productAttributes']['title']; $test2 = $array['productInfoList'][0]['productBaseInfo']['productIdentifier']['productId'];

echo $test1;  echo $test2;  

Answer by Ghulam Ali for JSON reply converted to Array shows no output when printed in PHP


In JSON { denotes and Object and [ denotes an Array. To get all the Attributes you can use something like this:

$array = json_decode($response, true);  $productInfoList_Array = $array['productInfoList'];  foreach($productInfoList_Array as $productInfoList){      $productBaseInfo = $productInfoList['productBaseInfo'];      $productAttributes = $productBaseInfo['productAttributes'];      foreach($productAttributes as $Attribute_Key => $Attribute_Value){          if (!is_array($Attribute_Value)){              //Attribute Value is not an array.              echo "{$Attribute_Key}: {$Attribute_Value}";              echo "
"; }else{ //Attribute Value is a sub array foreach($Attribute_Value as $Attribute_Sub_Key => $Attribute_Sub_Value){ echo "Sub Key: {$Attribute_Sub_Key}: {$Attribute_Sub_Value}"; echo "
"; } } } echo "
End of Product."; }

See that productAttributes has sub array also.

Answer by Vincent for JSON reply converted to Array shows no output when printed in PHP


You should first loop through the array values(decoded from json), and then fetch the needed data accordingly, do something like this -

$array = json_decode($r, true);  // print_r($array); //debug  foreach($array['productInfoList'] as $product){     echo  $product['productBaseInfo']['productAttributes']['title'];     echo $product['productBaseInfo']['productIdentifier']['productId'];  }  

Answer by Karthik for JSON reply converted to Array shows no output when printed in PHP


Remove all single quote. Try this.

             print_r($array['productInfoList'][0]['productBaseInfo']['productIdentifier']);       print_r($array['productInfoList'][0]['productBaseInfo']['productAttributes']['title']);      ?>  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Sunday, December 11, 2016

Assembly Performance Tuning

Assembly Performance Tuning


I am writing a compiler (more for fun than anything else), but I want to try to make it as efficient as possible. For example I was told that on Intel architecture the use of any register other than EAX for performing math incurs a cost (presumably because it swaps into EAX to do the actual piece of math). Here is at least one source that states the possibility (http://www.swansontec.com/sregisters.html).

I would like to verify and measure these differences in performance characteristics. Thus, I have written this program in C++:

#include "stdafx.h"  #include   #include     using namespace std;    int _tmain(int argc, _TCHAR* argv[])  {      __int64 startval;      __int64 stopval;      unsigned int value; // Keep the value to keep from it being optomized out        startval = __rdtsc(); // Get the CPU Tick Counter using assembly RDTSC opcode        // Simple Math: a = (a << 3) + 0x0054E9      _asm {          mov ebx, 0x1E532 // Seed          shl ebx, 3          add ebx, 0x0054E9          mov value, ebx      }        stopval = __rdtsc();      __int64 val = (stopval - startval);      cout << "Result: " << value << " -> " << val << endl;        int i;      cin >> i;        return 0;  }  

I tried this code swapping eax and ebx but I'm not getting a "stable" number. I would hope that the test would be deterministic (the same number every time) because it's so short that it's unlikely a context switch is occurring during the test. As it stands there is no statistical difference but the number fluctuates so wildly that it would be impossible to make that determination. Even if I take a large number of samples the number is still impossibly varied.

I'd also like to test xor eax, eax vs mov eax, 0, but have the same problem.

Is there any way to do these kinds of performance tests on Windows (or anywhere else)? When I used to program Z80 for my TI-Calc I had a tool where I could select some assembly and it would tell me how many clock cycles to execute the code -- can that not be done with our new-fangeled modern processors?

EDIT: There are a lot of answers indicating to run the loop a million times. To clarify, this actually makes things worse. The CPU is much more likely to context switch and the test becomes about everything but what I am testing.

Answer by Bo Persson for Assembly Performance Tuning


The Z80, and possibly the TI, had the advantage of synchronized memory access, no caches, and in-order execution of the instructions. That made it a lot easier to calculate to number of clocks per instruction.

On current x86 CPUs, instructions using AX or EAX are not faster per se, but some instructions might be shorter than the instructions using other registers. That might just save a byte in the instruction cache!

Answer by ybungalobill for Assembly Performance Tuning


Go here and download the Architectures Optimization Reference Manual.

There are many myths. I think the EAX claim is one of them.

Also note that you can't talk anymore about 'which instruction is faster'. On today's hardware there are no 1 to 1 relation between instructions and execution time. Some instructions are preferred to others not because they are 'faster' but because they break dependencies between other instructions.

Answer by 500 - Internal Server Error for Assembly Performance Tuning


I believe that if there's a difference nowadays it will only be because some of the legacy instructions have a shorter encoding for the variant that uses EAX. To test this, repeat your test case a million times or more before you compare cycle counts.

Answer by Bjarke H. Roune for Assembly Performance Tuning


Starting your program is going to take much longer than running 4 assembly instructions once, so any difference from your assembly will drown in the noise. Running the program many times won't help, but it would probably help if you run the 4 assembly instructions inside a loop, say, a million times. That way the program start-up happens only once.

There can still be variation. One especially annoying thing that I've experienced myself is that your CPU might have a feature like Intel's Turbo Boost where it will dynamically adjust it's speed based on things like the temperature of your CPU. This is more likely to be the case on a laptop. If you've got that, then you will have to turn it off for any benchmark results to be reliable.

Answer by ninjalj for Assembly Performance Tuning


I think what the article tries to say about the EAX register, is that since some operations can only be performed on EAX, it's better to use it from the start. This was very true with the 8086 (MUL comes to mind), but the 386 made the ISA much more orthogonal, so it's much less true these days.

Answer by Jerry Coffin for Assembly Performance Tuning


To even have a hope of repeatable, determinstic timing at the level that RDTSC gives, you need to take some extra steps. First, RDTSC is not a serializing instruction, so it can be executed out of order, which will usually render it meaningless in a snippet like the one above.

You normally want to use a serializing instruction, then your RDTSC, then the code in question, another serializing instruction, and the second RDTSC.

Nearly the only serializing instruction available in user mode is CPUID. That, however, adds one more minor wrinkle: CPUID is documented by Intel as requiring varying amounts of time to execute -- the first couple of executions can be slower than others.

As such, the normal timing sequence for your code would be something like this:

XOR EAX, EAX  CPUID  XOR EAX, EAX  CPUID  XOR EAX, EAX  CPUID            ; Intel says by the third execution, the timing will be stable.  RDTSC            ; read the clock  push eax         ; save the start time  push edx        mov ebx, 0x1E532 // Seed // execute test sequence      shl ebx, 3      add ebx, 0x0054E9      mov value, ebx    XOR EAX, EAX      ; serialize  CPUID     rdtsc             ; get end time  pop ecx           ; get start time back  pop ebp  sub eax, ebp      ; find end-start  sbb edx, ecx  

We're starting to get close, but there's on last point that's difficult to deal with using inline code on most compilers: there can also be some effects from crossing cache lines, so you normally want to force your code to be aligned to a 16-byte (paragraph) boundary. Any decent assembler will support that, but inline assembly in a compiler usually won't.

Having said all that, I think you're wasting your time. As you can guess, I've done a fair amount of timing at this level, and I'm quite certain what you've heard is an outright myth. In reality, all recent x86 CPUs use a set of what are called "rename registers". To make a long story short, this means the name you use for a register doesn't really matter much -- the CPU has a much larger set of registers (e.g., around 40 for Intel) that it uses for the actual operations, so your putting a value in EBX vs. EAX has little effect on the register that the CPU is really going to use internally. Either could be mapped to any rename register, depending primarily on which rename registers happen to be free when that instruction sequence starts.

Answer by zwol for Assembly Performance Tuning


You're getting ridiculous variance because rdtsc does not serialize execution. Depending on inaccessible details of the execution state, the instructions you're trying to benchmark may in fact be executed entirely before or after the interval between the rdtsc instructions! You will probably get better results if you insert a serializing instruction (such as cpuid) immediately after the first rdtsc and immediately before the second. See this Intel tech note (PDF) for gory details.

Answer by Matthew Slattery for Assembly Performance Tuning


I'd suggest taking a look at Agner Fog's "Software optimization resources" - in particular, the assembly and microarchitecture manuals (2 and 3), and the test code, which includes a rather more sophisticated framework for measurements using the performance monitor counters.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Saturday, December 10, 2016

Spanned columns collapsing on Android web-browser (when using auto-fit pages)

Spanned columns collapsing on Android web-browser (when using auto-fit pages)


Update: I've logged a bug report with Google - http://code.google.com/p/android/issues/detail?id=22447&can=4&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars


Update: @benni_mac_b points out that the problem goes away if you disable auto-fit pages. This 'solution' works on 2.1 and 2.2 - turns out that the 2.3 phone I was testing on had disabled auto-fit to start with, and when enabled the table breaks again.

Guess I'm now looking for a way to tell Android not to auto-fit the table (and override the browser setting). Not liking my chances judging by my Google searches so far.


I've encountered an odd issue with the Android web-browser and spanned columns - for example, if I have this structure:

Modifying circumstance Common pathogens First choice Alternative Additional information
SECTION TITLE
column 1 column 2 column 3 column 4 column 5

The spanned row will reduce to fit the size of the screen, even if the table itself is still wider. This means that the heading2 row's background is missing across most of the table in some cases, making it look quite odd.

This is not happening on iPhone, or any desktop browser (Chrome, IE, FF, Safari) that we're aware of - just on Android (multiple devices and versions).

The CSS:

.amhtable {          border-width:1px;          border-style:solid;          border-color:#000000;          border-collapse: collapse;          border-spacing: 0;          padding: 5px;          font-weight: normal;           color: #000000;  }    .amhtable td {          border-width:1px;          border-style:solid;          border-color:black;          padding: 3px;  }    .amhtable th {          border-width:1px;          border-style:solid;          border-color:#777777;          background-color:#0084D6;  }    .amhtable .heading {          border-width:1px;          border-style:solid;          border-color:#000000;          background-color:#567ac4;          font-weight: bold;          font-style: italic;          font-family: Verdana, Arial, Helvetica, DejaVu Sans, Bitstream Vera Sans, sans-serif;   }    .amhtable .heading2 {          border-width:1px;          border-style:solid;          border-color:#000000;          background-color:#82a3e7;          font-weight: bold;          font-family: Verdana, Arial, Helvetica, DejaVu Sans, Bitstream Vera Sans, sans-serif;   }  

So far, I've tried the following:

  • Removing the elements
  • Adding a sixth column and empty elements into each row
  • Removing the border-collapse style ( after reading Webkit Browsers Rendering Problem for Table Depending on colspan )
  • Setting the width of the spanned column to 100% (along with the changes above)
  • Setting a fixed width on the table and setting the spanned column to 100%
  • Replaced the % based widths of the columns with fixed pixel widths
  • Set the position to be relative for the spanned cell (and then the row) and set left and right to 0.
  • Set the position to be relative for the row with left as 0, and width as 1000px
  • Wrapped the table in a 100% wide

One thing that we noticed yesterday is that the table should have a 1px black border - but there is a gap on the 2.1/2.2 devices we're testing on where the row doesn't complete. It really does seem to be a rendering problem on these devices.

Answer by Nicolas-Verley for Spanned columns collapsing on Android web-browser (when using auto-fit pages)


Maybe it's a mistake but did you tried to put on your table :

table class="amhtable" **cellspacing="0"**  

Answer by benni_mac_b for Spanned columns collapsing on Android web-browser (when using auto-fit pages)


Is the total width of the columns suppose to be 100.01%?

Try reducing first column to 16.71%?

Answer by dash for Spanned columns collapsing on Android web-browser (when using auto-fit pages)


I wonder if the following will help:

  1. Wrap those body rows in a tbody element:

  2. Remove the width="100%" from your header row. Colspan="5" should span the width of the table anyway, with the browser sizing accordingly. I wonder if the Google browser is interpreting that literally as the width of the current screen.

  3. Add the following to the class for .amhtable:

    float: left;  width: 100%;  

To see if it's a relative sizing bug.

Out of interest, does this happen if the heading row appears anywhere in the table? Or is it just the first time it occurs after thead?

Modifying circumstance Common pathogens First choice Alternative Additional information
SECTION TITLE
column 1 column 2 column 3 column 4 column 5

What happens if you try that?

Other things you might try are putting the actual heading text in an element like:

      SECTION TITLE    

Answer by Vlad Stratulat for Spanned columns collapsing on Android web-browser (when using auto-fit pages)


I'm not sure, but try this method http://jsfiddle.net/DhAYd/9/

Answer by PointedEars for Spanned columns collapsing on Android web-browser (when using auto-fit pages)


The (X)HTML document in your bug report is not Valid; at best it is incomplete. A DOCTYPE declaration (HTML 4.01, XHTML 1.0) or a doctype (HTML5) is required. In the current HTML5 Working Draft, the col element does not have a width attribute (the W3C Validator says it is obsolete; you should use CSS instead). But this also cannot be Valid HTML or XHTML 1.0, as the title element is missing.

As a result of the missing DOCTYPE declaration, the layout engine is likely going into Quirks Mode, and you cannot expect interoperable behavior.

Also, percentages in (X)HTML are not specified to support decimals, although it is not explicitly forbidden. A HTML syntax validator would not catch this error as %Length is an alias for CDATA (any character data).

You should

  1. Validate your document: W3C Validator
  2. Make it Valid.
  3. See if using integer percentages or CSS helps.

Only if you are still seeing different behavior, you should file a bug.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Friday, December 9, 2016

Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file

Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file


Original Title: What is the hotkey, if any, for navigating to layout file or a resource's value?

(This question didn't really describe the issue at hand. And as you can imagine, it attracted some obvious answers. My apologies, this is the first question I've posted.)

I'm using Android Studio version 1.1.0 on Mac.

Say I have a line of code similar to this:

    setContentView(R.layout.layout_main);  

In Eclipse, I could simply use 'command + click' on the resource ID and it would navigate to the respective xml file then highlight the string, view, or color declaration. However, doing so in Android Studio navigates me to the declaration within the R file, which is utterly useless.

Is there a separate hotkey that I missed, or a separate event/action I could bind the current hotkey to, that would cause AS to operate more like Eclipse in this manner?

EDIT

After a couple answers -- which were correct according to the original question -- and some experimentation (created a fresh new project - I feel silly for not doing that earlier), it seems Android Studio should in fact navigate to the exact line in the xml where the View, String, or Color resource is declared, just like Eclipse does. However in my situation, it isn't for some odd reason.

This is merely speculation, but I suppose the culprit could be one or a combination of three things:

  1. The project I was working on - It was recently migrated from an Eclipse project to Android Studio project. This seems to be the most likely since the issue persists after updating items 2 and 3.
  2. The JDK version - When I created the new project, AS complained that my compiler was outdated (was running 1.6, upgraded to 1.7).
  3. Target SDK - the reason I was prompted to upgrade the JDK.

Answer by Catalina for Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file


CTRL + B should do it. Otherwise you can create your own shortcuts.

Answer by Mohammad Arman for Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file


I am using Mac (OS X Yosemite).

Holding down the Command + Tapping the id of an Item is taking me to the xml right now.

But another shortcut is point your cursor over the ID and click Command + B

If you want to go to the class file from the xml then click Command + O I can share some additional shortcuts: Command + E for recent files.

If you want to search from the recent list Then click "Shift" twice

Answer by Amir for Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file


in windows Ctrl+B switched between Design Mode and Text Mode.
Ctrl + leftClick moves to declaration

Answer by user3829751 for Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file


So I figured it out! I don't know why, but it turns out that my main project's root folder (main 'app' module) was on the file type ignore list. All you have to do is remove the folder name from the list (highlighted in picture below).

Oddly enough, this also resolved some the other anomalies I was experiencing. One issue was I could never see the AndroidManifest file in 'manifests' folder of the Hierarchy/Project Viewer ('Android' selected). Another issue was whenever I'd build and run the app, I'd get a warning about the AndroidManifest and have to click "Continue Anyway". Also, the app wouldn't auto-launch once installed.

Ignore List

Answer by jayeffkay for Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file


My problem was that I, after recently changing the package name, accidentally added a blank space in the Manifest package name.

Answer by ralphspoon for Android Studio - Hotkey for navigating to xml declaration is instead navigating to R file


In Android Studio you can just click "Shift" button twice. You can either open java Class, xml layout, gradle files, android manifest and almost everything. hope it helps.

-cheers / happy codings.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

What is the best way to determine if a string contains a character from a set in Swift

What is the best way to determine if a string contains a character from a set in Swift


I need to determine if a string contains any of the characters from a custom set that I have defined.

I see from this post that you can use rangeOfString to determine if a string contains another string. This, of course, also works for characters if you test each character one at a time.

I'm wondering what the best way to do this is.

Answer by Cesare for What is the best way to determine if a string contains a character from a set in Swift


You could do it this way:

var string = "Hello, World!"    if string.rangeOfString("W") != nil {       println("exists")  } else {       println("doesn't exist")  }    // alternative: not case sensitive  if string.lowercaseString.rangeOfString("w") != nil {       println("exists")  } else {       println("doesn't exist")  }  

Answer by Martin R for What is the best way to determine if a string contains a character from a set in Swift


You could create a NSCharacterSet containing the set of your custom characters:

let charset = NSCharacterSet(charactersInString: "aw")  

and then test the membership against this character set:

if str.lowercaseString.rangeOfCharacterFromSet(charset, options: nil, range: nil) != nil {      println("yes")  }  

Answer by rintaro for What is the best way to determine if a string contains a character from a set in Swift


From Swift 1.2 you can do that using Set

var str = "Hello, World!"  let charset: Set = ["e", "n"]    charset.isSubsetOf(str)     // `true` if `str` contains all characters in `charset`  charset.isDisjointWith(str) // `true` if `str` does not contains any characters in `charset`  charset.intersect(str)      // set of characters both `str` and `charset` contains.  

Answer by Chris Hatton for What is the best way to determine if a string contains a character from a set in Swift


func isAnyCharacter( from charSetString: String, containedIn string: String ) -> Bool  {      return Set( charSetString.characters ).isDisjointWith( Set( string.characters) ) == false  }  

Answer by fs_tigre for What is the best way to determine if a string contains a character from a set in Swift


Swift 3:

let myString = "Some Words"    if (myString.range(of: "Some") != nil){      print("myString contains the word `Some`")  }else{      print("Word does not contain `Some`")  }  

Answer by AndyDunn for What is the best way to determine if a string contains a character from a set in Swift


Using Swift 3 to determine if your string contains characters from a specific NSCharacterSet:

    let letters = CharacterSet.alphanumerics      let string = "my-string_"      if (string.trimmingCharacters(in: letters) != "") {          print("Invalid characters in string.")      }      else {          print("Only letters and numbers.")      }  

Answer by t4ncr3d3 for What is the best way to determine if a string contains a character from a set in Swift


swift3

var str = "Hello, playground"  let res = str.characters.contains { ["x", "z"].contains( $0 ) }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Finding the ranking of a word (permutations) with duplicate letters

Finding the ranking of a word (permutations) with duplicate letters


I'm posting this although much has already been posted about this question. I didn't want to post as an answer since it's not working. The answer to this post (Finding the rank of the Given string in list of all possible permutations with Duplicates) did not work for me.

So I tried this (which is a compilation of code I've plagiarized and my attempt to deal with repetitions). The non-repeating cases work fine. BOOKKEEPER generates 83863, not the desired 10743.

(The factorial function and letter counter array 'repeats' are working correctly. I didn't post to save space.)

while (pointer != length)  {      if (sortedWordChars[pointer] != wordArray[pointer])      {          // Swap the current character with the one after that          char temp = sortedWordChars[pointer];          sortedWordChars[pointer] = sortedWordChars[next];          sortedWordChars[next] = temp;          next++;            //For each position check how many characters left have duplicates,           //and use the logic that if you need to permute n things and if 'a' things           //are similar the number of permutations is n!/a!              int ct = repeats[(sortedWordChars[pointer]-64)];          // Increment the rank          if (ct>1) { //repeats?              System.out.println("repeating " + (sortedWordChars[pointer]-64));              //In case of repetition of any character use: (n-1)!/(times)!              //e.g. if there is 1 character which is repeating twice,              //x* (n-1)!/2!                                        int dividend = getFactorialIter(length - pointer - 1);                  int divisor = getFactorialIter(ct);                  int quo = dividend/divisor;                  rank += quo;          } else {              rank += getFactorialIter(length - pointer - 1);                           }                             } else      {          pointer++;          next = pointer + 1;      }  }  

Answer by David Eisenstat for Finding the ranking of a word (permutations) with duplicate letters


Note: this answer is for 1-based rankings, as specified implicitly by example. Here's some Python that works at least for the two examples provided. The key fact is that suffixperms * ctr[y] // ctr[x] is the number of permutations whose first letter is y of the length-(i + 1) suffix of perm.

from collections import Counter    def rankperm(perm):      rank = 1      suffixperms = 1      ctr = Counter()      for i in range(len(perm)):          x = perm[((len(perm) - 1) - i)]          ctr[x] += 1          for y in ctr:              if (y < x):                  rank += ((suffixperms * ctr[y]) // ctr[x])          suffixperms = ((suffixperms * (i + 1)) // ctr[x])      return rank  print(rankperm('QUESTION'))  print(rankperm('BOOKKEEPER'))  

Java version:

public static long rankPerm(String perm) {      long rank = 1;      long suffixPermCount = 1;      java.util.Map charCounts =          new java.util.HashMap();      for (int i = perm.length() - 1; i > -1; i--) {          char x = perm.charAt(i);          int xCount = charCounts.containsKey(x) ? charCounts.get(x) + 1 : 1;          charCounts.put(x, xCount);          for (java.util.Map.Entry e : charCounts.entrySet()) {              if (e.getKey() < x) {                  rank += suffixPermCount * e.getValue() / xCount;              }          }          suffixPermCount *= perm.length() - i;          suffixPermCount /= xCount;      }      return rank;  }  

Unranking permutations:

from collections import Counter    def unrankperm(letters, rank):      ctr = Counter()      permcount = 1      for i in range(len(letters)):          x = letters[i]          ctr[x] += 1          permcount = (permcount * (i + 1)) // ctr[x]      # ctr is the histogram of letters      # permcount is the number of distinct perms of letters      perm = []      for i in range(len(letters)):          for x in sorted(ctr.keys()):              # suffixcount is the number of distinct perms that begin with x              suffixcount = permcount * ctr[x] // (len(letters) - i)              if rank <= suffixcount:                  perm.append(x)                  permcount = suffixcount                  ctr[x] -= 1                  if ctr[x] == 0:                      del ctr[x]                  break              rank -= suffixcount      return ''.join(perm)  

Answer by John for Finding the ranking of a word (permutations) with duplicate letters


@Dvaid Einstat, this was really helpful. It took me a WHILE to figure out what you were doing as I am still learning my first language(C#). I translated it into C# and figured that I'd give that solution as well since this listing helped me so much!

Thanks!

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Threading.Tasks;  using System.Text.RegularExpressions;    namespace CsharpVersion  {      class Program      {          //Takes in the word and checks to make sure that the word          //is between 1 and 25 charaters inclusive and only          //letters are used          static string readWord(string prompt, int high)          {              Regex rgx = new Regex("^[a-zA-Z]+$");              string word;              string result;              do              {                  Console.WriteLine(prompt);                  word = Console.ReadLine();              } while (word == "" | word.Length > high | rgx.IsMatch(word) == false);              result = word.ToUpper();              return result;          }            //Creates a sorted dictionary containing distinct letters           //initialized with 0 frequency          static SortedDictionary Counter(string word)          {              char[] wordArray = word.ToCharArray();              int len = word.Length;              SortedDictionary count = new SortedDictionary();             foreach(char c in word)             {                 if(count.ContainsKey(c))                 {                 }                 else                 {                     count.Add(c, 0);                 }               }             return count;          }            //Creates a factorial function          static int Factorial(int n)          {              if (n <= 1)              {                  return 1;              }              else              {                  return n * Factorial(n - 1);              }          }          //Ranks the word input if there are no repeated charaters           //in the word          static Int64 rankWord(char[] wordArray)          {              int n = wordArray.Length;               Int64 rank = 1;               //loops through the array of letters              for (int i = 0; i < n-1; i++)               {                   int x=0;               //loops all letters after i and compares them for factorial calculation                  for (int j = i+1; j wordArray[j])                       {                          x++;                      }                  }                  rank = rank + x * (Factorial(n - i - 1));                }              return rank;          }            //Ranks the word input if there are repeated charaters          //in the word          static Int64 rankPerm(String word)           {          Int64 rank = 1;          Int64 suffixPermCount = 1;          SortedDictionary counter = Counter(word);          for (int i = word.Length - 1; i > -1; i--)           {              char x = Convert.ToChar(word.Substring(i,1));              int xCount;              if(counter[x] != 0)               {                  xCount = counter[x] + 1;               }              else              {                 xCount = 1;              }              counter[x] = xCount;              foreach (KeyValuePair e in counter)              {                  if (e.Key < x)                  {                      rank += suffixPermCount * e.Value / xCount;                  }              }                suffixPermCount *= word.Length - i;              suffixPermCount /= xCount;          }          return rank;          }                  static void Main(string[] args)          {             Console.WriteLine("Type Exit to end the program.");             string prompt = "Please enter a word using only letters:";             const int MAX_VALUE = 25;             Int64 rank = new Int64();             string theWord;             do             {                 theWord = readWord(prompt, MAX_VALUE);                 char[] wordLetters = theWord.ToCharArray();                 Array.Sort(wordLetters);                 bool duplicate = false;                 for(int i = 0; i< theWord.Length - 1; i++)                 {                   if(wordLetters[i] < wordLetters[i+1])                   {                       duplicate = true;                   }                 }                 if(duplicate)                 {                 SortedDictionary counter = Counter(theWord);                 rank = rankPerm(theWord);                 Console.WriteLine("\n" + theWord + " = " + rank);                 }                 else                 {                 char[] letters = theWord.ToCharArray();                 rank = rankWord(letters);                 Console.WriteLine("\n" + theWord + " = " + rank);                 }             } while (theWord != "EXIT");                Console.WriteLine("\nPress enter to escape..");              Console.Read();          }      }  }  

Answer by Peiti Peter Li for Finding the ranking of a word (permutations) with duplicate letters


I would say David post (the accepted answer) is super cool. However, I would like to improve it further for speed. The inner loop is trying to find inverse order pairs, and for each such inverse order, it tries to contribute to the increment of rank. If we use an ordered map structure (binary search tree or BST) in that place, we can simply do an inorder traversal from the first node (left-bottom) until it reaches the current character in the BST, rather than traversal for the whole map(BST). In C++, std::map is a perfect one for BST implementation. The following code reduces the necessary iterations in loop and removes the if check.

long long rankofword(string s)  {      long long rank = 1;      long long suffixPermCount = 1;      map m;      int size = s.size();      for (int i = size - 1; i > -1; i--)      {          char x = s[i];          m[x]++;          for (auto it = m.begin(); it != m.find(x); it++)                  rank += suffixPermCount * it->second / m[x];            suffixPermCount *= (size - i);          suffixPermCount /= m[x];      }      return rank;  }  

Answer by Shubham Nanda for Finding the ranking of a word (permutations) with duplicate letters


If there are k distinct characters, the i^th character repeated n_i times, then the total number of permutations is given by

            (n_1 + n_2 + ..+ n_k)!  ------------------------------------------------                 n_1! n_2! ... n_k!  

which is the multinomial coefficient.
Now we can use this to compute the rank of a given permutation as follows:

Consider the first character(leftmost). say it was the r^th one in the sorted order of characters.

Now if you replace the first character by any of the 1,2,3,..,(r-1)^th character and consider all possible permutations, each of these permutations will precede the given permutation. The total number can be computed using the above formula.

Once you compute the number for the first character, fix the first character, and repeat the same with the second character and so on.

Here's the C++ implementation to your question

#include    using namespace std;    int fact(int f) {      if (f == 0) return 1;      if (f <= 2) return f;      return (f * fact(f - 1));  }  int solve(string s,int n) {      int ans = 1;      int arr[26] = {0};      int len = n - 1;      for (int i = 0; i < n; i++) {          s[i] = toupper(s[i]);          arr[s[i] - 'A']++;      }      for(int i = 0; i < n; i++) {          int temp = 0;          int x = 1;          char c = s[i];          for(int j = 0; j < c - 'A'; j++) temp += arr[j];          for (int j = 0; j < 26; j++) x = (x * fact(arr[j]));          arr[c - 'A']--;          ans = ans + (temp * ((fact(len)) / x));          len--;      }      return ans;  }  int main() {      int i,n;      string s;      cin>>s;      n=s.size();      cout << solve(s,n);      return 0;  }  

Answer by Kiran for Finding the ranking of a word (permutations) with duplicate letters


If we use mathematics, the complexity will come down and will be able to find rank quicker. This will be particularly helpful for large strings. (more details can be found here)

Suggest to programmatically define the approach shown here (screenshot attached below)enter image description here given below)


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

How can I analyze Python code to identify problematic areas?

How can I analyze Python code to identify problematic areas?


I have a large source repository split across multiple projects. I would like to produce a report about the health of the source code, identifying problem areas that need to be addressed.

Specifically, I'd like to call out routines with a high cyclomatic complexity, identify repetition, and perhaps run some lint-like static analysis to spot suspicious (and thus likely erroneous) constructs.

How might I go about constructing such a report?

Answer by freespace for How can I analyze Python code to identify problematic areas?


For static analysis there is pylint and pychecker. Personally I use pylint as it seems to be more comprehensive than pychecker.

For cyclomatic complexity you can try this perl program, or this article which introduces a python program to do the same

Answer by Pierre-Jean Coudert for How can I analyze Python code to identify problematic areas?


Thanks to Pydev, you can integrate pylint in the Eclipse IDE really easily and get a code report each time you save a modified file.

Answer by Mike Griffith for How can I analyze Python code to identify problematic areas?


For measuring cyclomatic complexity, there's a nice tool available at traceback.org. The page also gives a good overview of how to interpret the results.

+1 for pylint. It is great at verifying adherence to coding standards (be it PEP8 or your own organization's variant), which can in the end help to reduce cyclomatic complexity.

Answer by Anonymous for How can I analyze Python code to identify problematic areas?


There is a tool called CloneDigger that helps you find similar code snippets.

Answer by msemelman for How can I analyze Python code to identify problematic areas?


Pycana works like charm when you need to understand a new project!

PyCAna (Python Code Analyzer) is a fancy name for a simple code analyzer for python that creates a class diagram after executing your code.

See how it works: http://pycana.sourceforge.net/

output:

alt text

Answer by Dave Halter for How can I analyze Python code to identify problematic areas?


For cyclomatic complexity you can use radon: https://github.com/rubik/radon

(Use pip to install it: pip install radon)

Additionally it also has these features:

  • raw metrics (these include SLOC, comment lines, blank lines, &c.)
  • Halstead metrics (all of them)
  • Maintainability Index (the one used in Visual Studio)

Answer by Wes Kendall for How can I analyze Python code to identify problematic areas?


Use flake8, which provides pep8, pyflakes, and cyclomatic complexity analysis in one tool

Answer by A-B-B for How can I analyze Python code to identify problematic areas?


For checking cyclomatic complexity, there is of course the mccabe package.

Installation:

$ sudo pip install --upgrade mccabe  

Usage:

$ python -m mccabe --min=6 /path/to/myfile.py  

Note the threshold of 6 above. Per this answer, scores >5 probably should be simplified.

Sample output with --min=3:

68:1: 'Fetcher.fetch' 3  48:1: 'Fetcher._read_dom_tag' 3  103:1: 'main' 3  

It can optionally also be used via pylint-mccabe, etc.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Popular Posts

Powered by Blogger.