text:
Q: Xamarin Forms XamlParseException Class not found in clr-namespace I recently purchased Grialkit and was creating a simple walkthrough for an app that I'm developing.
I'm following the examples that are included in my grialkit.
I have a page, called WalkthroughPage. The XAML of this page looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<CarouselPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

    x:Class="WhoseKitchenApp.Views.Walkthroughs.WalkthroughPage"
    xmlns:artina="clr-namespace:UXDivers.Artina.Shared;assembly=UXDivers.Artina.Shared"
    xmlns:local="clr-namespace:WhoseKitchenApp;assembly=WhoseKitchenApp">
    <!-- following line is line 9 -->
    <local:Views.Walkthroughs.Templates.WalkthroughStepItemTemplate BackgroundColor="#FF6600" Header="Header text 1" Text="Welcome slide 1" IconColor="#5F7DD4" ButtonBackgroundColor="#5F7DD4" ButtonText="Next" />
    <!-- following line is line 11 -->
    <local:Views.Walkthroughs.Templates.WalkthroughStepItemTemplate BackgroundColor="#FF6600" Header="Header text 2" Text="Hello slide 2"  IconColor="#7C4ECD" ButtonBackgroundColor="#7C4ECD" ButtonText="Next" />

    <local:Views.Walkthroughs.Templates.WalkthroughStepItemTemplate BackgroundColor="#FF6600" Header="Header text 3" Text="Last slide, slide 3"  IconColor="#E51E61" ButtonBackgroundColor="#E51E61" ButtonText="Finish" />
</CarouselPage>

I created an template called WalkthroughStepItemTemplate which I use to display information about the app.
When running my app, I get an XamlParseException:

Position 11:6. Type local:Views.Walkthroughs.Templates.WalkthroughStepItemTemplate not found in xmlns clr-namespace:WhoseKitchenApp;assembly=WhoseKitchenApp

In  the code above, I placed a comment where that line 11 is. As you can see, the first time WalkthroughStepItemTemplate is called it looks just fine, but on the second try, it generates the exception.
I tried changing the clr-namespace to WhoseKitchenApp.Views.Walkthroughs.Templates, but I still have the same exception than. Also changing line 11 in the example to
<local:WalkthroughStepItemTemplate ...

has no effect.
Linker Behavior for both iOS and Android apps is set to Don't Link - Tip from the SO question
I'm wondering why the second (and third) time I get an XamlParseException.


text:
Q: XACML as an evolution step in an existing application I've begun doing some research on XACML and external authorization. Right now I have an existing application which utilizies an RBAC model. However the implementation has a lot of shortcomings (roles can't be easily defined, roles are too coarsly grained).
Is XACML a good alternative to look at? Are there any exisitng applications which have switched to XACML from an RBAC origin? Are there any shortcomings?

A: Disclaimer:  I'm a developer for IBM, and I work on our product that uses XACML extensively (Tivoli Security Policy Manager).  I'm a little biased towards XACML.
I think XACML is a great alternative, mainly because it can support almost any security model.  I'd suggest modelling your existing RBAC solution in XACML (see the profile), then extending it to include finer-grained access control where your business requirements demand it.
Externalizing your authorization code into policy has the added advantage of being able to modify your application's security model without recompiling it.

Are there any exisitng applications which have switched to XACML from an RBAC origin?

Unfortunately I'm not aware of any particular examples, at least ones that I can talk about publicly.  There is an internal IBM project that allocated a month for implementing their authorization module, but got it done in a week by externalizing it using our XACML implementation.  This is obviously different to your example as it was a "green fields" development project, but highlights that there are benefits to be had with the general approach you're considering.

A: I am the security architect at WSO2 - which develops WSO2 Identity Server, an open source Identity and Entitlement management server, with XACML suport.
I too believe XACML is a good alternative to externalize authorization logic from the application code. We recently worked with few customers [one of them is among Fortune 100] - moving to XACML from different proprietary authorization rules.

A: I agree with my counterparts from IBM and WS02 respectively. I work for Axiomatics. We focus exclusively on authorization based on XACML.
We have customers who moved from RBAC to ABAC. Some decided to use the RBAC profile for XACML as a middle step (http://docs.oasis-open.org/xacml/3.0/xacml-3.0-rbac-v1-spec-cd-03-en.html). What's interesting is that you can use your existing RBAC infrastructure to build ABAC on top.
We haven't seen any shortcomings as yet. If anything, customers quickly see the ROI with XACML: it's cheaper and more flexible. You can use multiple implementations (you could mix IBM, WS02, and Axiomatics together and it would still work) and there is strong support from the industry.
Check out the XACML TC page for more info: http://www.oasis-open.org/committees/xacml/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Что за вид адресных ссылок Я знаю ссылки скажем example.com/index.html или axample.th/ololo.php?q=089564.
Но что такое, например, 'https://ru.wikipedia.org/wiki/Город_потерянных_детей' ?
Как здесь переданы данные? Это такой вид get? Или там действительно есть файл "Город_потерянных_детей"? Мне кажется это как-то переменная передаётся, только не пойму куда и как (то есть там есть файл https://ru.wikipedia.org/wiki/index.php который обрабатывает переменную и формирует ответ пользователю?).

A: Это ЧПУ - человекопонятный URL. Когда идёт запрос в сервер, то строку запроса можно изменять через файл htaccess, или доставать отдуда данные и переделывать всё в довольно громоздкий GET запрос. Это делается через mod_rewrite. Поэтому и используют ЧПУ, чтобы адресная строка была понятна пользователю.
Я только начинаю это изучать, вот на этом ресурсе очень толково объясняеться, как это работает https://hackware.ru/?p=5564
P. S. Не наступайте на мои грабли - используйте для настройки и тестирования htaccess хрум, потому что огненный лис кешировал правила, что изрядно съело мои нервы, пока я не догадался, в чем же причина.


text:
Q: writing a caching version of Mechanize I'd like a caching version of Mechanize.  The idea is that #get(uri...) checks to see if that uri has been previously fetched, and if so, fetch the response from the cache rather than hitting the web.  If not in the cache, it hits the web and saves the response in the cache.
My naive approach doesn't work.  (I probably don't need to mention that CachedWebPage is a subclass of ActiveRecord::Base):
class CachingMechanize < Mechanize

  def get(uri, parameters = [], referer = nil, headers = {})
    page = if (record = CachedWebPage.find_by_uri(uri.to_s))
             record.contents
           else
             super.tap {|contents| CachedWebPage.create!(:uri => uri, :contents => contents)}
           end
    yield page if block_given?
    page
  end

end

This fails because the object returned by Mechanize#get() is a complex, circular structure that neither YAML nor JSON want to serialize for storage into the database.
I realize that what I want is to capture the low-level contents before Mechanize parses it.

*

*Is there clean way to do this?  I think I can use Mechanize's post_connect hook to access the raw page coming in, but I don't see how to subsequently pass the cached raw page to Mechanize for parsing.

*Is there some package I should be using that does web page caching already?

A: It turns out the solution was simple, albeit not entirely clean.  It's a simple matter to cache the results of Mechanize#get() like this:
class CachingMechanize < Mechanize
  def get(uri, parameters = [], referer = nil, headers = {})
    WebCache.with_web_cache(uri.to_s) { super }
  end
end

... where with_web_cache() uses YAML to serialize and cache the object returned by super.
My problem was that by default, Mechanize#get() returns a Mechanize::Page object containing some lambda object, which cannot be dumped and loaded by YAML.  The fix was to eliminate those lambdas, which turned out to be rather simple.  Full code follows.
class CachingMechanize < Mechanize

  def initialize(*args)
    super
    sanitize_scheme_handlers
  end

  def get(uri, parameters = [], referer = nil, headers = {})
    WebCache.with_web_cache(uri.to_s) { super }
  end

  # private

  def sanitize_scheme_handlers
    scheme_handlers['http']      = SchemeHandler.new
    scheme_handlers['https']     = scheme_handlers['http']
    scheme_handlers['relative']  = scheme_handlers['http']
    scheme_handlers['file']      = scheme_handlers['http']
  end

  class SchemeHandler
    def call(link, page) ; link ; end
  end

end

the moral: don't try to YAML.dump and YAML.load objects containing lambda or proc
This goes beyond just this example: if you see a YAML error that reads:
TypeError: allocator undefined for Proc

Check to see if there's a lambda or proc in the object you're trying to serialize and deserialize.  If you are able (as I was in this case) to replace the lambda with a method call to an object, you should be able to work around the problem.
Hope this helps someone else.
Update
In response to @Martin's request for the definition of WebCache, here 'tis:
# Simple model for caching pages fetched from the web.  Assumes
# a schema like this:
#
#   create_table "web_caches", :force => true do |t|
#     t.text     "key"
#     t.text     "value"
#     t.datetime "expires_at"
#     t.datetime "created_at", :null => false
#     t.datetime "updated_at", :null => false
#   end
#   add_index "web_caches", ["key"], :name => "index_web_caches_on_key", :unique => true
#
class WebCache < ActiveRecord::Base
  serialize :value

  # WebCache.with_web_cache(key) {
  #    ...body...
  # }
  #
  # Searches the web_caches table for an entry with a matching key.  If
  # found, and if the entry has not expired, the value for that entry is
  # returned.  If not found, or if the entry has expired, yield to the
  # body and cache the yielded value before returning it.
  #
  # Options:
  #   :expires_at sets the expiration date for this entry upon creation.
  #               Defaults to one year from now.
  #   :expired_prior_to overrides the value of 'now' when checking for
  #                     expired entries.  Mostly useful for unit testing.
  #
  def self.with_web_cache(key, opts = {})
    serialized_key = YAML.dump(key)
    expires_at = opts[:expires_at] || 1.year.from_now
    expired_prior_to = opts[:expired_prior_to] || Time.zone.now
    if (r = self.where(:key => serialized_key).where("expires_at > ?", expired_prior_to)).exists?
      # cache hit
      r.first.value
    else
      # cache miss
      yield.tap {|value| self.create!(:key => serialized_key, :value => value, :expires_at => expires_at)}
    end
  end

  # Prune expired entries.  Typically called by a cron job.
  def self.delete_expired_entries(expired_prior_to = Time.zone.now)
    self.where("expires_at < ?", expired_prior_to).destroy_all
  end

end


text:
Q: how to overflow text to do this I have multiple elements each has a short and main divs. I want to keep short to one line. Right now, when the content exceeds one line, it moves to the next line. What I want however is to make it cut off the remaining text and display dots like this ... instead. Is this possible?

   Text should stay on one line

.elem{
  width:150px;
}

Ideally, when the user hovers over the title and dots ..., he could see the full title in a simple html pop-up or something like that.

A: The following CSS will achieve the effect you want in browsers with CSS3 support:
.elem { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; width: 150px; }
.elem:hover { white-space: normal; }

Note that the text will expand when the mouse is over any part of it, not just the ellipsis.

A: For a Jquery solution, try this: http://jsfiddle.net/kA3uN/
$short = $('.short');
$short.html($short.html().substring(0,10) + " ...");

Just change 10 to whatever character length agrees with your layout.  No need for CSS3! :D

A: You can use CSS's 3 text-overflow: ellipsis; property
EDIT
Sorry, guess I clicked to fast on send and didn't read the full question. With that CSS property you can clip the text to the width you want.
If you want it to appear on hover you only have to increase the div's width with the hover pseudo class like:
.elem:hover {
  width: 300px:
}


text:
Q: Web project requires missing web component ASP.NET Web pages with Razor syntax 3.0.0.0 I Migrate my project to mvc 5.0 and razor engin 3 with Microsoft Instruction
But when open my solution Get this:

The Web project 'ProjectName' requires missing web components to run with Visual Studio. Would you like to download and install them using the Web Platform Installer now?
(Note: Some components might require restart to take effect.)
ASP.NET Web pages with Razor syntax 3.0.0.0
I also read this and this
but these answer doesn't help me
I appreciate for any help
Update:
My Project Build Very well and works without any exception with razor 3 and mvc 5 but just Intellisense doesn't sense my Typing and coloring my Code
and also when change this line to Value="2.0.0.0" in Application web Config file above error vanish and intelisens works fine
<appSettings>
    <add key="webpages:Version" **value="3.0.0.0"** />
...
</appSettings>

Update
After some while, now you can user razor 3 on vs 2012.
Here you can upgrade

A: I had this problem after installing Visual Studio 2012.
What solved for me was installing the Visual Studio Updates:

*

*Tools> Extensions And Updates

*Select "Updates" in the accordion list on the left.

*Select "Product Updates".

*Update to the newest version (At the time of writing of this answer it was Update 4)

A: Solved:
Follow the below steps, It worked for me:
a)Install VS 2012 Update 4 (http://www.microsoft.com/en-gb/download/details.aspx?id=39305)
b)ASP.NET and Web Tools 2013.1 for Visual Studio 2012  Download link Available here (http://blogs.msdn.com/b/webdev/archive/2013/11/18/announcing-release-of-asp-net-and-web-tools-2013-1-for-visual-studio-2012.aspx)
c) Restart your dev box

