text:
Q: Colocar filtro de validación en producto Estoy construyendo una web con woocommerce instale un plugin llamado tm opction extra, pero no me permite validar los campos adicionales en la página producto antes de agregarlo al proceso de pago, ahora bien realice un código en php que puse en el archivo funtion.php de mi tema y realizo la comprobación que necesitaba,  ahora el problema que me ocurre es que dicha validación se esta cargando en todos los demás productos, y quisiera poder delimitarlo a un producto especifico de woocommerce, y no se como hacerlo mi código es algo parecido a esto, como puede verse es un filtro general para todos los productos.
function filtrodeproducto_add_to_cart_validation($passed, $product_id, $qty){
/* primer campo validados con los demas
 */
    if( isset(  $_POST['tmcp_textfield_0'] ) && sanitize_text_field( $_POST['tmcp_textfield_0'] ) ==  $_POST['tmcp_textfield_1'] ){
        $product = wc_get_product( $product_id );
        wc_add_notice( sprintf( __( '%s Utilice numeros diferentes para cada caso.', 'filtrodeproducto-plugin-textdomain' ), $product->get_title() ), 'error' );
        return false;

    }
add_filter( 'woocommerce_add_to_cart_validation', 'filtrodeproducto_add_to_cart_validation', 10, 3 );

Campos para validar
tmcp_textfield_0  este es el campo que estoy intentando validar con este otro tmcp_textfield_1 pero todos los demás productos tienen campos llamados de la misma manera y no puedo modificarlos por el plugin

A: Buenas Tardes logre resolver y fue mas facil de lo que pensaba, solo tendrian que colocar luego de
function filtrodeproducto_add_to_cart_validation($passed, $product_id, $qty){
/* primer campo validados con los demas

if(  $product_id== 4239 )
ya que la misma función esta trayendo el id del producto y asi delimitaria la funcion solo para el producto que quiero validar. Fue muy tonto no darme cuenta antes de esto.


text:
Q: Azure Linux server not responding I installed Lamp server and phpmyadmin on my linux azure server but phpmyadmin was not working. I restarted the system and now I am unable to connect to it. Putty returns error saying " connection rejected" . Even I am unable to ping this server from my command prompt.
Also this forum (http://www.windowsazure.com/en-us/manage/linux/how-to-guides/ssh-into-linux/) says that I have to get a private key for authentication. If this is the case, from where I can get a private key using my windows system? Any help would be highly appreciated.

A: If you've already used the machine, you already have all the information you need to connect to the Virtual Machine via SSH. If you created the VM using the Quick Create option in the management portal, you created a password-based VM - easy.
If you cannot connect using the same ssh command you used before, then perhaps the machine is hung or went down.
In the portal, find the VM, select it, and use the Restart option to reset it. Try connecting again to the machine in a few minutes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Esper/Nesper runtime configuration add generic event type can anyone tell me how to add generic type (bean) to configure the CEP runtime? I'm in NEsper environment using C#., I have an event(bean) - Signal which has the attribute - value. Depends on what kind of Signal it is, the value can be bool or double or string ... value. So I've define Signal as a generic: Signal. My following code return an exception. If I'm not using generic type as event, it works. How should I add the generic event type correctly?
var container = ContainerExtensions.CreateDefaultContainer()
                        .InitializeDefaultServices()
                        .InitializeDatabaseDrivers();
var configuration = new Configuration(container);
configuration.Common.AddEventType("Signal", typeof(Signal<bool>));
configuration.Common.AddEventType("Signal", typeof(Signal<double>));
var runtime = EPRuntimeProvider.GetDefaultRuntime(configuration);

Thanks for any help!
Narisu

A: There is no support for generic type-parameterized bean events in Nesper yet. There is support in the Java version.


text:
Q: Seaborn FacetGrid col_wrap (wide to long) plotting issue I am trying to plot each row(in wide table) using Seaborn's FacetGrid and col_wrap.
First I convert wide to long:
-- stack() the wide data to a series, s.
-- use get_level_values
-- append the series to the dataframe
FacetGrid only plots the first plot though ?
dt1 = pd.DataFrame({'s1':[0,1,2,3,4], 's2':[4,2,3,6,7], 's3':[6,7,3,4,7] })
def fct(data):
    #toy model dataframe
    #dt1.index.names = ['ind']
    dt = data.stack()
    dt.index.names = ['i','s']
    ind = pd.Series( dt.index.get_level_values(0).values )
    sub = pd.Series( dt.index.get_level_values(1).values )
    dtt = pd.DataFrame( ind , columns=['ind'])
    dtt['sub'] = sub
    dtt['ind'] = ind
    dtt['dt'] = dt.values
    #dt.reindex(columns='v')
    print ( 'dt ', dtt.describe)
    g = sns.FacetGrid( dtt, col='sub', col_wrap=1, size=2, ylim=(0, 10) )
    g.map( sns.pointplot, 'ind', 'dt', color=".3", ci=None );

`

A: I'm not sure what's causing that, but you should be able to do row='sub' and get exactly what you want.
By the way, you can use factorplot with kind='point' to draw this plot without using FacetGrid directly, it may be easier.


text:
Q: while loop returning the second to last value So I understand the logic but don't know how to get it to do what I want. I feel it's super simple but... I need it to record the last valid answer and store it into I but it returns the second to last value since the while loop doesn't iterate again. Relevant code and pictures are attached. Thank you all for any help.
INVALID_CHARACTERS = r"!#$%&'()*+,-.:;<=>?@[]^_`{|}~\/" + '"'
INVALID_NUMBERS = "1234567890"
INVALID_LETTERS = "abcdefghijklmnopqrstuvwxyz"

def letter_validity_check(i, msg):
    """Function checks entered answers against a list of invalid characters and invalid numbers"""

    while len(i) == 0 or any(c in INVALID_CHARACTERS for c in i) or any(c in INVALID_NUMBERS for c in i):
        i = input("First name can not be blank, contain special characters, or numbers. Try again. \n" + msg)

    while len(i) != 0 and any(c not in INVALID_CHARACTERS for c in i) and any(c not in INVALID_NUMBERS for c in i) and any(c in INVALID_LETTERS for c in i):
        print (i)
        return i

while len(FIRST_NAME) == 0:
    MESSAGE =  "What is your first name?: "
    FIRST_NAME = input(MESSAGE)
    letter_validity_check(FIRST_NAME, MESSAGE)
    print(FIRST_NAME)
    exit_checker(FIRST_NAME)

While loop and the logic

A: You have a few issues here:

*

*syntax errors mixing i and I

*not saving the corrected name to FIRST_NAME

*unnecessary 2nd while loop in letter_validity_check
Here's a working solution that corrects these issues:
INVALID_CHARACTERS = r"!#$%&'()*+,-.:;<=>?@[]^_`{|}~\/" + '"'
INVALID_NUMBERS = "1234567890"
INVALID_LETTERS = "abcdefghijklmnopqrstuvwxyz"

def letter_validity_check(name, msg):
    """Function checks entered answers against a list of invalid characters and invalid numbers"""

    while (
        len(name) == 0
        or any(c in INVALID_CHARACTERS for c in name)
        or any(c in INVALID_NUMBERS for c in name)
    ):
        name = input(
            "First name can not be blank, contain special characters, or numbers. Try again. \n"
            + msg
        )

    return name

FIRST_NAME = ""

while len(FIRST_NAME) == 0:
    MESSAGE = "What is your first name?: "
    FIRST_NAME = input(MESSAGE)
    FIRST_NAME = letter_validity_check(FIRST_NAME, MESSAGE)

print("Your first name is", FIRST_NAME)

A simpler version might be:
MESSAGE = "What is your first name? "
first_name = input(MESSAGE)

while not first_name.isalpha():
    print("First names may only contain alphabetic characters. Please try again.")
    first_name = input(MESSAGE)

print("Your first name is", first_name)


text:
Q: drawable from progress bar cover text view I have a progress bar and need to put some text over it. I've search for solutions but none of it worked. I've realized that what covers my Textview is the drawer from my progress bar (if I remove it, the text is visible)
Here's my layout code:
<RelativeLayout
            android:id="@+id/progressbarContainer"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:gravity="center_vertical">
            <!--      BARRA DE PROGRESSO DOS MEMES    -->
            <ProgressBar
                android:elevation="10dp"
                android:id="@+id/progressBar"
                style="@style/myProgressBar"
                android:layout_width="match_parent"
                android:layout_height="20dp"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:progressDrawable="@drawable/progress_bar"/>
            <TextView
                android:background="#00000000"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/progressBar"
                android:layout_alignTop="@+id/progressBar"
                android:layout_alignEnd="@+id/progressBar"
                android:layout_alignStart="@+id/progressBar"
                android:layout_above="@+id/progressBar"
                android:text="00:99"
                android:textColor="#ff0000"/>
</RelativeLayout>

and here is my drawable xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id = "@android:id/background">
        <shape>
            <corners android:radius="10dp"/>
            <solid android:color="#ffff"/>
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="10dp" />
                <solid android:color="@color/progressBlue"/>
            </shape>
        </clip>
    </item>
</layer-list>

The progress bar style has nothing but "Base.Widget.AppCompat.ProgressBar.Horizontal" as its parent and max and min height. I've changed those  and that doesn't seem to be the problem.

A: You have set width of progressbar to android:layout_width="match_parent" try setting it to wrap_content and check.

A: You have 2 options.
Option 1: Remove android:elevation="10dp" from ProgressBar in xml file.
<ProgressBar
            android:id="@+id/progressBar"
            style="@style/myProgressBar"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:progressDrawable="@drawable/progress_bar"/>

Option 2: If you want to keep android:elevation="10dp" for ProgressBar, then add android:elevation="11dp" for TextView in xml file.
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/progressbarContainer"
        android:layout_width="match_parent"
        android:layout_height="30dp" android:gravity="center_vertical">
    <!--      BARRA DE PROGRESSO DOS MEMES    -->
    <ProgressBar
            android:elevation="10dp"
            android:id="@+id/progressBar"
            style="@style/myProgressBar"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:progressDrawable="@drawable/progress_bar"/>
    <TextView
            android:elevation="11dp"
            android:background="#00000000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/progressBar"
            android:layout_alignTop="@+id/progressBar"
            android:layout_alignEnd="@+id/progressBar"
            android:layout_alignStart="@+id/progressBar"
            android:layout_above="@+id/progressBar"
            android:text="00:99"
            android:textColor="#ff0000"/>
</RelativeLayout>

You can see this post to understand how android:elevation works in Android.


text:
Q: cho-han bakuchi Estou tentando fazer em C o jogo cho-han bakuchi. Ele é bem simples, o jogo japonês consiste em lançar dois dados de 6 lados em um copo, antes dos dados serem mostrado o jogador faz a aposta dizendo cho (pares) ou han (impar). Então mostra os dados e os valores são somados.
O que estou errando no meu código?
Não gostaria do código completo, apenas do ponto em que estou errando para poder fazer a correção.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i,x,apost,cred=100,result=0;

    while(apost!=EOF)
    {
        printf("faça a aposta:(digite -1 para sair)\n");
        scanf("%d", &apost);

        cred=cred-apost;

        printf("escolha 1-cho(par) 2-han(impar):\n");
        scanf("%d", &x);

        switch(getc(x))
        {
            case 1:
                i=2+rand()%12;
                printf("\n%10d", i);

                if(i%2==0)
                {
                    printf("ganhou!\n");
                    cred=cred+(apost*2);
                }

                else
                    printf("perdeu!");

                break;

                case 2:
                    i=2+rand()%12;
                    printf("\n%10d", i);

                    if(i%2!=0)
                    {
                        printf("ganhou!\n");
                        cred=cred+(apost*2);
                    }

                    else
                    printf("perdeu!");
        }

    }

    return 0;
}

A: Sempre compile usando warnings! Se você usa o GCC ou o Clang, passe essa opção: -Wall para habilitar todas as principais. Pode adicionar -Wextra para ter ainda mais alertas. Eles lhe pontariam alguns dos erros que vou listar:

*

*Variável não inicializada:
Você declarou a variável int apost e logo em seguida leu seu valor: while(apost!=EOF). Ler o valor de uma variável sem antes dar um valor a ela é inválido, o seu executável pode fazer qualquer coisa. Na prática, essa condição pode dar verdadeira ou falsa de forma imprevisível. Sempre inicialize suas variáveis!

*Testar EOF em um int:
apost é um inteiro, armazena o valor da aposta. scanf("%d", &apost); lê um número. Por outro lado EOF é um char que indica fim da leitura e nunca vai ser retornado pelo scanf se você pediu a ele um número. Considere usar a seguinte lógica:
while (true) {
    int apost;

    printf("faça a aposta:(digite -1 para sair)\n");
    scanf("%d", &apost);

    if (apost < 0) break;

    /* ... */
}

*getc retorna uma letra, não um número:
Entenda que '3' não é a mesma coisa que 3. O primeiro é uma letra, que equivale ao inteiro 53 na maioria dos sistemas (se usam ASCII). Você deve testar pelas letras no seu switch, assim: case '1':.

*Distribuição de probabilidade:
A soma de dois números aleatórios de 1 a 6 é diferente de um número aleatório de 2 a 12. Isso ocorre por que combinações que resultam em 5, por exemplo são muito mais prováveis que combinações que resultam em 2. Para formar 5 podemos ter: 1+4, 2+3, 3+2, 4+1. Enquanto que 2 pode ser apenas 1+1. Sendo assim ele será 4 vezes mais provável. Isso é a chamada distribuição normal. A correção, no entanto, é simples: gere os dois valores separadamente e depois some.


text:
Q: RAILS: How to query if there's already a team formed by an array of users I'm working on an rails API, more specifically in a create operation.
The workflow that I have is this, I have two rails applications, one is an API and the other is an interface. The API manages the different backend operations in order to handle data, store data, and respond in json format to the interface. The interface serves as the frontend, just making http requests to the API in order to display the information.
In my API I have the 3 model listed below:
class Team < ApplicationRecord
  has_many :team_users
  has_many :users, through: :team_users
end

class User <ApplicationRecord
  has_many :team_users
  has_many :teams, through: :team_users
end

class TeamUser < ApplicationRecord
  belongs_to :user
  belongs_to :team
end

Basically I'm sending an array of user ids from the Interface to the API and I would like to make a query to find out if there's already a team formed by the users (user ids) that I've passed to the API.
I have already tried to do this:
Team.joins(:team_users).where('team_users.user_id' => [3,5])

The problem with this query is that it returns every team that contains  the users with id that are equal to 3 or 5. The correct result would be to return a team that has the users 3 and 5 or 5 and 3 as their team members.
Thanks in advance.
Update
The original business rule is this, have an aplication that keeps track of trees, so I have a model named tree and when we create a tree whe must say what team created this tree. So I used a multi select user dropdown field with select2 js library that is how I'm passing the user_ids to the API. So the basic idea is to check is theres already a team composed only by the users passed to the API, if there is already a team I use it's id and say that the tree was registered by that team, if there insn't a team with coposed only buy the users I create a new team and reference it's Id to the tree.

A: i have implemented this as
add a field key: string on Team and in Team model
class Team < ApplicationRecord
  has_many :team_users
  has_many :users, through: :team_users
  #callback
  before_validation :update_key

  def update_key
    self.key = Team.key_for_users(self.users)
  end

  def self.key_for_users(users)
    users.sort.map(&:id).join("_")
  end
end

so basically after this callback whenever you will create a team there will be a key
for example: -
users = [3,5]

then key in Team will be 3_5
or users = [5,3]
then key in Team will be 5_3
From this we can easily get the result what you wanted
example: -
user_ids = [3,5]
[14] pry(main)> user_ids_simple = user_ids.join('_')
=> "3_5"
[15] pry(main)> user_ids_reverse = user_ids.reverse.join('_')
=> "5_3"

and query will be like this: -
Team.where("key IN (?)",[user_ids_simple, user_ids_reverse])

it may be helpful for you. thanks

A: You can approach the problem in different ways. Scrolling over each Team record to check if it contains the associated user_ids is pretty straightforward but inefficient:
team.user_ids.sort == user_ids.sort

But we can make it performant by reversing the process, i.e. iterating over the user_ids to find out corresponding teams, taking their intersection of Team ids and finally checking if any team_id holds those user_ids. This line will return true if there's already a team formed by the users (user ids):
user_ids.map { |id| User.find(id).team_ids }.reduce(:&).present?

You may include it in the User class scope like below:
class User < ApplicationRecord
  ...
  def self.team_exists_for?(user_ids)
    # return early

    # what should it return when user_ids is empty
    # return ??? if user_ids.blank?

    # what should it return when any of the id is absent from :users table
    # set_of_all_user_ids = Set.new(User.pluck(:id))
    # set_of_user_ids     = Set.new(user_ids)
    # return ??? unless set_of_user_ids.subset? set_of_all_user_ids

    # finally
    user_ids.map { |id| User.find(id).team_ids }.reduce(:&).present?
  end
  ...
end

Update
So you want to find the team which only has those users provided by user_ids or create a team with them and assign back to the Tree model instance. Combining both approaches described above and defining a scope in the Team model itself seems like a better solution.
class Team < ApplicationRecord
  ...
  def self.find_or_create_for(user_ids)
    # find all team_ids which contain user_ids (inclusive)
    team_ids = user_ids.map { |id| User.find(id).team_ids }.reduce(:&).flatten

    if team_ids.present? # search for the team which ONLY has 'user_ids'
      team_id = team_ids.find { |id| Team.find(id).user_ids.sort == user_ids.sort }
    end

    return Team.find(team_id) if team_id

    # or create a team with user_ids and return
    team = Team.create! # create a team with required attributes
    team.user_ids = user_ids
    team
  end
  ...
end


text:
Q: Adjust volume of sound effect based on speed of collision I am using Cocos2D with Box2D to create a simple physics game. I want to adjust the volume of a collision sound effect depending on the speed of the colliding body. The faster the body is travelling when it collides, the louder the sound. I am using the SimpleAudioEngine library which has a playSound method with a gain parameter. Is there a way to convert the speed of the colliding body (a b2Body object) to a value between 0 and 1 that I can apply to the gain?

A: In the post solve function get an impulse value, divide it by 100 perhaps? I'm not sure what the levels of impulse you get are.
void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)

