text:
Q: CSS3 transition seems to modify z-index during animation I'm building a quick bullshit website for a friend, and I can't figure this problem out.
Link: http://designbyhawk.com/LOSO/
Mousing over the central image will rotate it 180deg. I want it to look like the ribbon is rotating out from under the american flag. However, as soon as the animation starts, the ribbon appears over the flag.
I'm using the z-index property to keep the ribbon under the flag, and I'm not sure how to achieve my desired effect.
Thanks everyone, and please let me know of any bad practices in the code.
html:
<!DOCTYPE HTML>

        <title>LOSO 2012</title>
        <link href="style.css" type="text/css" rel="stylesheet" media="all">

© Julien Mothafreakin Cohen 2012

css:
/*--------------------------
RESET
---------------------------*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video{margin:0; padding:0}
article, aside, details, figcaption, figure, footer,
header, hgroup, menu, nav, section{display:block}

table{border-collapse:collapse; border-spacing:0}
fieldset, img{border:0}
address, caption, cite, dfn, th, var{font-style:normal; font-weight:normal}
caption, th{text-align:left}
h1, h2, h3, h4, h5, h6{font-size:100%; font-weight:normal}
q:before, q:after{content:''}
abbr, acronym{border:0}

/*-----------------------*/

#stripes{
    background: url('flag-stripes.jpg') repeat;
    width: 100%;
    height:1000px;
    z-index:5;
}

#gradient-top{
    width: 100%;
    height: 400px;
    background: url('gradient-bg.jpg') repeat-x;
}

/*-----bgs done----*/

#doughnut {  /*--- Full credit for this CSS to Seth from stackoverflow: http://stackoverflow.com/users/605698/seth ---*/
    border: 50px solid #FFFFFF;
    border-radius: 200px;
    border-style:ridge;
    height:200px;
    width:200px;
    margin: 0 auto;
    position: relative;
    bottom: 160px;

                -webkit-transition: all 2s ease-in-out;
        -moz-transition: all 2s ease-in-out;
        -o-transition: all 2s ease-in-out;
        -ms-transition: all 2s ease-in-out;
}

    #doughnut:hover{

        transform: rotate(180deg);
        -webkit-transform: rotate(180deg);
        -moz-transform: rotate(180deg);
        -o-transform: rotate(180deg);
        -ms-transform: rotate(180deg);

        -webkit-transition: all 2s ease-in-out;
        -moz-transition: all 2s ease-in-out;
        -o-transition: all 2s ease-in-out;
        -ms-transition: all 2s ease-in-out;
    }

    #LOSO{
        background:url('LOSO.png');
        width:223px;
        height:264px;
        position:relative;
        bottom:64px;
        left:-4px
    }

        img{
            position: relative;
            right: 364px;
            top: 175px;
            z-index: -100 !important;
        }

#footer{
    width:100%;
    height:60px;
    background: #222;
    opacity:.9;
    position:relative;
    top:240px;
    z-index:10;

    padding: 10px 0 0 10px;
    color: white;
    font-size:15px;
}

A: Instead of animating all properties, just animate the transformation:
   -webkit-transition: -wekbit-transform 2s ease-in-out;
    -moz-transition: -moz-transform 2s ease-in-out;
    -o-transition: -o-transform 2s ease-in-out;
    -ms-transition: -ms-transform all 2s ease-in-out;
    transition: transform all 2s ease-in-out;

The only other tip I can give you is to not use negative z-indexes, as they are finicky in Mobile Safari. Also, add the generic transition declaration for when browsers drop vendor prefixes.


text:
Q: Есть ли аналог SETNX redis'a в FSMContext? Пишу telegram-бота на aiogram.
Чтобы избежать записи двух запросов, обрабатываемых параллельно, я хотел бы проверить state_data перед записью, например так, как это делает SETNX в стандартном redis.
Есть ли такая возможность в FSMContext?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cosmos IO exception error in C# Hello guys I was recently using Cosomos to get Started in OS developemt , So I was using VS2010 and when I try to debug it, it gives some warning , and so I tried to debug it on VS2008 it debuged with no Waring and then it give me IO exception error keep in mind I never touched with single line of code, I've downloaded and installed created project and that was the first debug that had happened. all I'll provied some Images to be more clear
Edit: I've fixed by choosing QEMU Radiobtn but sometimes give the IO error and someother no !!
one more question why does it works only in VS2008 even all tutorails was made
on vs2008 even the recent one ,First stepHere is the main exciption

A: Current versions of the Dev Kit and the User Kit require Visual Studio 2015 Update 1 or higher. Previous versions did work with older versions, and there was some (limited) support for express editions, but I believe those were dropped when the community version of visual studio was released without the limitations that express version imposed. If you pick up VS 2015 Community and install the latest updates you should be in working order.
From the FAQ:

Why doesn't it work in VS [insert version number]?
Latest versions only support VS2015. Older versions of Cosmos worked with VS2010 (including Express). Support skipped VS2012 and jumped to VS2013 (not including Express) and then to VS2015 (including Community Edition).

As to why it works partially in your older versions? I'm not entirely sure. .NET 3.5 is a required target, so VS 2008 is in scope, and you may have the required SDK components installed for it's requirements but it's certainly no longer supported by the dev team.


text:
Q: Logic behind numpy element wise multiplication between 1d array and 2d array I have two arrays a and b, a with shape (1000, ) and b with shape (1000, 1)
a = np.sin(x)
b = np.cos(x[:, np.newaxis])

Could anyone explain to me the reason why if i do element wise multiplication
c = a * b

I get that c has shape (1000, 1000)?
Thank you very much for your help.

A: numpy has the concept of broadcasting. It means that that if an axis shape is 1, then it can match another array with a different size, and the element of that axis will be broadcast to all the elements of the other array.
That what happens when you do:
x = np.zeros((1,))
y = np.zeros((100,))

x+y

Now, there is also the concept of automatic broadcasting. This means that a shape of (n,) is also understood as (1,n).
So now in your case, you have this automatic broadcast for a happening, meaning that you are multiplying size (1,1000) by size (1000,1) which are both broadcast through the first broadcast rule, hence giving a result of size (1000,1000).


text:
Q: I need help on android Toast view as icon on error My activity is a Video Player Activity and its working fine, On some Videos it must throw a message (handleHardwareAccelerationError) if the video is not supported or high quality.
It shows as Toast with message fine.
Now I would like to change this Toast message to show a picture or small icon instead, is this possible? Here is my code for handleHardwareAccelerationError, Thanks in advance.
private void handleHardwareAccelerationError() {
    mHardwareAccelerationError = true;
    if (mSwitchingView)
        return;

    Toast.makeText(this, R.string.hardware_acceleration_error, Toast.LENGTH_LONG).show();

}

what I have tried is this but didnt show anything.
private void handleHardwareAccelerationError() {
    mHardwareAccelerationError = true;
    if (mSwitchingView)
        return;
            final View popupView = getLayoutInflater().inflate(R.layout.myinforbar, null);
    mError = (ImageView) popupView.findViewById(R.id.errornew);
    mError.setVisibility(View.VISIBLE);

}

and here is myinforbar.xml
<LinearLayout android:gravity="center_vertical" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="21dp" android:layout_marginLeft="0.0dip" android:layout_marginTop="5.0dip"
            android:background="@drawable/button5_background">

            <ImageView
            android:id="@+id/errornew"
                android:src="@drawable/everyone_icon_nearby_cur"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
                android:visibility="invisible"/>
        </LinearLayout>

EDITED:
The original activity is long and it can be found here rather then pasting the whole activity you can see it here VideoPlayerActivity
( private void handleHardwareAccelerationError)
New Update...

This is without the message (onHardwareError) applied, I want to see icon inside this bottom little box that popup when video playing (infobar) instead of Toast message.