A: I Found The Problem, vs 2012 doesn't support it(see update section of this answer)
From Here
said:

Unlike Razor V2 runtime and design time, VS2013 did not GAC these
  binaries. Instead, the binaries are installed in the project bin
  folder when corresponding NuGet package is installed, and in
  "%ProgramFiles (x86)%\Microsoft Visual Studio
  12.0\Common7\IDE\CommonExtensions\Microsoft\Web\Razor\v3.0" to support design time.

So we don't have these dlls in above path when upgrade to mvc5 /razor 3
also read this stack question
update: now support it , update vs from here

A: I solve this problem. VS 2012 support it.
from install setup file here upgrade for Visual Studio 2012

A: For me was installing the Visual Studio Updates:
Tools> Extensions And Updates
Select "Updates" in the accordion list on the left.
Select "Product Updates".
Update to the newest version

(At the time of writing of this answer it was Update 4)


text:
Q: jQuery - 2 level slider return to level 1 with click I have modified this jsFiddle http://jsfiddle.net/tV9z9/23/ to work like this jsFiddle http://jsfiddle.net/warmwhisky/N68wX/13/
When the script is first run I call this Level 1. Then you click one of the thumbnails and you move to level 2. I would like to return to the run state (Level 1) with a click. Maybe a close button or a return to first run state?
I have tried using an onclick with js but I cannot make it work.
Should I be using an onlick or can I save a state of the jquery and return to it?
Here is the code
JS...
$(function() {
    var content = $('#content'),
        services_level2 = $('#services_level2'),
        contentHeight = content.height(),
        contentWidth = content.width(),
        level2Width = services_level2.width(),
        nav = $('#nav'),
        count = 0;

    // on load content height is shorter
    content.width(0);
    services_level2.width(613);

    nav.find('a').on('click', function() {

        var $this = $(this),
            parent =  $this.parent(),
            targetElement = $this.attr('href');

        //Does the slide animation once
        if (count === 0) {

            //Slide out and fade away the main copy
            services_level2.animate({'width': services_level2 }, function() {
                $(services_level2).animate({
                    'margin-left': '300%',
                    opacity: 0
                }, 900);
            });

            content.animate({'width': contentWidth }, function() {
                parent.addClass('active');
                //animate in
                $(targetElement).animate({
                    left: '-=210px',
                    'margin-left': '30%',
                    opacity: 1
                }, 400);
            });
            count = 1;

        } else {

            //only add active class if parent does not have it and then animate it
            if ( !parent.hasClass('active') ) {

                parent.addClass('active');

                //animate in
                $(targetElement).animate({
                    left: '-=210px',
                    'margin-left': '30%',
                    opacity: 1
                }, 500);

                //Gets older clicked element
                var oldClickedElement = $('.active').not(parent).removeClass('active').find('a').attr('href');

                //only if old click element exists the do the animation
                if (oldClickedElement) {
                    //animate out + reset to start
                    $(oldClickedElement).animate({
                        left: 0,
                        'margin-left': '-50%',
                         opacity: 0
                    }, 500, function() {
                         $(oldClickedElement).css({
                            'margin-left' : '100%',
                            left: 0
                        });
                    });
                }
            }

        }

        return false;
    });

});

HTML...

IT Services

Lorem ipsum dolor sit amet, et mel falli simul platonem, cu consul utroque neglegentur duo. Omnis soluta periculis eu sit.

Repairs

              Sit te habeo neglegentur, nam no dicit intellegat. Epicuri blandit sea eu, eum nibh adhuc mundi eu.

Other

              Pri nihil scaevola salutatus id, esse minimum vis ne. Verear corrumpit vim ex, vim tollit scaevola ea.

Objective

Lorem ipsum dolor sit amet, et mel falli simul platonem, cu consul utroque neglegentur duo.

Delivery

Sit te habeo neglegentur, nam no dicit intellegat.

Performance

Pri nihil scaevola salutatus id, esse minimum vis ne. Verear corrumpit vim ex, vim tollit scaevola ea, est id suas delectus deseruisse.

Two

Three

Four

Five

Six

CSS...
#container {

    height:390px;
    overflow:hidden;
    float:left;
    background: #ccc no-repeat;
    min-width:918px;
    padding: 10px 10px 10px 10px;
}

#services_level2 {
    position:fixed;
    background:white;
    padding:20px;
    height: 345px;
}

#content {
    width: 650px;
    height: 385px;
    position: relative;
    overflow: hidden;
    float: right;
}
#content > div {
    display:block;
    width:600px;
    height:385px;
    background:white;
    position:absolute;
    margin-left:100%;
    /*left:-200px;*/
    opacity: 0;
    padding:10px 20px 0 40px;
}
#nav {
    list-style: none;
    display: table;
    margin: 0px 0 0 0;
    position: relative;
    width: 260px;
    float:right;
}
#nav li {
    /* width: 100px; */
    /* height: 100px; */
    float: left;
    margin-right:5px;
    /*border: 1px solid black;*/
}
#nav a {
    color:#fff;
    text-decoration:none;
    width:100%;
    height:100%;
}
ul {
    padding:0;
}
li.active {
    opacity:0.4;
    filter:alpha(opacity=40);
}

A: You need to comb your code and make a list off all the values that change on the first click, then when #reset is clicked reverse each value. -=200px will become +=200px and so on.

A: I found a solution to this (JSFiddle) by adding a button and assigning a click function to it which has 3 actions:

*

*Slide out and fade level2 copy. This forces the thumbnails to move

*slide in and fade in level1 copy

*deletes the active thumbnail class

Button Code:
    $('#moveleft').click(function() {
        count = 0;

        // Slide Level 2 description back into view
        $('#services_level2').animate({
            'margin-left': '0%',
            'opacity' : "1"
        }, 800);

        // Slide Level 3 out of view. The thumbnails follow Level 3.
        $(level3_content).animate({
            'width': '0px',
            opacity: 1
        }, 400);

        // Delete the active class
        var oldClickedElement = $('.active').removeClass('active').find('a').attr('href');

        console.log(oldClickedElement);

        //only if old click element exists the do the animation
        if (oldClickedElement) {
            //animate out + reset to start
            $(oldClickedElement).animate({
                left: 0,
                'margin-left': '-50%',
                opacity: 0
            }, 500, function() {
               $(oldClickedElement).css({
                'margin-left' : '100%',
                left: 0
            });
           });
        }
    });

Here is the JSFiddle http://jsfiddle.net/warmwhisky/N68wX/24/
It is rather a nice slider with two levels. Unfortunately it is not responsive yet.


text:
Q: PHP only variables should be passed by reference I was setting up a PHP server when this error came up:

Strict Standards: Only variables should be passed by reference in C:\xamp\htdocs\Xce Source\Source\Extra\Xce.php on line 75
  PHP Strict Standards:  Only variables should be passed by reference in C:\xamp\htdocs\Xce Source\Source\Extra\Xce.php on line 75

This is the line 75:
$ready = socket_select($read, $w = null, $e = null, $t = 0);