{
    b2Fixture* fixtureA = contact->GetFixtureA();
    b2Fixture* fixtureB = contact->GetFixtureB();

    void* userDataA = fixtureA->GetBody()->GetUserData();
    CCNode *myActorA = (CCNode*)userDataA;
    void* userDataB = fixtureB->GetBody()->GetUserData();
    CCNode *myActorB = (CCNode*)userDataB;

            // stuff above will allow you to work out which objects are hitting each other

            // get the impulse
        int impulseInt = impulse->normalImpulses[0];

}


text:
Q: How can I convert an IEEE-754 binary representation String to a float or double in Java? Since all Java floating-point numbers, which are floats and doubles, are internally represented as bits, I want to find an efficient algorithm to convert a String representing the bits of that float or double and convert it into its corresponding floating-point number - I couldn't find a built-in library function for it so I resorted to writing it by myself.
A binary String of length 32 represents a float, where as a binary String of length 64 will be converted to a double. All floats can be converted to doubles without loss of accuracy. Spaces are ignored.
Examples

*

*"0 10000000 10010010000111111011011" becomes 3.141592 as a float.

*"1 11111111 00000000000000000000000" becomes -infinity.

*"0 11111111 10010010000111111011011" becomes a float NaN.

*"1 10000000000 0101101111110000101010001011000101000101011101101001"becomes a double value closest to -e, which is 2.71828182845904509079559829843
So far I have this mass of a code:
public static double ieee(String binString) throws Exception {
    binString = binString.replace(" ", "");
    if (binString.length() == 32) {
        String exponentB = binString.substring(1, 9);
        String mantissaB = binString.substring(9, 32);
        int sgn = binString.charAt(0) == '0' ? 1 : -1;
        int exponent = Integer.parseInt(exponentB, 2) - 127; // Biased by 127
        double mantissa = 1 + Integer.parseInt(mantissaB, 2) / Math.pow(2, 23);

        if (exponent == 128 && mantissa == 1)
            return sgn == 1 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
        if (exponent == 128 && mantissa != 0)
            return Double.NaN;
        if (exponent == -127)
            return sgn*Math.pow(2,-126)*(mantissa - 1);
        return sgn*Math.pow(2, exponent)*mantissa;
    }
    else if (binString.length() == 64) {
        String exponentB = binString.substring(1, 12);
        String mantissaB = binString.substring(12, 64);
        int sgn = binString.charAt(0) == '0' ? 1 : -1;
        int exponent = Integer.parseInt(exponentB, 2) - 1023; // Biased by 1023
        double mantissa = 1 + Long.parseLong(mantissaB, 2) / Math.pow(2, 52);

        if (exponent == 1024 && mantissa == 1)
            return sgn == 1 ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY;
        if (exponent == 1024 && mantissa != 0)
            return Double.NaN;
        if (exponent == -1023)
            return sgn*Math.pow(2,-1022)*(mantissa - 1);
        return sgn*Math.pow(2, exponent)*mantissa;
    }
    else {
        throw new Exception("Does not represent internal bits of a floating-point number");
    }
}