A: Toast is farily limited, you cannot show icons.
Edit: Gunjav Dave says it's possible, so it's approach worth a try.
Anyway this free library: SuperToast
can make what you need.
If you prefer to stick to Google's standards you can use, instead, the Snackbars, that don't allow, as far as I know, to put an icon, but can anyway be associated with an action/button, and they are standard.
I can't understand what you try to do with popupView, if you want to use a PopupWindow you have to use a completely different syntax. This Balloon Popup library of mine helps you to make a popup attached to a View, using a PopupWindow, you can also inflate into it a layout, or use it as an example on how to make a PopupWindow.
Edit:
You are inflating a layout inside a view, but this doesn't show the view. Instead, you should use a PopupWindow, and inflate inside it a layout.
This is an example taken from my BalloonPopup library:
// ....
    hostedView = ((LayoutInflater) ctx.getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(layoutRes, null);
    textView = (TextView) hostedView.findViewById(R.id.text_view);
    textView.setText(text);
// ....
    popupWindow = new PopupWindow(hostedView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

In other words, you should be able to do something like
PopupWindow popupWindow = new popupWindow(mError, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

in your code to show the popup window.
These are the essential points of the code, then you can reposition the popup, and eventually keep track of it to edit and re-show it instead of always creating from scratch. Please consider, anyway, to use BalloonPopup library, that does what you need, without getting crazy with animations, display times, window's permanence and positioning. You can just inflate into it your layout, for example with an icon and a text, and make it appear exactly on the center of another View, that can be your (already present) media player.
More edit:
Another very simple solution.
To get it simple, create a RelativeLayout, that hosts all your video player, and then create a simple ImageView in the center of it. Set its visibility to GONE when hidden and to VISIBLE when the error must be shown. Subsequently, you can use a timer or a touchListener to close it making it GONE again.

A: XML Name or Layout Name would be
<LinearLayout xmlns:androidclass="http://schemas.android.com/apk/res/android"
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button5_background">

<ImageView
android:id="@+id/errornew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"/>

</LinearLayout>

Put This in Class:
LayoutInflater inflater = LayoutInflater.from(this);
View layout= inflater.inflate(R.layout.myinforbar, null);
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setView(layout);
toast.show();

A: Try this
  private void handleHardwareAccelerationError() {
            mHardwareAccelerationError = true;
            if (mSwitchingView)
                return;
                    final View popupView = getLayoutInflater().inflate(R.layout.myinforbar, null);
        PopupWindow pw = new PopupWindow(popupView , 300, 400, true);
        pw.showAtLocation(popupView , Gravity.CENTER, 0, 0);
mError = (ImageView) popupView.findViewById(R.id.errornew);
            mError.setVisibility(View.VISIBLE);
        }


text:
Q: How do I use MiG Layout with Eclipse? I've been Googling and checking on Stack Overflow and nothing has helped... hopefully someone can.
I usually just write my code by hand, but I'm working on a Java project that has a GUI aspect and I like what MiG Layout has to offer so I want to use it. I've downloaded the .jar file from the website, but I can't seem to be able to access it from my project.
I'm using Eclipse now as my IDE for this project because I don't want to have to deal with this particular thing by hand. I'm new to Eclipse, but here's what I've been trying: import the .jar file (via the Import tool for the project), then add the following code to my files:
import net.miginfocom.swing.MigLayout;
import javax.swing.*;

According to this page, this should work, right?
But when I try to run the program, I'm met with this message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    MigLayout cannot be resolved to a type

What am I doing wrong?

A: It sounds like the "import tool" part didn't work properly - that Eclipse isn't actually using the jar file.
I suggest you right-click on the project, choose Properties, and go to the Build Path page. Look under the "Libraries" tab. Assuming the jar file isn't there, add it and all should be well.


text:
Q: How to find the attempted URL when site user gets 404 error with php? When a user attempts to go to an invalid link on my page and is forwarded to a 404 page, is there a way to see what was the attempted url.
Example: If user types "example.com/stary" instead of "example.com/start"; how can I retrieve the attempted url ("example.com/stary") using php.

A: You can use .htaccess rule
if index.php is your main file you can manage all request GET/POST...
if you get the URL GET start you may take action action can define in index.php
sample .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

A: For this you just check
$_SERVER['REQUEST_URI']

or
$_SERVER['REDIRECT_URL']

For better under standing , use print_r (php function ) on index.php file to check other fields in this variable.
print_r($_SERVER['REQUEST_URI']);


text:
Q: Include graphics from subfolders I have this structure:

*

*mainfolder/main.tex

*mainfolder/frontmatter/front.tex

*mainfolder/frontmatter/images/logo.jpg

Now i include front.tex in main.tex, but i can't view the logo.
PS: I want specify graphicspath in front.tex and include all in main.tex


text:
Q: Get icon from single png image I have seen this so many times until now, but I never used myself. Can somebody explain how you can get specific icon picture from this single png image, for example the icons i selected with red ... using css

A: That is called CSS sprites. It is used to cut down the http requests. Basically all icons are placed on a single canvas and are used as background-image property and later they are mapped using CSS background-position property, so for example
.icon1 {
   background-image: url('YOUR_URL_HERE');
   background-position: 10px 10px; /* X and Y */
   height: 30px;
   width: 30px;
}

Demo
So inshort just define a fix height/width to your element, and than map the canvas using background-position property. Hence, if you have 100 small icon images on a page, it will make 100 requests to the server, thus to increase the performance, CSS Sprites are used.

A: *

*Set a fixed (in pixels) height and width on an element

*Set the image as the background-image

*Adjust background-position so the part of the image you want to be visible is in view

A: Using background shorthand for the positioning of image.
div {
    background:url(http://i.stack.imgur.com/mUhg1.png) -82px -104px;
    width:27px;
    height:27px;
}

http://jsfiddle.net/T2EtY/1/


text:
Q: Where to Store Local Software Packages for Chef Recipe I have a Ruby .deb package that I built from source using checkinstall. I'm using it with a Chef recipe to install Ruby on one of my nodes. Right now I'm storing it under files/default in my recipe, where one would normally store config files or templates to upload to the server. This works well enough but I wonder what the "right" way to solve this problem would be. Where do people store local binaries or packages when they want to install them with Chef this way? Should I create a server to store these, then download them as needed through my recipes?

A: Ideally you would host a repository server like apt (or gem, etc. Whatever suits) and configure your repository sources on chef clients to include that server.


text:
Q: How to make one data frame into multiple data frames So I am trying to split one data frame into multiple. I currently have:
y <- data.frame(day=c('1','1','2','2'),amount=c(1,2,3,4))

for(i in 1:2){
    i <- as.character(i)
    for(j in 1:4){
        if (grep(i, y$day, value = TRUE) > 0){
            assign(paste0('df', i)) <- rbind(assign(paste0('df', i)),y[j])
        }
    }
}

It then gives me an error and warning saying:
Error in assign(paste0("df", i)) :
argument "value" is missing, with no default
In addition:
Warning message:

In if (grep(i, y$day, value = TRUE) > 0) { :the condition has length >
  1 and only the first element will be used

I can't seem to find what value is supposed to be or where to put it.

A: I'd steer clear of assign unless you're setting up a new environment.  If you're trying to split by day, then you can just use split
y <- data.frame(day=c('1','1','2','2'),amount=c(1,2,3,4))
split(y, y$day)
# $`1`
#   day amount
# 1   1      1
# 2   1      2
#
# $`2`
#   day amount
# 3   2      3
# 4   2      4

If you want them assigned to their own data frames in the global environment (not recommended), you can use list2env
s <- setNames(split(y, y$day), paste0("df", unique(y$day)))
list2env(s, globalenv())

Now you have data frames df1 and df2 in the global environment
df1
#   day amount
# 1   1      1
# 2   1      2
df2
#   day amount
# 3   2      3
# 4   2      4


text:
Q: Prolog Predicate that returns Sum of weights of items in a list I want to write a prolog predicate that takes in a list of items, searches for the weights of these items, and returns their sum. I got the corresponding weights but I don't know how to get the sum in the predicate it's not working.
This is my very first project in Prolog so I'm still learning. Thank you :)
weight(mum,60).
weight(dad,85).
weight(alfie,20).
weight(bianca,25).
weight(daisy,50).
weight(puppy,10).
list_sum([],0).
list_sum([Head|Tail], TotalSum):-
    list_sum(Tail, Sum1),
    TotalSum is Head+Sum1.

total_weight([], []).
total_weight([H_entity | T_entity], [H_weight | T_weight]) :-
    weight(H_entity, H_weight),
    total_weight(T_entity, T_weight).

This returns a list of the weights of the items given. I tried getting the sum but it didn't work.
The output I am looking for is total_weight([mum,dad,puppy],W): W=155

A: Try this:
?- total_weight([mum,dad,puppy], WeightList), sum_list(WeightList, Sum).
WeightList = [60, 85, 10],
Sum = 155.

EDIT
Combining both predicates:
sum_of_weights([], 0).
sum_of_weights([E|Es], S) :-
    sum_of_weights(Es, T),
    weight(E, W),
    S is T + W.

Example:
?- sum_of_weights([mum,dad,puppy], S).
S = 155.


text:
Q: Converting a 32bit number in a proprietary timestamp with PHP I have a 32 bit number represented as a HEX string that I need to convert to a timestamp following these rules:

What I want to check is that I'm not doing something glaringly stupid? Does my conversion look sane given the timestamp specification?
I've put together the following code to do this. I know PHP isn't the best for this sort of work but it's part of a larger legacy application all written in PHP.
$t is taken from an XML file of readings, one every 5 mins.
    // convert the hex string to binary
    // sprintf pads leading zeros
    $binStr = sprintf('%032s', base_convert($t, 16, 2));

    //get a decimal representation so we can use the bitwise operator on it
    // I know I could have converted straight to decimal, but I'm debugging
    $decimal = bindec($binStr);

     // get the first 6 bits
    $min = $decimal & bindec('111111');

    // drop the first 8 bits then apply a mask to the next 5
    $hour = ($decimal >> 8) & bindec('11111');

    // drop the first 15 bits then apply a mask to the next 1
    $daylightSaving = ($decimal >> 15) & 1;

    // etc
    $day  = ($decimal >> 16) & bindec('11111');
    $yearLsb  = ($decimal >> 21) & bindec('111');
    $month = ($decimal >> 24) & bindec('1111');
    $yearMsb  = ($decimal >> 28) & bindec('1111');

    Logger::debug(
        $t . " Incoming timestamp converted to  \n" .
        $binStr . " then converted to  \n" .
        " Day: " . $day . "\n" .
        " Month: " . $month . "\n" .
        " Year: " . $yearMsb . $yearLsb . "\n" .
        " Hour: " . $hour . "\n" .
        " Min: " . $min . "\n" .
        " Daylight saving: ". $daylightSaving
    );

The output for the last entry in the file is:
2DAC1B0A Incoming timestamp converted to
00101101101011000001101100001010 then converted to
 Day: 12
 Month: 13
 Year: 25
 Hour: 27
 Min: 10
 Daylight saving: 0

I know the file was created at 11:25am on the 12th Nov 2013, the readings are for 11:10 to 11:25 with the last one in the file being the 11:10am one.
The mins match those in the file I get 10 through 25 in 5 min increments. The day is also accurate if I run it against other files.
There's a chance that the equipment manufacturer who wants us to purchase some expensive software to do this parsing has munged the timetamp specification but that being an option I've played with lots of possible combinations in that 32bit integer and I can't see how I can get all the numbers I require from the supplied timestamps.

A: I've found a C code and converted it to PHP. The results are a bit different but also obviously wrong. But perhaps that helps you.
The C code you find here. Search for Compound CP32. (There are no line numbers)
$hex = 0x2DAC1B0A;
$dt0 = $hex & 0xff;
$dt1 = ($hex >> 8) & 0xff;
$dt2 = ($hex >> 16) & 0xff;
$dt3 = ($hex >> 24) & 0xff;

$min = $dt0 & 0x3F;
$hour  = $dt1 & 0x1F;
$day  = $dt2 & 0x1F;
$mon   = ($dt3 & 0x0F) - 1;
$year  = (($dt2 & 0xE0) >> 5) | (($dt3 & 0xF0) >> 1);
$dayLightSaving = ($dt1 & 0x80) ? 1 : 0;

echo $min.'
'; // 10
echo $hour.'
'; // 27
echo $day.'
'; // 12
echo $mon.'
'; // 12
echo $year.'
'; // 21
echo $dayLightSaving; // 0

A: The year is decoded (or rather, displayed) incorrectly:
" Year: " . $yearMsb . $yearLsb . "\n" .

This looks like you assume the year to be in BCD.
To calculate the correct year you should do:
$year = $yearLSB | ($yearMSB << 3);

Note that EN 13757 (the MBUS standard you try to decode) also defines a "hundred year" (century) field:
$hy = ($decimal >> 13) & 0x03;
$year = 1900 + 100 * $hy + $year;

if ($year < 1980)
  $year += 100;

The if corrects timestamps of older meters, as even suggested by the standard itself.
I don't see the reason for the wrong hour, though, as ($hour >> 8) & 0x1F should be correct. Same applies for the rest of the fields. I guess the value of $decimal itself does not match the value sent by the meter. Try to avoid converting to/from stings, perhaps.


text:
Q: Items of std::array are changed unintentionally out of context I'm trying passing the reference of array to class object by constructor, and operating the items in that object.
But, I'm afraid that these items in array are changed just after reaching at the beginning of MySort::sort() below. (not changed before entering MySort::sort())
#include <iostream>
#include <utility>
#include <array>

using namespace std;

template <typename T>
struct MySort
{
    T &_n;
    size_t _s;

public:
    MySort(T n) : _n(n)
    {
        _s = _n.size();
    }

    void sort()
    {
        for (size_t i = 0; i < _s - 1; i++)
        {
            for (size_t j = i + 1; j < _s; j++)
            {
                if (_n[i] > _n[j])
                    std::swap(_n[i], _n[j]);
            }
        }
        cout << "teste" << endl;
    }
    friend ostream &operator<<(ostream &ost, const MySort &c)
    {
        for (size_t i = 0; i < c._s; i++)
            ost << c._n[i];
        return ost;
    }
};

int main(int argc, const char **argv)
{
    array<int, 5> numbers{2, 5, 1, 7, 3};

    MySort<array<int, 5>> bubble{numbers};
    bubble.sort();
    cout << bubble << endl;

    return 0;
}

*

*In the case of passing array by copy, It works correctly.

Thank you for your attention.

A: The constructor
MySort(T n) : _n(n)
{
    _s = _n.size();
}

Here you set _n to reference a input object which will get destroyed upon leaving the constructor. This is plain UB.
To fix it write
MySort(T& n) : _n(n)
{
    _s = _n.size();
}

A: In the constructor MySort(T n),  you are making a copy of the array,  then storing a reference to the copy,  but then the copy goes out of scope,  so you have a dangling reference.
If you want to use a reference,  you should pass a reference to the original object,  MySort(T &n), and make sure that the original object is always in scope during the lifetime of the MySort object.


text:
Q: Toral subalgebra In the proof that a Toral subalgebra $T$ of a semisimple Lie algebra $L$ is abelian, one argues that if $x\in  T$ is ad-simple ($ad_x:L\to L$ is diagonalizable), the restriction $ad_x|_T:T\to T$ is also diagonalizable. Why this is true? I can follow the rest of he argument.

A: This is an instance of a more general fact from linear algebra:

Let $T : V \to V$ be a linear map, with $U \subseteq V$ a
  $T$-invariant subspace, so that $T(U)\subseteq U$. Then $T_{\big \vert
U}$ is diagonalisable whenever $T$ is.

You can find multiple proofs of this fact here:
Diagonalizable transformation restricted to an invariant subspace is diagonalizable

Note that in our case, that $T$ is an invariant subspace under $\operatorname{ad}_x$ for each $x \in T$ is precisely the condition that $T$ is a subalgebra of $L$.


text:
Q: A way to release the resource inside ValidationEventHandler I am validating an xml with an xsd schema.
When ValidationEventHandler callback is triggered I can log if it's an error or a warning but I also want to release the xml under validation and move it from one directory to another. Right now I get "used by another process" exception if I try to do so.
Any idea how I can overcome this? Could throwing an exception from inside the ValidationEventHandler to be caught from outside could work?
Thanks,


text:
Q: Centre items in a JComboBox in addition to displaying text clearly when it is disabled I'm using
((JLabel)comboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
to centre text items in my JComboBox.
But I also would like the text to appear clearly when the ComboBox is disabled (i.e. the text appearance should not/barely change).
By solution was to use comboBox.setEditable(true) (see below for more) when I use comboBox.setVisible(false) which works well except that it aligns the text back to the left. And it seems that fixing this issue would require a lot of work.
I'm wondering if someone can suggest another way to display the text clearly in a disabled comboBox?
Many thanks.
Edit: The full code I'm using to improve the disabled text display is
        ComboBoxEditor editor = comboBox.getEditor();
        JTextField etf = (JTextField) editor.getEditorComponent();
        etf.setDisabledTextColor(UIManager.getColor("ComboBox.foreground"));
        etf.setBackground(UIManager.getColor("ComboBox.background"));
        comboBox.setEnabled(false);
        comboBox.setEditable(true);

Edit 2:
Here is a full example:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class GUITest extends JPanel {

    static JFrame frame;
    static JButton changeButton;
    static JComboBox exampleComboBox;

    public GUITest() {
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        String[] examples = {
            "abcd",
            "efgh",
            "ij"
        };

        exampleComboBox = new JComboBox(examples);

        // centre text of items in combo box
        ((JLabel) exampleComboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);

        JLabel buttonLabel = new JLabel("Click to make combo box disabled but text show clearly",
                JLabel.LEADING); //== LEFT

        JPanel patternPanel = new JPanel();
        patternPanel.setLayout(new BoxLayout(patternPanel,
                BoxLayout.PAGE_AXIS));

        exampleComboBox.setAlignmentX(Component.LEFT_ALIGNMENT);
        patternPanel.add(exampleComboBox);

        JPanel resultPanel = new JPanel(new GridLayout(0, 1));
        resultPanel.add(buttonLabel);
        changeButton = new JButton();
        resultPanel.add(changeButton);
        addButtonListener();

        patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        add(patternPanel);
        add(Box.createRigidArea(new Dimension(0, 10)));
        add(resultPanel);

        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    } //constructor

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ComboBoxDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new GUITest();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    private static void addButtonListener() {
        changeButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ComboBoxEditor editor = exampleComboBox.getEditor();
                JTextField etf = (JTextField) editor.getEditorComponent();
                etf.setDisabledTextColor(UIManager.getColor("ComboBox.foreground"));
                etf.setBackground(UIManager.getColor("ComboBox.background"));
                exampleComboBox.setEnabled(false);
                exampleComboBox.setEditable(true);
            }
        });
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Edit 3: It's working now but the text moves up slightly and the comboBox border is removed when the button is clicked. Is there a way to prevent this?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class GUITest extends JPanel {

    static JFrame frame;
    static JButton changeButton;
    static JComboBox exampleComboBox;

    public GUITest() {
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
        String[] examples = {
            "abcd",
            "efgh",
            "ij"
        };

        exampleComboBox = new JComboBox(examples);
        exampleComboBox.setEditor(new TextPaneComboBoxEditor());

        // centre text of items in combo box
        ((JLabel) exampleComboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);

        JLabel buttonLabel = new JLabel("Click to make combo box disabled but text show clearly",
                JLabel.LEADING); //== LEFT

        JPanel patternPanel = new JPanel();
        patternPanel.setLayout(new BoxLayout(patternPanel,
                BoxLayout.PAGE_AXIS));

        exampleComboBox.setAlignmentX(Component.LEFT_ALIGNMENT);
        patternPanel.add(exampleComboBox);

        JPanel resultPanel = new JPanel(new GridLayout(0, 1));
        resultPanel.add(buttonLabel);
        changeButton = new JButton();
        resultPanel.add(changeButton);
        addButtonListener();

        patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        add(patternPanel);
        add(Box.createRigidArea(new Dimension(0, 10)));
        add(resultPanel);

        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    } //constructor

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ComboBoxDemo2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new GUITest();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    private static void addButtonListener() {
        changeButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ComboBoxEditor editor = exampleComboBox.getEditor();
                JTextPane etf = (JTextPane) editor.getEditorComponent();
                etf.setDisabledTextColor(UIManager.getColor("ComboBox.foreground"));
                etf.setBackground(UIManager.getColor("ComboBox.background"));
                exampleComboBox.setEnabled(false);
                exampleComboBox.setEditable(true);
            }
        });
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

class TextPaneComboBoxEditor implements ComboBoxEditor {
    protected JTextPane editor;
    private Object oldValue;

    public TextPaneComboBoxEditor() {
        editor = createEditorComponent();
    }

    public Component getEditorComponent() {
        return editor;
    }

    /**
     * Creates the internal editor component. Override this to provide
     * a custom implementation.
     *
     * @return a new editor component
     * @since 1.6
     */
    protected JTextPane createEditorComponent() {
        JTextPane editor = new BorderlessTextPane("",9);
        editor.setBorder(null);

        SimpleAttributeSet center = new SimpleAttributeSet();
        StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
        StyledDocument doc = editor.getStyledDocument();
        doc.setParagraphAttributes(0, doc.getLength(), center, false);

        return editor;
    }

    /**
     * Sets the item that should be edited.
     *
     * @param anObject the displayed value of the editor
     */
    public void setItem(Object anObject) {
        String text;

        if ( anObject != null )  {
            text = anObject.toString();
            if (text == null) {
                text = "";
            }
            oldValue = anObject;
        } else {
            text = "";
        }

        // workaround for 4530952
        if (! text.equals(editor.getText())) {
            editor.setText(text);
        }

    }

    public Object getItem() {
        Object newValue = editor.getText();

        // This code only works for Strings. The default implementation would
        // use reflection to create Object of whatever class was stored in the
        // ComboBoxModel. You will need to fix the reflection code if you want
        // to support other types of data in the model

/*
        if (oldValue != null && !(oldValue instanceof String))  {
            // The original value is not a string. Should return the value in it's
            // original type.
            if (newValue.equals(oldValue.toString()))  {
                return oldValue;
            } else {
                // Must take the value from the editor and get the value and cast it to the new type.
                Class<?> cls = oldValue.getClass();
                try {
                    Method method = MethodUtil.getMethod(cls, "valueOf", new Class[]{String.class});
                    newValue = MethodUtil.invoke(method, oldValue, new Object[] { editor.getText()});
                } catch (Exception ex) {
                    // Fail silently and return the newValue (a String object)
                }
            }
        }
*/
        return newValue;
    }

    public void selectAll() {
        editor.selectAll();
        editor.requestFocus();
    }

    public void addActionListener(ActionListener l) {
//        editor.addActionListener(l);

        Action enter = new WrappedActionListener(l);
        editor.getActionMap().put("insert-break", enter);
    }

    public void removeActionListener(ActionListener l) {
//        editor.removeActionListener(l);
    }

    static class BorderlessTextPane extends JTextPane {
        public BorderlessTextPane(String value,int n) {
//            super(value,n);
            setText(value);
        }

        // workaround for 4530952
        public void setText(String s) {
            if (getText().equals(s)) {
                return;
            }
            super.setText(s);
        }

        public void setBorder(Border b) {
            if (!(b instanceof UIResource)) {
                super.setBorder(b);
            }
        }
    }

    /**
     * A subclass of TextPaneComboBoxEditor that implements UIResource.
     * TextPaneComboBoxEditor doesn't implement UIResource
     * directly so that applications can safely override the
     * cellRenderer property with TextPaneListCellRenderer subclasses.
     *

     * Warning:
     * Serialized objects of this class will not be compatible with
     * future Swing releases. The current serialization support is
     * appropriate for short term storage or RMI between applications running
     * the same version of Swing.  As of 1.4, support for long term storage
     * of all JavaBeans™
     * has been added to the java.beans package.
     * Please see {@link java.beans.XMLEncoder}.
     */
    public static class UIResource extends TextPaneComboBoxEditor
    implements javax.swing.plaf.UIResource {
    }

    static class WrappedActionListener extends AbstractAction
    {
        private ActionListener listener;

        public WrappedActionListener(ActionListener listener)
        {
            this.listener = listener;
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            listener.actionPerformed(e);
        }
    }
}

A: There is no need to play with the editor when you disable the combo box. Just disable the combo box. So the code in the ActionListener is:
changeButton.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        exampleComboBox.setEnabled(false);
        //exampleComboBox.setEditable(true);
    }
});