What do I need to change? I always have this problem with exactly this same code

A: Instead of $ready = socket_select($read, $w = null, $e = null, $t = 0); use this:
$w = null;
$e = null;
$t = 0;

$ready = socket_select($read, $w, $e, $t);

When you do something like this $w = null as a function parameter, you are actually passing null, not a reference to the $w variable. socket_select requires references as parameters to work.

A: As said in the documentation there, it should be:
$w = null;
$e = null;
$t = 0;
$ready = socket_select($read, $w, $e, $t)


text:
Q: How to convert cumsum() result values from float to integer? I have this dataframe:
              DP1           DP2           DP3           DP4           DP5           DP6           DP7           DP8           DP9          DP10          DP11          DP12
OP1     2197389.0  8.334035e+06  1.416121e+07  2.112566e+07  2.353240e+07  2.521456e+07  2.626701e+07  2.815038e+07           NaN  2.894672e+07           NaN           NaN
OP2     8859402.0  3.405393e+07  5.225385e+07  6.641002e+07  7.142158e+07  7.567666e+07  7.919994e+07  8.301265e+07  8.549990e+07  8.619976e+07  8.682675e+07  8.732952e+07
OP3    14787376.0  5.051932e+07  7.526720e+07  1.109929e+08  1.197162e+08  1.261469e+08  1.338973e+08  1.354751e+08  1.388290e+08  1.414128e+08  1.422856e+08           NaN
OP4    21493250.0  6.590146e+07  1.171731e+08  1.638118e+08  1.782883e+08  1.900619e+08  1.986440e+08  2.007501e+08  2.012454e+08  2.049792e+08  2.092219e+08  2.098224e+08
OP5    21700836.0  7.355879e+07  1.157970e+08  1.607273e+08  1.744825e+08  1.836202e+08  1.976620e+08  2.020817e+08  2.048174e+08  2.067469e+08  2.104735e+08  2.123310e+08
OP6    27197016.0  8.379447e+07  1.368874e+08  1.799347e+08  1.973877e+08  2.126034e+08  2.240213e+08  2.267334e+08  2.280336e+08  2.326177e+08  2.366704e+08  2.387043e+08
OP7    28312408.0  7.638481e+07  1.235895e+08  1.656576e+08  1.802400e+08  1.934127e+08  2.064300e+08  2.095814e+08  2.135559e+08  2.163695e+08  2.182680e+08  2.204437e+08
OP8    21161654.0  7.164625e+07  1.173728e+08  1.507630e+08  1.614412e+08  1.762703e+08  1.874506e+08  1.915259e+08  1.943434e+08  1.981648e+08  2.007807e+08  2.011242e+08
OP9    22030953.0  7.391936e+07  1.188640e+08  1.502157e+08  1.577981e+08  1.702076e+08  1.790455e+08  1.829043e+08  1.843653e+08  1.877471e+08  1.897388e+08  1.912022e+08
OP10   19800999.0  5.958667e+07  1.000103e+08  1.350046e+08  1.467698e+08  1.602286e+08  1.708699e+08  1.731278e+08  1.743493e+08  1.787757e+08  1.806712e+08           NaN
OP11   26744235.0  7.160570e+07  1.086724e+08  1.423295e+08  1.527055e+08  1.640139e+08  1.719841e+08  1.747707e+08  1.763537e+08  1.861115e+08           NaN           NaN
OP12   14967698.0  4.827327e+07  8.318845e+07  1.093670e+08  1.209002e+08  1.287389e+08  1.429479e+08  1.450573e+08  1.530010e+08           NaN           NaN           NaN
OP13   15860127.0  5.116424e+07  8.653871e+07  1.143786e+08  1.280226e+08  1.368423e+08  1.446488e+08  1.532531e+08           NaN           NaN           NaN           NaN
OP14   16421831.0  4.605250e+07  7.286290e+07  9.995756e+07  1.093182e+08  1.195463e+08  1.367919e+08           NaN           NaN           NaN           NaN           NaN
OP15   15452224.0  4.796981e+07  7.958047e+07  1.084661e+08  1.166676e+08  1.431275e+08           NaN           NaN           NaN           NaN           NaN           NaN
OP16   12994042.0  4.893026e+07  7.764653e+07  1.025860e+08  1.350187e+08           NaN           NaN           NaN           NaN           NaN           NaN           NaN
OP17   14602038.0  4.720123e+07  7.812935e+07  1.341007e+08           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN
OP18   17740235.0  5.648562e+07  1.517327e+08           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN
OP19   23064250.0  1.879731e+08           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN
OP20  221345563.0           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN           NaN
OP21  566733526.0  1.424700e+09  2.119047e+09  2.676880e+09  2.868863e+09  3.035883e+09  3.173159e+09  3.216514e+09  3.245888e+09  3.284416e+09  3.306339e+09  3.315317e+09

Above dataframe is created using cumsum(). Here the result is in the form of Float. values are correct but it is in Floating format.
I need like below:
          DP1          DP2          DP3          DP4          DP5
 OP1     2197389.0    8334035.0   14161207.0   21125657.0   23532404.0   ...
 OP2     8859402.0   34053933.0   52253851.0   66410020.0   71421580.0   ...
 OP3    14787376.0   50519318.0   75267203.0  110992853.0  119716151.0   ...
 OP4    21493250.0   65901456.0  117173071.0  163811817.0  178288346.0   ...
 OP5    21700836.0   73558786.0  115797026.0  160727304.0  174482464.0   ...
 ...
 ...

For example 8.334035 value will change to 8334035. D1 is in right form but other columns is not.

A: To convert it to int use ->
df = df.astype('Int64')


text:
Q: MVC on unobtrusive validation fire method I'm trying to run a method on my MVC view when the unobtrusive validation returns an error. My current script doesn't fire at all. I'm trying to only run a certain method when an error is returned.
I've tried on $("#submitButton").click and similar methods but to no avail.
Is there anyway to do this from the inline script only? does the validation have any triggers?
<fieldset class="step">
                <legend>
                    Contact:
                </legend>

Let us know how we can contact you with your quote, or anything else we may need from you coming up to your ski trip.

                                Full Name*

                                @Html.DropDownListFor(x => x.Title, Model.Titles, "...........", new { style = "width:70px; padding: 5px;" })

                                @Html.TextBoxFor(x => x.FirstName, new { style = "width:115px; padding: 5px;" })

                                @Html.TextBoxFor(x => x.LastName, new { style = "width:115px; padding: 5px;" })

                                City*

                                @Html.TextBoxFor(x => x.City, new { style = "width:320px; padding: 5px;" })

                                Postcode*

                                @Html.TextBoxFor(x => x.Postcode, new { style = "width:320px; padding: 5px;" })

                                Email*

                                @Html.TextBoxFor(x => x.Email, new { style = "width:320px; padding: 5px;" })

                                Telephone*

                                @Html.TextBoxFor(x => x.Telephone, new { style = "width:320px; padding: 5px;" })

                                Preferred Time of Contact

                                @Html.TextBoxFor(x => x.PreferredTime, new { style = "width:200px; padding: 5px;" })

                <input id="submitButton" type="image" alt="Submit" src="/images/global/submit_button.gif" />
            </fieldset>

edit: just tried binding to the invalid-form.validate method and it didnt work:
 $(function () {
    $("form").bind("invalid-form.validate", function () {
        alert('invalid!');
    });
});

A:  var controls = $("#divid").find('.class');
 $.each(controls, function (index, item) {
       $("#form1").validate().element($(this));
       if ($(this).valid) {
         //skip it maybe
       } else {
            //do something, even an ajax call if need be
       }


text:
Q: Linux: get list of files a program currently has open In Linux, how can I get a list of files currently open in program X?
(Specifically, I'm on Fedora, and the program is Zend Studio, but I assume there's a general answer.)

A: You can find symbolic links to the actual files in /proc/PID/fd where PID is the process ID.

A: ls -l /proc/<zend studio's pid>/fd will print a list of file descriptors. Those that map to files that were opened through open() will be symlinks to the file path used to open them.

A: Use e.g. lsof ("list open files") and filter the output, or use the -c programX option to restrict it to files opened by programX.  This expression can be a wildcard.

A: Install the program lsof if you haven't already.  Get the pid of the running program.  Run lsof -p [pid].

A: lsof -p [PID]

Or, to get the PID in one go
lsof -p `pgrep [PROG_NAME]`

Or, even simpler
lsof -c [PROG_NAME]

A: You can use
ls /proc/PID/fd | wc -l

Which retuns the count of files opened by PID
or you can use lsof(list of open files)
lsof -a -p pid


text:
Q: Quick like button on Tumblr Can anybody explain me how the like button in this page works?
As you can see,once the whole page finishes loading, hovering on a post or a picture would show a couple of buttons, including a like button(the heart shape one on the bottom left corner).
Can anybody explain how it works? I've been trying to figure it out for a while now, trying the script on the source code, but to no avail.

A: I wrote a Tumblr tutorial on this: http://like-button.tumblr.com
To save a Like to the server, you use the following URL and set it as the src attribute of an invisible :
http://www.tumblr.com/<command>/<oauthId>?id=<postId>

*

*command: like or unlike

*oauthId: last eight characters of {ReblogURL}

*postId: {PostID}
Example:
http://www.tumblr.com/like/23err8u4?id=844392923

Cut and paste the following code block into your theme immediately before . This will give you a like button on each post that looks like the default Tumblr grey heart. It will turn red when you hover over it and when you click it. If you click it again, it will turn grey again and delete the Like.

Then cut and paste the following button code into your theme where you want your like button to be (this must be inside your {block:Posts} block).
Code:

A: This is what i found in the sourcecode, it means that the div's with the links of the like button and the reblog button are just hard coded and hidden with css. As you can see there is a css block for when you hover over the element. So it's just CSS.
EDIT:
I added the HTML code of a post, as you can see there are a couple of div's with class permalink
CSS code
 /* CLAW */
   .claw .permalink {height: 60px; width: 60px; margin-bottom: -60px; position:       relative; background-repeat: no-repeat; background-position: -31px -31px;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)";
filter: alpha(opacity=60);
-moz-opacity: 0.6;
-khtml-opacity: 0.6;
opacity: 0.6;
}
.claw .permalink:hover {
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=85)";
filter: alpha(opacity=85);
-moz-opacity: 0.85;
-khtml-opacity: 0.85;
opacity: 0.85;
}
.claw.permalink {display: none;}
.claw .claw.permalink {display: block!important;}
  .post-shell.claw:hover .perma-link {background-position: 0px 0px;}
  .post-shell.claw:hover .perma-source {background-position: -62px 0px;}
  .post-shell.claw:hover .perma-like {background-position: 0px -62px;}
  .post-shell.claw:hover .perma-reblog {background-position: -62px -62px;}
  .claw .perma-link {margin-left: 12px;}
  .claw .perma-source {margin-right: 12px; float: right;}
  .claw .perma-reblog {margin: -60px 0 0 0; float: right;}
  .claw .perma-like {margin: -60px 0 0 0;}