Though my code works as of now, what is the neatest or fastest method to convert a IEEE-754 binary representation String to its float or double, in terms of speed and amount of code? The most efficient method with a good explanation of its efficiency and expertise is preferred.

A: This approach is probably more efficient.  It is certainly simpler and more maintainable.

*

*Remove spaces from string

*Validate string length ...

*Convert binary string to int

*Call Float.intBitsToFloat(int) to convert to an float.

For doubles, use long and the equivalent Double method.

Is the simplified code more efficient?

The only way to be sure is to benchmark it.  But based on what your code is doing, I believe so.

A: From @StephenC, the improved code to convert the IEEE-754 binary representation to its corresponding floating-point value takes up just one line:
return Float.intBitsToFloat(Integer.parseUnsignedInt(binString, 2));

*

*Integer.parseUnsignedInt(binString, 2) converts the unsigned int in binary digits from range 0 to 232-1 to the int representation. The parseInt(...) does not work because parseInt involves an explicit sign in its binString, and if it represents a negative int, a leading hyphen is required instead of a value that is 231 or greater. Similarly, Long.parseUnsignedLong(binString, 2) appiles for the 64-bit case.

*Float.intBitsToFloat(int n) represents the float value with the same bits internally stored as the int value n. Similarly, Double.longBitsToDouble(long n) works for the 64-bit case.

*Using "method composition", this line first converts the (unsigned) binary string into its corresponding int, and then converts it into the floating-point value with the same stored bits.
The final code would be
public static double ieeeToFloat(String binString) throws Exception {
    binString = binString.replace(" ", "");
    /* 32-bit */
    if (binString.length() == 32) {
        return Float.intBitsToFloat(Integer.parseUnsignedInt(binString, 2));
    }
    /* 64-bit */
    else if (binString.length() == 64) {
        return Double.longBitsToDouble(Long.parseUnsignedLong(binString, 2));
    }
    /* An exception thrown for mismatched strings */
    else {
        throw new Exception("Does not represent internal bits of a floating-point number");
    }
}

A: public class IEEE754ToFloatingValues {

public static double convertToInt(String mantissa_str) {

    int power_count = -1;
    double mantissa_int = 0.0;
    for (int i = 0; i < mantissa_str.length(); i++) {
        // System.out.print(Integer.parseInt(mantissa_str.charAt(i) + ""));
        mantissa_int += (Integer.parseInt(mantissa_str.charAt(i) + "") * Math.pow(2, power_count));
        power_count -= 1;
    }
    return mantissa_int + 1.0;
}

public static String convertToBinary(int i) {

    return Integer.toBinaryString(i + 0b10000).substring(1);
}

public static String decimalToHex(String decimal) {

    int i = Integer.parseInt(decimal);
    System.out.println("<<>>" + i);
    String my_hexdata = Integer.toHexString(i);

    System.out.println(my_hexdata);

    return String.valueOf(ReturnFloatingValue(my_hexdata));

}

public static double ReturnFloatingValue(String my_hexdata) {

    String myString = "";
    if (my_hexdata == null) {
        return -2.0;
    }
    if (my_hexdata.length() != 8) {
        myString = String.format("%1$-" + 8 + "s", my_hexdata).replace(' ', '0');

        System.out.println("My hex data after appending 0's is : " + myString);
    }

    String binary = "";
    for (int i = 0; i < myString.length(); i++) {
        int num = Integer.parseInt(myString.charAt(i) + "", 16);
        binary += convertToBinary(num);
    }

    System.out.println("Binary length is :  " + binary.length());

    System.out.println("Binary number is : " + binary);
    if (binary == null || binary.isEmpty()) {
        return -3.0;
    }
    String ieee_32 = binary.substring(2);

    ieee_32 = String.format("%1$-32s", binary).replace(' ', '0');

    long sign_bit = Long.parseLong(new StringBuilder().append(ieee_32.charAt(0)).toString());

    long exponent_bias = Long.parseLong(ieee_32.substring(1, 9), 2);
    long exponent_unbias = exponent_bias - 127L;

    System.out.println("Exponent unbias is  : " + exponent_unbias);
    String mantissa_str = ieee_32.substring(9);
    double mantissa_int = convertToInt(mantissa_str);
    double real_no = Math.pow(-1.0, (double) sign_bit) * mantissa_int * Math.pow(2.0, (double) exponent_unbias);

    System.out.println("Real no is : " + real_no);
    return real_no;
}

public static void main(String[] args) {

    //decimalToHex("16547");
}

}


text:
Q: What is the Azure Guest operating system? According to this article Azure supports only Windows Server 2012 R2 Windows Server 2012
Windows Server 2008R2.
That's mean that I cannot deploy anything else?

A: Expanding a bit on @Erik's comment:
The article you linked to is all about Cloud Services. Azure Cloud Services (web and worker role instances) are stateless Windows Server VMs that you don't have to manage (you just deploy a package built by specific developer tools such as Visual Studio). Very easy to scale out (or in), and no worries about maintaining the OS.
Azure's Virtual Machines, on the other hand, support many different flavors of both Windows Server (2012, 2016 preview, etc) and Linux (Ubuntu, Red Hat, CentOS, etc). You have to manage the OS maintenance, and you have some more work to do around scaling (and there are different features around this, such as VM scale sets).

A: Those are the limitations for Cloud Services. Web Apps would be similar to that too since you can't explicitly choose which server operating system to host those.
With Azure VM's (Virtual Machines) you have a much wider array of options to choose from. There are a number of Operating Systems, different Windows versions as well as Linux, to choose from in the Azure Marketplace. You can also build a VM locally using Hyper-V and then upload the .VHD into Azure to run it there as a VM.


text:
Q: Scrape a webpage contents after ::before tag using Python [Sample code from the webpage][1]
I am using BeautifulSoup with Python to extract the article headers from the following website [Knappily][2]
While importing the html data using BS4, the part after

::before

is not getting imported.
As shown in the image, the

following tags contain details about the articles.
But i am unable to find these
* tags using find/find_all.
Any suggestion will be helpful.
[1]: https://i.stack.imgur.com/ncJDH.jpg
[2]: https://knappily.com

A: The page is dynamically loaded using javascript, so you have to use selenium:
from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get('https://knappily.com/')

time.sleep(3)

st = time.time()

while True:
    if time.time() - st <= 120: #Keeps loading more articles for 2 mins. You can increase the time if u want.
        try:
            WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="buttons"]'))).click()
            time.sleep(1)
        except:
            break
    else:
        break

main_art = driver.find_element_by_class_name('impr-content').find_element_by_xpath('.//h1').text

print(f"{'-'*80}\nMain Article:\n{'-'*80}\n{main_art}\n{'-'*80}\nOther Articles:")

articles = driver.find_elements_by_class_name('article-content')

for article in articles:
    print('-'*80)
    print(article.find_element_by_xpath('.//h3').text)