Then at the top of your class you can use:
UIManager.put("ComboBox.disabledForeground", Color.BLACK);

to see the foreground color used by the disable combobox. When the combo box is disabled the editor is not displayed so normal rendering is done.
So you don't need to use the JTextPane as the editor.


text:
Q: In Ag-Grid react how to check if cell value is present and if not how to create one? I am new to react and Ag-Grid as well, I need to have two columns, Column-A and Column-B. In Column-A it should be text-box and Column-B should be a dropdown where the list of values are from Column-A, if the entered value is not present in Column-A a new row should be added,
ex:
Column-A | Column-B
10       |  10
20       |  10
30       |  20
40       |  70
Now in the above table for Column-B I have entered value as 70, but in Column-A the value 70 does not exist, hence it should create a new row with Column-A having value as 70 and leaving Column-B as empty, like below.
Column-A | Column-B
10       |  10
20       |  10
30       |  20
40       |  70
70       |
I did not got any idea for creating this functionality, please help me on this.


text:
Q: What's the difference between $v = a\cdot t$ and $\vec{v} = \int \vec{a} \, \mathrm dt$ In highschool, I learned $v = at$ and in university, I am learning $\vec{v} = \int \frac{\vec{F}}{m} \, \mathrm dt = \int \vec{a} \, \mathrm dt$.
I understand one is for $v= at$ is for one-dimension and the latter for multiple dimensions. However, I don't understand why in one dimension, we don't do $v = \int a(t) \, \mathrm dt$ but rather multiply it by the time to get the acceleration at time $t$. Shouldn't the acceleration accumulate and therefore do the integral instead?
I am confused.