HTML code of one post:


text:
Q: Passing dataframe and using its name to create the csv file I have a requirment where i need to pass different dataframes and print the rows in dataframes to the csv file and the name of the file needs to be the dataframe name. Example Below is the data frame
 **Dataframe**

  | Students | Mark | Grade |
  | -------- | -----|------ |
  | A        | 90   | a     |
  | B        | 60   | d     |
  | C        | 40   | b     |
  | D        | 45   | b     |
  | E        | 66   | d     |
  | F        | 80   | b     |
  | G        | 70   | c     |

A_Grade=df.loc[df['grade']=='a']

B_Grade=df.loc[df['grade']=='b']

C_Grade=df.loc[df['grade']=='c']

D_Grade=df.loc[df['grade']=='d']

E_Grade=df.loc[df['grade']=='e']

F_Grade=df.loc[df['grade']=='f']

each of these dataframes A_Grade,B_Grade,C_Grade etc needs to be created in separate file with name A_Grade.csv,B_Grade.csv,C_Grade.csv.
i wanted to use a for loop and pass the dataframe so to create it rather than writing separate lines to create the files as number of dataframe varies . This also sends msg using telegram bot.so the code snippet i tried is below. but it didnt work. in short the main thing is dynamically create the csv file with the dataframe name.
 for df in (A_Grade,B_Grade,C_Grade):
  if(len(df))
    dataframeitems.to_csv(f'C:\Documents\'+{df}+'{dt.date.today()}.csv',index=False)
    bot.send_message(chat_id=group_id,text='##{dfname.name} ##')

The solution given @Ynjxsjmh by work. Thanks @Ynjxsjmh. but i have another senario  where in a function as below has dataframe passed as argument and the result on the dataframe needs to be saved as csv with dataframe name.
def func(dataframe):
  ...
  ...
  ...
  dataframe2=some actions and operations on dataframe
  result = dataframe2

result.to_csv(params.datafilepath+f'ResultFolder\{dataframe}_{dt.date.today()}.csv',index=False)

The file needs to be saved as per the name of the dataframe.csv

A: I could get using below code
def get_df_name(df):
   name =[x for x in globals() if globals()[x] is df][0]
   return name

filename=get_df_name(dataframe)
print(filename)

A: Your f-string is weird, you can use Series.unique() to get unique values in Series.
for grade in df['Grade'].unique():
    grade_df = df[df['Grade'].eq(grade)]
    grade_df.to_csv(f'C:\Documents\{grade.upper()}_Grade_{dt.date.today()}.csv', index=False)


text:
Q: Query from more than one table Python Mysql Connector I have the following sql query:
SELECT
    pc.patente,
    cs.cpc_group_codigo_cpc_group

FROM
    patente_pc pc
    ,
    patente_cpc cpc,
    cpc_subgroup cs,
    cpc_group cg

WHERE
    pc.codigo_patente_pc = cpc.patente_pc_codigo_patente_pc AND
    cpc.cpc = cs.codigo_cpc_subgroup AND
    cs.cpc_group_codigo_cpc_group = cg.codigo_cpc_group

GROUP BY
    pc.patente, cs.cpc_group_codigo_cpc_group

I add this query to python, separating line by line the string in a tuple to not have a problem with the syntax..
and it executes correctly
but when I need to retrieve the data, I use
lista_cpcs = []
lista_patentes = []
for (pc.patente, cs.cpc_group_codigo_cpc_group) in cursor:
    lista_cpcs.append(cs.cpc_group_codigo_cpc_group)
    lista_patentes.append(pc.patente)

return [lista_cpcs, lista_patentes]

and I get the error Global name 'pc' is not defined
I get whats happening, it's interpreting pc and cs as python modules, but they are from the sql..
how to work in this?
Ps: I search for python mysql connector and didn't found anything with this.

A: The variables in your for loop: (pc.patente, cs.cpc_group_codigo_cpc_group) are user defined; the names used do not have anything to do with the names from the query.  Thus, you can call them whatever you want.  You may consider using (pc__patente, cs__cpc_group_codigo_cpc_group) or something.
The problem is that the dot notation in python != the dot notation from your SQL.

A: Got it, sorry for the post..
Searching in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-description.html
I learned a few attributes of the cursor, and using the Eclipse debugger I saw that it comes just the name, not the table connection..so I use
for (patente, cpc_group_codigo_cpc_group) in cursor:
    lista_cpcs.append(cpc_group_codigo_cpc_group)
    lista_patentes.append(patente)

and it's working now, and thanks for the help @Scott


text:
Q: What has happened to the function "grid.draw" I tried to use the function grid.draw when making a plot in ggplot2, but I got an error message:
could not find function "grid.draw"

Is this function defunct? Has it been replaced?

A: grid.draw has always been in the grid package (Recommended, hence included with most R distributions)


text:
Q: Exogenous variable in both the mean and variance model? \begin{aligned}
y_t &= \beta_0 + \beta_1 y_{t-1} + \beta_2 x_{t-1} + \epsilon_t, \\
\epsilon_t &= \sqrt{h_t}\eta_t, \\
h_t &= \alpha_0 + \alpha_1 \epsilon_{t-1}^2 + \alpha_2 h_{t-1} + \alpha_3 e^{x_{t-1}}, \\
\eta_t &\sim N(0,1) \ \forall \ t. \\
\end{aligned}

*

*Does it make sense to include an exogenous variable ($x_t$) in both the mean and the variance model?

*Do standard inferences about the coefficients still apply here?

*Given the exogenous variable is in both the mean and the variance, we would see endogeneity and hence biased estimate of the $\beta_2$ parameter?

A: *

*This may make sense. There is nothing contradictory or paradoxical in including $x_t$ in both the conditional mean and the conditional variance equations.

*It depends on what do you mean by standard. Inference on $\alpha$s is in a way nonstandard even in a simple GARCH model; see Part II of Francq & Zakoian "GARCH Models: Structure, Statistical Inference and Financial Applications" (2010), e.g. Chapter 8 "Tests Based on the Likelihood". Other than that, I do not expect that adding an exogenous variable to the equations should mess up the inference further, at least when $y_t$ and $x_t$ are stationary.

*No, I do not think there is endogeneity, because $x$ is not a function of $y$. Regarding unbiasedness, even without exogeneous regressors, coefficient estimates may be biased. In a simple AR(1) model, I think both the OLS and the ML estimators are biased. Adding an exogenous regressor and making the conditional variance time varying will not change that.


text:
Q: If $B \subseteq A$ and $f:A\overset{1-1}\longrightarrow B$ then $A \supseteq B \supseteq f^1(A) \supseteq f^1 (B) \supseteq f^2(A) \supseteq...$ In The Foundations of Mathematics by Kenneth Kunen, the following Lemma is posited:
If $B \subseteq A$ and $f:A\overset{1-1}\longrightarrow B$ then $A \approx B$
In the course of proving this statement, the author makes the intermediary claim:

$A \supseteq B \supseteq f^1(A) \supseteq f^1 (B) \supseteq f^2(A) \supseteq f^2(B) \supseteq...$

The aim of this question is to prove this above claim.
The only other information necessary is the explanation of the notation $f^n$...
Kunen alludes to the creation of a recursive function, which I have attempted to formalize below:
$$F(n): \begin{cases}
I_A \quad \quad \quad \quad \quad \quad \quad \quad \quad \text{if } n=0 \\
f \circ (F\upharpoonright n) (n-1) \quad \quad \ \text {if } 1\leq n \lt \omega
\end{cases}$$
where $f$ is the aforementioned  $f:A\overset{1-1}\longrightarrow B$.
For notational convenience, for all $0 \leq n \lt \omega$, $F(n)$ will be written as $f^n$.
For example, $F(0)=f^0$, $F(1)=f^1$, etc.
And from our rule: $f^0 = I_A$, $f^1=f\circ f^0$, $f^2=f\circ f^1$, $f^3=f\circ f^2$, etc.

Proving The Claim If $B \subseteq A$ and $f:A\overset{1-1}\longrightarrow B$ then $A \supseteq B \supseteq f^1(A) \supseteq f^1 (B) \supseteq f^2(A) \supseteq f^2(B) \supseteq...$
I believe the above statement amounts to proving the following two statements:
Statement 1. $\forall n \in \omega\big( f^n(B) \subseteq f^n(A)\big)$
Statement 2. $\forall n \in \omega\big( f^{n+1}(A) \subseteq f^n(B)\big)$
Also, I think it is necessary to demonstrate that $\forall n \in \omega \big(f^n(A) \subseteq A \land f^n(B) \subseteq A \big)$. Recognizing that $f$ could be rewritten as $f:A\overset{1-1}\longrightarrow A$ (because $B \subseteq A$), this is straightforward so will not be proven.

Proof of Statement 1:
Base Case $n=0$: $f^0(B)\subseteq f^0(A)$
$f^0 = I_A$, $I_A(B)=B, I_A(A)=A$, $B \subseteq A$
Assume for $n$: $f^n(B) \subseteq f^n(A)$
Prove for $n+1$: $f^{n+1}(B) \subseteq f^{n+1}(A)$
Note that $f^{n+1}(B) = f \circ f^n (B)$ and $f^{n+1}(A) = f \circ f^n (A)$
By definition of function composition:
$f \circ f^n (B)=f\big(f^n (B)\big)$ and $f \circ f^n (A)=f\big(f^n (A)\big)$
Let $y$ be an arbitrary element in $f\big(f^n (B)\big)$.
Therefore, there is an $x \in f^n (B)$ such that $f(x)=y$.
By assumption, $f^n(B) \subseteq f^n(A)$, which means that $x \in f^n(A)$.
But then $f(x) \in f\big(f^n(A)\big)$...so $y\in f\big(f^n(A)\big) \quad \square$

Proof of Statement 2 - A very similar argument
Base Case $n=0$: $f^1(A) \subseteq f^0(B)$
$f^1(A)=f(A)$ and $f^0(B)=B$. By the definition of $f$, $f(A) \subseteq B$
Assume for $n$:  $f^n+1(A) \subseteq f^n(B)$
Prove for $n+1$: $f^{n+2}(A) \subseteq f^{n+1}(B)$
$f^{n+2}(A)=f\big(f^{n+1}(A)\big)$ and $f^{n+1}(B)=f\big(f^n(B)\big)$
Let $y$ be an arbitrary element in $f\big(f^{n+1}(A)\big)$.
Therefore, there is an $x \in f^{n+1}(A)$ such that $f(x)=y$.
By assumption, $f^n+1(A) \subseteq f^n(B)$, which means $x \in f^n(B)$.
But then $f(x) \in f\big(f^n(B)\big)$...so $y\in f\big(f^n(B)\big) \quad \square$


text:
Q: Solr, Tomcat 7 on windows Server 2008 (64 bit), admin screens return 404 I'm not sure if this belongs here or on super user.
We have set up Tomcat 7 on our server and have configured Solr.  We can go to localhost/solr and localhost/solr/admin, but on the admin screen when we click "configure" or "schema" we get a 404 error for "/solr/admin/file/?file=solrconfig.xml"
We tried entering the url /solr/admin/get-file.jsp?file=solrconfig.xml and we get an access denied.
Our solr home, as shown on our admin page, is c:\solr.  We have granted "everyone" full control to this folder (and verified the xml files have this permission) and yet it still errors.
We have tried putting bin and conf in the webapps\solr folder and that didn't help.
Any suggestions are greatly appreciated

A: We found out it is a bug in the solr implementation.  There is an extra "/" in the url which causes the 404 error.  If you remove it, so the url looks like

/solr/admin/file?file=solrconfig.xml

instead of

/solr/admin/file/?file=solrconfig.xml

the error goes away.  Hope this helps someone else.


text:
Q: Can you use functions within a switch case in JavaScript I would like to be able to call a function on a switch case statement but I can't seem to figure it out. Example:
switch(message.toLowerCase()) {
    // the startsWith would be an extension of the message.toLowerCase()
    // so that the case would be checking for message.toLowerCase().startsWith("pay")
    case startsWith("pay"):
        console.log(message)
        break
}

I have tried using case.function(), function(case), and case function(), but none of them work. Thanks!

A: Switch statements in JavaScript don't support pattern matching, they only do simple equality checks (the result of lowerCase() gets compared to the return value of startsWith(...) [if that function would exist]). You could do something like this though:
switch(true) {
  case message.toLowerCase().startsWith("pay"): // if this is true, the case matches
    console.log(message);
    break;
 }

You could also write some helpers to achieve more flexible pattern matching:
  const match = (...patterns) => value=> patterns.find(p => p.match(value))(value);
   const pattern = match => fn => Object.assign(fn, { match });
  const startWith = a => pattern(v => v.startsWith(a));

 match(
    startsWith("b")(console.error),
    startsWith("a")(console.log),
    startsWith("a")(console.error)
 )("abc")

A: One option is to use switch(true).
var m = message.toLowerCase()
switch(true) {
    case m.startsWith("pay"):
        console.log(message)
        break
}

Read the original thread for more details (e.g. that the case return value must be truely true, e.g. 1 would not work (but would work for if-else.
Also consider to use ordinary if-else, sometimes it might be more readable and maintainable than switch (and especially than this "non-standard" swith(true))
Also consider using regular expression. From the OP it is not really clear what you are looking for.


text:
Q: Fatal Exception on Google SignInButton Encounter fatal error invoking on null object from
signInButton = (SignInButton) findViewById(R.id.sign_in_button);

Although I believe it's already been instantiated before invoking setSize in onCreate
I'm all out of idea, anyone could point out what's causing this error?
package artlvlup.how.to.draw;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import artlvlup.how.to.draw.drawer.MenuItemCallback;
import artlvlup.how.to.draw.drawer.NavItem;
import artlvlup.how.to.draw.drawer.SimpleMenu;
import artlvlup.how.to.draw.drawer.TabAdapter;
import artlvlup.how.to.draw.inherit.BackPressFragment;
import artlvlup.how.to.draw.inherit.CollapseControllingFragment;
import artlvlup.how.to.draw.inherit.PermissionsFragment;
import artlvlup.how.to.draw.providers.CustomIntent;
import artlvlup.how.to.draw.providers.fav.ui.FavFragment;
import artlvlup.how.to.draw.util.Log;
import artlvlup.how.to.draw.util.Helper;
import artlvlup.how.to.draw.util.layout.DisableableViewPager;

import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This file is part of the Universal template
 * For license information, please check the LICENSE
 * file in the root of this project
 *
 * @author Sherdle
 * Copyright 2016
 */
public class MainActivity extends AppCompatActivity implements
        MenuItemCallback, ConfigParser.CallBack,
        OnConnectionFailedListener, View.OnClickListener {

    private Toolbar mToolbar;
    private TabLayout tabLayout;
    private DisableableViewPager viewPager;
    private NavigationView navigationView;
    private TabAdapter adapter;
    private static SimpleMenu menu;

    private DrawerLayout drawer;
    private ActionBarDrawerToggle toggle;

    private SignInButton signInButton;
    private TextView sign_in_text_button;
    private GoogleSignInOptions gso;
    private GoogleApiClient mGoogleApiClient;

    //Keep track of the interstitials we show
    private int interstitialCount = -1;

    //Data to pass to a fragment
    public static String FRAGMENT_DATA = "transaction_data";
    public static String FRAGMENT_CLASS = "transation_target";

    public static boolean TABLET_LAYOUT = true;

    //Permissions Queu
    List<NavItem> queueItem;
    MenuItem queueMenuItem;

    @Override
    public void configLoaded(boolean facedException) {
        if (facedException || menu.getFirstMenuItem() == null){
            if (Helper.isOnlineShowDialog(MainActivity.this))
                Toast.makeText(this, artlvlup.how.to.draw.R.string.invalid_configuration, Toast.LENGTH_LONG).show();
        } else {
            //Load the first item (we assume the first item doesn't require purchase)
            menuItemClicked(menu.getFirstMenuItem().getValue(), menu.getFirstMenuItem().getKey(), false);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Google Sign-in
        // Configure sign-in to request the user's ID, email address, and basic
        // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

        //Initializing signinbutton
        signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);
        signInButton.setOnClickListener(this);

        // Build a GoogleApiClient with access to the Google Sign-In API and the
        // options specified by gso.
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        //Load the appropriate layout
        if (useTabletMenu()){
            setContentView(artlvlup.how.to.draw.R.layout.activity_main_tablet);
            Helper.setStatusBarColor(MainActivity.this,
                    ContextCompat.getColor(this, artlvlup.how.to.draw.R.color.myPrimaryDarkColor));
        } else {
            setContentView(artlvlup.how.to.draw.R.layout.activity_main);
        }

        mToolbar = (Toolbar) findViewById(artlvlup.how.to.draw.R.id.toolbar);
        setSupportActionBar(mToolbar);

        if (!useTabletMenu())
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        else {
            getSupportActionBar().setDisplayShowHomeEnabled(false);
        }

        //Drawer
        if (!useTabletMenu()) {
            drawer = (DrawerLayout) findViewById(artlvlup.how.to.draw.R.id.drawer);
            toggle = new ActionBarDrawerToggle(
                    this, drawer, mToolbar, artlvlup.how.to.draw.R.string.drawer_open, artlvlup.how.to.draw.R.string.drawer_close);
            drawer.setDrawerListener(toggle);
            toggle.syncState();
        }

        //Layouts
        tabLayout = (TabLayout) findViewById(artlvlup.how.to.draw.R.id.tabs);
        viewPager = (DisableableViewPager) findViewById(artlvlup.how.to.draw.R.id.viewpager);

        //Check if we should open a fragment based on the arguments we have
        if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(FRAGMENT_CLASS)) {
            try {
                Class<? extends Fragment> fragmentClass = (Class<? extends Fragment>) getIntent().getExtras().getSerializable(FRAGMENT_CLASS);
                if (fragmentClass != null) {
                    String[] extra = getIntent().getExtras().getStringArray(FRAGMENT_DATA);

                    HolderActivity.startActivity(this, fragmentClass, extra);
                    finish();
                    //Optionally, we can also point intents to holderactivity directly instead of MainAc.
                }
            } catch (Exception e) {
                //If we come across any errors, just continue and open the default fragment
                Log.printStackTrace(e);
            }
        }

        //Menu items
        navigationView = (NavigationView) findViewById(artlvlup.how.to.draw.R.id.nav_view);
        menu = new SimpleMenu(navigationView.getMenu(), this);
        if (Config.USE_HARDCODED_CONFIG) {
            Config.configureMenu(menu, this);
        } else if (!Config.CONFIG_URL.isEmpty() && Config.CONFIG_URL.contains("http"))
            new ConfigParser(Config.CONFIG_URL, menu, this, this).execute();
        else
            new ConfigParser("config.json", menu, this, this).execute();
        tabLayout.setupWithViewPager(viewPager);

        if (!useTabletMenu()) {
            drawer.setStatusBarBackgroundColor(
                ContextCompat.getColor(this, artlvlup.how.to.draw.R.color.myPrimaryDarkColor));
        }

        applyDrawerLocks();

        Helper.admobLoader(this, getResources(), findViewById(artlvlup.how.to.draw.R.id.adView));
        Helper.updateAndroidSecurityProvider(this);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageScrollStateChanged(int state) {}
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

            public void onPageSelected(int position) {
                onTabBecomesActive(position);
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                boolean foundfalse = false;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        foundfalse = true;
                    }
                }
                if (!foundfalse){
                    //Retry to open the menu item
                    //(we can assume the item is 'purchased' otherwise a permission check would have not occured)
                    menuItemClicked(queueItem, queueMenuItem, false);
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, getResources().getString(artlvlup.how.to.draw.R.string.permissions_required), Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void menuItemClicked(List<NavItem> actions, MenuItem item, boolean requiresPurchase) {
        // Checking if the user would prefer to show the menu on start
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        boolean openOnStart = prefs.getBoolean("menuOpenOnStart", false);
        if (drawer != null)
            if (openOnStart && !useTabletMenu() && adapter == null) {
                drawer.openDrawer(GravityCompat.START);
            } else {
                //Close the drawer
                drawer.closeDrawer(GravityCompat.START);
            }

        //Check if the user is allowed to open item
        if (requiresPurchase && !isPurchased()) return; //isPurchased will handle this.
        if (!checkPermissionsHandleIfNeeded(actions, item)) return; //checkPermissions will handle.

        if (isCustomIntent(actions)) return;

        //Uncheck all other items, check the current item
        if (item != null) {
            for (MenuItem menuItem : menu.getMenuItems())
                menuItem.setChecked(false);
            item.setChecked(true);
        }

        //Load the new tabs
        adapter = new TabAdapter(getSupportFragmentManager(), actions, this);
        viewPager.setAdapter(adapter);

        //Show or hide the tab bar depending on if we need it
        if (actions.size() == 1) {
            tabLayout.setVisibility(View.GONE);
            viewPager.setPagingEnabled(false);
        } else {
            tabLayout.setVisibility(View.VISIBLE);
            viewPager.setPagingEnabled(true);
        }

        //Show in interstitial
        showInterstitial(false);

        onTabBecomesActive(0);
    }

    private void onTabBecomesActive(int position){
        Fragment fragment = adapter.getItem(position);
        //If fragment does not support collapse, or if OS does not support collaps, disable collapsing toolbar
        if ((fragment instanceof CollapseControllingFragment
                && !((CollapseControllingFragment) fragment).supportsCollapse())
                ||
                (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT))
            lockAppBar();
        else
            unlockAppBar();

        if (position != 0)
            showInterstitial(true);
    }

    /**
     * Show an interstitial ad
     * @param fromPager if the showing is triggered from a swipe in the viewpager
     */
    private void showInterstitial(boolean fromPager){
        //if (fromPager) return;
        if (getResources().getString(artlvlup.how.to.draw.R.string.admob_interstitial_id).length() == 0) return;
        if (SettingsFragment.getIsPurchased(this)) return;

        if (interstitialCount == (Config.INTERSTITIAL_INTERVAL - 1)) {
            final InterstitialAd mInterstitialAd = new InterstitialAd(this);
            mInterstitialAd.setAdUnitId(getResources().getString(artlvlup.how.to.draw.R.string.admob_interstitial_id));
            AdRequest adRequestInter = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
            mInterstitialAd.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    mInterstitialAd.show();
                }
            });
            mInterstitialAd.loadAd(adRequestInter);

            interstitialCount = 0;
        } else {
            interstitialCount++;
        }

    }

    /**
     * Checks if the item is/contains a custom intent, and if that the case it will handle it.
     * @param items List of NavigationItems
     * @return True if the item is a custom intent, in that case
     */
    private boolean isCustomIntent(List<NavItem> items){
        NavItem customIntentItem = null;
        for (NavItem item : items){
            if (CustomIntent.class.isAssignableFrom(item.getFragment())){
                customIntentItem = item;
            }
        }

        if (customIntentItem == null) return false;
        if (items.size() > 1) Log.e("INFO", "Custom Intent Item must be only child of menu item! Ignorning all other tabs");

        CustomIntent.performIntent(MainActivity.this, customIntentItem.getData());
        return true;
    }

    /**
     * If the item can be opened because it either has been purchased or does not require a purchase to show.
     * @return true if the app is purchased. False if the app hasn't been purchased, or if iaps are disabled
     */
    private boolean isPurchased(){
        String license = getResources().getString(artlvlup.how.to.draw.R.string.google_play_license);
        // if item does not require purchase, or app has purchased, or license is null/empty (app has no in app purchases)
        if (!SettingsFragment.getIsPurchased(this) && !license.equals("")) {
            String[] extra = new String[] {SettingsFragment.SHOW_DIALOG};
            HolderActivity.startActivity(this, SettingsFragment.class, extra);

            return false;
        }

        return true;
    }

    /**
     * Checks if the item can be opened because it has sufficient permissions.
     * @param tabs The tabs to check
     * @return true if the item is safe to open
     */
    private boolean checkPermissionsHandleIfNeeded(List<NavItem> tabs, MenuItem item){
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) return true;

        List<String> allPermissions = new ArrayList<>();
        for (NavItem tab : tabs){
            if (PermissionsFragment.class.isAssignableFrom(tab.getFragment())) {
                try {
                    allPermissions.addAll(Arrays.asList(((PermissionsFragment) tab.getFragment().newInstance()).requiredPermissions()));
                } catch (Exception e) {
                    //Don't really care
                }
            }
        }

        if (allPermissions.size() > 1) {
            boolean allGranted = true;
            for (String permission : allPermissions) {
                if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED)
                    allGranted = false;
            }

            if (!allGranted) {
                //TODO An explaination before asking
                requestPermissions(allPermissions.toArray(new String[0]), 1);
                queueItem = tabs;
                queueMenuItem = item;
                return false;
            }

            return true;
        }

        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(artlvlup.how.to.draw.R.menu.settings_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case artlvlup.how.to.draw.R.id.settings:
                HolderActivity.startActivity(this, SettingsFragment.class, null);
                return true;
            case artlvlup.how.to.draw.R.id.favorites:
                HolderActivity.startActivity(this, FavFragment.class, null);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onBackPressed() {
        Fragment activeFragment = null;
        if (adapter != null)
            activeFragment = adapter.getCurrentFragment();

        if (drawer != null && drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else if (activeFragment instanceof BackPressFragment){
            boolean handled = ((BackPressFragment) activeFragment).handleBackPress();
            if (!handled){
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null)
            for (Fragment frag : fragments)
                if (frag != null)
                    frag.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getWindow().getDecorView().findViewById(android.R.id.content).invalidate();
    }

    //Check if we should adjust our layouts for tablets
    public boolean useTabletMenu(){
        return (getResources().getBoolean(artlvlup.how.to.draw.R.bool.isWideTablet) && TABLET_LAYOUT);
    }

    //Apply the appropiate locks to the drawer
    public void applyDrawerLocks(){
        if (drawer == null) {
            if (Config.HIDE_DRAWER)
                navigationView.setVisibility(View.GONE);
            return;
        }

        if (Config.HIDE_DRAWER){
            toggle.setDrawerIndicatorEnabled(false);
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        } else {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        }
    }

    public void lockAppBar() {
        AppBarLayout.LayoutParams params =
                (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        params.setScrollFlags(0);
    }

    public void unlockAppBar() {
        AppBarLayout.LayoutParams params =
                (AppBarLayout.LayoutParams) mToolbar.getLayoutParams();
        params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
                | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
    }

    private void updateUI(boolean signedIn) {
        if (signedIn) {
            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, 100);
    }

    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    // [START_EXCLUDE]
                    updateUI(false);
                    // [END_EXCLUDE]
                }
            });
    }

    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    // [START_EXCLUDE]
                    updateUI(false);
                    // [END_EXCLUDE]
                }
            });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            case R.id.sign_out_button:
                signOut();
                break;
            case R.id.disconnect_button:
                revokeAccess();
                break;
        }
    }
}