Output:
--------------------------------------------------------------------------------
Main Article:
--------------------------------------------------------------------------------
Coronavirus has exposed India's digital divide in education
--------------------------------------------------------------------------------
Other Articles:
--------------------------------------------------------------------------------
Live with no doubts
--------------------------------------------------------------------------------
October 30, 1917: British government approves Balfour Declaration
--------------------------------------------------------------------------------
Delhi is choking again
--------------------------------------------------------------------------------
US Election: the final countdown
--------------------------------------------------------------------------------
At least I tried.
--------------------------------------------------------------------------------
Scam 1992: The real Harshad Mehta story
--------------------------------------------------------------------------------
October 29, 1969: The Internet is born
--------------------------------------------------------------------------------
Terrorist attack in Nice as French cartoon row escalates
--------------------------------------------------------------------------------
Manual scavenging: India must now end the evil
--------------------------------------------------------------------------------
In solitude I find my answers.
--------------------------------------------------------------------------------
October 28, 1929: Black Monday begins the Great Depression
--------------------------------------------------------------------------------
Digital payments are skyrocketing in India
--------------------------------------------------------------------------------
COVID antibodies drop over time, but that's alright
--------------------------------------------------------------------------------
Detach from what destroys you.
--------------------------------------------------------------------------------
US and India step up defence cooperation
--------------------------------------------------------------------------------
October 27, 1913: Woodrow Wilson swears by pacifism
--------------------------------------------------------------------------------
Cyber Crimes are rising in India
--------------------------------------------------------------------------------
France targets 'radical Islam', faces Muslim backlash
--------------------------------------------------------------------------------
You'll never know 'til you go.
--------------------------------------------------------------------------------
The never-ending crisis of IL&FS
--------------------------------------------------------------------------------
October 26, 1858: Theodore Roosevelt is born
--------------------------------------------------------------------------------
Reducing inequality: Chile shows how it's done
--------------------------------------------------------------------------------
The Indus Valley Tech continues to amaze us
--------------------------------------------------------------------------------
And into the forest I go...
--------------------------------------------------------------------------------
NASA and asteroid Bennu: the problem of plenty
--------------------------------------------------------------------------------
October 25, 1760: George III becomes King
--------------------------------------------------------------------------------
Urban Floods: the deluge of Hyderabad
--------------------------------------------------------------------------------
I doubt, therefore I am.
--------------------------------------------------------------------------------
India: where pollution is deadlier than the pandemic
--------------------------------------------------------------------------------
October 24, 1945: The United Nations is founded
--------------------------------------------------------------------------------
Europe's hospitals are filling up again
--------------------------------------------------------------------------------
Let go...or be dragged.
--------------------------------------------------------------------------------
Pakistan remains on the FATF grey list
--------------------------------------------------------------------------------
October 23, 1917: Lenin calls for October Revolution
--------------------------------------------------------------------------------
Coronavirus makes America sick again
--------------------------------------------------------------------------------
Courage, dear heart.
--------------------------------------------------------------------------------
Lagos is in total chaos
--------------------------------------------------------------------------------
October 22, 1859: Spain declares war on Morocco
--------------------------------------------------------------------------------
Mysterious deaths in South Korea raise flu vaccine safety concerns
--------------------------------------------------------------------------------
One life. Read more.
--------------------------------------------------------------------------------
The curious rise of 'Robin Hood' hackers
--------------------------------------------------------------------------------
October 21, 1854: Florence Nightingale leaves for the Crimea
--------------------------------------------------------------------------------
The United States sues Google
--------------------------------------------------------------------------------
Time flies, we don't.
--------------------------------------------------------------------------------
Neanderthals became 'feminine' by mating with humans
--------------------------------------------------------------------------------
October 20, 1911: Roald Amundsen sets out to South Pole
--------------------------------------------------------------------------------
Biden is winning, but Trump may still win
--------------------------------------------------------------------------------
Courage is a daily decision.
--------------------------------------------------------------------------------
Coronavirus cases cross 40 million
--------------------------------------------------------------------------------
October 19, 1910: Subrahmanyan Chandrasekhar is born
--------------------------------------------------------------------------------
Come grow old with me...
--------------------------------------------------------------------------------
Chinese economy continues to grow
--------------------------------------------------------------------------------
Antarctica's Emperors have no future
--------------------------------------------------------------------------------
October 18, 1954: Transistor Radio is born
--------------------------------------------------------------------------------
The pandemic philosophy of Albert Camus
--------------------------------------------------------------------------------
One big adventure. Or nothing.
--------------------------------------------------------------------------------
India vs. Bangladesh, per capita basis
--------------------------------------------------------------------------------
October 17, 1973: The Oil Crisis begins
--------------------------------------------------------------------------------
French teacher beheaded for "insulting" Islam
--------------------------------------------------------------------------------
Collect memories, not things.
--------------------------------------------------------------------------------
The United Kingdom prepares for no-deal Brexit
--------------------------------------------------------------------------------
October 16, 1923: The Walt Disney Company is founded
--------------------------------------------------------------------------------
Three-finger salute: Thais protest for democracy
--------------------------------------------------------------------------------
But not every man really lives.
--------------------------------------------------------------------------------
Digital Inequality and the Coronavirus
--------------------------------------------------------------------------------
October 15, 1917: Mata Hari is executed
--------------------------------------------------------------------------------
Jacinda Ardern prefers to earn her victory
--------------------------------------------------------------------------------
One life. Complain less.
--------------------------------------------------------------------------------
Resignation Syndrome: And I hereby withdraw from the world
--------------------------------------------------------------------------------
October 14, 1933: Germany quits the League of Nations
--------------------------------------------------------------------------------
Europe leads the world in COVID cases, again
--------------------------------------------------------------------------------
Quiet men are deep & dangerous
--------------------------------------------------------------------------------
2020: the year MBA went online
--------------------------------------------------------------------------------
October 13, 1792: The construction of 'The White House' begins
--------------------------------------------------------------------------------
Donald Trump's last great fight is on
--------------------------------------------------------------------------------
It is what it is.
--------------------------------------------------------------------------------
October 12, 1999: Pervez Musharraf scripts a coup in Pakistan
--------------------------------------------------------------------------------
Nobel Memorial Prize in Economics goes to auction theorists
--------------------------------------------------------------------------------
Coronavirus can survive for 28 days in cold and dark
--------------------------------------------------------------------------------
Be. Here. Now.
--------------------------------------------------------------------------------
Rafael Nadal wins French Open to tie Grand Slam record
--------------------------------------------------------------------------------
October 11, 1987: Operation Pawan begins in Sri Lanka
--------------------------------------------------------------------------------
North Korea flaunts monster missiles and zero COVID cases
--------------------------------------------------------------------------------
To seek nothing takes time
--------------------------------------------------------------------------------
Women political leaders don't exist in China
--------------------------------------------------------------------------------
October 10, 1967: The Outer Space Treaty comes into force
--------------------------------------------------------------------------------
The speed limit of sound has been found
--------------------------------------------------------------------------------
Good travelers never arrive.
--------------------------------------------------------------------------------
October 9, 1941: The Manhattan Project begins
--------------------------------------------------------------------------------
World Food Program wins Nobel Peace Prize 2020
--------------------------------------------------------------------------------
Is China winning the vaccine race?
--------------------------------------------------------------------------------
Rise above the crowd.
--------------------------------------------------------------------------------
Louise Glück wins Nobel Prize in Literature
--------------------------------------------------------------------------------
October 8, 1912: First Balkan War begins
--------------------------------------------------------------------------------
Coronavirus: making the poor poorer
--------------------------------------------------------------------------------
Your library is your paradise.
--------------------------------------------------------------------------------
Gene editing pioneers win the Chemistry Nobel
--------------------------------------------------------------------------------
October 7, 1952: Vladimir Putin is born
--------------------------------------------------------------------------------
Facebook bans conspiracy group QAnon
--------------------------------------------------------------------------------
When I do good, I feel good
--------------------------------------------------------------------------------
Black Hole hunters win Nobel Prize in Physics
--------------------------------------------------------------------------------
October 6, 1973: Yom Kippur War begins
--------------------------------------------------------------------------------
Donald Trump is back in action
--------------------------------------------------------------------------------
Believing is Seeing.
--------------------------------------------------------------------------------
Hepatitis C virus hunters win Nobel Prize in Medicine
--------------------------------------------------------------------------------
October 5, 1910: Portugal becomes a Republic
--------------------------------------------------------------------------------
Europe is breaking coronavirus records again
--------------------------------------------------------------------------------
Keep it simply, silly.
--------------------------------------------------------------------------------
The President has been put on steroids
--------------------------------------------------------------------------------
October 4, 2006: WikiLeaks is founded
--------------------------------------------------------------------------------
Remdesivir: the President's drug for COVID-19
--------------------------------------------------------------------------------
Write the first true word you know
--------------------------------------------------------------------------------
No place for nuclear waste in Germany
--------------------------------------------------------------------------------
October 3, 1952: Britain explodes an atomic bomb
--------------------------------------------------------------------------------
Donald Trump has been hospitalized
--------------------------------------------------------------------------------
Seek what's seeking you.
--------------------------------------------------------------------------------
Gandhi: because right is right and wrong is wrong
--------------------------------------------------------------------------------
October 2, 1904: Lal Bahadur Shastri is born
--------------------------------------------------------------------------------
Donald Trump tests positive for coronavirus
--------------------------------------------------------------------------------
On and on it goes...
--------------------------------------------------------------------------------
EU sues Britain over breaching Brexit deal
--------------------------------------------------------------------------------
October 1, 1988: Gorbachev is the head of Supreme Soviet
--------------------------------------------------------------------------------
Japan fears 'suicide contagion' after celebrity suicides
--------------------------------------------------------------------------------
Timothy Ray Brown: the 'Berlin patient' who conquered HIV
--------------------------------------------------------------------------------
What the hell, leap.
--------------------------------------------------------------------------------
September 30, 1938: Munich Agreement is signed to appease Hitler
--------------------------------------------------------------------------------
The never-ending Babri demolition case has delivered its first verdict
--------------------------------------------------------------------------------
First Presidential Debate: what a hot mess
--------------------------------------------------------------------------------
The absurd is the first truth.
--------------------------------------------------------------------------------
The BTS IPO is a smash hit
--------------------------------------------------------------------------------
September 29, 1913: Rudolf Diesel vanishes in thin air
--------------------------------------------------------------------------------
Coronavirus: one million deaths is not just a statistic
--------------------------------------------------------------------------------
Conviction needs Courage.
--------------------------------------------------------------------------------
Can gene therapy cure glaucoma?
--------------------------------------------------------------------------------
September 28, 1970: Gamal Abdel Nasser is no more
--------------------------------------------------------------------------------
Donald Trump' tax returns have been outed
--------------------------------------------------------------------------------
Accept it. Endure it.
--------------------------------------------------------------------------------
September 27, 1940: Axis powers sign the Tripartite Pact
--------------------------------------------------------------------------------
Armenia and Azerbaijan are close to war
--------------------------------------------------------------------------------
India must prepare for a long coronavirus fight
--------------------------------------------------------------------------------
You got this.
--------------------------------------------------------------------------------
Coulrophobia: the irrational fear of clowns
--------------------------------------------------------------------------------
Children can fight coronavirus better
--------------------------------------------------------------------------------
September 26, 1820: Ishwar Chandra 'Vidyasagar' is born
--------------------------------------------------------------------------------
The battle for the soul of the Supreme Court
--------------------------------------------------------------------------------
Stop thinking. Start living.
--------------------------------------------------------------------------------
September 25, 1969: Organization of Islamic Cooperation is founded
--------------------------------------------------------------------------------
Vodafone wins international arbitration against India
--------------------------------------------------------------------------------
Divided nations clash at the United Nations
--------------------------------------------------------------------------------
When I do good, I feel good.
--------------------------------------------------------------------------------
September 24, 2014: Mangalyaan reaches the orbit of Mars
--------------------------------------------------------------------------------
Coronavirus may have a dominant mutant strain
--------------------------------------------------------------------------------
Will the silent majority rise again for Trump?
--------------------------------------------------------------------------------
Don't be a Maybe.
--------------------------------------------------------------------------------
September 23, 1908: Ramdhari Singh 'Dinkar' is born
--------------------------------------------------------------------------------
The unbearable tragedy of whale beaching
--------------------------------------------------------------------------------
US coronavirus death toll crosses 200,000
--------------------------------------------------------------------------------
Find comfort in the chaos
--------------------------------------------------------------------------------
Resilience: the obstacle is the path
--------------------------------------------------------------------------------
September 22, 1980: Iraq invades Iran
--------------------------------------------------------------------------------
Vaccine: arriving in November…or Never?
--------------------------------------------------------------------------------
Be a happy rebel.
--------------------------------------------------------------------------------
Who really owns TikTok now?
--------------------------------------------------------------------------------
September 21, 1743: Maharaja Jai Singh II is no more
--------------------------------------------------------------------------------
India debates agriculture marketing reforms
--------------------------------------------------------------------------------
It is what it is.
--------------------------------------------------------------------------------
We are overusing this planet
--------------------------------------------------------------------------------
September 20, 1933: Annie Besant is no more
--------------------------------------------------------------------------------
Tadej Pogacar: the impossible Tour de France winner
--------------------------------------------------------------------------------
The mountains are calling...
--------------------------------------------------------------------------------
India's contribution to the world: a big ZERO
--------------------------------------------------------------------------------
Europe prepares for a viral winter
--------------------------------------------------------------------------------
September 19, 1946: Winston Churchill proposes the United States of Europe
--------------------------------------------------------------------------------
Taiwan learns to play with fire
--------------------------------------------------------------------------------
Rise, little man.
--------------------------------------------------------------------------------
September 18, 2001: First Anthrax letters are mailed
--------------------------------------------------------------------------------
India's weird relationship with weed
--------------------------------------------------------------------------------
Talk Less. Do More.
--------------------------------------------------------------------------------
September 17, 2011: Occupy Wall Street begins, the 99 percent rise
--------------------------------------------------------------------------------
Everyone is a prepper in 2020
--------------------------------------------------------------------------------
Be fearlessly you.
--------------------------------------------------------------------------------
Yoshihide Suga: the self-made Prime Minister of Japan
--------------------------------------------------------------------------------
September 16, 1987: Montreal Protocol is signed
--------------------------------------------------------------------------------
The emptiness of Trump's Middle East 'peace' deal
--------------------------------------------------------------------------------
Let go...or be dragged.
--------------------------------------------------------------------------------
Do we need animals to make meat?
--------------------------------------------------------------------------------
September 15, 1861: M. Visvesvaraya is born
--------------------------------------------------------------------------------
Pakistan rises against 'rape culture'
--------------------------------------------------------------------------------
It's not What, but How you do it
--------------------------------------------------------------------------------
Are they on Venus?
--------------------------------------------------------------------------------
September 14, 1960: OPEC is founded
--------------------------------------------------------------------------------
This virus just keeps breaking records
--------------------------------------------------------------------------------
He who is brave is free.
--------------------------------------------------------------------------------
Dominic Thiem wins US Open with a stunning comeback
--------------------------------------------------------------------------------
September 13, 1948: Indian Army enters Hyderabad
--------------------------------------------------------------------------------
Naomi Osaka wins US Open and rallies for social justice
--------------------------------------------------------------------------------
The fight is everything.
--------------------------------------------------------------------------------
September 12, 1990: Two Plus Four Agreement to reunify Germany is signed
--------------------------------------------------------------------------------
Facultative parthenogenesis: the strange world of virgin births
--------------------------------------------------------------------------------
Afghan peace talks begin to end the forever war
--------------------------------------------------------------------------------
If it's endurable, then endure it.
--------------------------------------------------------------------------------
The curious case of India's low COVID-19 mortality rate
--------------------------------------------------------------------------------
September 11, 1965: Bashar al-Assad is born
--------------------------------------------------------------------------------
Shall we reopen the schools?
--------------------------------------------------------------------------------
One life. Live more.
--------------------------------------------------------------------------------
Brexit gets even more chaotic
--------------------------------------------------------------------------------
September 10, 2008: Acceleration begins at Large Hadron Collider
--------------------------------------------------------------------------------
Coronavirus did not stop Climate Change
--------------------------------------------------------------------------------
Let go...or be dragged.
--------------------------------------------------------------------------------
Caster Semenya: too fast to be a woman
--------------------------------------------------------------------------------
September 9, 1993: PLO recognizes Israel
--------------------------------------------------------------------------------
Oxford vaccine suffers a major setback
--------------------------------------------------------------------------------
Calm is a superpower.
--------------------------------------------------------------------------------
Are we inside a Matrioshka Brain?
--------------------------------------------------------------------------------
September 8, 1945: Hideki Tojo attempts suicide
--------------------------------------------------------------------------------
Remote workers of the world, unplug
--------------------------------------------------------------------------------
Let the dead leaves drop
--------------------------------------------------------------------------------
India: the economy can't wait, the virus won't stop
--------------------------------------------------------------------------------
September 7, 1923: The INTERPOL is founded
--------------------------------------------------------------------------------
The strange disqualification of Novak Djokovic
--------------------------------------------------------------------------------
Even anxieties have anxieties today
--------------------------------------------------------------------------------
Someone is mutilating horses in France
--------------------------------------------------------------------------------

