text:
Q: AWS Cloudformation: Loadbalancer Custom SSL Negotiation Policy Trying to set up a cloudformation template with a custom SSL Negotiation policy. The cloudformation error I am getting is:

CREATE_FAILED     AWS::ElasticLoadBalancing::LoadBalancer     BackendELB  SSLNegotiationPolicy cannot be enabled

My cloudformation template section is as follows:
"Policies" : [
                {
                    "PolicyName": "SSLNegotiationPolicy",
                    "PolicyType": "SSLNegotiationPolicyType",
                    "Attributes": [
                        { "Name" : "Protocol-TLSv1", "Value" : "true" },
                        { "Name" : "Protocol-TLSv1.1", "Value" : "true" },
                        { "Name" : "Protocol-TLSv1.2", "Value" : "true" },
                        { "Name" : "Protocol-SSLv2", "Value" : "false" },
                        { "Name" : "Protocol-SSLv3", "Value" : "false" },
                        { "Name" : "ECDHE-RSA-AES128-GCM-SHA256", "Value" : "true" },
                        { "Name" : "ECDHE-ECDSA-AES128-SHA256", "Value" : "true" },
                        { "Name" : "ECDHE-RSA-AES128-SHA256", "Value" : "true" },
                        { "Name" : "ECDHE-ECDSA-AES128-SHA", "Value" : "true" },
                        { "Name" : "ECDHE-RSA-AES128-SHA", "Value" : "true" },
                        { "Name" : "DHE-RSA-AES128-SHA", "Value" : "true" },
                        { "Name" : "ECDHE-ECDSA-AES256-GCM-SHA384", "Value" : "true" },
                        { "Name" : "ECDHE-RSA-AES256-GCM-SHA384", "Value" : "true" },
                        { "Name" : "ECDHE-ECDSA-AES256-SHA384", "Value" : "true" },
                        { "Name" : "ECDHE-RSA-AES256-SHA384", "Value" : "true" },
                        { "Name" : "ECDHE-RSA-AES256-SHA", "Value" : "true" },
                        { "Name" : "ECDHE-ECDSA-AES256-SHA", "Value" : "true" },
                        { "Name" : "AES128-GCM-SHA256", "Value" : "true" },
                        { "Name" : "AES128-SHA256", "Value" : "true" },
                        { "Name" : "AES128-SHA", "Value" : "true" },
                        { "Name" : "AES256-GCM-SHA384", "Value" : "true" },
                        { "Name" : "AES256-SHA256", "Value" : "true" },
                        { "Name" : "AES256-SHA", "Value" : "true" },
                        { "Name" : "DHE-DSS-AES128-SHA", "Value" : "true" },
                        { "Name" : "RC4-SHA", "Value" : "false" },
                        { "Name" : "ECDHE-ECDSA-RC4-SHA", "Value" : "false" }
                    ],
                    "InstancePorts" : [ "443" ]
               }
           ]

If I remove the InstancePorts section then the ELB creates with no errors, but the new load balancer doesn't use the policy outlined.
Any ideas?
Side question: Is it necessary to set every value of your policy to either true or false or if the cipher is not defined in the template, does it default to the value defined in the recommended SSL policy?

A: I think you're on the right track.  You can view the existing security policy contents with:
aws elb describe-load-balancer-policies

I specify everything for completeness, such as the policy below:
    "Policies" : [
      {
        "PolicyName" : "My-ELBSecurityPolicy-2014-10-DisableRC4",
        "PolicyType" : "SSLNegotiationPolicyType",
        "Attributes" : [
            { "Name": "Protocol-SSLv2", "Value": "false" },
            { "Name": "Protocol-TLSv1", "Value": "true" },
            { "Name": "Protocol-SSLv3", "Value": "false" },
            { "Name": "Protocol-TLSv1.1", "Value": "true" },
            { "Name": "Protocol-TLSv1.2", "Value": "true" },
            { "Name": "Server-Defined-Cipher-Order", "Value": "true" },
            { "Name": "ECDHE-ECDSA-AES128-GCM-SHA256", "Value": "true" },
            { "Name": "ECDHE-RSA-AES128-GCM-SHA256", "Value": "true" },
            { "Name": "ECDHE-ECDSA-AES128-SHA256", "Value": "true" },
            { "Name": "ECDHE-RSA-AES128-SHA256", "Value": "true" },
            { "Name": "ECDHE-ECDSA-AES128-SHA", "Value": "true" },
            { "Name": "ECDHE-RSA-AES128-SHA", "Value": "true" },
            { "Name": "DHE-RSA-AES128-SHA", "Value": "true" },
            { "Name": "ECDHE-ECDSA-AES256-GCM-SHA384", "Value": "true" },
            { "Name": "ECDHE-RSA-AES256-GCM-SHA384", "Value": "true" },
            { "Name": "ECDHE-ECDSA-AES256-SHA384", "Value": "true" },
            { "Name": "ECDHE-RSA-AES256-SHA384", "Value": "true" },
            { "Name": "ECDHE-RSA-AES256-SHA", "Value": "true" },
            { "Name": "ECDHE-ECDSA-AES256-SHA", "Value": "true" },
            { "Name": "AES128-GCM-SHA256", "Value": "true" },
            { "Name": "AES128-SHA256", "Value": "true" },
            { "Name": "AES128-SHA", "Value": "true" },
            { "Name": "AES256-GCM-SHA384", "Value": "true" },
            { "Name": "AES256-SHA256", "Value": "true" },
            { "Name": "AES256-SHA", "Value": "true" },
            { "Name": "DHE-DSS-AES128-SHA", "Value": "true" },
            { "Name": "CAMELLIA128-SHA", "Value": "false" },
            { "Name": "EDH-RSA-DES-CBC3-SHA", "Value": "false" },
            { "Name": "DES-CBC3-SHA", "Value": "false" },
            { "Name": "ECDHE-RSA-RC4-SHA", "Value": "false" },
            { "Name": "RC4-SHA", "Value": "false" },
            { "Name": "ECDHE-ECDSA-RC4-SHA", "Value": "false" },
            { "Name": "DHE-DSS-AES256-GCM-SHA384", "Value": "false" },
            { "Name": "DHE-RSA-AES256-GCM-SHA384", "Value": "false" },
            { "Name": "DHE-RSA-AES256-SHA256", "Value": "false" },
            { "Name": "DHE-DSS-AES256-SHA256", "Value": "false" },
            { "Name": "DHE-RSA-AES256-SHA", "Value": "false" },
            { "Name": "DHE-DSS-AES256-SHA", "Value": "false" },
            { "Name": "DHE-RSA-CAMELLIA256-SHA", "Value": "false" },
            { "Name": "DHE-DSS-CAMELLIA256-SHA", "Value": "false" },
            { "Name": "CAMELLIA256-SHA", "Value": "false" },
            { "Name": "EDH-DSS-DES-CBC3-SHA", "Value": "false" },
            { "Name": "DHE-DSS-AES128-GCM-SHA256", "Value": "false" },
            { "Name": "DHE-RSA-AES128-GCM-SHA256", "Value": "false" },
            { "Name": "DHE-RSA-AES128-SHA256", "Value": "false" },
            { "Name": "DHE-DSS-AES128-SHA256", "Value": "false" },
            { "Name": "DHE-RSA-CAMELLIA128-SHA", "Value": "false" },
            { "Name": "DHE-DSS-CAMELLIA128-SHA", "Value": "false" },
            { "Name": "ADH-AES128-GCM-SHA256", "Value": "false" },
            { "Name": "ADH-AES128-SHA", "Value": "false" },
            { "Name": "ADH-AES128-SHA256", "Value": "false" },
            { "Name": "ADH-AES256-GCM-SHA384", "Value": "false" },
            { "Name": "ADH-AES256-SHA", "Value": "false" },
            { "Name": "ADH-AES256-SHA256", "Value": "false" },
            { "Name": "ADH-CAMELLIA128-SHA", "Value": "false" },
            { "Name": "ADH-CAMELLIA256-SHA", "Value": "false" },
            { "Name": "ADH-DES-CBC3-SHA", "Value": "false" },
            { "Name": "ADH-DES-CBC-SHA", "Value": "false" },
            { "Name": "ADH-RC4-MD5", "Value": "false" },
            { "Name": "ADH-SEED-SHA", "Value": "false" },
            { "Name": "DES-CBC-SHA", "Value": "false" },
            { "Name": "DHE-DSS-SEED-SHA", "Value": "false" },
            { "Name": "DHE-RSA-SEED-SHA", "Value": "false" },
            { "Name": "EDH-DSS-DES-CBC-SHA", "Value": "false" },
            { "Name": "EDH-RSA-DES-CBC-SHA", "Value": "false" },
            { "Name": "IDEA-CBC-SHA", "Value": "false" },
            { "Name": "RC4-MD5", "Value": "false" },
            { "Name": "SEED-SHA", "Value": "false" },
            { "Name": "DES-CBC3-MD5", "Value": "false" },
            { "Name": "DES-CBC-MD5", "Value": "false" },
            { "Name": "RC2-CBC-MD5", "Value": "false" },
            { "Name": "PSK-AES256-CBC-SHA", "Value": "false" },
            { "Name": "PSK-3DES-EDE-CBC-SHA", "Value": "false" },
            { "Name": "KRB5-DES-CBC3-SHA", "Value": "false" },
            { "Name": "KRB5-DES-CBC3-MD5", "Value": "false" },
            { "Name": "PSK-AES128-CBC-SHA", "Value": "false" },
            { "Name": "PSK-RC4-SHA", "Value": "false" },
            { "Name": "KRB5-RC4-SHA", "Value": "false" },
            { "Name": "KRB5-RC4-MD5", "Value": "false" },
            { "Name": "KRB5-DES-CBC-SHA", "Value": "false" },
            { "Name": "KRB5-DES-CBC-MD5", "Value": "false" },
            { "Name": "EXP-EDH-RSA-DES-CBC-SHA", "Value": "false" },
            { "Name": "EXP-EDH-DSS-DES-CBC-SHA", "Value": "false" },
            { "Name": "EXP-ADH-DES-CBC-SHA", "Value": "false" },
            { "Name": "EXP-DES-CBC-SHA", "Value": "false" },
            { "Name": "EXP-RC2-CBC-MD5", "Value": "false" },
            { "Name": "EXP-KRB5-RC2-CBC-SHA", "Value": "false" },
            { "Name": "EXP-KRB5-DES-CBC-SHA", "Value": "false" },
            { "Name": "EXP-KRB5-RC2-CBC-MD5", "Value": "false" },
            { "Name": "EXP-KRB5-DES-CBC-MD5", "Value": "false" },
            { "Name": "EXP-ADH-RC4-MD5", "Value": "false" },
            { "Name": "EXP-RC4-MD5", "Value": "false" },
            { "Name": "EXP-KRB5-RC4-SHA", "Value": "false" },
            { "Name": "EXP-KRB5-RC4-MD5", "Value": "false" }
        ]
      }
    ]