Error as shown below:
06-23 18:24:14.987 24144-24144/artlvlup.how.to.draw E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: artlvlup.how.to.draw, PID: 24144
                                                                      java.lang.RuntimeException: Unable to start activity ComponentInfo{artlvlup.how.to.draw/artlvlup.how.to.draw.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2356)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
                                                                          at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:135)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5289)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                          at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
                                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setSize(int)' on a null object reference
                                                                          at artlvlup.how.to.draw.MainActivity.onCreate(MainActivity.java:126)
                                                                          at android.app.Activity.performCreate(Activity.java:5990)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
                                                                          at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:135)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5289)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                          at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)

A: You need to call setContentView method before accessing the items in layout.
It should be first,
//Load the appropriate layout
if (useTabletMenu()){
    setContentView(artlvlup.how.to.draw.R.layout.activity_main_tablet);
    Helper.setStatusBarColor(MainActivity.this,
    ContextCompat.getColor(this, artlvlup.how.to.draw.R.color.myPrimaryDarkColor));
} else {
    setContentView(artlvlup.how.to.draw.R.layout.activity_main);
}

then,
//Initializing signinbutton
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(this);

A: In onCreate after line super.onCreate... you have to call setContentView and initialize your layout where you have R.id.sign_in_button.


text:
Q: Frequent Corrupt Indexes in MySQL 5.6. Is this a MySQL bug? I´m having problems with mysql indexes with INNODB getting corrupted. Initially I solved it by rebuilding the tables but now the tables are to large to rebuild, and i´m tired of mysql not showing consistent results.
I´m inserting close to 10000 records daily among 4 or 5 tables, and I have some jobs continuously updating data on those records (probably 100000 updates a day)
Is this a bug in MySQL? How would you solve this issue?
In the following statements you can see the discrepancy because the row with 3 conditions shows 3433 results and if I remove one condition I get 0 results. I use the UNION to show that the queries are done almost at the same time so it´s very unlikely that the records are actually disappearing between the queries and coming back right after, because when I repeat the query I get the same results.
mysql> SELECT count(*) FROM licitaciones WHERE entidad_id = 103 AND estado_id = 7 and tipo_id > 0
       UNION
       SELECT count(*) FROM licitaciones WHERE entidad_id = 103 AND estado_id = 7;