...

--------------------------------------------------------------------------------
May 16, 1966: Cultural Revolution begins in China
--------------------------------------------------------------------------------
Coronavirus: 4.5 million cases, 300,000 deaths
--------------------------------------------------------------------------------
Above all, be kind.

>>> len(articles)
714


text:
Q: Google play services on Visual Studio Emulator I am trying to install Google play services.
I followed this https://developer.xamarin.com/guides/android/deployment,_testing,_and_metrics/debug-on-emulator/visual-studio-android-emulator/.
I have the play store icon. But when I click on it a splash screen appears and goes away. When I run my app, which has geolocator, I still get a message saying, it won't run without Google Play Services, which are missing from your phone. How do I see what the problem is?


text:
Q: Eigenvalues and Eigenvectors for matrix Let A=[1 4]
      [2 3]
Find all eigenvalues of A and for each eigenvalue give an eigenvector.  choose one of the eigenvalue/eigenvector pairs for A, (a, b) (That is Ab=ab) and let P(x)=x^3-5x^2+2x+9.  Evaluate P(A)b, that is, apply the matrix P(A) to the eigenvector b.
I found one of the pairs that I wanted to use for the second part to be:
eigenvalue=5
eigenvector: [1,1]
How do I use this information to  evaluate P(A)b?  Do I input the eigenvalue of 5 into P(x)?

A: Yes.  The reason you can do that is the following:
$A^2b=AAb=A5b=5Ab=25b$.
You can do the same for the whole polynomial, and $(A^3-5A^2+2A+9)b=(5^3-5.5^2+2.5+9)b$
So you don't need to calculate the matrix $A^3-5A62+2A+9I$


text:
Q: Creating a share class Flutter I am not sure if this is possible, but with SwiftUI I have a mediaplayer class which has all my media player controls in it.
I am wondering if it is possible to have a flutter class file that hold flutter_radio_player and 1 media player that can change audio source?
The issue I have ran into with our old android app is we can't change the track without it creating a whole new media player.
I can't find any sample code on how to do this.
My code currently:
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_radio_player/flutter_radio_player.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  var playerState = FlutterRadioPlayer.flutter_radio_paused;

  var volume = 0.8;

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _currentIndex = 0;
  final List<Widget> _children = [
    new MyApp(),
  ];

  FlutterRadioPlayer _flutterRadioPlayer = new FlutterRadioPlayer();

  @override
  void initState() {
    super.initState();
    initRadioService();
  }

  Future<void> initRadioService() async {
    try {
      await _flutterRadioPlayer.init(
          "DRN1", "Live", "http://stream.radiomedia.com.au:8003/stream", "false");
    } on PlatformException {
      print("Exception occurred while trying to register the services.");
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Radio Player Example'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              StreamBuilder(
                  stream: _flutterRadioPlayer.isPlayingStream,
                  initialData: widget.playerState,
                  builder:
                      (BuildContext context, AsyncSnapshot<String> snapshot) {
                    String returnData = snapshot.data;
                    print("object data: " + returnData);
                    switch (returnData) {
                      case FlutterRadioPlayer.flutter_radio_stopped:
                        return RaisedButton(
                            child: Text("Start listening now"),
                            onPressed: () async {
                              await initRadioService();
                            });
                        break;
                      case FlutterRadioPlayer.flutter_radio_loading:
                        return Text("Loading stream...");
                      case FlutterRadioPlayer.flutter_radio_error:
                        return RaisedButton(
                            child: Text("Retry ?"),
                            onPressed: () async {
                              await initRadioService();
                            });
                        break;
                      default:
                        return Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              IconButton(
                                  onPressed: () async {
                                    print("button press data: " +
                                        snapshot.data.toString());
                                    await _flutterRadioPlayer.playOrPause();
                                  },
                                  icon: snapshot.data ==
                                      FlutterRadioPlayer
                                          .flutter_radio_playing
                                      ? Icon(Icons.pause)
                                      : Icon(Icons.play_arrow)),
                              IconButton(
                                  onPressed: () async {
                                    await _flutterRadioPlayer.stop();
                                  },
                                  icon: Icon(Icons.stop))
                            ]);
                        break;
                    }
                  }),
              Slider(
                  value: widget.volume,
                  min: 0,
                  max: 1.0,
                  onChanged: (value) => setState(() {
                    widget.volume = value;
                    _flutterRadioPlayer.setVolume(widget.volume);
                  })),
              Text("Volume: " + (widget.volume * 100).toStringAsFixed(0))
            ],
          ),
        ),

      ),
    );
  }
}