You also have to reference the policy in the ELB specification itself:
    "Listeners" : [
      { "LoadBalancerPort" : "80",
        "InstancePort" : "80",
        "Protocol" : "HTTP" },
      { "LoadBalancerPort" : "443",
        "InstancePort" : "80",
        "Protocol" : "HTTPS",
        "SSLCertificateId" : "arn:aws:iam::111111111111:server-certificate/somedomain.com",
        "PolicyNames" : [ "My-ELBSecurityPolicy-2014-10-DisableRC4", "SomeOtherPolicy" ]
      }
    ],


text:
Q: How to Increase Speed of Cube on finger touch in Android OpenGL? I am working on an Android application in which I am facing a problem regarding rotation  of 3D Cube.I want to rotate my cube according to fingure touch.

*

*If User Touch Fast speed on mobile screen then cube should be move fast and stop slowly -2 after some time .

*And if user Touch slowly then cube should be move slowly.

Till Now I have tried this code which is not working for rotation--
            //Rotate around the axis based on the rotation matrix (rotation, x, y, z)
    gl.glRotatef(PhotoCube3DLWPActivity.xrot, 1.0f, 0.0f, 0.0f);    //X
    gl.glRotatef(PhotoCube3DLWPActivity.yrot, 0.0f, 1.0f, 0.0f);    //Y
    gl.glRotatef(PhotoCube3DLWPActivity.zrot, 0.0f, 0.0f, 1.0f);    //Z

    cube.draw(gl);                  //Draw the Cube

    //Change rotation factors (nice rotation)
    PhotoCube3DLWPActivity.xrot +=0.3f;;
    PhotoCube3DLWPActivity.yrot +=0.2f;
    PhotoCube3DLWPActivity.zrot +=0.4f;

where xrot,yrot and zrot are static variable of PhotoCube3DLWPActivity class which values are 0.3f,0.2f and 0.4f respectiblly.
for Touch event I am using-
     @Override
    public void onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN :
                Log.i("check", "Hey action down");
                downX = event.getX();
                downY = event.getY();
                downTime = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_MOVE :
                // handle in between rotation

                break;

            case MotionEvent.ACTION_UP :
                Log.i("check", "Hey action up");
                diffX = event.getX() - downX;
                diffY = event.getY() - downY;
                diffTime = System.currentTimeMillis() - downTime;

                diffTouch = (float) Math.sqrt(diffX * diffX + diffY * diffY);

                diffSpeed = diffTouch / diffTime * 1.0f;

                diffAngle = (float) Math.atan(diffY / diffX);

                xrot += diffSpeed * Math.sin(diffAngle);
                yrot += diffSpeed * Math.cos(diffAngle);

                break;
        }

    }//touch end

A: You could try implementing a simple Fling gesture detection, and based on the velocity, you could adjust the speed of the rotation.
To implement the GestureDetector, you could look into the following,
Fling Gesture

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to read a positive value in c i just want to make sure that i read a positive value for x not sure whats wrong here
#include <stdio.h>

void main() {
    unsigned x;
    int i;
    do {
        printf("donner un nombre\n");
        scanf("%u", &x);
    } while (x <= 1);
    /*
    for (i = 0; i++; i < x) {
        int prime = 0;
        int x = 2;
        do {
            if (i % x == 0 ) {
                prime = 1;
            }
            x++;
        } while (prime == 0 && x < i);

        if (prime == 0) {
            printf("%i",i);
        }
    }
    */
}

A: Unsigned is bad choice
First at all you change unsigned type to integer int, that alloved you to scan negative numbers such as -1, -5,...
Wrong condition in loop
Also there is bug in do while loop, where you scan until the x <= 1 but number 1 is positive number, so you have to change it to x < 1
Final code will looks like this:
#include <stdio.h>

int main() {
    int x;
    do {
        printf("donner un nombre\n");
        scanf("%u", &x);
    } while (x < 1);

    // your code working with positive x

    return 0;
}