+----------+
| count(*) |
+----------+
|     3433 |
|        0 |
+----------+
2 rows in set (0.16 sec)

Here is the mysql version... I´m using INNODB by the way.
mysql> select version();
+-------------------------+
| version()               |
+-------------------------+
| 5.6.33-0ubuntu0.14.04.1 |
+-------------------------+
1 row in set (0.00 sec)

Just to clarify. The UNION was only to expose the fact that the rows were not changing from one statement to the other, but the result is the same if the queries are performed in separate statements:
mysql> SELECT count(*) FROM licitaciones WHERE entidad_id = 103 AND estado_id = 7 and tipo_id > 0;
+----------+
| count(*) |
+----------+
|     3436 |
+----------+
1 row in set (0.55 sec)

mysql> SELECT count(*) FROM licitaciones WHERE entidad_id = 103 AND estado_id = 7;
+----------+
| count(*) |
+----------+
|        0 |
+----------+
1 row in set (0.06 sec)

MORE INFO:
mysql> EXPLAIN SELECT count(*) FROM licitaciones WHERE entidad_id = 103 AND estado_id = 7 and tipo_id > 0;
+----+-------------+--------------+-------------+------------------------------+----------------------+---------+------+------+----------------------------------------------------+
| id | select_type | table        | type        | possible_keys                | key                  | key_len | ref  | rows | Extra                                              |
+----+-------------+--------------+-------------+------------------------------+----------------------+---------+------+------+----------------------------------------------------+
|  1 | SIMPLE      | licitaciones | index_merge | entidad_id,tipo_id,estado_id | entidad_id,estado_id | 5,4     | NULL | 3557 | Using intersect(entidad_id,estado_id); Using where |
+----+-------------+--------------+-------------+------------------------------+----------------------+---------+------+------+----------------------------------------------------+