A: FlutterRadioPlayer Author here. With the new release of the player, you can do this.
You just have to call
_flutterRadioPlayer.setUrl('URL_HERE')

The player will automatically set the old stream to a halt and start the new stream. Yes, you can set it to autoplay when ready as well. Just refer to the docs in new release.


text:
Q: Morphing from an image to a shape in Silverlight 3 I have a requirement to morph from an image (png) to a shape (polygon) in Silverlight 3 as an effect, but of course there is no built in transition or method to do this.
At the moment the best I have is fade one out and the other in, but can anyone suggest a decent alternative that may work or look better?
Regards
Moo

A: I'm not a silverlight programmer, and  don't know the details of what you want to do, so this is just a shot in the dark, but... if the shape you want the image to morph to is always going to have the same initial visual appearance (or some limited set of appearances) you might try morphing from the original image to an image of that shape, and then swapping the image that's the morph target for the geometry once you're done the morph. Course whether that would work or not is very dependent on the details of what you're doing. Sorry if you've already considered that and ruled it out.

A: You could possibly morph the image brush to the path of the shape by using an appropriate projection matrix. Or render a shape using the image brush and then morph that shape to the target shape, i.e. go from a rectangle to the target shape but using the image brush as the shape background. You may need to still warp the image brush somehow though.
An example of rendering a warped image is here in Charles Petzold's blog.

A: In Blend:

*

*Create a rectangle.  Set stroke to No Brush and Fill to Tile Brush.

*For the ImageBrush of the Tile Brush, select your image.

*In the object browser, select the rectangle, right click > Path > Convert to Path.

*Use the pen tool to add some points to the path.

*Add a storyboard.

*Add a keyframe at 1 second.  Blend will go into record mode

*Use the direct selection tool to move the points into the polygon shape you want.  Test out your animation.

At this point, the image morphs into a shape, but the image is still there.  If you need to remove the image as well as morph it:

*

*In your storyboard, at the keyframe at 1 second, change the opacity to 0.

*Create a copy of the rectangle, but make sure fill is set to No Brush and Stroke is set to a color and width.  Set the opacity to 0.

*Add points, and mimic the animation you just set up for the image's rectangle.

*Add a keyframe at 1 second for this element.  In record mode, change the opacity to 100%.

The end result will be both paths morphing, the one with the image fading out while the one with no fill fading in.


text:
Q: The Membership.CreateUser() method in ASP.NET returns InvalidAnswer status all the time I am using AspNetSqlMembershipProvider to implement user management in my ASP.NET website. I have set up the database and the forms to accept user input as well. Everything works fine when I call the below method.
Membership.CreateUser(txtUserID.Text, txtPassword.Text);

with my web.config tag as below.
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" applicationName="/" minRequiredPasswordLength="8" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"/>

But when I am trying out the overloaded method,
Membership.CreateUser(txtUserID.Text, txtPassword.Text, null, null, null, false, out status);

It doesn't work. I have changed my web.config to enable the overload as shown below.
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" passwordFormat="Hashed" applicationName="/" minRequiredPasswordLength="8" />

All I get is the status variable set to "InvalidAnswer". Though I am passing in a very valid answer to this method. Am i missing something here?


text:
Q: Dimension of polynomial ring Suppose I have a polynomial ring $k[x_0,\cdots,x_n]$ and let $k[x_0,\cdots,x_n]_m$ denote the homogeneous part with degree $m$. How can I see that this $k[x_0,\cdots,x_n]_m$ has dimension $\binom{m+n}{m}$? Or more exactly, why does this give the Krull dimension?

A: Hint:
If you denote $k_i$ the exponent of $xi$in such a monomial, it is the number of solutions in natural numbers of the equation
$$k_0+k_1+\dots+ k_n=m.$$


text:
Q: data structure for sorted browsing history Suppose i want to implement the browser history functionality. If i visit the the url for this first time it goes into the history , if i visit the same page again it comes up in the history list.
lets say that i only display the top 20 sites, but i can choose to see history say for the last month , last week and so on .
what is the best approach for this ? i would use hash map for inserting / checking if it is visited earlier , but how do i sort efficiently for recently visited, i don't want to use tree map or tree set . also, how can i store history of weeks and months. Is it written on disk when browser closes ? and when i click clear history , how is the data structure deleted ?

A: This is in Java-ish code.
You'll need two data structures: a hash map and a doubly linked list.  The doubly linked list contains History objects (which contain a url string and a timestamp) in order sorted by timestamp; the hash map is a Map<String, History>, with urls as the key.
class History {
  History prev
  History next
  String url
  Long timestamp
  void remove() {
    prev.next = next
    next.prev = prev
    next = null
    prev = null
  }
}