As an example,

A particle of mass $m=2$ is acted on by a force
$$
\mathbf{F}=\left(4 t, 6 t^{2},-4 t\right)
$$
At $t=0,$ the particle has velocity zero and is located at the point $(1,2,3)$ .
Find the velocity vector $\mathbf{v}(t)$ for $t \geq 0$

We can easily know that $\vec{a} = \langle 2t,3t^2,-2t\rangle$. However, the velocity is not $\vec{a}\cdot t$ (which is possible with no problem since $t$ is a scalar and it still returns a vector), but rather anti-integral of the vector?

A: The formula $v = v_0 + at$ assumes that the acceleration is constant. The formula $v = v_0 +  \int_{t_0}^{t_f} a(t) \, dt$ allows for the possibility that the acceleration changes with time.

A: The first formula $v=at$ is valid for a constant whereas the second one is valid also for not constant acceleration that is $v=\int_0^t a(u)du$.


text:
Q: Deleting an instance of a class via a method of that class I have a class for pieces on a board. I want to be able to delete an instance of Piece so that anything else in the program that points to that piece will just point to nil.
Here's the very basic code version of what I want to do:
piece = Piece.new
variable = piece
variable #=> <Piece:0x0000000xxxxxxxx>
piece.delete
variable #=> nil

This seems like a very basic task so I feel like I'm missing something obvious. I've tried creating a delete method for the class with "self = nil", but this returns an error ("Can't change the value of self").
So far I have just worked around this by updating the other things that point to the object in my 'delete' method, but it seems like there should be a better way.

A: This is not possible.
Firstly, Ruby is an object-oriented language, which means that all manipulation is done via messages to objects, and all that is manipulated are objects. Variables are not objects, therefore you cannot manipulate them. (The only things you can do with variables are assign a value to them and dereference them.)
And even if you could manipulate variables, you would still need to hunt down every single reference to the object in question and remove it, in order for the object to be eligible for "deletion" (i.e. garbage collection).


text:
Q: MSSQL - union all with different decimal precision When I execute this SQL
SELECT 1.4 UNION ALL
SELECT 2.0400 union all
SELECT 1.24

I get the following result:
1.4000
2.0400
1.2400
But when I execute the following SQL
SELECT sum(1.4) UNION ALL
SELECT sum(2.0400) union all
SELECT sum(1.24)

I get the following result:

1.4
2.0
1.2
Why is there a difference in what precision (scale) is applied for all records?
Shouldn't it always use the precision where no data is loss, just like the 1st sql?
Thx.

A: I know that this is quite an old question, but none of the existing answers seem to address the "why?" aspect to your question.
First, what is the data type for your literal expressions? I wasn't sure (and didn't look it up) so I ran the following:
select 1.4 union all
select 'frob'

which returns the error:

Msg 8114, Level 16, State 5, Line 1
  Error converting data type varchar to numeric.

Okay, so 1.4 and the other literals are numeric - a.k.a decimal.
Next, what is the return type of the SUM function, if passed a decimal(p,s)1:

decimal(38, s)

Okay, so the data types of the 3 SUM expressions in your query are decimal(38,1), decimal(38,4) and decimal(38,2). Given those 3 data types available to pick from, decimal(38,1) is the final chosen type, based on the rules for differing precisions and scales.

The result precision and scale have an absolute maximum of 38. When a result precision is greater than 38, the corresponding scale is reduced to prevent the integral part of a result from being truncated.

So, finally, back to the documentation on decimal:

By default, SQL Server uses rounding when converting a number to a decimal or numeric value with a lower precision and scale. However, if the SET ARITHABORT option is ON, SQL Server raises an error when overflow occurs. Loss of only precision and scale is not sufficient to raise an error.

So that's your final result.

1 At first this type may seem surprising, until you realise that generally, sum will operate against multiple rows and it's easily possible for multiple values of a given precision and scale to overflow their own data type. decimal(38,s) gives the largest possible space to accommodate any overflows without losing any precision, for a particular SUM() occurrence, and means that the final data type can be decided upon before the query has executed.

A: Try this for same result,
SELECT Cast(Sum(1.4) As Numeric(18,4)) UNION ALL
SELECT Cast(Sum(2.0400) As Numeric(18,4)) union all
SELECT Cast(Sum(1.24) As Numeric(18,4))

A: Try this
SELECT sum(1.4)/1.0 UNION ALL
SELECT sum(2.0400)/1.0 union all
SELECT sum(1.24)/1.0

OR
SELECT sum(1.4)/1.0 UNION ALL
SELECT sum(2.0400) union all
SELECT sum(1.24)

A: Normal Query passing String Value otherwise using sum or decimal it is string convert to specified format this is fact
SELECT sum(convert(decimal,1.4,3)) UNION ALL
SELECT sum(2.0400) union all
SELECT sum(1.24)

A: Try this Query
SELECT convert(decimal(18,4),Sum(1.4)) UNION ALL

SELECT convert(decimal(18,4),Sum(2.0400)) UNION ALL

SELECT convert(decimal(18,4),Sum(1.24))


text:
Q: How to create a view to list all unpublished page in library? It maybe a SharePoint dummy level question for but I cannot find a way to do it.
In the Pages library we have enabled publishing feature. Only major version 1.0, 2.0, 3.0... are published and minor version are draft. I want to create a view to show all unpublished pages (and another view for all published pages). I can add a column shows version number only.
Can I accomplish it without programming?

A: Without code
On library click Create new view based on for ex. All items.
Check columns you want to view and sort it how you like.
Under Filter
click Show items only when the following is true
Approval Status ---
is greater than ---
0 << this is for all unpublished(Rejected, Pending, Draft)
Click OK
For Published view create one more view with
Approval Status ---
is equal to ---
0 << this is for published(Approved)
And that's it
Reference
Display Name ---    Approval Status
Internal Name ---   _ModerationStatus
GUID ---    {fdc3b2ed-5bf2-4835-a4bc-b885f3396a61}
Type --- ModStat

FYI
Status    ---  Internal Value
Approved    --- 0
Rejected    --- 1
Pending --- 2
Draft   --- 3
Scheduled  --- 4

EDIT
With code
unpublished-view
In the Code view just paste the following into your View's XML inside the Query element:
<Where>
<Or>
    <Eq>
        <FieldRef Name="_ModerationStatus"/>
        <Value Type="ModStat">Draft</Value>
    </Eq>
    <IsNotNull>
        <FieldRef Name="CheckoutUser"/>
    </IsNotNull>
</Or>
</Where>

EDIT FINAL
If content Approval is disabled you can't see Approval status in edit view under filters so you must add it in code for that 2 new views (published.aspx and draft.aspx).
Open SPDesigner and go to Pages/forms and edit that view. Find <Query> and paste that code after  <Query>
For Draft view:
<Where>
<Or>
    <Eq>
        <FieldRef Name="_ModerationStatus"/>
        <Value Type="ModStat">Draft</Value>
    </Eq>
    <IsNotNull>
        <FieldRef Name="CheckoutUser"/>
    </IsNotNull>
</Or>
</Where>

For Publish view:
<Where>
<Or>
    <Eq>
        <FieldRef Name="_ModerationStatus"/>
        <Value Type="ModStat">Approved</Value>
    </Eq>
    <IsNotNull>
        <FieldRef Name="CheckoutUser"/>
    </IsNotNull>
</Or>
</Where>

*You can set 3 for Draft and 0 for Approved for _ModerationStatus value.
Save file and that's it. :)

A: The other easiest method is to create a calculated column with formula =IF((Version-INT(Version))<>0,"Draft","Published") and use the column in a view.
For detailed explanation you can visit this article.


text:
Q: How do i start converting my image string file into a byte array so I can store it in my data base? So this is the image file I got. Now, how do I convert this picturePath into a byte array so I can store it in my database?
Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    ivFoodPicture.setImageBitmap(BitmapFactory.decodeFile(picturePath));

A: You would need to get the Bitmap from the URI.
Pseduo:
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

And then to get the byte[] you can do:
   private byte[] toByteArray(@NonNull Bitmap bm)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
        return baos.toByteArray();
    }

But do take care as these could Out Of Memory error with large files. Even base64Encoding these into a String can cause OOM.