mysql> EXPLAIN SELECT count(*) FROM licitaciones WHERE entidad_id = 103 AND estado_id = 7;
+----+-------------+--------------+-------------+----------------------+----------------------+---------+------+------+-----------------------------------------------------------------+
| id | select_type | table        | type        | possible_keys        | key                  | key_len | ref  | rows | Extra                                                           |
+----+-------------+--------------+-------------+----------------------+----------------------+---------+------+------+-----------------------------------------------------------------+
|  1 | SIMPLE      | licitaciones | index_merge | entidad_id,estado_id | entidad_id,estado_id | 5,4     | NULL | 3557 | Using intersect(entidad_id,estado_id); Using where; Using index |
+----+-------------+--------------+-------------+----------------------+----------------------+---------+------+------+-----------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> show create table licitaciones;
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table        | Create Table                                                                                |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| licitaciones | CREATE TABLE `licitaciones` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `detected` datetime DEFAULT CURRENT_TIMESTAMP,
  `num_constancia` varchar(60) DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  `fila` int(11) DEFAULT NULL,
  `num_proceso` varchar(255) DEFAULT NULL,
  `tipo_id` tinyint(4) DEFAULT NULL,
  `estado_id` mediumint(9) DEFAULT NULL,
  `entidad_id` int(11) DEFAULT NULL,
  `objeto` longtext,
  `cuantia` bigint(20) DEFAULT NULL,
  `tipo_fecha_id` smallint(6) DEFAULT NULL,
  `fecha` date DEFAULT NULL,
  `extra_updated` date DEFAULT NULL,
  `extra_json` mediumtext,
  `fastcodes` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `num_constancia` (`num_constancia`),
  KEY `entidad_id` (`entidad_id`),
  KEY `tipo_id` (`tipo_id`),
  KEY `estado_id` (`estado_id`),
  KEY `tipo_fecha_id` (`tipo_fecha_id`),
  KEY `fecha` (`fecha`),
  KEY `cuantia` (`cuantia`),
  KEY `num_proceso` (`num_proceso`),
  KEY `extra_updated` (`extra_updated`),
  KEY `detected` (`detected`),
  FULLTEXT KEY `fulltextidx` (`objeto`,`fastcodes`,`extra_json`)
) ENGINE=InnoDB AUTO_INCREMENT=32050336 DEFAULT CHARSET=latin1 |
+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

A: The Rick James's answer is right, I just could not add a comment.
We got a very similar problem, the query with special conditions can not find the record, but that record is here by other where conditions. The problem is the "index_merge", it solved by avoiding the "index_merge_intersection":
SET SESSION optimizer_switch='index_merge_intersection=off';

or
SET GLOBAL optimizer_switch='index_merge=off';

It also worked by adding or removing some indexes to avoid the "index_merge".

A: The index is not corrupt.
There is nothing controlling the order of the rows.  In fact, if the two counts had been the same you would have gotten only one row of output -- because UNION means UNION DISTINCT.
Do the query this way instead:
SELECT "with tipo" As the_case,
       count(*)
    FROM licitaciones
    WHERE entidad_id = 103 AND estado_id = 7 and tipo_id > 0
UNION DISTINCT
SELECT "without",
       count(*)
    FROM licitaciones
    WHERE entidad_id = 103 AND estado_id = 7;

Better yet, do both in a single SELECT:
SELECT count(*)         AS "without tipo test",
       SUM(tipo_id > 0) AS "with tipo test"
    FROM licitaciones
    WHERE entidad_id = 103 AND estado_id = 7;

A: Thanks for updating with the EXPLAIN and SHOW CREATE TABLE output.
It appears you have only single-column indexes, and MySQL is trying to use the index-merge optimization to make use of more than one index. Index-merge is not a well-tested feature of MySQL.
I can't find a reference to a bug regarding index-merge except some that involve partitioned tables. But it's possible a bug exists that have not been reported.
I would suggest that you learn how to use multi-column indexes instead of relying on the index-merge feature. It'll be more reliable, and probably have much better performance too.
This index should help both your queries:
ALTER TABLE licitaciones ADD KEY (entidad_id, estado_id, tipo_id);

Read my presentation How to Design Indexes, Really. Watch the video of me presenting this talk here: https://www.youtube.com/watch?v=ELR7-RdU9XU


text:
Q: how to upgrade firmware intel wifi iwlwifi ? unstable wireless Intel 7260 with lenovo t440p How to upgrade the  firmware intel WiFi  from 7260-10 to 7260-12.
on Intel page said: "Installation of the firmware is simply:"
# cp iwlwifi-*.ucode /lib/firmware

So I have
#sudo ls -al /lib/firmware/iwlwifi-7260-*
-rw-r----- 1 root root 672352 Mar 19 14:19 /lib/firmware/iwlwifi-7260-10.ucode
-rw-r--r-- 1 root root 782300 Mar 19 13:35 /lib/firmware/iwlwifi-7260-12.ucode
-rw-r--r-- 1 root root 683236 Nov 24 15:42 /lib/firmware/iwlwifi-7260-7.ucode
-rw-r--r-- 1 root root 679780 Dec  1 15:16 /lib/firmware/iwlwifi-7260-8.ucode
-rw-r--r-- 1 root root 680508 Dec  1 20:45 /lib/firmware/iwlwifi-7260-9.ucode

But I doesn't load the last version 7260-12, trying to reboot but no luck it stays with 7260-10 .
sudo dmesg | grep iwl
[    4.673076] iwlwifi 0000:03:00.0: found PCI INT A -> IRQ 10
[    4.673090] iwlwifi 0000:03:00.0: sharing IRQ 10 with 0000:00:1c.1
[    4.680093] iwlwifi 0000:03:00.0: loaded firmware version 23.15.10.0 op_mode iwlmvm

and
modinfo iwlmvm
filename:       /lib/modules/3.19.0-6-generic/updates/drivers/net/wireless/iwlwifi/mvm/iwlmvm.ko
version:        backported from Linux (v3.19-rc1-0-g97bf6af) using backports v3.19-rc1-1-0-g74aaf28

I have unstable WiFi connection.

A: Have you tried
sudo cp /lib/firmware/iwlwifi-7260-10.ucode /lib/firmware/iwlwifi-7260-10.ucode.bak
sudo cp /lib/firmware/iwlwifi-7260-12.ucode /lib/firmware/iwlwifi-7260-10.ucode

Then reboot, renaming the file works sometimes
You could edit the source from the backports by going into the backports directory and into /driver/net/wireless/iwlwifi and edit iwl-7000.c line 72 as it should be
#define IWL7260_UCODE_API_MAX   10

and change it to
#define IWL7260_UCODE_API_MAX   12

Save and exit text editor, then you can
make clean
make defconfig-iwlwifi
make
sudo make install

and see if it will load the 12.ucode without changing file names.


text:
Q: Как установить Docker на OS X Yosemite (10.10) Пытался качать старые версии под Yosemite, но они при запуске отваливаются.
Начал ставить с помощью homebrew, там получаю ошибку
==> Installing dependencies for docker: go and go-md2man
go: macOS El Capitan or newer is required.
Error: An unsatisfied requirement failed this build.

Последняя версия golang для Yosemite - 1.12, ее поставить получилось, однако, попытка поставить docker закончилась той же ошибкой.
iMac27-2 ~$ brew info go
go: stable 1.14.5, HEAD
Open source programming language to build simple/reliable/efficient software
https://golang.org
Not installed
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/go.rb
License: BSD-3-Clause
==> Requirements
Required: macOS >= 10.11 ✘
==> Options
--HEAD
Install HEAD version
==> Analytics
install: 95,497 (30 days), 262,945 (90 days), 1,299,007 (365 days)
install-on-request: 78,643 (30 days), 214,033 (90 days), 1,031,655 (365 days)
build-error: 0 (30 days)

iMac27-2 ~$ brew info go@1.12
go@1.12: stable 1.12.17 [keg-only]
Go programming environment (1.12)
https://golang.org
/usr/local/Cellar/go@1.12/1.12.17 (9,630 files, 449MB) *
  Built from source on 2020-07-17 at 09:30:03
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/go@1.12.rb
License: BSD-3-Clause
==> Caveats
go@1.12 is keg-only, which means it was not symlinked into /usr/local,
because this is an alternate version of another formula.
==> Analytics
install: 790 (30 days), 2,886 (90 days), 30,056 (365 days)
install-on-request: 659 (30 days), 2,261 (90 days), 18,651 (365 days)
build-error: 0 (30 days)

iMac27-2 ~$ go version
go version go1.12.17 darwin/amd64

Вариантов решения два:

*

*Подскажите, пожалуйста, откуда скачать нормальную версию docker`а

*Подскажите, пожалуйста, как homebrew указать, чтобы при установке докера он брал golang из уже установленной формулы


text:
Q: nginx Wordpress URL rewrite I've just installed nginx 1.0.8 and php-fpm and for the last 30 minutes I'm trying to rewrite the URL for Wordpress.
Here is what the Wordpress URL should look like:
http://localhost/website/blog/2011/10/sample-post/
I've looked at this tutorial: http://wiki.nginx.org/WordPress + many other on the web but every time I receive an 404 error (sometimes 403).
Here is what I did in my configuration file:
    location /website/blog {
            try_files $uri $uri/ /website/blog/index.php;
    }

    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_intercept_errors on;
        fastcgi_split_path_info ^(/website/blog)(/.*)$;
        include        fastcgi_params;
        error_page  404 /404.html;
    }

With this configuration I'm receiving "403 forbidden" status.
What am I missing?

A: Could be the permission of the root site folder
This is an example that i use to wordpress
server {
listen 80;
server_name www.mysite.com mysite.com;
root /srv/www/mysite.com/public_html;
location / {
    index  index.html index.htm index.php;
    try_files $uri $uri/ /index.php?$args;
}
 rewrite /wp-admin$ $scheme://$host$uri/ permanent;
 include /srv/www/mysite.com/public_html/*.conf;
 location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

}

A: Did you try restarting nginx after you have saved your config?
Also, check out my nginx/WordPress setup guide here:
http://themesforge.com/featured/high-performance-wordpress-part-3/


text:
Q: How To Configure Django Authy For Two Factor Authentication I have been researching Django 2 factor for the last couple days.  I've finally come to a point where I've gotten the Django Twilio phone verification to work.  Here is the code the working code...
from authy.api import AuthyApiClient
from django.conf import settings
from django.shortcuts import render, redirect

from .forms import VerifyForm, TokenForm

authy_api = AuthyApiClient(settings.ACCOUNT_SECURITY_API_KEY)

def SetupView(request):
    if request.method == 'POST':
        form = VerifyForm(request.POST)
        if form.is_valid():
            request.session['phone_number'] = form.cleaned_data['phone_number']
            request.session['country_code'] = form.cleaned_data['country_code']
            authy_api.phones.verification_start(
                form.cleaned_data['phone_number'],
                form.cleaned_data['country_code'],
                via=form.cleaned_data['via']
            )
            return redirect('token_validation')
    else:
        form = VerifyForm()
    return render(request, 'registration/verify.html', {'form': form})

def token_validation(request):
    if request.method == 'POST':
        form = TokenForm(request.POST)
        if form.is_valid():
            verification = authy_api.phones.verification_check(
                request.session['phone_number'],
                request.session['country_code'],
                form.cleaned_data['token']
            )
            if verification.ok():
                request.session['is_verified'] = True
                return redirect('verified')
            else:
                for error_msg in verification.errors().values():
                    form.add_error(None, error_msg)
    else:
        form = TokenForm()
    return render(request, 'registration/token_validation.html', {'form': form})

def verified(request):
    if not request.session.get('is_verified'):
        return redirect('phone_verification')
    return render(request, 'registration/verified.html')

Using the code above along with specifying the ACCOUNT_SECURITY_API_KEY in my settings.py file is all that was required to get the code above to pass a 4 digit code to my phone.  Progress...
However, what I'm really trying to accomplish is to leverage the AUTHY app to provide the login code....I've looked at the following page...https://www.twilio.com/docs/authy/quickstart/two-factor-authentication-python-django#linkcode And the code does not load on this page...does anyone have experience or know where to look so that I can get Django to work with Authy and get the code that changes every 20 seconds as opposed to the 4 digit pin example shown above?  Thanks in advance for any thoughts.

A: Twilio developer evangelist here.
Your issue here is that you are using the verification API, which is for one time phone number verification and doesn't use the Authy app.
Instead you want the APIs for one time passwords. I don't know what's wrong with the tutorial you linked to, but all the code for the app can be found here: https://github.com/TwilioDevEd/account-security-quickstart-django.
Let me know if that helps at all.


text:
Q: Check for duplicates when using tab-separated txt file to generate iTunes playlist I'm using the following code in Applescript to generate iTunes playlists from a tab-separated .txt file. However, I wondered if there is a way of getting it to check if the files are already in the target playlist before adding each file?
set thisTSVFile to (choose file with prompt "Select the CSV file")
readTabSeparatedValuesFile(thisTSVFile)

set theList to readTabSeparatedValuesFile(thisTSVFile)

tell application "iTunes"
    set myPlaylist to playlist "InSLtxtLists"
    set sourcePlaylist to playlist "Music"
end tell

repeat with i from 2 to number of items in readTabSeparatedValuesFile(thisTSVFile)
    --gets first column
    set theName to item 1 of item i of theList
    --gets second
    set theArtist to item 2 of item i of theList
    tell application "iTunes"
        try
            duplicate (some track of sourcePlaylist whose name is theName and artist is theArtist) to myPlaylist
            on error the errorMessage
            set
        end try
    end tell
    delay 0.1
end repeat

on readTabSeparatedValuesFile(thisTSVFile)
    try
        set dataBlob to (every paragraph of (read thisTSVFile))
        set the tableData to {}
        set AppleScript's text item delimiters to tab
        repeat with i from 1 to the count of dataBlob
            set the end of the tableData to (every text item of (item i of dataBlob))
        end repeat
        set AppleScript's text item delimiters to ""
        return tableData
    on error errorMessage number errorNumber
        set AppleScript's text item delimiters to ""
        error errorMessage number errorNumber
    end try
end readTabSeparatedValuesFile

For reference, each line in the .txt file is formatted like this:
'Allo 'Allo! Theme (David Croft & Roy Moore)   Jack Emblow 1982


text:
Q: "missing value" result when automating a buttonclick apple script Although I have already posted a similar question that has been well answered, I still do not get why this error happens and how to fix it. Here is my code...
to ClickNameClass(theClass, elementnum)
    tell application "Google Chrome"
    open location "https://www.google.com"
        tell active tab of front window
            execute javascript "document.getElementsByClassName(' " & theClass & " ')[' " & elementnum & " '].click();"
        end tell
    end tell
end ClickNameClass

Is this the syntax for an automated button click and if so why is the error coming? Any help appreciated.....

A: Just for completeness I'm adding an answer...
Like your other question, the execute javascript ... code is malformed, having spaces where they do not belong around the className as well as having single-quotes around the indexValue that shouldn't be there.
The following clickElementByClassName handler, which has been rewritten from what you originally posted, will open the target URL, "https://www.google.com" in this instance, wait for the page to load and then click the Sign In button on Google's Home Page.
on clickElementByClassName(thisURL, className, indexValue)
    tell application "Google Chrome"
        open location thisURL
        repeat until (loading of active tab of front window is false)
            delay 0.1
        end repeat
        tell active tab of front window
            execute javascript "document.getElementsByClassName('" & className & "')[" & indexValue & "].click();"
        end tell
    end tell
end clickElementByClassName

clickElementByClassName("https://www.google.com", "gb_7f gb_Fa gb_Jb", 0)

Looking at the Replies pane in Script Editor it shows:
tell application "Google Chrome"
    open location "https://www.google.com"
    get loading of active tab of window 1
        --> true
    get loading of active tab of window 1
        --> true
    get loading of active tab of window 1
        --> true
    get loading of active tab of window 1
        --> false
    execute active tab of window 1 javascript "document.getElementsByClassName('gb_7f gb_Fa gb_Jb')[0].click();"
        --> missing value
end tell

Result:
missing value

As you can see the execute line of code is not processed until the page has finished loading and there are no spaces on each side of the className or single-quotes around the indexValue as there would have been using the original coding.
I also removed the hard coding of the URL from within the handler, thus making it a bit more versatile and reusable.
As you can see the result was missing value and in this instance is not a bad thing as in testing I was taken to the Sign in - Google Accounts page as desired in this example.


text:
Q: how to resolve spring security context holder result null? I am new to spring MVC bellow is my spring-security.xml when i am retrieving the user details from security context holder its giving null.Please help me how can i resolve this problem.?
 <http auto-config="true" >
        <intercept-url pattern="/login*"
                       access="IS_AUTHENTICATED_ANONYMOUSLY,ROLE_USER"/>
        <intercept-url pattern="/login.jsp*"
                       access="IS_AUTHENTICATED_ANONYMOUSLY,ROLE_USER"/>
     <intercept-url pattern="/employee/*" access="ROLE_EMPLOYEE"/>
        <intercept-url pattern="/campaign/*" access="ROLE_EMPLOYEE"/>
        <intercept-url pattern="/marketing/*" access="ROLE_EMPLOYEE"/>
        <intercept-url pattern="/company*" access="ROLE_USER,ROLE_ANONYMOUSLY,ROLE_USER,ROLE_EMPLOYEE"/>
        <intercept-url pattern=" /j_ascend_security_check*" access="ROLE_USER,ROLE_ANONYMOUSLY,ROLE_USER,ROLE_EMPLOYEE"/>

        <form-login login-page="/pages/login.jsp"
                    authentication-success-handler-ref="authenticationSuccessRedirectHandler"
                    authentication-failure-handler-ref="authenticationFailureRedirectHandler"/>
    </http>

Java code
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println("user at sh:::"+user.getCompanyShortName()); //getting null here

what is the problem.Can any one helpme out??