When you add a url to the history, check to see if it's in the hash map; if it is then update its timestamp, remove it from the linked list, and add it to the end of the linked list.  If it's not in the hash map then add it to the hash map and also add it to the end of the linked list.  Adding a url (whether or not it's already in the hash map) is a constant time operation.
class Main {
  History first // first element of the linked list
  History last // last element of the linked list
  HashMap<String, History> map

  void add(String url) {
    History hist = map.get(url)
    if(hist != null) {
      hist.remove()
      hist.timestamp = System.currenttimemillis()
    } else {
      hist = new History(url, System.currenttimemillis())
      map.add(url, hist)
    }
    last.next = hist
    hist.prev = last
    last = hist
  }
}

To get the history from e.g. the last week, traverse the linked list backwards until you hit the correct timestamp.
If thread-safety is a concern, then use a thread-safe queue for urls to be added to the history, and use a single thread to process this queue; this way your map and linked list don't need to be thread-safe i.e. you don't need to worry about locks etc.
For persistence you can serialize / deserialize the linked list; when you deserialize the linked list, reconstruct the hash map by traversing it and adding its elements to the map.  Then to clear the history you'd null the list and map in memory and delete the file you serialized the data to.
A more efficient solution in terms of memory consumption and IO (i.e. (de)serialization cost) is to use a serverless database like SQLite; this way you won't need to keep the history in memory, and if you want to get the history from e.g. the last week you'd just need to query the database rather than traversing the linked list.  However, SQLite is essentially a treemap (specifically a B-Tree, which is optimized for data stored on disk).

A: Here is a Swift 4.0 implementation based on Zim-Zam O'Pootertoot's answer, including an iterator for traversing the history:
import Foundation

class SearchHistory: Sequence {
    var first: SearchHistoryItem
    var last: SearchHistoryItem
    var map = [String: SearchHistoryItem]()
    var count = 0
    var limit: Int

    init(limit: Int) {
        first = SearchHistoryItem(name: "")
        last = first
        self.limit = Swift.max(limit, 2)
    }

    func add(name: String) {
        var item: SearchHistoryItem! = map[name]
        if item != nil {
            if item.name == last.name {
                last = last.prev!
            }
            item.remove()
            item.timestamp = Date()
        } else {
            item = SearchHistoryItem(name: name)
            count += 1
            map[name] = item
            if count > limit {
                first.next!.remove()
                count -= 1
            }
        }
        last.next = item
        item.prev = last
        last = item
    }

    func makeIterator() -> SearchHistory.SearchHistoryIterator {
        return SearchHistoryIterator(item: last)
    }

    struct SearchHistoryIterator: IteratorProtocol {
        var currentItem: SearchHistoryItem

        init(item: SearchHistoryItem) {
            currentItem = item
        }

        mutating func next() -> SearchHistoryItem? {
            var item: SearchHistoryItem? = nil
            if let prev = currentItem.prev {
                item = currentItem
                currentItem = prev
            }
            return item
        }
    }
}

class SearchHistoryItem {
    var prev: SearchHistoryItem?
    var next: SearchHistoryItem?
    var name: String
    var timestamp: Date

    init(name: String) {
        self.name = name
        timestamp = Date()
    }

    func remove() {
        prev?.next = next
        next?.prev = prev
        next = nil
        prev = nil
    }
}


text:
Q: rails form_for and route with nested param Don't really know how to look for this, so without a long search I post this here.
What I want is a url like this:
/domains/whois/domainname.com

The problem is when I use a form the params get in the url like this:
/domains/whois/?utf8=✓&whois%5Bdomain%5D=domainname.com&commit=submit

My routes are like this at the moment:
namespace :domains do

    match "whois(/:domain)" => "whois#index"

end

My form is like this:
<%= form_for :whois, :method => :get do |form| %>
    <%= form.text_field :domain %>
    <%= form.submit "Vertel" %>
<% end %>

Anybody knows what I should do to get the param nested in the route?
Thanks!

A: You should be using post instead of get for forms.
This means all the forms will be posted in the body of the http request and you get to keep you're pretty url like /domains/whois/domainname.com

A: Found my answer here:
Simple search form passing the searched string through GET
Guess it's not possible without the redirect.


text:
Q: How do I fix error "use of undeclared identifier n" in C? I'm sure there are probably tons of syntax/other errors, but I'm trying to figure out the two that it's picking up on.  I'm very new to this so I don't really know how to fix undeclared identifiers. Note that #include <cs50.h> is just CS50's library.
#include <cs50.h>
#include <stdio.h>

int main (void)
{
   int add, fee, disc;
   printf("For rate with tax and Security Deposit, type y. For 10 percent off, type n:");
   string name = GetString();
   if (name == y)
   {
     printf("PreTax Amount: ");
     scanf("%d", &fee);
     printf("Okay. I will add the 10 percent tax to %d.\n ", fee);

     add        = (1.1 * fee);

     printf("Plus Tax Amount = %d\n", add);
     printf("Security Deposit = 1000 dollars\n");
     printf("Total = (%d + 1000)", add);
   }
   else if (name == n)
   {
     printf("PreTax Amount: ");
     scanf("%d%d", &fee, &disc);
     printf("Okay. I will minus the 10 percent discount to %d and then add tax.\n ", fee);

     add        = (0.9 * fee);
     disc       = (add * 1.1);

     printf("Minus Discount Amount plus tax = %d\n", disc);
     printf("Security Deposit = 1000 dollars\n");
     printf("Total = (%d + 1000)", disc);
   }

   return 0;
}

errors:
ContractualHelper.c:10:17: error: use of undeclared identifier 'y'
if (name == y)
            ^
ContractualHelper.c:22:22: error: use of undeclared identifier 'n'
else if (name == n)
                 ^
2 errors generated.

A: y and n are undeclared because they do not have definitions.
int y; is a declaration, which would get rid of that error.
However, your code
if (name == y)

is comparing a variable name to a variable y, and I think what you want to do is see if name contains the string y.
How to do that comparison is another issue.

A: Since you want just to compare with either 'Y' or 'N' I suggest you use char instead of string.
so :
char name;
scanf("%c", &name);
than when comparing use :
if (name == 'Y') ...
ADD
you also should consider wrong inputs from user so add another else like :
#include <stdio.h>
#include <string.h>

main()
{
   char name;
   scanf("%c", &name);

   if (name == 'y')
    printf("Yes");

   else if (name == 'n')
    printf("No");

   else
        printf("wrong input");
}


text:
Q: NUnit marking inconclusive results as "Test Not Run" I have a unit test with Assert.Inconclusive but the test result in the VS test explorer is "Test Not Run" instead of "Inconclusive". Assert.Fail and Assert.Pass both return the correct test result. What am I doing wrong?
Visual Studio 2015, class library project with NUnit 3. Thanks!
[TestFixture]
public class Class1
{
    [Test]
    public void scratch()
    {
        Assert.Inconclusive();
    }
}

packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="NUnit" version="3.6.0" targetFramework="net452" />
  <package id="NUnit.Console" version="3.6.0" targetFramework="net452" />
  <package id="NUnit.ConsoleRunner" version="3.6.0" targetFramework="net452" />
  <package id="NUnit.Extension.NUnitProjectLoader" version="3.5.0" targetFramework="net452" />
  <package id="NUnit.Extension.NUnitV2Driver" version="3.6.0" targetFramework="net452" />
  <package id="NUnit.Extension.NUnitV2ResultWriter" version="3.5.0" targetFramework="net452" />
  <package id="NUnit.Extension.TeamCityEventListener" version="1.0.2" targetFramework="net452" />
  <package id="NUnit.Extension.VSProjectLoader" version="3.5.0" targetFramework="net452" />
</packages>

A: The NUnit 3 VS Adapter is exactly that... an adapter. It does it's best to adapt NUnit's concepts of tests and test outcomes to the concepts that are understood by Visual Studio and its Test Explorer.
The NUnit notion of an Inconclusive result doesn't exist in Visual Studio, so it has to be reported as something else. Not Run seems to be as close as we can get.
Another discrepancy you will notice is that the new NUnit outcome of Warning is reported by Visual Studio as Skipped. That's an even worse fit, but we use it so that Visual Studio will display the result with the same warning icon it uses for Ignored tests.
As it stands, I don't think we can get a better translation, although suggestions are welcome. Now that Microsoft has open-sourced their test platform (https://github.com/Microsoft/vstest) maybe someone will give them a PR that extends the values supported for test outcomes.

A: I know this is old but whenever I get those kind of results it's almost always one of two things:

*

*Possible error in configuration, like a something missing in the app.config

*Incorrect TestCase arguments, eg Test accepts 2 arguments and I've only passed one

That's my experience anyway

A: I had same problem.
In my case I had UnitTests project with MSTests. I decided to change MSTests to NUnit. I installed NUnit, altered tests and ran them. All run tests displayed with Inconclusive as result. So I installed NUnit3TestAdapter and tests were run successfully.


text:
Q: I want my disabled text will be the placeholder for my select box I want my "-- Please Select --" should be like the placeholder for my select box. But when I put disabled the output of my select box placeholder appears "1", any idea?
      here's my code.
    <!DOCTYPE html>
    <html>
    <body>
         <select>
           <option value="" disabled>--- Please Select ---</option>
           <option value="1">1</option>
           <option value="2">2</option>
           <option value="3">3</option>
         </select>
    </body>
    </html>

A: You have to put in selected too. It will auto-select the first non-disabled item.
<option value="" disabled selected>--- Please Select ---</option>

And the demo.

A: Try using this HTML:
    <option value="--Please Select--" disabled>select</option>


text:
Q: Div splitter resize problems I created a splitter using javascript component, but it works only with two columns, if I add a third column, start to have problems with resizing.
In the excerpt below is where is the logic to resize.
var pos = (e.pageX - dragoffset.x);

el.style.left = (pos) + "px";

var total_area = $(el).prev().width() + $(el).next().width();

var f_1 = (pos);
var f_2 = (total_area - pos);

$(el).prev().width(f_1);
$(el).next().width(f_2);

I have posted my project in https://jsfiddle.net/m4y3rkqc/7/
What parameters should I consider to calculate the size correctly and dynamically?

A: I identified two problems:
Your second divider likes to "jump" away from you. The reason for that is that you didn't take the size of the element before the divider into account, you can fix this by changing your calculation for dragoffset to
dragoffset.x = e.pageX - el.offsetLeft
               + $(el).prev().offset().left - $(el).parent().offset().left;

Notice I also added a term to correct for the offset of the parent.
The other thing is that you could move a divider completely to the left or the right of a column and beyond, moving both dividers at half(?) speed while changing the size of all columns and the size of the dividers themselves. To correct this, you need to add 2 checks to make sure pos is not out of bounds before further using its value:
if (pos < 0) {pos = 0;}
if (pos > total_area) {pos = total_area;}

var f_1 = pos;
var f_2 = (total_area - pos);

And here is your full code with these changes. Hope this helps.


text:
Q: T-SQL How can I get the most common value from a result set Trying to get a single result for the most common date in a result set :
SELECT col1, col2,
(SELECT MIN(CONVERT(VARCHAR,[date], 103)) FROM TABLE )  AS [Date]
FROM TABLE WHERE [Date] BETWEEN '20160101' AND '20160131'

Results :

So I just want 15/01/2016. I know I need to use a subquery and a count for this and have tried many different solutions, being a newbie I'm finding subqueries harder to get my head around than JOINs especially correlated nested subqueries.

A: Group by date, order by count descending and select top 1:
select top 1 with ties [date]
from table
where [date] between '20160101' and '20160131'
group by [date]
order by count(*) desc

with ties will select multiple dates if max count can be the same for some dates.


text:
Q: How to run legacy native module with react native 0.70+? I had react-native 0.63.4 and updated to 0.71.2. My native module doesn't work on react-native 0.70+. I tried different versions of RN.
I started a new turbo native module and moved my native code to the new module. On android it works very well, but on ios the code don't compile because my module has been written with pure Objective-C (.m extension)
Is there any solution to use my old file.m instead of the new file type file.mm?


text:
Q: How to select this datepicker button with Selenium (Python)? Ok, so I am trying to clicking on this next button on this test automation test page (https://www.phptravels.net/). Picture:
See the button and DOM here.
I tried locating it by XPATH:
current_browser.find_element_by_xpath("//th[@class='next']").click()

and by XPATH but waiting for it to load:
WebDriverWait(current_browser, 10).until(EC.presence_of_element_located((By.XPATH, '//th[@class="next"]'))).click()

Despite my efforts it always throws elementNotVisibleException:
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible

How should I target and click this button?

A: Have you tried using the xpath generated by Chrome Dev Tools? It gives me this xpath: "/html/body/div[9]/div[2]/table/thead/tr/th[3]" and it seems to be working

A: The issue here is that there are 21 th tags with a class of next within the page. It seems like there are 7 datepicker dropdowns, each containing an option for days, months and years - your current XPath will always pick up the first one that it finds in the page, which is the datepicker for selecting the check-in date by day (which is why you are getting an ElementNotVisibleException).
From your screenshot it seems like you are trying to select by month, in which case your XPaths can be as follows...
Check-in:
//div[@class='datepicker dropdown-menu'][1]/div[@class='datepicker-months']//th[@class='next']
Check-out:
//div[@class='datepicker dropdown-menu'][2]/div[@class='datepicker-months']//th[@class='next']
If you are hoping to reference the different datepickers, then you can swap out months, days and years in these XPaths as appropriate - I hope this helps!


text:
Q: clickhouse Columns are from different tables i want to calculate the contain relationship ,Columns a.fistname and b.fullname are from different tables a and b,for example:
CREATE TABLE users (uid Int16, firstname String) ENGINE=Memory;
INSERT INTO users VALUES (1231, 'john');
INSERT INTO users VALUES (6666, 'ksenia');
INSERT INTO users VALUES (8888, 'alice');

CREATE TABLE users_money (fullname String, money Int16) ENGINE=Memory;
INSERT INTO users_money VALUES ('johnblack', 33);
INSERT INTO users_money VALUES ('jonhwhite', 48);
INSERT INTO users_money VALUES ('aliceblack', 50);

SELECT a.firstname,b.fullname,b.money FROM users a LEFT JOIN   users_money  b on startswith(b.fullname,a.firstname)==1;

i hope this startswith can work,but i got error
" Unsupported JOIN ON conditions. Unexpected 'startswith(fullname, firstname)': While processing startswith(fullname, firstname). (INVALID_JOIN_ON_EXPRESSION)"
you can try:  https://fiddle.clickhouse.com/
the result i want:
john    johnblack   33
john    Jonhwhite   48
ksenia      0
alice   aliceblack  50

A: JOIN conditions require an equality operator:
https://clickhouse.com/docs/en/sql-reference/statements/select/join/#on-section-conditions
For example you can split the full name and reuse the first element in the JOIN condition
CREATE TABLE users (uid Int16, firstname String) ENGINE=Memory;
INSERT INTO users VALUES (1231, 'John');
INSERT INTO users VALUES (6666, 'Ksenia');
INSERT INTO users VALUES (8888, 'Alice');

CREATE TABLE users_money (uid Int16,fullname String, money Int16) ENGINE=Memory;
INSERT INTO users_money VALUES (1231,'John Black', 33);
INSERT INTO users_money VALUES (1231,'Jonh  White', 48);
INSERT INTO users_money VALUES (8888,'Alice  Black', 50);

SELECT a.firstname, splitByWhitespace(b.fullname)[1] as splitFN,b.money FROM users a LEFT JOIN   users_money  b on a.firstname == splitFN

Output:
John    John    33
Ksenia      0
Alice   Alice   50


text:
Q: Spark sql- how to choose max value from a column as key for join For the two input data frames below, how can I join the two tables on date column, using the max value from t2, using spark sql (not sql api)? For example in scenario one we want to join t1 with t2 where t2.date= 2204, and in scenario 2 we want to join t1 with t2 where t2.date= 2203.
If there's a logic to join on t2 data from one month or two month earlier, depending on which one is latest available, it'd also work. I can't use the condition where t1.name= t2.name and t1.date <= t2.date, because in that case it will not only join on the Max date value from t2, but all the date values. There are many other columns in both t1 and t2.
Many thanks for your help. Please let me know if I can explain it better.
scenario one input t1:
+----+-----+
|name|date |
+----+---- +
|  a | 2205|
|  b | 2205|
+----+-----+

scenario one input t2:
+----+-----+------+
|name|date | value|
+----+---- +------+
|  a | 2204| 100  |
|  b | 2204| 200  |
|  a | 2203| 50   |
+----+-----+------+

expected output scenario one:
+----+-----+------+
|name|date | value|
+----+---- +------+
|  a | 2205| 100  |
|  b | 2205| 200  |
+----+-----+------+

scenario two input t1:
+----+-----+
|name|date |
+----+---- +
|  a | 2205|
|  b | 2205|
+----+-----+

scenario two input t2:
+----+-----+------+
|name|date | value|
+----+---- +------+
|  a | 2203| 100  |
|  b | 2203| 200  |
|  a | 2202| 50   |
+----+-----+------+

expected output scenario two:
+----+-----+------+
|name|date | value|
+----+---- +------+
|  a | 2205| 100  |
|  b | 2205| 200  |
+----+-----+------+


text:
Q: mysql querying for matches in many to many relations I need to build a complicated query and I don't even know where to start. Any help would be welcome.
I've got an users table and a games table with 2 Many to Many relationships between them, the tables and relevant columns are:

*

*users: id

*games: id

*game_users_A: id, user_id, game_id. (A relationship)

*game_users_B: id, user_id, game_id. (B relationship)

Let's say I chose an user and one of the relationships, for example user1, relationship A.
I want to get every other user and order them by how many games in their B relationships match the games in user1's A relationship.
Thanks. I've been trying to find similar questions but I don't even know how to call what I'm trying to do.
Edit.
Thanks to Hayden's help I was able to build the query I needed.
I just had to adapt his a little:
His query compares every user with each other. That is a lot more than I need to do, with around 3000 users it will return more than 900000 rows.
I only need to compare the user that's logged into my application with every other user in the database, so with N users I'll get N - 1 rows.
So I just added a couple of WHERE clouses and changed the ORDER BY.
Assuming the user making the request has an Id of 3 and wants to see the users matching the games in his A relationship with the games in their B relationship (and not the other way around), this is the query:
SELECT U1.id, U2.id, SUM(GCol) AS matches
FROM users U1 JOIN users U2 ON U1.id <> U2.id
LEFT JOIN (SELECT A.user_id AS A_id, B.user_id as B_id, (A.id IS NOT NULL) AS GCol
FROM game_users_A A JOIN game_users_B B
ON A.game_id = B.game_id AND A.user_id <> B.user_id WHERE A.user_id = 3) G
ON U1.id = G.A_id AND U2.id = G.B_id
WHERE U1.id = 3
GROUP BY GCol, U1.id, U2.id
ORDER BY matches desc

Thanks again.

A: I played around with a little test database with those tables, and here's what I have.
I broke it down into two queries. The first one was to match all users against all other users, which is simply:
SELECT U1.id, U2.id
FROM users U1 JOIN users U2 ON U1.id <> U2.id
ORDER BY U1.id, U2.id

The second query was to match up records in the B group to records in the A group, where the game is the same. This gave me:
SELECT A.user_id AS A_id, B.user_id as B_id
FROM game_users_A A JOIN game_users_B B
ON A.game_id = B.game_id AND A.user_id <> B.user_id

To combine these two, I did a left join of the first query against the second query, since for any pair of users, it's possible that there isn't a matching set of games. In these cases, the results of the second query will show up as NULL values. What we want is a value of 1 when those appear, so if you look in the query below, there's a value of
(A.id IS NOT NULL) AS GCol

which is used so we can find the sum. If there is a record, there's a value of 1, or NULL otherwise. When there are no values there, the total is still null, but when there are matches, the total is summed up and displayed. This gives a final query of:
SELECT U1.id, U2.id, SUM(GCol)
FROM users U1 JOIN users U2 ON U1.id <> U2.id
LEFT JOIN (SELECT A.user_id AS A_id, B.user_id as B_id, (A.id IS NOT NULL) AS GCol
FROM game_users_A A JOIN game_users_B B
ON A.game_id = B.game_id AND A.user_id <> B.user_id) G
ON U1.id = G.A_id AND U2.id = G.B_id
GROUP BY GCol, U1.id, U2.id
ORDER BY U1.id, U2.id

I think that's what you're looking for.


text:
Q: Add nodes to almost all branches in a tree I'm trying to create a tree structure of all possible combinations of value pairs from two lists
I have two linked lists L1 = {A, B, C} and L2 = {1, 2, 3}. I want to create a tree structure that lets me pull out all unique combinations of these two lists:
root--A1--B2--C3
 | |   |
 | |   --B3--C2
 | |
 | A2--B1--C3
 |  |
 |   --B3--C1
 |
 --A3--B1--C2
    |
    --B2--C1

Only 1 instance of any member of each list can be in any complete branch of the tree. I want this to work with any size of both L1, L2
Requirements for the tree:

*

*Each node contains an array of pointers to each element pair

*Each branch can only contain one instance of each element of the two lists

*Each branch has to be as long as possible

*

*The length of a branch should be the size of L1, and the amount of nodes connected to the root node should be the same as the length of L2.

My tree consists of 2 structs:
typedef struct _TR tree;
typedef struct _TN tree_node;

struct _TR
{
    unsigned int tree_depth;
    tree_node * root;
};

struct _TN
{
    List_item * items[2];
    unsigned int node_count;
    tree_node  * parent_node;
    tree_node ** child_nodes;
};

The tree is built by the following function
void addToAllBranches(List_item * item_array[2], tree_node * curr_node)
{
    if (curr_node->node_count == 0) // Problem, some how
    {

        if (!checkIfExistsInBranch(curr_node->parent_node, item_array)) // Checks if any member of the pair exists in the current branch (straight following each parent node)
            addNode(curr_node, createNode(item_array)); //If it doesn't exist, add it. Otherwise do nothing
        return;
    }
    int i = 0;
    while (i < curr_node->node_count)
    {
        addToAllBranches(item_array, curr_node->child_nodes[i]);
        i++;
    }

}

Which is called by
/* Walks through each possible pair and tries to add them to the tree*/
void addPairsToTree(List * L1, List * L2, tree * root_tree)
{
    List_item * L1_list_wlkr = L1->top_item;
    List_item * L2_list_wlkr;
    List_item * item_array[2];

    while (L1_list_wlkr != NULL)
    {
        L2_list_wlkr = L2->top_item;
        while (L2_list_wlkr != NULL)
        {
            item_array[0] = L1_list_wlkr;
            item_array[1] = L2_list_wlkr;
            addToAllBranches(item_array, root_tree->root);

            L2_list_wlkr = L2_list_wlkr->next_item;
        }

        L1_list_wlkr = L1_list_wlkr->next_item;
    }

}

With the checking function:
int checkIfExistsInBranch(tree_node * curr_node, List_item * check[2])
{
    tree_node * tree_wlkr = curr_node;
    while(tree_wlkr != NULL)
    {
        if(tree_wlkr->items[0] == check[0] || tree_wlkr->items[1] == check[1])
        {
            return 1;
        }
        tree_wlkr = tree_wlkr->parent_node;
    }
    return 0;
}

Looking at the tree structure I get it seems to look like something like this:
root--A1--A2--B2--B3--C3

Which doesn't make sense, I feel like the output should be something along the lines of:
root--A1--B2--C3

I am pretty sure that the problem is caused by the line:
if (curr_node->node_count == 0) // Problem, some how

Which causes the adding function only to add onto empty branches.
I am unsure on what to change it to which still makes the tree fulfill the size requirements.
My questions are:

*

*What do I change the if (curr_node->node_count == 0) // Problem, some how line to?

*How come the checkIfExistsInBranch fails with the current way the algorithm is implemented?


text:
Q: android build: add jar to endstate via command-line builds With respect to this question, simply putting a jar into the /libs does not auto-magically include that jar into the .dex when invoking, say, ant debug. Not at least with Android SDK ver 15.
I've verified this by comparing the same project created two different ways. First (call it 'Alpha'), by Eclipse. Second, via android create project ..., blah blah blah (the Ant way, call it 'Bravo').
Both Alpha and Bravo I built using ant debug. Comparing their /bin dirs, the jar under <project_root>/libs is missing from Bravo's *.d; Alpha's aren't.
What magic is Eclipse embedding during project creation?
Better still, how can I ensure a jar is passed to ant debug|release when building a project, that a jar is included in the endstate?

A: You may just have to adjust the build.xml to include something like the following in the -pre-build node if you want to hardwire it in.  You can also add this in a custom target in the build.xml file that would able you do include from the command line when you want.  Something like the following could work.
<target name="add-jar">
    <copy file="${src.folder}/YourJarHere.jar" tofile="libs/YourJarHere.jar" overwrite="true"/>
</target>

Where ${src.folder} is defined in your ant.properties file.
Something like src.folder=PATHOFYOURJAR

Then you should be able to run
ant debug add-jar

including the file.
I have had to manually create the libs folder in the past but I don't see why you can't do this through the build.xml file.  Hope this helps!