text:
Q: Failed to connect to websocket I need your help...I've basically exhausted all the link proposed by Google :D
And nothing help me pinpoint the problem...hence the fix.
If I use the command: npm run dev, I have the following error in the browser console (the page is nonetheless displayed...it just take longer)
enter image description here
The error does not appear with the: npm run build.
I`m using the following .env config
APP_NAME=App
APP_ENV=local
APP_KEY=*censored*
APP_DEBUG=true
APP_URL=https://app.dev

and .vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

Laragon is launched with following environment
enter image description here
Thank you !!
LN
I saw that it might be due to SSL and that I might need to install a self-serving certificate module...but I did not see clear instructions so for now I have not try this piste

A: I realize this question is from November, but if you or other visitors from Google are having this issue, my solution was to update my vite.config.js:
export default defineConfig({
    plugins: [
        laravel({
            input: ["resources/css/app.css", "resources/js/app.js"],
            refresh: true,
        }),
    ],
    server: {
        hmr: {
            host: "localhost",
            protocol: "ws",
        },
    },
});

I'm using valet secure to host my test site. Falling-back to ws instead of wss, and specifying localhost (Firefox and other browsers permit CORS to this location) fixed live reload, and things are working normally again.

A: It happened to me when I hosted it. My solution was to add :
server: {
    hmr: {
        host: 'localhost'
    }
}

To your vite.config.js file. So yours will be :
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.js',
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

The references can be found here and here


text:
Q: Python Pandas error: ImportError: cannot import name 'isna' Full listing:
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-7-7dd3504c366f> in <module>()
----> 1 import pandas as pd

/usr/local/lib/python3.6/dist-packages/pandas/__init__.py in <module>()
     40 import pandas.core.config_init
     41
---> 42 from pandas.core.api import *
     43 from pandas.core.sparse.api import *
     44 from pandas.tseries.api import *

 /usr/local/lib/python3.6/dist-packages/pandas/core/api.py in <module>()
       6
       7 from pandas.core.algorithms import factorize, unique, value_counts
----> 8 from pandas.core.dtypes.missing import isna, isnull, notna, notnull
      9 from pandas.core.arrays import Categorical
     10 from pandas.core.groupby.groupby import Grouper

ImportError: cannot import name 'isna'

This is obviously from the line:
import pandas as pd

Current version:
pandas==0.23.4

I have tried going back to version 0.22 and 0.19, but that didn't sort the problem.
Here is pip3 show pandas:
% pip3 show pandas

Name: pandas
Version: 0.23.4
 Summary: Powerful data structures for data analysis, time series, and                  statistics
Home-page: http://pandas.pydata.org
Author: None
Author-email: None
License: BSD
Location: /usr/local/lib/python3.6/dist-packages
Requires: numpy, python-dateutil, pytz
Required-by: pandas-datareader

Solved by both Mike Palmice and Reddi Mohan
I tried uninstalling and reinstalling with both pip and pip3, but that didn't help.  I then used virtualenv and it worked.  Python3 and Pandas 0.23.4.  I have no idea why.  I thought they used the same when you first create the environment!!
Thanks, Mike and Reddi!


text:
Q: How to find a marker using map.eachLayer of leaflet? I am able to display contents of clustered markes but could not display the contents of a single marker.
Please find the below code, where else statement will handle the single marker.
map.eachLayer(function(marker) {
   if (marker.getChildCount) { // to get cluster marker details
     console.log('cluster length ' + marker.getAllChildMarkers().length);
   } else {
     // how to display the contents of a single marker ??

     alert(marker.options.title); // doesn't work
   }

Thanks.

A: Remember that map.eachLayer() works on every layer of the map.  This includes popups and the map tile layer, as well as markers and clusters of markers.  Not all these types of layers will have the same options as markers or clusters.  You will need to test to check whether each layer is a Marker, a cluster, or something else.  Also, remember that markers may not necessarily have a title set.
This works for me:
map.eachLayer(function(layer) {
    if(layer.options && layer.options.pane === "markerPane") {
        alert("Marker [" + layer.options.title + "]");
    }
});


text:
Q: UIWebView opening the camera and images when a button is clicked I am currently wrapping a webApp up as an app. With in the web app there is a button that when clicked automatically asks if you want to go to the camera of the stored images and when selected will upload the image for you. In the web app from the phone browser this works as expected.
Now I have wrapped the webApp up in a UIWebView this function no longer works. It actually appears to close the UIWebview when selecting either of the above options. Does anyone know what the procedure is to get this to work through the UIWebView.
Do I have to give permission? Or is there more to it like detecting the HTML when the button is clicked and handling it from the UIWebView.
The HTML on the button looks like this.
   <input type="file" required id="file" name="file" accept="image/*" multiple>

ADDED CODE
WebViewController.h
 #import <UIKit/UIKit.h>

 @interface WebViewController : UIViewController <UIWebViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    UIViewController *viewController;
}

........
WebViewController.m
 #import "WebViewController.h"
 #import <AssetsLibrary/AssetsLibrary.h>
 #import "AppDelegate.h"
 @end
 @implementation WebViewController

 - (void)viewDidLoad
 {
      [super viewDidLoad];
      viewController = [[UIViewController alloc] init];
      NSString *fullURL = self.mainURL; // get this from defualts - have removed code for this

NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];

ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];

[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
    NSLog(@"%i",[group numberOfAssets]);
} failureBlock:^(NSError *error) {
    if (error.code == ALAssetsLibraryAccessUserDeniedError) {
        NSLog(@"user denied access, code: %i",error.code);
    }else{
        NSLog(@"Other error code: %i",error.code);
    }
}];
 }
  -(void)webViewDidStartLoad:(UIWebView *)viewWeb
 {
      [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
 }
 - (void)webViewDidFinishLoad:(UIWebView *)viewWeb
 {

 }

 //Note: I check to make sure the camera is available.  If it is not (iPod touch or Simulator) I show the photo library instead.
 -(void) showCamera
 {
     UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
     if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
     {
         imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
     }
     else
     {
          imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
     }
     imagePicker.delegate = self;
     [viewController presentViewController:imagePicker animated:YES completion:nil];
 }

  //Here we intercept any time the webview tries to load a document.  When the user hits our "showcamera: url" we go to work.
  - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:
  (UIWebViewNavigationType)navigationType
  {
        if ([request.URL.scheme isEqualToString:@"myApp"])
        {
            if ([request.URL.host isEqualToString:@"myFunction"])
            {
                [self showCamera];
            }
            return NO;
        }
        return YES;
   }

 //After the imagepicker has done it's thing, we pass the data back to the webview to be displayed.
 //If we wanted to be fancy here, we could have done this via Javascript so we could dynamically insert an image without reloading the page.
 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [viewController dismissViewControllerAnimated:YES completion:nil];
    UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImageJPEGRepresentation (image, 0.5);
    NSURL *tmp = [NSURL URLWithString:@"ignore"];
    [_viewWeb loadData:imageData MIMEType:@"image/jpeg" textEncodingName:@"UTF-8" baseURL:tmp];
   }
   @end

I have removed some code that was irrelevant

A: I have managed to fix the issue and it goes way back to bug that was found in iOS 8 that still hasn't been fixed. Its to do with how the UIWebView is being presented.
Adding this code fixed it.
 -(void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion
 {
     if ( self.presentedViewController)
     {
         [super dismissViewControllerAnimated:flag completion:completion];
     }
 }

For any one else confused or struggling with this Note that you do not need to start messing around with UIImagePicker or UIWebView delegates. Your web view should take care of opening the camera library or camera. This was a real pain of an issue so hopefully this may help others in my position. you can also see THIS Question as this is where i got my answer from. Thanks Andrey for helping too

A: As an alternative you can try to use UIWebViewDelegate's method webView:shouldStartLoadWithRequest:navigationType: to catch custom events:
In your HTML:
Do something
<button onclick="window.location.href='myApp://myFunction'">Do some action</button>

And then:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ([request.URL.scheme isEqualToString:@"myApp"]) {
        if ([request.URL.host isEqualToString:@"myFunction"]) {
            // do something
        }
        return NO;
    }
    return YES;
}


text:
Q: Mysql join two tables sum, where and group by I have two tables in the following structure:
sales
 |date       |time     | name   | total |
 |2017-04-01 |10:23:59 | aaa    |  100  |
 |2017-04-01 |10:23:59 | aaa    |  150  |
 |2017-04-01 |11:33:30 | bbb    |  200  |
 |2017-04-01 |11:33:30 | bbb    |  120  |
 |2017-04-02 |10:50:59 | aaa    |  70   |
 |2017-04-02 |10:30:59 | bbb    |  35   |

payment
 |date       |time     | name   | amount |
 |2017-04-01 |10:23:59 | aaa    |  300   |
 |2017-04-01 |11:33:30 | bbb    |  400   |
 |2017-04-02 |10:50:59 | aaa    |  425   |
 |2017-04-02 |10:30:59 | bbb    |  600   |

Terms

*

*sales.time = payment.time

*where date = 2017-04-01

*sum(sales.total) and sum(payment.amount)

*group by time

i want this result
 |date       |time     | name   | sum(total) | sum(amount)|
 |2017-04-01 |13:23:59 | aaa    |    250     |    300     |
 |2017-04-01 |12:33:30 | bbb    |    320     |    400     |

Table structure
CREATE TABLE `payment` (`id` int(5) NOT NULL,`date` date NOT NULL,`time` time NOT NULL,`name` varchar(10) NOT NULL,`amount` varchar(10) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT;
INSERT INTO `payment` (`id`, `date`, `time`, `name`, `amount`) VALUES(3, '2017-04-01', '10:23:59', 'aaa', '300'),(4, '2017-04-01', '11:33:30', 'bbb', '400'),(5, '2017-04-02', '10:50:59', 'aaa', '425'),(6, '2017-04-02', '10:30:59', 'bbb', '600');
CREATE TABLE `sales` ( `id` int(5) NOT NULL,`date` date NOT NULL,`time` time NOT NULL,`name` varchar(10) NOT NULL,`total` int(10) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `sales` (`id`, `date`, `time`, `name`, `total`) VALUES(1, '2017-04-01', '10:23:59', 'aaa', 100),(2, '2017-04-01', '10:23:59', 'aaa', 150),(3, '2017-04-01', '11:33:30', 'bbb', 200),(4, '2017-04-01', '11:33:30', 'bbb', 120),(5, '2017-04-02', '10:50:59', 'aaa', 70),(6, '2017-04-02', '10:50:59', 'bbb', 35);
ALTER TABLE `payment` ADD PRIMARY KEY (`id`);
ALTER TABLE `sales` ADD PRIMARY KEY (`id`);
ALTER TABLE `payment` MODIFY `id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
ALTER TABLE `sales` MODIFY `id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

Query
SELECT sales.time,sales.name,
SUM(sales.total),SUM(payment.amount)
FROM sales,payment
WHERE sales.time=payment.time
and sales.date like '2017-04-01%'
GROUP BY sales.time
ORDER BY sales.time;

Result is
10:23:59    aaa 250 600
11:33:30    bbb 320 800

A: You are multiplying the payments amount with the number of sales records, because you are joining all payments records with all sales records before summing up the amounts.
Aggregate first, and only join then.
In case there can always only be one payments record per date, time and name:
select p.name, p.time, p.name, s.sales_total, p.amount
from payments p
join
(
  select date, time, name, sum(total) as total
  from sales
  group by date, time, name
) s
 on s.date = p.date and s.time = p.time and s.name = p.name
where p.date = date '2017-04-01';

Otherwise:
select p.name, p.time, p.name, s.total, p.amount
(
  select date, time, name, sum(amount) as amount
  from payments
  group by date, time, name
) p
join
(
  select date, time, name, sum(total) as total
  from sales
  group by date, time, name
) s
 on s.date = p.date and s.time = p.time and s.name = p.name
where p.date = date '2017-04-01';


text:
Q: Two commands for the same line not drawn identically I have a line with equation y = (3/5)x + 1 drawn, and I have grid lines drawn using TikZ.  Each unit corresponds to 0.5cm.  The commands
\draw[<->] ({-7/2},{((3/5)*(-7) + 1)/2}) -- ({7/2},{((3/5)*7 + 1)/2});
and
\draw[<->] (-3.5, -3.2) and (3.5, 5.2);
should draw the same lines.  They do not.  At first, I noticed that the points (-5,-2), (0,1), and (5,4) did not belong to both lines.  Now, I see that the domains of the two lines are not even the same!
I understand that the first code for the line seems unnecessarily messy.  The calc package should be able to "handle" this, though.  There may be occasions when I need to graph a line with a slope of $1/\sqrt{2}$, too.
    \documentclass{amsart}
    \usepackage{amsmath}
    \usepackage{amsfonts}

    \usepackage{tikz}
    \usetikzlibrary{calc,positioning,intersections}

    \begin{document}

    \begin{tikzpicture}

    %Some distances from the origin along the axes are labeled. (The horizontal spacing occupied by
    %the minus sign indicating the additive inverse of a number is ignored so that the number is
    %centered a horizontal or vertical line.)
    \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (-3,0){\makebox[0pt][r]{$-$}$6$};
    \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (-2,0){\makebox[0pt][r]{$-$}$4$};
    \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (-1,0){\makebox[0pt][r]{$-$}$2$};
    \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (1,0){2};
    \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (2,0){4};
    \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (3,0){6};

    \node[fill=white, anchor=east, inner sep=0.15cm, font=\tiny] at (0,-2){\makebox[0pt][r]{$-$}$4$};
    \node[fill=white, anchor=east, inner sep=0.15cm, font=\tiny] at (0,-1){\makebox[0pt][r]{$-$}$2$};
    \node[fill=white, anchor=east, inner sep=0.15cm, font=\tiny] at (0,1){2};
    \node[fill=white, anchor=east, inner sep=0.15cm, font=\tiny] at (0,2){4};

    %The axes are drawn.
    \draw[latex-latex] (-4,0) -- (4,0);
    \draw[latex-latex] (0,-3) -- (0,3);
    \node [anchor=north west] at (4,0) {$x$};
    \node [anchor=south west] at (0,3) {$y$};

    %A grid on the Cartesian plane is drawn with dashed, gray lines.
    \foreach \x in {-2.5,-2,...,2.5} \draw[dashed,gray!50] (-3.75,\x) -- (3.75,\x);
    \foreach \x in {-3.5,-3,...,3.5} \draw[dashed,gray!50] (\x,-2.75) -- (\x,2.75);

%Line k is drawn with two commands. An equation for the line is y = (3/5)x + 1.
%This line is drawn a bit to the left of the vertical line x=-7
%and a bit  to the right of the vertical line x=7.

%
    \draw[<->] ($({-7/2},{((3/5)*(-7) + 1)/2}) +({(-1/2)/2}, {{(3/5)*((-1/2)/2)}})$)
    -- ($({7/2},{((3/5)*7 + 1)/2}) +({(1/2)/2}, {{(3/5)*((-1/2)/2)}})$);
    %
    \draw[<->] (-3.5,-1.6) -- (3.5,2.6);

    \end{tikzpicture}

    \end{document}

A: Are you overcomplicating, or am I oversimplifying? I'm too stupid to see where you got those coordinate calculations from, don't you just want \draw[<->] (-7/2,{((3/5)*(-7) + 1)/2}) -- (7/2,{((3/5)*7 + 1)/2});?
(Incidentally, if you use pgfplots you don't have to think about these things at all.)

However, your mistake is in the last y-coordinate of the line:
\draw[<->] ($({-7/2},{((3/5)*(-7) + 1)/2}) +({(-1/2)/2}, {{(3/5)*((-1/2)/2)}})$)
    -- ($({7/2},{((3/5)*7 + 1)/2}) +({(1/2)/2}, {{(3/5)*((-1/2)/2)}})$);

You have (-1/2) where it should be (1/2).
That said, you are really making this harder than you need to. What the \draw command above does is to draw the line from -7.5 to 7.5 instead of from -7 to 7. You get exactly the same result by saying
\draw[<->] (-7.5/2,{((3/5)*(-7.5) + 1)/2}) -- (7.5/2,{((3/5)*7.5 + 1)/2});

which is shorter and easier to read, I think.
Also worth to mention that if your goal was simply to extend the line a bit, you could use shorten, as in \draw[<->,shorten >=-0.125cm,shorten <=-0.125cm] (-7/2,{((3/5)*(-7) + 1)/2}) -- (7/2,{((3/5)*7 + 1)/2});.
\documentclass{amsart}
\usepackage{tikz}
\usetikzlibrary{calc,positioning,intersections}
\begin{document}
\begin{tikzpicture}
%Some distances from the origin along the axes are labeled. (The horizontal spacing occupied by
%the minus sign indicating the additive inverse of a number is ignored so that the number is
%centered a horizontal or vertical line.)
\foreach \x in {2,4,6}
  {
   \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (-\x/2,0){\makebox[0pt][r]{$-$}$\x$};
   \node[fill=white, anchor=north, inner sep=0.15cm, font=\tiny] at (\x/2,0){$\x$};
  }

\foreach \y in {2,4,6}
  {
   \node[fill=white, anchor=east, inner sep=0.15cm, font=\tiny] at (0,-\y/2,0){\makebox[0pt][r]{$-$}$\y$};
   \node[fill=white, anchor=east, inner sep=0.15cm, font=\tiny] at (0,\y/2){$\y$};
  }

%The axes are drawn.
\draw[latex-latex] (-4,0) -- (4,0);
\draw[latex-latex] (0,-3) -- (0,3);
\node [anchor=north west] at (4,0) {$x$};
\node [anchor=south west] at (0,3) {$y$};

%A grid on the Cartesian plane is drawn with dashed, gray lines.
\foreach \x in {-2.5,-2,...,2.5} \draw[dashed,gray!50] (-3.75,\x) -- (3.75,\x);
\foreach \x in {-3.5,-3,...,3.5} \draw[dashed,gray!50] (\x,-2.75) -- (\x,2.75);

%Line k is drawn with two commands. An equation for the line is y = (3/5)x + 1.
%
\draw[<->,green,ultra thick] (-7.5/2,{((3/5)*(-7.5) + 1)/2}) -- (7.5/2,{((3/5)*7.5 + 1)/2});
%
\draw[<->,red,thick] (-3.5,-1.6) -- (3.5,2.6);

\draw[<->,blue,thin,,samples at={-3.5,3.5}] plot (\x,{\x*3/5 + 0.5});

\draw[<->] ($({-7/2},{((3/5)*(-7) + 1)/2}) +({(-1/2)/2}, {{(3/5)*((-1/2)/2)}})$)
    -- ($({7/2},{((3/5)*7 + 1)/2}) +({(1/2)/2}, {{(3/5)*((1/2)/2)}})$);
\end{tikzpicture}
\end{document}


text:
Q: Замена определенных конструкций текста во всех файлах, python Господа, подскажите пожалуйста
У меня есть куча MD файлов, в которых есть ссылки на соседний html файлик. Хочу сделать скрипт, который во всех файлах в указанной папке будет заменять конструкцию вида [xxx_name](../ReferenceManual.html#operation/xxx) на xxx_name')
чтобы потом после конвертации MD файла в html ссылки открывались в новой вкладке
Я только начинаю знакомится с питоном и у меня получилось написать простой скриптик, который заменяет указанный текст на другой (в интернете полно примеров), но тут дело в том, что текст xxx_name и xxx всегда разный и если использовать простой скрипт, то нужно заранее указать миллион вариантов, которые нужно заменить
Видимо нужно использовать библиотеку re, но пока нет идей как ее можно использовать
Пока что есть только такое:
files_for_replacement = (         // не получается указать папку
  "/home/user/Documents/1.md",    // для поиска всех документов :(
  "/home/user/Documents/2.md",
  "/home/user/Documents/3.md",
  "/home/user/Documents/4.md",
)

for files_for_replacement in files_for_replacement:
  with open (files_for_replacement, 'r') as f:
    old_data = f.read()
    old_data1 = f.read()

    new_data = old_data.replace(
      '["get data"](../ReferenceManual.html#operation/getData)', '"get data"'
    )
    new_data1 = old_data1.replace(
      '["put file"](../ReferenceManual.html#operation/putFile)', '"put file"'
    )
  with open (files_for_replacement, 'w') as f:
    f.write(new_data)
    f.write(new_data1)

A: import re
t1=open('/path/to/file.md').read()
t2=re.sub(r'\[([\w\s]+)\]\(([\w:\/\.\-]+)\)', r'\1', t1)
open('/path/to/file.md').write(t2)

как-то так примерно


text:
Q: How to edit datagrid i.e populated using Linq to entities query? I have used linq to entities for making a join of multiple tables, the result of(Linq to entity query) which i have bound to datagrid. As excepted data is populated in datagrid but it is not editable. So how i can make this datagrid editable so i can edit and update data?
My code is as follows:
public static void displaydata()
    {
      //  MessageBox.Show("Hiii");

        rDatabaseEntities rde = new rDatabaseEntities();

        var displayquery = from del in rde.Deliveries
                           join tr in rde.Transporters on del.TransporterID equals tr.TransporterID
                           join it in rde.Items on del.ItemID equals it.ItemID
                           join pu in rde.Pumps on del.PumpID equals pu.PumpID
                           join pa in rde.Parties on del.PartyID equals pa.PartyID
                           join src in rde.Sources on del.SourceID equals src.SourceID
                           join dest in rde.Destinations on del.DestinationID equals dest.DestinationID

                           select new
                           {
                               del.TruckNo,
                               del.Weight,
                               del.LR_No,
                               del.cashAdv,
                               del.dieselAdv,
                               del.Dcpino,
                               del.Bal,
                               del.Freight,
                               del.Remarks,
                               tr.transporterName,
                               it.itemName,
                               pu.pumpName,
                               pa.partyName,
                               dest.destinationName

                           };
        var display = displayquery.ToList();

        displaygrid.ItemsSource = display;

    }

Your help would be highly appreciated.


text: Q: Execute find and cp command through shell_exec in PHP I am currently facing an issue. When I am executing command (find /home/vivek36/ -name '*$indexnumber*.wav'  -exec cp {} /home/main/backup \;) from terminal. then it executes. But when I am executing this command from shell_exec() in PHP, It does not execute.I am executing php script from root users. Any help would be appriciated.


text:
Q: How to add path variable as a Global Variable in Postman Documentation?
Whenever I am adding this documentation to Postman, it changes my global variable /{{tenantName}} to an object like /:tenantName.
Does anybody have solution for it?


text:
Q: Matlab: out of memory for 3 D matrices I am N = 10^6 data points and want to create (a) a N by N 2D matrix,A (b) and assign the values of P into the third dimension of a 3D matrix B. For N = 256 to N =1000, the following works
A = 0.1*eye(N,N);
 B(:,:,1) =A;

But for higher values of N, I am getting out of memory error. So, I found that I can create a sparse matrix instead of using eye as A = 0.1*eye(N,N); But then B cannot be created as that operation does not work for sparse. How can I find a way out? Thank you

A: You can use cell arrays.
B=cell(1000000);
B{1}=A;

This is for memory storage only.I don't know what you are going to do finally.
Hope this will help.


text:
Q: ACF Wysiwyg Editor Image srcset for responsive images I cannot find a way to generate srcset for images added inside Wysiwyg Editor field of Advanced Custom Field (ACF) plugin. Obviously, i know how to generate WordPress image srcset using:
wp_get_attachment_image_srcset($attachment_id);
function, as described at WordPress codex: https://developer.wordpress.org/reference/functions/wp_get_attachment_image_srcset/
But my real problem is to figure out most efficient way to get image srcset for images added inside ACF Wysiwyg Editor as the way my website is structured there is too much content inside my Wysiwyg Editor like text, images, videos and different heading tags.
Also, all the images added inside WordPress default Wysiwyg Editor is showing image srcset properly.
It's just that ACF Wysiwyg Editor is not supporting this. Any pointers to add efficient filter/hooks will be really helpful.


text:
Q: django suit and select2 autocomplete inlines I had a serious problem with Django-Select2 and Django-Suit, I'm trying to include a autocomplete field from select2 in admin suit, but I fail, the problem is that the links to add another do not appear in the result admin form; please any help is well received.
My two forms are:
class EstudianteNominaInlineForm(ModelForm):
    class Meta:
        model = EstudianteNomina

        fields = [
            'becado',
            'pago',
            'nomina',
            ]

        widgets = {
            'pago': EnclosedInput(append='icon-check'),
            }

    becado = EstudiantesNominaAdminSelect(
        label = 'Beneficiario',
        widget = AutoHeavySelect2Widget(select2_options={'width':'220px', 'minimumInputLength': 5})
        )

class NominaAdminForm(forms.ModelForm):
    class Meta:
    model = Nomina

    fields = [
            'tipo',
            'beneficio',
            'carrera_sedes',
            'pago',
            ]

    widgets = {
        'tipo': Select2Widget(select2_options={'width': '300px'}),
        'pago': EnclosedInput(append='icon-pencil'),
    }

And my admin.py is:
class NominaInline(SortableTabularInline):
    form = EstudianteNominaInlineForm
    model = EstudianteNomina
    extra=1
    sortable = 'becado'
    verbose_name_plural = 'Estudiantes en nomina'

class NominaAdmin(SortableModelAdmin):
form = NominaAdminForm
inlines = (NominaInline,)

def suit_row_attributes(self, obj, request):

    css_class = {
        True: 'success',
        False: 'error',
    }.get(int(obj.activa))
    if css_class:
        return {'class': css_class}

search_fields=['tipo', 'fecha']
list_filter=['tipo', 'fecha']
list_display=['id','get_carrera','Tipo', 'fecha', 'Pago', 'activa']
exclude = ['beneficio','carrera_sedes']
actions = [CerrarNominas, Normal, Especial, GeneraAbonos, GeneraAbonosN, GeneraTarjetas, GeneraAbonosE, GeneraAbonosEN]

def get_carrera(self, obj):
    if  obj.carrera_sedes.all().count() == 0:
        return u'NO EXISTEN CARRERAS ASOCIADAS'
    else:
        carreras =''
        for carrera in obj.carrera_sedes.all():
            carreras += '  {'+str(carrera.carreras.codigo_interno)+' - '+str(carrera.carreras.nombre)+'}  '
        return carreras
get_carrera.short_description = 'carreras'

def Tipo(self,obj):
    if obj.tipo=='0':
        return "NORMAL"
    else:
        return "ESPECIAL"
Tipo.short_description = 'nominas disponibles'

def Pago(self,obj):
    if obj.pago==None:
        return '400'
    else:
        return obj.pago
Pago.short_description = 'Pago'
admin.site.register(Nomina, NominaAdmin)

This is the result form (the add another button not has been found in form):


text:
Q: Bug in DateListPlot in Mathematica 10 Bug introduced in 10.0.0 and fixed in 10.0.1

Mentioned this already in an answer to a related question. DateListPlot in Mathematica 10 has a horrible bug: If two points have the same time coordinate, only one is plotted; the others are ignored. This is different in Mathematica 9, where all points are plotted correctly.
Wolfram tells me that they have this bug in their list to be fixed in the next update. For now I made a workaround with a function that makes identical time coordinates differ by a few seconds, so that DateListPlot plots all points. Has anybody another solution?

A: Here's my current workaround. Works only if the distinct time coordinates are sufficiently separated.
corr[z_] :=
  Module[{z1, z2},
    z1 = SplitBy[SortBy[z, First], #[[1]] &];
    z2 =
      Table[
        Transpose[{z1[[k, All, 1]] + Range[0, Length[z1[[k]]] - 1], z1[[k, All, 2]]}],
        {k, Length[z1]}];
    Partition[Flatten[z2], 2]]

and DateListPlot on a two column array z is then called as
DateListPlot[corr[z], ...]


text:
Q: C# XML Serialization Attribute before class declaration I have this class
public class dtoObject : CommonBase
{
    [XmlArray("SomeItems"), XmlArrayItem("SomeItem")]
    public List<dtoSomeItem> SomeItems
    {
        get { return _SomeItems; }
        set { _SomeItems = value; }
    }
 }

and I would would like to use XML Serialization to make the XML string appear to be:
<Objects>
    <Object>
        <SomeItems>
            <SomeItem>
              1
            </SomeItem>
            <SomeItem>
              2
            </SomeItem>
        </SomeItems>
    </Object>
    <Object>
        <SomeItems>
            <SomeItem>
              3
            </SomeItem>
            <SomeItem>
              4
            </SomeItem>
        </SomeItems>
    </Object>
</Objects>

But for the life of me I cant figure out what to put before
public class dtoObject

in terms of Attributes, so that I get
<Objects><Object>...</Object><Object>...

when I serialize this.
Any ideas?

A: I don't think that you can do this with your object structure because the XML effectively declares a wrapper around the SomeItems collection. For example:
[XmlType("Objects")]
public class dtoObject : CommonBase
{
    [XmlElement("Object")]
    public List<dtoSomeItemWrapper> SomeItemsWrappers
    {
        get { return _SomeItemsWrappers; }
        set { _SomeItemsWrappers = value; }
    }
 }

class dtoSomeItemWrapper
{
    [XmlArray("SomeItems"), XmlArrayItem("SomeItem")]
    public List<dtoSomeItem> SomeItems
    {
        get { return _SomeItems; }
        set { _SomeItems = value; }
    }
}

A: Here is what I got to work. Thanks to comptent_tech and dthorpe for their help. I created my DTO like so:
[XmlType("Object", Namespace = "", TypeName = "Object")]
public class dtoObject : CommonBase
{
    [XmlArray("SomeItems"), XmlArrayItem("SomeItem")]
    public List<dtoSomeItem> SomeItems
    {
        get { return _SomeItems; }
        set { _SomeItems = value; }
    }
}

My function that does the serializing is this:
public string ToXML(List<dtoObject> oObject)
{
    XmlDocument xmlDoc = new XmlDocument();
    XmlSerializer xmlSerializer = new XmlSerializer(oObject.GetType(), new XmlRootAttribute("Objects"));
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
    ns.Add("", "");

    using (MemoryStream xmlStream = new MemoryStream())
    {

        xmlSerializer.Serialize(xmlStream, oObject, ns);

        xmlStream.Position = 0;
        xmlDoc.Load(xmlStream);
        return xmlDoc.InnerXml;
    }
}

Doing this creates the xml format of:
<?xml version="1.0"?>
    <Objects>
        <Object>
            <SomeItems>
                <SomeItem>
                </SomeItem>
            </SomeItems>
        </Object>
    <Objects>

A: You'll need something like XmlRootAttribute("Object", Namespace="", IsNullable=false) in front of the class declaration. That tells the XML serializer to use the <Object> tag to represent the dtoObject in the XML text.
As for the <Objects> tag, you won't get that unless you are serializing an array of dtoObject. That is beyond the scope of the dtoObject type.


text:
Q: How to perform aggregate query with where condition I have this MongoDB query:
var array=[]; //some string values

collection.aggregate(
    { $match: { '_id': { $in : array } } }
)

But this is not returning any results. How do I perform this?

A: As noted in the comments, your array variable is an array of hex string values ex :["57f36e94517f72bc09ee761e"] and for mongo shell, you need to first cast those string values to ObjectIds. Use the JavaScript map()
method to accomplish the casting in a list.
For example:
mongo shell
var array = ["585808969e39db5196444c07", "585808969e39db5196444c06"];
var ids = array.map(function(id){ return ObjectId(id); });

which you can then query using the aggregate function as in the following
db.collection.aggregate([
    { "$match": { "_id": { "$in" : ids } } }
])

The above is essentially the same as
db.collection.find({ "_id": { "$in": ids } })

Node.js
var {ObjectId} = require('mongodb'); // or ObjectID
var ids = array.map(id => ObjectId.isValid(id) ? new ObjectId(id) : null;);


text:
Q: what is resources? what is difference between <resources> and <Linearlayout>? what is <resources> and where do we use it?
I searched and i see android site but i dont understand that what is <resources>.
why in strings.xml we use <resources>?
for example, in this code we use  so why not use <LinearLayout>?
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="difficulty">
        <item>@string/easy_label</item>
        <item>@string/medium_label</item>
        <item>@string/hard_label</item>
    </array>
</resources>

Cheers.

A: Resources basically refer to the resources that you make for your android project and store in res folder. You can access these resources through R.java file. Difference between resources and linear layout is linear layout defines a layout format.
Strings.xml is a resource file. Resources kept in here can be accesed through R.strings.yourStringName. For more details refer http://developer.android.com/guide/topics/ui/declaring-layout.html
http://developer.android.com/guide/topics/resources/available-resources.html


text:
Q: Tibco AMX Administrator: Empty page after login I have an issues with Tibco Active Matrix Administrator console and Firefox. After log-in I got an empty white page. Few days ago I hadn't this problem and it is looks like I have not changed anything in Firefox.
Does anyone had this problem too and how it was fixed?

A: I had faced this same issue a couple of months back. What i did to resolve was i noticed there was a plugin update on my FireFox browser which i felt hindered the Admin page to load. I just removed the updated plugin and also cleared my cookies. It worked soon after the restart of the browser and my machine. Hope this helps


text:
Q: Can I make a command to be the col-offset always 1 on every screen sizes in bootstrap? Let's assume I want to make an element which has equivalent offset all on the screen sizes. I only saw examples where people concretely adjusted the size like:
col-offset-md-2
What if I want to do something like this?

As you can see it's not a nice solution, the lines are growing too big. Can I make a command to be the offset always 1 on every screen sizes? Something like this:

A: You can use col-xs-offset-1 to offset all column size by one.
Note: The way you are writing the column offset col-offset-xs-1 is not correct either.
Here is an example:

   Offset Every Column By 1


text:
Q: Jekyll kramdown does not support reference links I try using kramdown reference links in Jekyll. Reference links do not work (Jekyll does not produce  tags). Inline links work as expected.
I simply copied the example from the kramdown syntax reference into my Kramdown document.
This is a [reference style link][linkid] to a page. And [this]
[linkid] is also a link. As is [this][] and [THIS].

Please could one reproduce this issue or confirm, that it's working.

A: You need to define the reference though..
For example:
This is a [reference style link][linkid] to a page. And [this]
[linkid] is also a link.

[linkid]: http://www.example.com/

A: I think you want a footnote:
This is a text with a footnote[^1].

[^1]: And here is the definition.

https://kramdown.gettalong.org/quickref.html#footnotes


text:
Q: Unit test of a function containing promises is not working as expected I'm trying to unit test a controller that handles signing a user in. I'm getting an error and think it may have something to do with the code using promises but I'm not really sure at this point. Here's the controller.
angular.module('app').controller('SignIn', SignIn);

function SignIn ($scope, $state, auth) {

    $scope.credentials = {};

    // signin
    $scope.signIn = function () {
        auth.signIn($scope.credentials)
            .then(function () {
                $state.go('user.welcome');
            }, function (res) {
                $scope.signInError = res.statusText;
            });
    };
}

Here's the auth services.
angular.module('app').factory('auth', auth);

function auth (session, api) {
    return {
        signIn : function (credentials) {
            return api.signIn(credentials)
                .then(function (res) {
                    session.create(res.data.sessionId, res.data.userName);
                });
        },
        signout: function () {
            return session.destroy();
        },
        isAuthenticated: function () {
            return !!session.userName;
        }
    };
}

The api just returns $http promises.
signIn : function (credentials) {
    return $http.post(base + '/auth/credentials', credentials);
}

And session is just a factory to store the current session info as well as save it to the browser's cookies.
Here is my jasmine test
describe('SignIn', function () {

// setup ------------------------------------------------------------------

    // init app module
    beforeEach(module('app'));

    // inject Session service
    beforeEach(angular.mock.inject(function (_$rootScope_, _$controller_, _auth_) {
        $rootScope             = _$rootScope_;
        $scope                 = $rootScope.$new();
        controller             = _$controller_("SignIn", {$scope: $scope});
        auth                   = _auth_;
    }));

    // setup spies
    beforeEach(function () {
        spyOn(auth, 'signIn');
    });

// tests ------------------------------------------------------------------

    // signin in
    it("should call auth.signIn with the user's credentials", function () {
        $scope.signIn();
        expect(auth.signIn).toHaveBeenCalled();
    });

});

I'm just trying to test that auth.signIn is called when you call $scope.signIn(). The application itself it working but I am getting this error when trying to run this test.
SignIn should call auth.signIn with the user's credentials FAILED
TypeError: 'undefined' is not an object (evaluating 'auth.signIn($scope.credentials).then')

Although there is an expectation there, the error is happening when I call $scope.signIn(); If I log auth right before $scope.signIn(); is called I get this.
LOG: Object{signIn: function () { ... }, signout: function () { ... }, isAuthenticated: function () { ... }}

So I assume the DI is working as expected. I've looked at different ways of setting up spies but haven't figured out what is actually wrong yet. Any help would be appreciated.

A: That is because you are spying on auth's signIn function. When you spy on it, it wont be your real function in the api any more. So you need to send a promise from the spy by using .and.returnValue.
So do:-
beforeEach(inject(function (_$rootScope_, _$controller_, _auth_, _$q_) {
    $rootScope             = _$rootScope_;
    $scope                 = $rootScope.$new();
    controller             = _$controller_("SignIn", {$scope: $scope});
    auth                   = _auth_;
    fakePromise = _$q_.when(); //get a fake promise
}));

beforeEach(function () {
  spyOn(auth, 'signIn').and.returnValue(fakePromise); //return fakepromise
});

Plnkr
and if you were to return some value fro signIn (or any other function's promise, just do)
  fakeAuthPromise = _$q_.when(somedata);


text:
Q: Data Loss in Azure I have a VM running on Azure and I have a CRM system running on this VM. For some reason, all the data entered in the CRM got lost and the person who set up the VM did not enable backup. So I can't restore to the last instance as well.
I don't know what exactly happened. I can't find Azure support to get on a call with them to check if any of the data is recoverable.
Please anyone guide me on what to do.

A: There's a very big chance the data that got lost was stored on the VM's temporary disk:

Temporary disk - Temporary disks use a solid-state drive that is located on the same Azure host as the VM. Temp disks are highly performant and may be used for operations such as temporary data processing. However, if the VM is moved to a new host, any data stored on a temporary disk is removed. The size of the temporary disk is determined by the VM size. Temporary disks are assigned a drive letter of D: by default.

Source: Default Azure Disks
Unfortunately any data lost from the temporary disk is not recoverable.


text:
Q: Click action not working on notification pwa I am working pwa where notifications are coming fine.But when i click on notification nothing happens. I know this question already asked. My code is below:-
firebase.initializeApp({
   'messagingSenderId': 'SEnder_id'
});

  // Retrieve an instance of Firebase Messaging so that it can handle background
  // messages.
 const messaging = firebase.messaging();
 messaging.setBackgroundMessageHandler(function(payload) {
     //console.log('[firebase-messaging-sw.js] Received background message ', payload);
     // Customize notification here
     const notificationTitle = 'Background Message Title';
     const notificationOptions = {
     body: 'Background Message body.',
     icon: '/itwonders-web-logo.png',
    data: {
        click_action: payload.notification.click_action
    }
  };
  // Notifcation click event
        self.addEventListener('notificationclick', function (event) {
        event.notification.close();
       clients.openWindow("https://youtu.be/PAvHeRGZ_lA"); //even simple static link not opening
   });
   return self.registration.showNotification(notificationTitle,
        notificationOptions);
});

I am also getting click_action value when notification come.


text:
Q: LUIS return DatetimeV2 entities but my app is receiving just datetime entities If a enter a query directly to LUIS in my browser it will return the correct DatetimeV2 entity:
 "entities": [
{
  "entity": "after 2010",
  "type": "builtin.datetimeV2.daterange",
  "startIndex": 43,
  "endIndex": 52,
  "resolution": {
    "values": [
      {
        "timex": "2010",
        "Mod": "after",
        "type": "daterange",
        "start": "2010-12-31"
      }
    ]
  }
},

When I submit the same query in my app, the RecognizerResult only returns:
"datetime": [
{
  "type": "daterange",
  "timex": [
    "2010"
  ]
}]

I am using Microsoft Bot Builder 4.0.1 and the built in Luis recognizer middleware . This is how I am accessing the RecognizerResult
  public static RecognizerResult GetRecognizerResult(ITurnContext context)
    {
        return context.Services.Get<RecognizerResult>
                (LuisRecognizerMiddleware.LuisRecognizerResultKey);
    }


text:
Q: AdMob account migration and AdSense account Today I tried to upgrade my old AdMob account to new AdMob (using this guide https://support.google.com/admob/v2/answer/3077517). But I failed on frist step with validation info:
You need a valid AdSense account to sign up with AdMob, but your AdSense account application is currently unapproved. To update and resubmit your application, please visit AdSense directly.
Some time ago I tried to create an AdSense account for one of my page, but it was rejected due to lack of good content. And here is my question: do I need a site that will pass AdSense content revied to be able to publish adds via AdMob in Android apps?

A: As I understand, if you have failed to use AdSense on your account, you cannot use that e-mail address as your new Admob account.
I faced the same issue and the following scenario succeeded:

*

*Create a new gmail account.

*Create a new admob account using that e-mail address.

*Link your new admob and legacy admob. (This is described on the new admob and google support pages)

*Import your data on legacy admob to the new admob.
To be honest, I am reluctant to perform that last step because of the new policies of new admob:

*

*Payment methods are changed: As I understand, paypal is no longer a valid payment method. EFT and western union checks are valid forms of payment.

*To select the payment method, one has to reach $10 balance.

*More information may be required to select the payment method, for example, valid tax identifiers, and more if applicable. This "more information" is available after $10 balance.

*Payment thresholds are changed: The thresholds are increased to 100 USD. If you have a monthly revenue of $30, it is sufficient to receive payments every month with a threshold of $20. However, with the increased threshold of $100, you will receive payments in every 3-4 months.