A: Reading input, especially when it involves a numeric conversion is something done time and time again. It's worth taking the time to understand how to do it properly.
For starters, using scanf() for user-input can be done, but it is so full of pitfalls for the new C programmer that it is highly discouraged. This is due to the state that scanf() leaves your input buffer in both after good input (with potential additional characters and the '\n' left unread), and after invalid input (where all characters from the point of matching-failure forward are left unread). To avoid all of these pitfalls, simply read all input into a sufficiently sized buffer (character array) with fgets() and then convert the contents of the array as needed.
Why fgets() and a sufficiently sized buffer? fgets() reads an entire line of input (including the trialing '\n' produced by the user pressing Enter ensuring the input buffer (stdin in your case) is left in a proper state for your next read.
To convert the contents of the array to an integer value, strtol() provides the most robust diagnostics and error reporting in the event the user failed to enter a valid integer, but using sscanf() for the conversion at least provides a valid success/failed indication through its return.
(you couldn't have used scanf() correctly to begin with without checking the return)
How To Read User Input?
The approach is simple, and it virtually the same for any input needed. You simply:

*

*loop continually prompting for input until a valid input is provided by the user (your read-loop),

*read the user input into a sufficiently sized buffer (don't skimp on buffer size),

*check if the user canceled input by generating a manual EOF by pressing Ctrl + d (or Ctrl + z on windows),

*attempt conversion of the contents of your buffer as needed (to int in your case) checking the return of the conversion function used,

*if the input is valid, check against any other constraints you have (positive int in your case)

*if all conditions for good input met -- break out of the read-loop, otherwise,

*handle the invalid input, and loop again.

No matter what you need to get from the user, you can use this approach. It's something you use so often, it makes sense to put it in a function you can call any time you need that type of input. For an int value, where you can provide an optional prompt to the user to be displayed, you can do something similar to:
...

#define MAXC 256    /* if you need a constant, #define one (or more) */

/* read integer value from 'fp', update value at 'val' address.
 * returns 1 on success, 0 if user cancels input with ctrl+d (or
 * ctrl+z on windows)
 */
int read_int (int *val, FILE *fp, const char *prompt)
{
  char buf[MAXC];   /* buffer (char array) to hold line of input */

  for (;;) {        /* loop continually until valid input or user cancels */

    if (prompt) {                         /* if prompt not NULL, display */
      fputs (prompt, stdout);
    }

    if (!fgets (buf, MAXC, fp)) {         /* read/validate line of input */
      puts ("(user canceled input)");
      return 0;
    }

    /* attempt conversion to int validating return/handle error */
    if (sscanf (buf, "%d", val) != 1) {
      fputs ("  error: invalid integer input.\n", stderr);
    }
    else {        /* otherwise, valid int received */
      break;      /* break input loop */
    }
  }

  return 1;       /* return success */
}

The function above will require the user to enter a valid integer, looping displaying the prompt and handling any input errors until the user does while still allowing the user to cancel input with a manual EOF. What it doesn't do is apply your constraint of requiring a positive value. This you add as an additional requirement where you call read_int() in your code.
For example, in main()1 since you need a positive value, you simply call the read_int() function in another continual loop until a positive value is returned (handling the manual EOF case as well). That can look like the following:
int main (void) {   /* proper invocation of main unless on freestanding sys */

  int x = 0;

  for (;;) {   /* loop continually prompting for input until x positive */
    /* validate return of read_int() checking if user canceled */
    if (read_int (&x, stdin, "donner un nombre: ") == 0) {
      return 0;     /* graceful exit on cancel -- not an error */
    }
    if (x > 0) {    /* test x in acceptable range (positive) */
      break;        /* break read loop */
    }
    /* handle x outside of range */
    fputs ("  error: invalid input, must be postive integer.\n", stderr);
  }

  printf ("\npostivie x: %d\n", x);
}

(note: above you simply apply a continual loop again, looping until the int value is in the range of positive integers -- handle the 0 case however you want to consider it)
If you need to cover the entire range of unsigned, then change the function to be read_long() (and change the types appropriately). Then in main() you can #include <limits.h> and test if (0 < x && x <= UINT_MAX) for input in range.
Putting it altogether simply requires adding #include <stdio.h> at the top, e.g.
#include <stdio.h>

#define MAXC 256    /* if you need a constant, #define one (or more) */

/* read integer value from 'fp', update value at 'val' address.
 * returns 1 on success, 0 if user cancels input with ctrl+d (or
 * ctrl+z on windows)
 */
int read_int (int *val, FILE *fp, const char *prompt)
{
  char buf[MAXC];   /* buffer (char array) to hold line of input */

  for (;;) {        /* loop continually until valid input or user cancels */

    if (prompt) {                         /* if prompt not NULL, display */
      fputs (prompt, stdout);
    }

    if (!fgets (buf, MAXC, fp)) {         /* read/validate line of input */
      puts ("(user canceled input)");
      return 0;
    }

    /* attempt conversion to int validating return/handle error */
    if (sscanf (buf, "%d", val) != 1) {
      fputs ("  error: invalid integer input.\n", stderr);
    }
    else {        /* otherwise, valid int received */
      break;      /* break input loop */
    }
  }

  return 1;       /* return success */
}

int main (void) {   /* proper invocation of main unless on freestanding sys */

  int x = 0;

  for (;;) {   /* loop continually prompting for input until x positive */
    /* validate return of read_int() checking if user canceled */
    if (read_int (&x, stdin, "donner un nombre: ") == 0) {
      return 0;     /* graceful exit on cancel -- not an error */
    }
    if (x > 0) {    /* test x in acceptable range (positive) */
      break;        /* break read loop */
    }
    /* handle x outside of range */
    fputs ("  error: invalid input, must be postive integer.\n", stderr);
  }

  printf ("\npostivie x: %d\n", x);
}

Example Use/Output
Now that you have written your input routine -- go try and break it, every way you can think of -- and make sure it handles all cases correctly. Then there will always be one or two corner-cases you didn't think about you will have to fix later.
Does the input routine work, requiring a positive value?
$ ./bin/read_int_function
donner un nombre: 0
  error: invalid input, must be postive integer.
donner un nombre: banannas and pickles
  error: invalid integer input.
donner un nombre: ten
  error: invalid integer input.
donner un nombre: 10

postivie x: 10

What about handling the user canceling input?
$ ./bin/read_int_function
donner un nombre: foo
  error: invalid integer input.
donner un nombre: (user canceled input)

Handling user-input is one area that gives new C programmers no end of grief. Best to take the time and think through it now, learning how to correctly approach it. Doing so will save you a great deal of time and frustration.
Let me know if you have further questions.

Footnotes:
1.) Unless you are programming in a freestanding environment (without the benefit of any OS), in a conforming implementation, the allowable declarations for main for are int main (void) and int main (int argc, char *argv[]) (which you will see written with the equivalent char **argv).  See: C11 Standard - §5.1.2.2.1 Program startup(p1). See also: What should main() return in C and C++?  In a freestanding environment, the name and type of the function called at program startup are implementation-defined. See: 5.1.2.1 Freestanding environment

A: If you are using Linux as a development environment, you can take a look at man 3 scanf. This will give you the function's documentation.
That being said, the function returns a number which indicates how many valid inputs were read.
Knowing that, you can read a positive integer with the following code to check for read status:
int rc;
unsigned int x;

rc = scanf("%u", &x);
if (rc == 1) {
    // valid input data
}


text:
Q: Default datacontext Having the xaml below in MainWindow.xaml:
<Window x:Class="TestDependency.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
    <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Label Name="someLabel" Grid.Row="0"  Content="{Binding Path=LabelText}"></Label>
    <Button Grid.Row="2"  Click="Button_Click">Change</Button>
  </Grid>
</Window>

And the following code behind in MainWindow.xaml.cs:
public static readonly DependencyProperty LabelTextProperty = DependencyProperty.Register("LabelText", typeof(String), typeof(MainWindow));

public int counter = 0;

public String LabelText
{
  get
  {
    return (String)GetValue(LabelTextProperty);
  }

  set
  {
    SetValue(LabelTextProperty, value);
  }
}

private void Button_Click(object sender, RoutedEventArgs e)
{
  LabelText = "Counter " + counter++;
}

I would have thought that the default DataContext is the code behind. But I'm forced to specify the DataContext. Which DataContext is the default? Null? I would have thought that the code behind would have been (as is the same class).
And as in this sample I'm using the code behind to modify the content of the Label, could I use directly:
someLabel.Content = "Counter " + counter++;

I will expect that being the code behind, it shouldn't have the UI update problem that you have if the DataContext is in a different class.

A: Yes, the default value of DataContext is null, here is how it's declared in FrameworkElement class -
public static readonly DependencyProperty DataContextProperty =
    DependencyProperty.Register("DataContext", typeof(object),
    FrameworkElement._typeofThis,
    (PropertyMetadata) new FrameworkPropertyMetadata((object)null,
        FrameworkPropertyMetadataOptions.Inherits,
        new PropertyChangedCallback(FrameworkElement.OnDataContextChanged)));

FrameworkPropertyMetadata takes first param for default Value of property.
As it gets inherited by all the child controls your lable's DataContext remains null unless you specify the window data context.
and you can use someLabel.Content = "Counter " + counter++; in codebehind to set labels content; as such it's perfectly fine to access your controls in code behind.

A: Since you are binding a property of a Label, unless you specify a different binding source somehow the binding engine assumes that LabelText is a property on that class. It cannot magically determine that because the Label is a descendant of a MainWindow the binding source should be that window, which is why you need to explicitly declare it.
It's important to note that the concepts of "data context" and "binding source" are distinct: DataContext is one way to specify the binding source, but there are also others.


text:
Q: Apache-Superset variable filter chart size I use  multi-select filterboxes in superset-apache by checking the box in the filter for "Allow Multiple Selections".
However upon usage I realized that while the box of the filter itself expands on selection of multiple items, the parent-box (white background + header) did not, which led to the last of my four filters being "pushed out of the box" (see screenshot) and upon selecting even more elements disappeared completely behind the chart below.
Is there a way to enable the parent box to adjust its size variably depending on its contents?

A: As an interrim solution I used CSS in the dashboard itself:
.resizable-container {
     height: auto !important
}

This had the sideffect that all containers in the dashboard shrink to their content size - e.g. three different charts in one row have different lengths now (which does not look very clean...), but at least I can use multi-select filters.
Sadly the filter-containers don't have a specific css-tag so it is not possible to set their height specifically.


text:
Q: MySQL query with left and right join taking 15 minutes to execute We have an old system which displays newsfeed saved on the database. It worked fine before and there were no problem at all. However, now the query does not work and it takes more than 15 minutes to finish the query. For testing i tried out many ways to optimize the query. However, no luck. I would appreciate if any one can give some suggestion. Current database does not have any Index. If anyone think i should create index. please let me know for which tables and what should be the index. I have very little knowledge on indexing. Please find the query that i am running as well the ERD.
select *, DATEDIFF(Now(), Date) as Day, DATE_ADD(Date, INTERVAL 1 MONTH) as Diff from users
left join users_propertyvalues UPV USING(UserId)
left join propertyvalues PV USING(ValueId)
right join item_categories IC ON (IC.CategoryId=UPV.ValueId)
left join newsfeed USING(ItemId)
left join rss_feeds F ON(PV.ValueId=F.FeedId)
where EmailEnabled
having NOW() <= Diff
order by UserId, CategoryId, Date DESC

Stack overflow does not allow me to upload the ERD picture. Please let me know if anyone want i can upload it to somewhere.
Thanks for the help.![enter image description here][1]

A: Indexes should be on "joining" columns + add PK for them... aditional You can add unique inedexes
ADD PK (it's primary, and UNIQUE):
`ALTER TABLE `test`     CHANGE `test` `test` INT(11) NOT NULL,    ADD PRIMARY KEY(`test`);`

ADD INDEX (name does no matter):
ALTER TABLE `test` ADD UNIQUE `NewIndex1` (`test`);

see info http://dev.mysql.com/doc/refman/5.5/en/optimization-indexes.html


text:
Q: How to find dominant color RGB using histograms? I am currently developing a series of test code to explore different ways of processing image data, and one of my main topics is color extraction.
I have developed the following Python code, which, given an image, is capable of extracting its correspondent histograms with R, G and B values:
# Reading original image, in full color
img = mpimg.imread('/content/brandlogos/Images/14 (48).jpg')

# Displaying the image
imgplot = plt.imshow(img)
plt.show()

# Creating a tuple to select colors of each channel line
colors = ("r", "g", "b")
channel_ids = (0, 1, 2)

# Making an histogram with three lines, one for each color
# The X limit is 255, for RGB values
plt.xlim([0,256])
for channel_id, c in zip(channel_ids, colors):
  histogram, bin_edges = np.histogram(
      img[:, :, channel_id], bins = 256, range=(0,256)
  )
  plt.plot(bin_edges[0:-1], histogram, color=c )

# Displaying the histogram
plt.xlabel("Color Value")
plt.ylabel("Pixels")

plt.show()

Example:

However, I now want to find the RGB value of the most dominant color, according to the histogram information.
Expected output: (87, 74, 163) (or something similar)
How would I go about finding the highest bin counts for the three color channels, combining them into a single color?

A: You can focus on the unique colors in your image, and find the one with the highest count:
import matplotlib.image as mpimg
import numpy as np

img = np.uint8(mpimg.imread('path/to/your/image.png') * 255)
img = np.reshape(img, (np.prod(img.shape[:2]), 3))
res = np.unique(img, axis=0, return_counts=True)
dom_color = res[0][np.argmax(res[1]), :]
print(dom_color)

Alternatively, you can use Pillow's getcolors, and get the one with the highest count:
from PIL import Image

img = Image.open('path/to/your/image.png')
dom_color = sorted(img.getcolors(2 ** 24), reverse=True)[0][1]
print(dom_color)

Both also can easily provide the second, third, ... dominant colors, if needed.
For some logo like this

the dominant color is given as :
[208  16  18]

respectively
(208, 16, 18)

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.9.1
PyCharm:       2021.1.1
Matplotlib:    3.4.1
NumPy:         1.20.2
Pillow:        8.2.0
----------------------------------------

EDIT: Maybe, to give an adversary for the histogram approach, as also explained by Cris in the comments, see this image:

It's hard so see, but there are three different types of red, the largest rectangle has RGB values of (208, 0, 18).
Now, let's compare your histogram approach with Pillow's getcolors:
import numpy as np
from PIL import Image

adv = np.zeros((512, 512, 3), np.uint8)
adv[:200, :200, :] = [208, 16, 18]
adv[:200, 200:, :] = [208, 16, 0]
adv[200:, :200, :] = [0, 16, 18]
adv[200:, 200:, :] = [208, 0, 18]

# Histogram approach
dom_color = []
for channel_id in [0, 1, 2]:
    dom_color.append(np.argmax(np.histogram(adv[..., channel_id], bins=256, range=(0, 256))[0]))
print(dom_color)
# [208, 16, 18]

# Pillow's getcolors
dom_color = sorted(Image.fromarray(adv).getcolors(2 ** 24), reverse=True)[0][1]
print(dom_color)
# (208, 0, 18)

The adversary is build up to give histogram peaks at (208, 16, 18). Nevertheless, the dominant color is (208, 0, 18) as we can easily derive from the image (or the code).


text:
Q: How to prevent interrupted mv moving data On Ubuntu 18.04 I am running a small PHP web application which moves directories one by one with nested dirs and files from one filesystem to another via exec(mv filepath) method.
Now I have the problem that when a nested directory or file is missing read rights or is somehow corrputed the mv fails (because it cannot delete the file in the src). But at that point the data is already moved into dest.
Which means in the end I have a fully copied dir in dest and still the dir in src but only with the dirs/files which have invalid permission or are corrupted. I do not want this behaviour. As soon as the mv fails for whatever reason it should revert the whole process/leave src as it was.
In my PHP Script I already check if the mv fails. If yes I could then check if the dir exists in dest and mv back to src.
But is there no better/easier way to achieve this bahaviour?


text:
Q: Am I loading datatable twice & update row item with boolean value I call the following function in a module
Public Function GetExcelData(ByVal ExcelFile As String) As System.Data.DataTable
Then I have the following code
            If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            gblCompName = openFileDialog1.FileName
        End If

        Dim reader As New DataTableReader(GetExcelData(gblCompName))
        Dim table As New DataTable

        table.Load(reader)
        table.Columns.Add("Single", GetType(Boolean), False)
        table.Columns.Add("CouplesInFinal", GetType(Int32))
        table.Columns.Add("EvtNum", GetType(String))
        table.Columns.Add("EvtStruct", GetType(Int32))
        table.Columns.Add("EvtCplID", GetType(Int32))
        table.Columns.Add("CouplesInClass", GetType(Int32))
        table.Columns.Add("Valid", GetType(Boolean), True)

        Dim result() As DataRow = table.Select("[class]" Like "Single")
        For Each row In result
            If row.Item("Class") Like "Single" Then
                table.Rows(0)("Single") = True
            End If
        Next

        DataGridView1.DataSource = table

My logic tells me I'm loading the table twice & the data row field "Single" is boolean which I'm trying to update to True if string field "class" is like "Single"
I realize it's 2 questions in one but it seems to load quite slowly & it's all one form procedure. Any advice on this will be very welcome thanks

A: Dim reader As New DataTableReader(GetExcelData(gblCompName))
Dim table As New DataTable

Without seeing GetExcelData it is hard to say if you are filling twice. If this function returns a populated DataTable then
Dim table as DataTable = GetExcelData(gblCompName)

and delete the table.Load and the DataReader.
Here is my version of updating a DataTable against my sample database.
Private Sub TestDataTableUpdate()
        Try
            Using cmd As New SqlCommand("Select * From Coffees", CoffeeCn)
                Dim dt As New DataTable
                CoffeeCn.Open()
                Using dr As SqlDataReader = cmd.ExecuteReader
                    dt.Load(dr)
                End Using
                CoffeeCn.Close()
                For index As Integer = 0 To dt.Rows.Count - 1
                    If dt.Rows(index)("Name").ToString = "Cinnamon Stick" Then
                        dt.Rows(index)("Roast") = "N/A"
                    End If
                Next
                'The above does not update the database
                Dim da As New SqlDataAdapter(cmd) 'provides the connection and Select command
                Dim sqlCB As New SqlCommandBuilder(da) 'Associates the DataAdapter to the command builder
                sqlCB.GetUpdateCommand() 'Retrieve the update command for the DataAdapter
                'Note: the DataAdapter opens and closes the connection for you
                da.Update(dt) 'This updates the database by finding the changed rows in the datatable
                'and running the Update command
                dt.AcceptChanges() 'Reset the row status to unchanged
                DataGridView1.DataSource = dt
            End Using
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            CoffeeCn.Close()
        End Try
    End Sub

PS. I am self-taught also.

A: The table update method that I got to work is
                Dim i As Integer = 0
            For i = 0 To table.Rows.Count - 1
                If table.Rows(i)("Class") Like "*Single*" Then
                    table.Rows(i)("Single") = True
                End If
            Next

I took out the ",False" on this line table.Columns.Add("Single", GetType(Boolean)


text:
Q: How to enable screen auto rotation on Dell 5378 2 in 1? I bought a new laptop, 2 in 1 Dell 13" 5378 and would like to use it as a tablet from time to time. The problem is that the screen won't flip when in tablet mode and onscreen keyboard won't open up automatically  when I open a browser. It will open with Libre office and some other text editing programs.
I have tried some options to install:
apt install iio-sensor-proxy inotify-tools
but so far unlucky. The screen has to be turned,flipped manually. The touchpad and physical keyboard is disabled in tablet mode and touchscreen works normally.
Anyone with a solution?
Thank you.


text:
Q: Maximise singular value decay by sparse matrix approximation I have a large matrix $A \in \mathbb{R}^{n \times m}$ and would like to subtract a sparse matrix $B \in \mathbb{R}^{n \times m}$ with less than $c (n+m)$ non-zero entries, where $c > 0$ is a constant one is free to choose, such that the singular values of $A-B$ decay as quickly as possible.
I have no idea how to approach this problem. Any thoughts?

A: Maximizing the "decay" of the singular values could be thought of as minimizing the (numerical) rank. Hence, I believe that the original problem could be rephrased as follows:

Given $\mathrm A \in \mathbb R^{m \times n}$, find a sparse matrix $\mathrm X \in \mathbb R^{m \times n}$ such that $\mbox{rank} (\mathrm X - \mathrm A)$ is minimized.

which is hard. Convex proxies$^\dagger$ for sparsity and rank are the entry-wise 1-norm and the nuclear norm, respectively. Hence, relaxing the original problem, we obtain the following convex program
$$\begin{array}{ll} \underset{\mathrm X \in \mathbb R^{m \times n}}{\text{minimize}} & \| \mathrm X \|_1 + \gamma \| \mathrm X - \mathrm A \|_*\\ \end{array}$$
where $\gamma > 0$. Varying parameter $\gamma$, if we find a matrix $\rm X$ that is sufficiently sparse, we are done.

$\dagger$ Maryam Fazel, Recovering simultaneously structured objects, Simons Institute, September 2014.


text:
Q: Choosing Projection for Gulf coast region of USA? What are the most appropriate datum and projection I could use for the Gulf coast region - spanning  Louisiana, Mississippi, Alabama, and Florida? I have to analyze block group data along the coast.

A: For areal interpolation, all that really matters is that relative distortion in areas within the individual interpolation units (such as block groups) is substantially smaller than inherent uncertainties in the data themselves and in the interpolation method.  Areal interpolation will routinely create errors of 10% or larger, so keeping relative areal distortion down to, say, about 1% within the interpolation units would be a reasonable target.
Choice of datum will not matter at all.
Although any equal-area projection will assure there is no areal distortion, most projections will do fine.  This suggests employing a secondary criterion for selecting the projection.  Foremost should be using one that applies well across the entire study region (the Gulf Coast) and maybe even a little beyond.  This will avoid the problems of breaking from one projection to another, which will happen when using UTM (say).
The land along the Gulf Coast roughly follows an ellipse: it is neither purely east-west nor purely north-south in extent.  For the best visual representation (that is, mapping), an oblique conformal conic (or pseudoconic) projection centered in the middle of the Gulf would be ideal: unfortunately, few GISes support oblique projections.  The one oblique projection that is commonly found is the Orthographic, aka "world from space."
Adopting an Orthographic projection centered at 28 degrees N latitude, 90 degrees W longitude (near the center of the map below) produces only a +-0.6% variation in areal distortion across the entire map.  Within any block group (or tract or even county), the change in areal distortion will be less than 0.1%, which should be more than good enough for interpolation.

In this map, the lines are a 5 degree graticule and the circles are Tissot indicatrices.  Their uniform circularity and size testify to the quality of this projection across the entire Gulf Coast.


text:
Q: Google Maps JS API Suggestion AutocompletionService does not returns the same address all the time The Google Maps API Suggestion does not return the same address all the time. We have a probe that runs every 10 minutes, and about 8 times per days the PlaceService.GetPlaceDetails does not return the same address.
Here are the HTTP calls :
Most of the time :
GET https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions?1s169%20Avenue%20Boll%C3%A9e%2C%20Le%20Mans%2C%20France&4sfr-FR&7scountry%3Afr&15e3&client=*******&callback=_xdc_._ca6qq&token=18520 HTTP/1.1
HTTP/1.1 200 OK ../.. ["169 Avenue Bollée, Le Mans, France", ../..

then the Google JS API calls:
GET https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails
HTTP/1.1 200 OK
../..
     {
        "long_name" : "169",
        "short_name" : "169",
        "types" : [ "street_number" ]
     },

And about 8 times per day :
the same request
GET https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions?1s169%20Avenue%20Boll%C3%A9e%2C%20Le%20Mans%2C%20France&4sfr-FR&7scountry%3Afr&15e3&client=******&callback=_xdc_._ca6qq&token=123244 HTTP/1.1
HTTP/1.1 200 OK ../.. ["169 Avenue Bollée, Le Mans, France", ../..

but the GetPlaceDetails returns another street number (notice the "181-167" instead of "169")
GET https://maps.googleapis.com/maps/api/place/js/PlaceService.GetPlaceDetails?2sfr-FR&8sEiMxNjkgQXZlbnVlIEJvbGzDqWUsIExlIE1hbnMsIEZyYW5jZQ&10e3&client=gme-giecovea1&callback=_xdc_._8rimfj&token=108576 HTTP/1.1
HTTP/1.1 200 OK
../..
         {
            "long_name" : "181-167",
            "short_name" : "181-167",
            "types" : [ "street_number" ]
         },

Does anyone know how it can be possible ? I don't see any other HTTP call between these one. It causes me error in the probe process because it cannot find the corresponding client of the address in 181-167.

A: Answer from Google Map Premium (translated from French) :

The Places database changes all the time due to the interactions with the Google Services, in order to improve continiously the results. In your case the location is the same (same coords) but the address binded to this location slighty differs. Google results won't be changed. You should either:

*

*change your code to accept street number range

*or use the adresse selected by the user

Actually, as the result switches from a accurate adress to a street numbers range, I think it is due to a bad cluster sync as @xomena stated it.
Secondly, we noticed that this "random" address was a building address and in a way Google is right to said that this address cannot be always accurate : as you can see on Street View
We decided to choose another test address with less risk of low accurate suggestion.


text:
Q: How can I merge unallocated partition with an extended partition? I need to combine the unallocated space on my computer into one partition. Originally I had Windows in the other partition but I recently deleted it because I no longer use it and I only ever use Linux. I use GParted Partition Editor to try and fix it but the partition I want to expand is the one that is in use thus it won't let me resize or move it. I want to know if there is a way to fix this without having to use a live CD or usb? This is what it looks like:

If there's no way to do it without using a live CD then I guess I just have to  do it, but I really don't want to have to buy anything.

A: You can't resize a partition if it's mounted, see this link to the Ubuntu documentation for a good guide to resizing partitions:
https://help.ubuntu.com/community/HowtoPartition/ResizingPartition
The easiest thing to do would be to use a live CD but you shouldn't have to buy anything. If you've got the disk or USB stick you orginally installed Ubuntu from you can use this, follow the instructions in the link:
http://www.ubuntu.com/download/desktop/try-ubuntu-before-you-install
The live version of Ubuntu has GParted included. You can now use to manipulate your hard drive as you wish.
As alternative suggestions, if you have a spare disc or USB stick you could Google for GParted or Knoppix live CDs, both are free.


text:
Q: how to insert a class instance into RTTR sequential view without getting its wrapped value? All
I am creating a generic binary serializer and got block on how to insert a class instance into a sequential view.
Here is the example code:
#include <iostream>
#include <rttr/type>
#include <rttr/registration.h>
using namespace rttr;

struct Item {
    int i ;
};
struct MyTestClass {
    std::vector<Item> seq;
};

RTTR_REGISTRATION
{
    using namespace rttr;
    registration::class_<MyTestClass>("TestClass")
        .constructor<>()
        .property("seq", &MyTestClass::seq);

    registration::class_<Item>("Item")
        .constructor<>()
        .property("item", &Item::i);

}

void CreateInst(rttr::instance inst) {
    auto localobj = inst.get_type().get_raw_type().is_wrapper() ? inst.get_wrapped_instance() : inst;
    auto p = localobj.get_type().get_property("item");
    p.set_value(inst, 100);
}

int main()
{
    MyTestClass inst;
    for (auto prop : rttr::type::get_by_name("TestClass").get_properties()) {
        auto type = prop.get_type();

        if (type.is_sequential_container()) {
            auto val = prop.get_value(inst);
            auto view =val.create_sequential_view();
            view.set_size(1); //just for demo
            rttr::variant var = view.get_value_type().create();
            CreateInst(var);
            //get its wrapped and insert 'it', it will have the correct result
            //Item it=var.get_wrapped_value<Item>();
            view.set_value(0, var);
            prop.set_value(inst, val);
        }
    }
    std::cout << inst.seq[0].i << std::endl;

}

it always output '0' instead of '100' on screen, unless I get its wrapped value and insert.
But that is not what I want.
Could any expert help me to improve on this ?
Thank you.
BR
Ray

A: Ok. I finally find the solutions as following:
registration::class_<Item>("Item")
    .constructor<>()(policy::ctor::as_object)
    .property("item", &Item::i);

Remember to add the RTTR_DLL in Project Properties -  C/C++-preprocessor -preprocessor definition to avoid the LNK2001 error


text:
Q: Set startdate to countdown I have a countdown that ends at a specific time and date.
Is it possible to set a starting date for the countdown?
Start: June 14, 2018 15:00:00
End: June 17, 2018 23:59:59

// Set the date we're counting down to
var countDownDate = new Date("June 17, 2018 23:59:59").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("countdown").innerHTML = "TEXT Countdown" + days + " days, " + hours + " h, "
    + minutes + " min & " + seconds + " sec";

    // If the count down is over, write some text
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("countdown").innerHTML = "TEXT after countdown";
    }
}, 1000);

A: Just delay the call to setInterval until the time you want. Your best bet, since timers get throttled on inactive tabs, is to check periodically and then kick things off when the time arrives:
var waitingTimer = setInterval(function() {
    if (Date.now() < Date.parse("2018-06-14T15:00:00")) {
        return;
    }
    clearInterval(waitingTimer);
    // ...start the countdown
}, 1000);

You might want to express the time in UTC, since unfortunately the spec on what those strings mean without a timezone indicator changed (twice), whereas if you put the time in UTC and add a Z to the string, it's reliable.


text:
Q: How to config iPage php ini to work with laravel 4.2? I recently registered to iPage web hosting, they are providing PHP Version 5.3.13 but Laravel 4.2 required PHP Version >= 5.4
Please guide me, how can I upgrade iPage php version or how can I configure laravel 4.2 to run?

A: You can't.  Shared hosts like iPage (shared meaning they're based on traditional unix multiuser systems) do not allow end users to upgrade the version of PHP running on a server -- doing so would be chaos, as all users share the same PHP binaries.
Some shared hosts install multiple versions of PHP on their servers and provide a mechanism that allows users to switch between versions.  It looks like iPage might offer this feature, although it's unclear if PHP 5.4 will be an option.


text:
Q: outlook 2007: start showing full month view? How do I configure Outlook 2007 to show the calendar, preferably full month view, when it launches?
I'm using Win7 pro and am launching by typing "out" on the start menu, then hitting enter.

A: *

*In Outlook, choose the "Tools" menu, then click "Options...".

*Click on the "Other" tab.

*Under "General" (at the top of the dialog), click on "Advanced Options...".

*Under "General Settings" (at the top of the dialog), next to "Startup in this folder:", click "Browse...".

*Select "Calendar" form your desired (probably primary) mailbox, then click "OK".

*Close out of all remaining open dialogs using "OK".

This will cause Outlook to startup in the calendar.
Outlook (at least 2007) remembers the last Calendar view you use - so open the calendar, then select your desired "Month" view.  As long as this is the last Calendar view you use, this is how it will appear again the next time you open Outlook.


text:
Q: C# (where) to JAVA I am porting some C# code over to Java.
How can I filter element in if/else blok ?
How to rewrite this in JAVA ?
if(items.Where( x => x.rarity == rarity && x.getPriceByQuality(quality) != 0 && x.name.Contains("AA") == isFull).Count() != 0)

A: if (items.stream().filter(x -> x.rarity == rarity && x.getPriceByQuality(quality) != 0 && x.name.contains("aa") == isFull).count() != 0)

but this should be nicer:
if (items.stream().anyMatch(x -> x.rarity == rarity && x.getPriceByQuality(quality) != 0 && x.name.contains("aa") == isFull))


text:
Q: Django admin InlineModels for manytomany fields I have designed following models for my blog
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    body = models.TextField(default='')
    created_at = models.DateTimeField('created date', auto_now_add=True, auto_now=False)
    updated_at = models.DateTimeField('updated date', auto_now_add=False, auto_now=True)
    author = models.ForeignKey('Author', default='admin')

    def __str__(self):
        return self.title

class Author(models.Model):
    name = models.CharField(max_length=150)
    email = models.EmailField(blank=True)
    bio = models.TextField()

    def __str__(self):
        return self.name

class Category(models.Model):
    cat_name = models.CharField(max_length=200)
    post = models.ManyToManyField('Post')

    def __str__(self):
        return self.cat_name

class Tag(models.Model):
    tag_name = models.CharField(max_length=200)
    post = models.ManyToManyField('Post')

    def __str__(self):
        return self.tag_name

and I am trying to register this model under django admin in such a way that. I can edit the Category, Tags and Authors from the Post page. but I am having hard time to accomplish this talk, I have written this code in admin.py file
from django.contrib import admin
from .models import Post, Author, Tag, Category

class AuthorInline(admin.TabularInline):
    model= Author

class TagInline(admin.StackedInline):
    model= Tag

class CategoryInline(admin.StackedInline):
    model = Category

@admin.register(Post) #another method of registration admin.site.register(Post, PostAdmin)
class PostAdmin(admin.ModelAdmin):
    #Show the following fields in this order
    fields = ['body', 'title']
    #show the following filelds for nice formattng
    list_display = ['title', 'author', 'created_at']
    #display based on the date hirerarchy
    date_hierachy = 'created_at'
    #embed the following child models in this parent models
    inlines = [AuthorInline, TagInline, CategoryInline,]

    #to exclude fields
    exclude = ('author',)

When I run my server I got the errors like
ERRORS:
<class 'blogs.admin.AuthorInline'>: (admin.E202) 'blogs.Author' has no ForeignKey to 'blogs.Post'.
<class 'blogs.admin.CategoryInline'>: (admin.E202) 'blogs.Category' has no ForeignKey to 'blogs.Post'.
<class 'blogs.admin.TagInline'>: (admin.E202) 'blogs.Tag' has no ForeignKey to 'blogs.Post'.

when investigating the error, we cannot  have StackedInline class if the models doesn't have foreign key, but How can I put the Tags, Category and Author rendered formm under the Post page in django admin,

A: For using AuthorInline, you ned a foreignkey field in you Author model
ex:
class Author(models.Model):
    post = models.ForeignKey('Post')

This means one post may have multiple authors.
But here in your situation you have the correct model and fileds which have one author for one post, so you can remove AuthorInline.
And incase of Tag and Category, you are using many-to-many field, It will be good if you go through this documentation https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-models
You have to rewrite the CategoryInline and TagInline;
class TagInline(admin.StackedInline):
    model= Tag.post.through

class CategoryInline(admin.StackedInline):
    model = Category.post.through

A: This isn't what inlines are for, and you don't want them here.
Inlines are for the reverse relation: given an author, edit their details and enter all their books on the same page. Your foreign keys and many-to-many fields are best shown as simple widgets, which is what Django does by default; the author and category will be displayed as a dropdown allowing you to choose an item, and the tags will be displayed as a multi-select box.
You might also choose to register Book as an inline on the Author admin; that's up to you.

A: Finally I made, what I wanted, the main gist is to make the category, author and tags choosable from the post page, so to do that, we need to add all the fields in the post model, which is the modified model
from django.db import models
from django.utils import timezone

class Author(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(blank=True)
    bio = models.TextField()

class Tag(models.Model):
    tag_name = models.CharField(max_length=50)

class Category(models.Model):
    cat_name = models.CharField(max_length=50)

class Post(models.Model):
    '''post can have many categories
    and categories can have many post
    author can have many post but post
    can have single author
    post can have many tags, and tags
    can have many posts'''

    title = models.CharField('post title', max_length=200)
    body = models.TextField(default='', null=True)
    created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
    author = models.ForeignKey(Author, verbose_name = "List of Author") #many to one relationship

    def __str__(self):
        return self.title

    #Generally many to many fields should into that model which is going to be edited.
    tags = models.ManyToManyField(Tag)
    categories = models.ManyToManyField(Category)

    class Meta:
        ordering = ['-created_at']
        verbose_name_plural = "Posteeees"

    # def post_status(self):
    # return timezone.now() - self.updated_at <= 1

#Recursive realation, we can define the foreignkey itself to the model  and this is called rrecursive realation
#


text:
Q: How to make selection tool with 3 variables which depend on each other (ModelBuilder)? I try to create model to selection feature by attribute with 3 variables which depend on each other but i don't know how.
for example:
variables: kat_1, kat_2, kat_3
Kat_1{ gastronomy, education, sport, religion}
Kat_2{bar,restaurant, kindergarten, elementary school, middle school, high school, church, cemetery, playground, pool, tennis}
 Kat_3{names}
how to create some filtr which works that when I choose gastronomy from kat_1 then it only allow me to choose bar or restaurant from kat_2?

A: The way to do this using tool validation is described in this 10.1 Help Page which should apply equally to 10.0.


text:
Q: Bootstrap Form inline only works full screen not scaled Not sure why this is happening but when I have the page in full screen the form-inline works great.  But as soon as I start scaling it down the label goes on top of the form.
Using bootstrap 3
 <row>
     <form class="form-inline">

            Start:<input type="text" class="form-control" placeholder="{{ start_length }}" id="bar">

            End: <input type="text" class="form-control" placeholder="{{ end_length }}" id="bar1">

    </form>
 </row>

jsfiddle

A:

.inline{
    display:inline-block!important;
    width:auto!important;
}

    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.4/custom/bootstrap.min.css" rel="stylesheet"/>

<row>
                 <form class="form-inline">

                        Start:<input type="text" class="form-control inline" placeholder="0" id="bar">

                        End: <input type="text" class="form-control inline" placeholder="45" id="bar1">

                </form>
             </row>


text:
Q: how can i detect link on uilabel programatically? I want to detect URL like www.google.com from UILabel. How can I do this ??
I have made a textfield and what ever is typed in it, is displayed on label. I want to detect URl from this text. Pls Help
(void)displayMethod:btnOk
{
    name = textField.text;

    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 150, 280, 80)];
    label.backgroundColor = [UIColor clearColor];
    label.textColor=[UIColor blackColor];
    label.text = name;
    label.numberOfLines=0;
    [self.view addSubview:label];

A: NSURL's URLWithString returns nil if the string passed does not contain a valid URL. So simply check the return value of your label's text string to see if the URL is valid or not.
Here is some sample code.
if([NSURL URLWithString:label.text] == nil){
  //sring inside the label is not a valid url
}
else {
  //string inside is a valid url
}

//If you want to disable highlights, and hyperlinks it is possible to do
//it with UITextViews by doing something like this
myTextView.dataDetectorTypes = UIDataDetectorTypeNone;


text:
Q: Qt Unit Test repeats everything twice in Qt Creator's Application Output pane for Qt 4.8 (but not in Qt 5.2.2) I just noticed that even on a fresh new project, Qt Unit Test writes everything twice in the Application Output pane, in different colors - first in magenta, then in black. I assume this is because it writes to both stdout and stderr.
This happens on Qt 4.8 but not on Qt 5.2.2. In Qt 5.2.2 only the black text is printed, as it should.
As an example, for a unit test project that contains only this test:
void Untitled15Test::testCase1()
{
    QVERIFY2(false, "Failure");
}

The output is this (I use a screenshot so the colors show):

Is there a way to turn off this behavior? Is it a bug in Qt4?

A: After some searching on the Qt Bug Tracker site I found out it is indeed a bug. I found the bug report mentioning it:

Description If one turns off the "run on terminal" option on Windows,
  qDebug's output will be printed twice in the application output pane.
  This is due to qDebug using OutputDebugString and stderr to output
  it's messages. To solve this we could do one of these items: Display
  the OutputDebugString stream and stderr in different panes if "run on
  terminal" is off. Provide a checkbox to hide the OutputDebugString
  stream in the application output pane. Prevent QDebug from using
  OutputDebugString and stderr. Maybe using an environment variable that
  is set by Qt Creator.

I think that this happens because QTestLib uses CONFIG   += console
, while at the same time turning off the "Run in terminal" checkbox, thus triggering this bug.


text:
Q: How to fix this programming code? (MOOCFI java week7 exercise 8) I was following the Moocfi exercise 8 (java online course), and I'm unable to debug my programming code.
https://materiaalit.github.io/2013-oo-programming/part2/week-7/ (The question I am asking is on the very bottom of the page, named "airport")
Airport.java
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;

public class Airport {

    private HashMap<Plane, Flight> num;
    private Scanner read;
    private ArrayList<Plane> planes;

    public Airport(){
    read = new Scanner(System.in);
    this.num = new HashMap<Plane, Flight>();
    planes = new ArrayList<Plane>();

    }

    public void start(){

        while(true){
        System.out.print("Choose operation:\n[1] Add airplane" + "\n[2] Add flight\n[x] Exit\n> ");
        String ans = read.nextLine();
        if (ans.equals("1")){
            num1();

        } else if (ans.equals("2")){
            num2();

        } else if (ans.equals("x")){
            break;
        } else continue;
        }

        System.out.println("\nFlight service\n------------\n");

        while(true){

        System.out.print("Choose operation:\n[1] Print planes\n"
                + "[2] Print flights\n[3] Print plane info\n[x] Quit\n> ");
        String ans2 = read.nextLine();
        if (ans2.equals("1")){
            nus1();

        }
        else if (ans2.equals("2")){
            nus2();

        }
        else if (ans2.equals("3")){
            nus3();

        }
        else if (ans2.equals("x")){
            break;
        }
        else continue;
        }
    }

    public void num1(){
        System.out.print("Give plane ID: ");
        String pi = read.nextLine();
        System.out.print("Give plane capacity: ");
        int pin = read.nextInt();
        planes.add(new Plane(pi, pin));
        System.out.println("");
    }

    public void num2(){
        System.out.print("Give plane ID: ");
        String pi = read.nextLine();
        System.out.print("Give departure airport code: ");
        String pin = read.nextLine();
        System.out.print("Give destination airport code: ");
        String pim = read.nextLine();
        for (Plane a:planes){
            if (a.getName()==pi){
                Plane b = new Plane(a.getName(), a.getCap());
                num.put(b, new Flight(pin, pim));
            }
        }
        System.out.println("");
    }

    public void nus1(){
        for (Plane p: planes){
            System.out.println(p.getName() + " (" + p.getCap() + " ppl)");
        }
        System.out.println("");
    }

    public void nus2(){
        for (Plane p : num.keySet()){
            System.out.println(p.getName() + " (" +
                    p.getCap() + " ppl) " + num.get(p));
        }
        System.out.println("");
    }

    public void nus3(){
        System.out.print("Give plane ID: ");
        String b = read.nextLine();
        for (Plane a: planes){
            if (a.getName().equals(b)){
                System.out.println(a.getName() + " (" + a.getCap() + " ppl)");
            }
            System.out.println("");
        }
    }

}

Plane.java
public class Plane {
    private String name;
    private int capacity;

    public Plane(String name, int capacity){
        this.name = name;
        this.capacity = capacity;
    }

    public String getName(){
       return name;
    }

    public int getCap(){
       return capacity;
    }
}

Flight.java
public class Flight {
    private String departureCode;
    private String destinationCode;

    public Flight(String departureCode, String destinationCode){
        this.departureCode = departureCode;
        this.destinationCode = destinationCode;
    }

    public String toString(){
        return "(" + departureCode + "-" + destinationCode + ")";
    }
}

Main.java
public class Main {
    public static void main(String[] args) {
        Airport a = new Airport();
        a.start();
        // Write your main program here. Implementing your own classes will be useful.
    }
}

There are two problems I want to figure out:

*

*When I run the program and press 1 and save the plane information, it then prints out the following statement twice, which should have been just once.

System.out.print("Choose operation:\n[1] Add airplane" + "\n[2] Add flight\n[x] Exit\n> ");

*Also, on Airport.java, I saved the flight information in a HashMap variable to print out later, but it doesn't seem to work when I run the program.

A: It is the issue with nextInt(), it wouldn't consider the newline when you press enter. Use nextLine() and cast it to int
In num1() method, replace
int pin = read.nextInt();

with
int pin = Integer.parseInt(read.nextLine());

Coming to your HashMap problem, you are comparing strings using ==. Use equals
In num2() method, replace
if (a.getName() == pi)

with
if (a.getName().equals(pi))


text:
Q: AWS QuickSight rails integration authorization code error I have a rails application that needs to add QuickSight. Found that for these purposes it is necessary to use the get_dashboard_embed_url method. This method returns me the URL, but following it (manually, through an iframe tag) I get this error text

Embedding failed because of invalid URL or authorization code. Both of these must be valid and the authorization code must not be expired for embedding to work.

Where can I find the authenticate code? How can I get it? Thanks for your help

This is how i fetch the url
credential_options = {
  client: Aws::STS::Client.new(region: ENV['AWS_REGION']),
  role_arn: ENV['QUICK_SIGHT_ROLE_ARN'],
  role_session_name: self.user_email
}

assume_role_credential = Aws::AssumeRoleCredentials.new(credential_options)
qs_client = Aws::QuickSight::Client.new({
  credentials: assume_role_credential,
  region: ENV['AWS_REGION']
})

begin
  qs_client.register_user({
    identity_type: 'IAM', # accepts IAM, QUICKSIGHT
    email: self.user_email,
    user_role: 'READER', # accepts ADMIN, AUTHOR, READER, RESTRICTED_AUTHOR, RESTRICTED_READER
    iam_arn: ENV['QUICK_SIGHT_ROLE_ARN'],
    session_name: self.user,
    aws_account_id: ENV['AWS_ACCOUNT_ID'],
    namespace: 'default'
  })
rescue
end

options = {
  aws_account_id: ENV['AWS_ACCOUNT_ID'],
  dashboard_id: ENV['QUICK_SIGHT_DASHBOARD_ID'],
  identity_type: 'IAM',
  session_lifetime_in_minutes: 300,
  undo_redo_disabled: false,
  reset_disabled: false
}

qs_client.get_dashboard_embed_url(options, {}).embed_url

And how i try to display
iframe src=@url class='w-100 h-100' style='min-height: 500px;'

A: At the first, sorry for my weak english, but i hope that you'll understand what i mean

Ok, after completing these points, everything began to work for me. Also read "Underwater rocks", this is very important points list which will save you tons of time

*

*Replace my code in question with this
def fetch_url # this method fetch embed dashboard url
   credential_options = {
     client: Aws::STS::Client.new(
       region: ENV['AWS_REGION'],
       access_key_id: ENV['AWS_ACCESS_KEY_ID'],
       secret_access_key: ENV['AWS_SECRET_ACCESS_KEY']
     ),
     role_arn: ENV['QUICK_SIGHT_ROLE_ARN'],
     role_session_name: self.user_email # This is attr_accessor :user_email
   }

   assume_role_credential = Aws::AssumeRoleCredentials.new(credential_options)
   qs_client = Aws::QuickSight::Client.new({
     credentials: assume_role_credential,
     region: ENV['AWS_REGION']
   })

   begin
     qs_client.register_user({
       identity_type: 'IAM', # accepts IAM, QUICKSIGHT
       email: self.user_email,
       user_role: 'READER', # accepts ADMIN, AUTHOR, READER, RESTRICTED_AUTHOR, RESTRICTED_READER
       iam_arn: ENV['QUICK_SIGHT_ROLE_ARN'],
       session_name: self.user_email,
       aws_account_id: 'ENV['AWS_ACCOUNT_ID']',
       namespace: 'default'
     })
   rescue
   end

   options = {
     aws_account_id: ENV['AWS_ACCOUNT_ID'],
     dashboard_id: ENV['QUICK_SIGHT_DASHBOARD_ID'],
     identity_type: 'IAM',
     session_lifetime_in_minutes: 300,
     undo_redo_disabled: false,
     reset_disabled: false
   }

   qs_client.get_dashboard_embed_url(options).embed_url
 end

*Go to Manage QuickSight panel https://your-quicksight-region(us-east-2 for example).quicksight.aws.amazon.com/sn/admin#users and click on "Manage permissions" button (button is placed above of the table with users)

*On the new page click on "Create" button and select "Sharing dashboards" checkbox. Set the name of the permission, click on the "Create" button

*In your controller action: @url = fetch_url # fetch_url - method from 1 point

*Add to your view: iframe src=@url OR you can use a amazon-quicksight-embedding-sdk but for me the iframe works pretty well
Underwater rocks

*

*Remember that dashboard url (which you are get with this method qs_client.get_dashboard_embed_url(options).embed_url) can be used only once, i.e. you can't open two browsers tabs with the same URL. When you are will pass this URL to iframe, this URL will cease to be working and you will no longer be able to use it in others browser windows or others iframe's

*Add your app domain to whitelist domains on the QuickSight. You can do it in the Manage QuickSight panel https://your-quicksight-region.quicksight.aws.amazon.com/sn/admin#embedding

*!!!IMPORTANT!!! if you are trying to embed dashboard to your localhost:your_server_port_number rails server, then you will always get the error message into the iframe (but if you go to this URL through the address bar of the browser, then you should see your dashboard (comment out / remove the iframe so it doesn't use the link, because every embedded dashboard url is disposable)). This is because localhost:your_server_port_number is not provided in the whitelist (Underwater rocks p.2). For resolving this issue and testing your work you can use ngrok (maybe it's available only for macOS, i'm not sure).

When you'll download the ngrok open your terminal and run command

$ ./path_to_ngrok_script/./ngrok http your_server_port_number

For me it's:

$ ~/./scripts/ngrok http 3000

After that do these 3 things for adding your work station to QuickSight whitelist:

*In the terminal with ngrok copy generated domain which starts with
the https (i'll name it ngrok_domain), NOT WITH HTTP. For
example: https://047956358355.ngrok.io

*Go to the Underwater rocks p.2 and add ngrok_domain

*Open your browser and go to the path with iframe, but use ngrok_domain instead of localhost:3000. For example, your embedded dashboard path is localhost:3000/embed_dashboard. Change it to https://047956358355.ngrok.io/embed_dashboard

After all these steps all is start working for me. I'm sure that some of the points here are superfluous, but i'm really tired of working with this integration, so here you yourself decide what should be left and what should be removed.

I hope my answer helped at least someone


text:
Q: Font too small for linux applications launched using Xming on windows I installed ROS under windows, following the instructions here: https://janbernloehr.de/2017/06/10/ros-windows. However on running Ubuntu under windows and launching a GUI based linux application like rviz, the font size is too small to read.

A: The applications are launched using Xming. Though it would seem that the Linux application is launched on windows, the truth is that they are being launched under xWindows, on windows. So changing the DPI of Xming will fix the font size in the application you launch.
To change the dpi of Xming, do the following:

*

*Find the location of Xming. Do this by searching Xming in the windows search box. Right click on the Xming result and select "Open File location"

*At the file location, right click on Xming and select properties. In the window that pops up, edit the contents of shortcut -> target to add in the dpi option. In my case the contents of target looked like this: "C:\Program Files\Xming\Xming.exe" :0 -clipboard -multiwindow -nolisten inet6 -dpi 180

*Restart Xming - to do this find it on the system tray on the bottom right of the screen. Restart Xming and try and start the offending application again. The font sizes will be larger


text:
Q: Virtualizing NTP server
Possible Duplicate:
What are the limits of running NTP servers in virtual machines?

I was wondering if virtualizing NTP is okay. I have a VMware ESXi 5.0 box, and I want to virtualize my router since the original hardware bit it. The only thing is I have read in places that virtualizing NTP (which my router performed) was not good because you won't be as accurate as a hardware clock. Is this true?
My router was pfSense, it ran the OpenNTPD server and was pointed at tock.usno.navy.mil. Because I am syncing with a higher NTP server is the accuracy of the hardware that important?

A: This has been addressed before: What are the limits of running NTP servers in virtual machines?
Short answer: Don't do it.  The accuracy of your local clock is still important when setting up an NTP server, and there are too many variables when using virtual machines to guarantee reasonable accuracy.

A: Depends on how accurate you need the clock to be. The Virtual Clock provided by the VM will have an inconsistent slew; usually this is limited to milliseconds. So your VM may have a hard time keeping track of it's slew in greater accuracy than ~0.1s. For most applications this is plenty accurate enough.
For certain software/hypervisor combinations the inconsistent slew causes problems and the time eventually gets off by a large amount. I've never seen this problem with ESX however.
For all platforms be certain the VM's clock is not synched to the hardware clock. There's an option to disable this as it's normally enabled. The VM will constantly have the wrong time if the hypervisor is overriding NTP.
On a side note: There are restrictions on using the cluster (tick, tock, and ntp) at usno.navy.mil; unless you meet certain qualifications you should not be using it. You should be using Stratum 2 servers, such as the pool.ntp.org project.


text:
Q: How to load different xml file using @PropertySource in Spring I would like to load different query xml files at runtime using configuration file (helm or .property). What I want to achieve is to load 1.xml when I am loading Oracle database and 2.xml when loading Azure SQL.
These databases (Oracle/Azure SQL) are loaded interchangeably, which means I am defining which database is loading in my configuration like this:
datasource.project.driverClassName='Oracle' //or 'SQLServerDriver'
datasource.project.url='OracleUrl' // or 'SQLUrl'

I want to add flag like datasource.project.dialect='Oracle' or something like that so I can indicate which database I am loading.
Once this is done, I want my repository class to load different xml files that contains different sql queries. But I am not sure how I can define this in the @PropertySource annotation. Here is example:
@Configuration
@Import(DataSourceConfig.class)
@PropertySource("classpath:event-sql-oracle.xml") //HOW DO I LOAD XML DYNAMICALLY USING THE FLAG?

So if flag says 'Oracle', I want to load "classpath:event-sql-oracle.xml" and if it says 'Azure SQL', I want to load "classpath:event-sql-Azure.xml". Is this achieveable?

A: I found the answer. I just need to use placeholder for @PropertySource like this:
@PropertySource("classpath:event-sql-${dbtype}.xml")

then define dbtype in the configuration like .properties or helm.


text:
Q: Excel Rows to sentences Python Let's say I have an Excel file with 5 rows and 2 columns.
apples      color
honeycrsp   red
gala        red
goldendel   orange
fuji        red
grannys     green

I want to place each of the rows into a repeating sentence sentence. For example I want column1 and column2 to be added to a sentence.
e.g "this apple is honeycrsp with color red"
This is what I have coded so far:
import pandas as pd;

FILE_PATH = "C:\\Users\\apples.xls";
xl = pd.ExcelFile(FILE_PATH);
df = xl.parse('testone');

apples = []
color =[]
apples = list(df['apples'])
color = list(df['color'])

def f(string, n, c=0):
    if c < n:
       print(string)
       f(string, n, c=c + 1)

f('this apple is{0} with color {0}'.format(apples,color), 3)

Desired output:
"this apple is honeycrsp with color red"
"this apple is gala with color red"
"this apple is goldendel with color orange"
"this apple is fuji with color red"
"this apple is grannys with color green"

A: import pandas as pd

FILE_PATH = "C:\\Users\\apples.xls"
xl = pd.ExcelFile(FILE_PATH)
df = xl.parse('testone')

apples = list(df['apples'])
colors = list(df['color'])

for apple, color in zip(apples, colors):
    print('this apple is {0} with color {1}'.format(apple, color))

Ouputs:
this apple is honeycrsp with color red
this apple is gala with color red
this apple is goldendel with color orange
this apple is fuji with color red
this apple is grannys with color green

You can put the last two lines in a function if you would like. I think this is a much simpler and readable solution though.
Also, some mistakes to avoid in the future:

*

*Never use ; in python

*putting numbers inside of the {} tags when using .format will cause the arguments to be formatted by index (hence the reason you were getting apples where you wanted colors)

A: Read the data as a dataframe and use apply
import pandas as pd

data = pd.DataFrame({'apples':["honeycrsp","gala","goldendel","fuji","grannys"],'color':["red","red","orange","red","greeen"]})

def concat(r):
    return return 'this apple is ' + r[0] + ' with color ' + r[1]

data.apply(concat,axis=1)

The above program displays the following
0       this apple is honeycrsp with color red
1            this apple is gala with color red
2    this apple is goldendel with color orange
3            this apple is fuji with color red
4      this apple is grannys with color greeen

If you don't want index to appear
s = data.apply(concat,axis=1)
print(s.to_string(index=False))

that gives you the result
this apple is honeycrsp with color red
this apple is gala with color red
this apple is goldendel with color orange
this apple is fuji with color red
this apple is grannys with color greeen


text:
Q: JavaFX Script for server side applications Has anybody tried to use JavaFX Script in server side applications?
The language itself looks quite nice and modern, and is fully Java compatible. If Sun is serious about it, it could be quite ubiquitus on the server side too, where Java is strong.
What do you think?

A: Yes you are right , but the main focus for JavaFx is RIA and many organizations are thinking to opt this technology for themselves .


text:
Q: Set transparent background color div over black parent border I am trying to create some kind of selector menu which has active and nonactive elements and depending on which one is selected it shows one thing or another.
I have set a border for the menu and for the content but I would like to make it "connected" by removing the bottom-border when you select a different menu option. It looked fine since I decided to set a transparent background color to this: rgba(150,150,150,0.5). The border from parent is visible because the background of the selected menu child is not solid.
Simplified html:

    D

    +

  Nombre:*<input id="acc_f_nombre_1" value="D" type="text" class="acc-text upp">

  Nombre:*<input id="acc_f_nombre_0" value="" type="text" class="acc-text upp">

And css:
.menu-alias {
  float: left;
  width: 100%;
  border-bottom: 1px solid;
  display: flex;
}
.menu-alias .alias.aliselected {
  background-color: rgba(255,100,0,0.3);
  margin-bottom: -1px;
}
.menu-alias .alias{
  float: left;
  border: 1px solid;
  border-bottom: 0;
  border-right: 0;
  background-color: rgba(255,100,0,0.1);
}
.menu-alias .alias.ali-nuevo{
  border-right:1px solid;
}
.menu-alias .alias a{
  display: block;
  padding: 5px 10px;
  cursor: pointer;
}
.facturacion{
  padding: 5px;
  background-color: rgba(255,100,0,0.3);
  border-left: 1px solid;
  border-right: 1px solid;
  border-bottom: 1px solid;
  float:left;
}

Here a fiddle to better understanding. I have not put the jquery code so clicking not works but it is undertandable what it has to do in my opinion.
If you change the 0.3 transparency on aliselected to 1 you will see that it puts itself over the border, which is what I would like but maintaining the transparency.

A: You could always put the "transparent" color as .menu-alias .alias.aliselected background-color.
.menu-alias .alias.aliselected {
   background-color:#f7caad;
   margin-bottom: -1px;
}

Fiddle here: https://jsfiddle.net/w0mp3r/Lpcrd6jx/1/

A: EDIT: this answers is the opposite of what the OP looked for (my fault), but i leave it here since it brought some infos on how to paint background (background-clip).

You may fake this border with an inset shadow : http://jsfiddle.net/DytDA/32/
.menu-alias .alias.aliselected {
  background-color: rgba(255,100,0,1);
  box-shadow:inset 0 -1px black;/* unblured inset shadow showing at bottom */
  margin-bottom: -1px;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow

Or you may use background-clip to see it through with   padding over the area to be translucide : http://jsfiddle.net/DytDA/33/
.menu-alias .alias.aliselected {
  background-color: rgba(255, 100, 0, 1);
  padding-bottom: 1px;/* size of border underneath to see */
  background-clip: content-box;/* only paint the inside where content
  stands except padding and borders area */
  margin-bottom: -1px;
 }

https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip