text:
Q: jQuery require_from_group if a form field is filled/selected I have a page which allows people to input details of up to five Referrals which are non-compulsory. Each group of referral is contained within its own div.
When any one of the fields is filled/selected, I need to check that all the other fields and at least one contact number within the same div are filled as well. If no field is filled/selected, the form should pass through successfully.
I am stuck at this for the longest as I only managed to use require_from_group for the contact numbers which checks for at least one contact number filled, but it doesn't fulfill what I require.
HTML code for form fields

My Referral:

Salutation

            <select type="text" class="form-control" name="Referral_1_Salutation">
                <option value="" selected disabled>Please select</option>
                <option value="Mr">Mr</option>
                <option value="Mrs">Mrs</option>
                <option value="Ms">Ms</option>
                <option value="Mdm">Mdm</option>
            </select>

Name

            <input type="text" class="form-control" name="Referral_1_Name" value="" maxlength="50">

Contact Number (Mobile)

            <input type="text" class="oneormore form-control" name="Referral_1_Contact_Number_Mobile" value="" maxlength="20">

Contact Number (Home)

            <input type="text" class="oneormore form-control" name="Referral_1_Contact_Number_Home" value="" maxlength="20">

Contact Number (Office)

            <input type="text" class="oneormore form-control" name="Referral_1_Contact_Number_Office" value="" maxlength="20">

Email Address

            <input type="text" class="form-control" name="Referral_1_Email" value="" maxlength="50">

Best Time to Call

            <select type="text" class="form-control" name="Referral_1_Best_Time_To_Call">
                <option value="" selected disabled>Please select</option>
                <option value="9am_to_12pm">9am - 12 pm</option>
                <option value="12pm_to_2pm">12pm - 2pm</option>
                <option value="2pm_to_4pm">2pm - 4pm</option>
                <option value="4pm_to_6pm">4pm - 6pm</option>
                <option value="Anytime">Anytime</option>
            </select>

jQuery function which currently checks that at least one contact number is needed to be filled
var initCustomerReferralFormComponents = function() {
    jQuery.validator.addMethod("require_from_group_contact", function (value, element, options) {
        var validator = this;
        var minRequired = options[0];
        var selector = options[1];
        var validOrNot = jQuery(selector, element.form).filter(function () {
            return validator.elementValue(this);
        }).length >= minRequired;

        // remove all events in namespace upload

        jQuery(selector, element.form).off('.require_from_group_contact');

        if (this.settings.onkeyup) {
            jQuery(selector, element.form).on({
                'keyup.require_from_group_contact': function (e) {
                    jQuery(selector, element.form).valid();
                }
            });
        }
        if (this.settings.onfocusin) {
            jQuery(selector, element.form).on({
                'focusin.require_from_group_contact': function (e) {
                    jQuery(selector, element.form).valid();
                }
            });
        }
        if (this.settings.click) {
            jQuery(selector, element.form).on({
                'click.require_from_group_contact': function (e) {
                    jQuery(selector, element.form).valid();
                }
            });
        }
        if (this.settings.onkeyup) {
            jQuery(selector, element.form).on({
                'keyup.require_from_group_contact': function (e) {
                    jQuery(selector, element.form).valid();
                }
            });
        }
        return validOrNot;
    }, "Fill in all fields.");

    $("#customer_referral").validate({
        rules: {
            Referral_1_Contact_Number_Mobile: {
                require_from_group_contact: [1, ".oneormore"]
            },
            Referral_1_Contact_Number_Home: {
                require_from_group_contact: [1, ".oneormore"]
            },
            Referral_1_Contact_Number_Office: {
                require_from_group_contact: [1, ".oneormore"]
            }
        },
        highlight: function(element, errorClass) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        },
        errorPlacement: function (error, element) {
             $(element).closest('.form-group').find('.error-msg').text(error.text());
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success')
        },
        submitHandler: function(form) {
            console.log('form submit');
            form.submit();
        }
     });
 }

A: It's very tedious...
You create a conditional function to see if any of the other four fields are filled out and then apply the parameters of the require_from_group rule using a function.
Do the same for the other fields but instead using the required rule.
Adjust accordingly.
rules: {
    Referral_1_Contact_Number_Mobile: {
        require_from_group: function(element) {
            if ($('[name="Referral_1_Salutation"]').is(':filled') || $('[name="Referral_1_Name"]').is(':filled') || $('[name="Referral_1_Email"]').is(':filled') || $('[name="Referral_1_Best_Time_To_Call"]').is(':filled')) {
                return [1, ".oneormore"];
            } else {
                return [0, ".oneormore"];
            }
        }
    },
    ....
    // repeat same for remaining contact numbers
    ....

    Referral_1_Salutation: {
        required: function(element) {
            return ($('[name="Referral_1_Name"]').is(':filled') || $('[name="Referral_1_Email"]').is(':filled') || $('[name="Referral_1_Best_Time_To_Call"]').is(':filled') || $('[name="Referral_1_Contact_Number_Mobile"]').is(':filled') || $('[name="Referral_1_Contact_Number_Home"]').is(':filled') || $('[name="Referral_1_Contact_Number_Office"]').is(':filled'));
        }
    },
    ....
    // repeat same for remaining other fields
    ....

Working DEMO:  http://jsfiddle.net/cd5gy73u/

EDIT:
Much of the code could be replaced with the skip_or_fill_minimum rule:
http://jsfiddle.net/yo2vjwus/


text:
Q: View controller not being created I have a navigation controller that starts my app (rootViewController is the navigationController). Then inside one of the views of the navigation I call:
TabBarController *tab = [[TabBarController alloc] init];

// Presentation
[self presentViewController:tab animated:NO completion:nil];

Then one of the tabs calls the UIImagePickerController and then saves the image on another thread. Then I return to the main queue and run:
dispatch_async(dispatch_get_main_queue(), ^{

        [picker dismissViewControllerAnimated:YES completion:nil];

        PostViewController *post = [[PostViewController alloc] init];

        // Presentation
        [self presentViewController:post animated:NO completion:nil];
    });

But the post view never gets called and the viewDidLoad never gets hit in the PostViewController.m.  Instead the imagePicker disappears and returns to the tabBarController. How do I fix this?

A: Assuming that you PostViewController object is not nil , Present the view controller after the dismiss process of picker ViewController is completed . Try this Code
 dispatch_async(dispatch_get_main_queue(), ^{

    [picker dismissViewControllerAnimated:YES completion:^{

     PostViewController *post = [[PostViewController alloc] init];

    // Presentation
    [self presentViewController:post animated:NO completion:nil];
}];

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: On iPhone, Input element with "datepicker" class doesn't span the entire column width I am trying to render a datepicker input. I want the input field to span the entire width of the column. On Android (Chrome) it looks fine but on iOS (Safari) the input field is wrapping the text. The image attached shows ios on the left and android on the right. I want ios to show the input field same as what android is showing.
Following is the code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

    <input type="Date" name="123" class="datepicker form-control" value="2019-09-21" autocomplete="off">

A: try to add minimum width :
<input type="Date" name="123" class="datepicker form-control" value="2019-09-21" autocomplete="off" style="min-width:95%;">


text:
Q: Customize the devise edit method - Rails 4 I have a problem with customising Devise method. I want to edit an existing profile. But it doesn't change.
Here's my code
My controller:
class DashboardController < Users::RegistrationsController::ApplicationController

  def index
  end

  def update
    @user = current_user
    if @user.update_attributes(user_params)
        redirect_to 'index', :notice  => "Successfully updated profile."
    else
        Rails.logger.info(@user.errors.messages.inspect)
        render :action => 'edit'
    end
  end

  def edit
  end

  private

  def user_params
    params.require(:user).permit(:avatar, :username, :email, :password, :password_confirmation)
  end

end

My edit view

Edit the profile

      <fieldset>

                <%= form_for current_user, url: edit_dashboard_path(current_user), html: { method: :get, multipart: true }  do |f|%>

               <%= f.label :username%>

               <%= f.text_field :username, autofocus: true, :placeholder => 'Username', class:"form-control input-lg " %>

              <%= f.label :email %>

             <%= f.email_field :email, autofocus: true, :placeholder => 'Email' , class:"form-control input-lg" %>

              <%=  f.label :password%>

              <%= f.password_field :password, :placeholder => 'Password', class:"form-control input-lg"%>

              <%= f.label :password_confirmation%>

              <%= f.password_field :password_confirmation,:placeholder => 'Confirm your password' , class:"form-control input-lg"%>

              <%= f.file_field :avatar  %>

            <%= f.submit 'Edit the profile', class: "btn btn-primary btn-lg btn-block  btn-group" %>

            <% end %>
        </fieldset>

It can be a problem in my layout code, where i make the link to the edit page
<%= link_to "Edit the Profile", edit_dashboard_path %>

A: Your form is submitting to the edit dashboard using a get, which is the same page you are on.  Instead you want to update the current user something like this:
<%= form_for current_user, html: { multipart: true }  do |f|%>

This will default to the update attribute and CRUD action defined in your routes file for a user

A: I would suggest changing this line:
<%= form_for current_user, url: edit_dashboard_path(current_user), html: { method: :get, multipart: true }  do |f|%>

*

*In the url use your path to the 'update' method, not the edit (use rake routes on your command line)

*In the method use :put instead of :get


text: Q: Role based authorization in Jenkins I am running jenkins by extracting the jenkins.war file.I have installed role based authorization strategy plugin for jenkins security.I have created a admin who has full access to jenkins.And I have created users who have access to only their projects.But when I close the command prompt and run jenkins.war again and login as admin I find admin does not having any privilages and the users i have created does not have any access to the privilages.What might be the problem.Is there something I am doing wrong.Please help


text:
Q: How to inprove SVHN result with Keras? I'm using keras to build to CNN to train the famous SVHN (street view house number) data set(fist version, without cropping). I train the pictures as they all have five digit spot, for pictures have less numbers, I treat the empty spot as another category. So, I have 11 categories for each digit spot. I didn't use bbox yet. I can just get only 30% accuracy best for first two accuracy. I try different dropout rate, or adding one more convolution layer. But accuracy still very low. How can I tune my model to get a better accuracy? I don't to use the bbox at this stage. Is that possible to get a decent perform model?
from keras.models import Sequential
from keras.models import Model
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.layers import Input
from keras.layers.core import Dropout
identifier = Sequential()
x = Input((30,70,1))
y = (Convolution2D(64,3,3,activation = "relu",border_mode = "valid"))(x)
y = (MaxPooling2D(pool_size = (2,2)))(y)
y = (Convolution2D(64,3,3,activation = "relu",border_mode = "valid"))(x)
y = (MaxPooling2D(pool_size = (2,2)))(y)
#y = (Dropout(0.5))(y)
y= (Convolution2D(32,3,3,activation = "relu"))(y)
y = (MaxPooling2D(pool_size = (2,2)))(y)
#y = (Dropout(0.5))(y)
y= (Convolution2D(32,3,3,activation = "relu"))(y)
y = (MaxPooling2D(pool_size = (2,2)))(y)
y = (Dropout(0.5))(y)

y = (Flatten())(y)
y =(Dense(output_dim = 512,activation = "relu"))(y)
y = (Dense(output_dim=256,activation = "relu"))(y)
y = (Dense(output_dim=256,activation = "relu"))(y)
y = (Dense(output_dim=128,activation = "relu"))(y)
digit1 = (Dense(output_dim =11,activation = "softmax"))(y)
digit2 = (Dense(output_dim =11,activation = "softmax"))(y)
digit3 = (Dense(output_dim =11,activation = "softmax"))(y)
digit4 = (Dense(output_dim =11,activation = "softmax"))(y)
digit5 = (Dense(output_dim =11,activation = "softmax"))(y)
identifier = Model(input =x, output = [digit1,digit2,digit3,digit4,digit5])
identifier.compile(optimizer = "adam", loss = "categorical_crossentropy",metrics = ["accuracy"])
nb_epoch =3
identifier.fit(training_data.reshape(29329,30,70,1),train_labels,batch_size= 64,nb_epoch= nb_epoch,
               verbose= 1,validation_data=(test_data.reshape(600,30,70,1),test_labels))

A: Follow the famous SVHN paper (https://arxiv.org/abs/1312.6082). He had great ideas how to improve the classification.
In this paper, they introduce a convolutional layer, composed by a convolution, like you created, a batch normalization, a activation and a maxpooling.
They added 11 convolutional layers in the architecture. The convolution has a 5x5 filter and they use sometimes a stride of 2 in the maxpooling and sometimes a stride of 1.
The number of filters is much bigger too, starting with 48 filters in the first layer and finishing with 192 filters in the end.
The convolutional layer should look like this:
def svhn_layer(model, filters, strides, name):

    model.add(Conv2D(filters, (kernel_size, kernel_size),
           padding='same', name='conv2d_' + name))

    model.add(BatchNormalization())
    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2), strides=(strides, strides),
              name='maxpool_2d_' + name))

    model.add(Dropout(0.2))

    return model

where model is a keras Sequential.
After defining this layer, you can play with many combinations, varying filters and strides. Considering the paper, the network should look something like this:
model = Sequential()

svhn_layer(model, 48, 2, 'hidden1')
svhn_layer(model, 48, 1, 'hidden2')
svhn_layer(model, 48, 1, 'hidden3')

svhn_layer(model, 64, 2, 'hidden4')
svhn_layer(model, 64, 1, 'hidden5')
svhn_layer(model, 64, 1, 'hidden6')

svhn_layer(model, 128, 2, 'hidden7')
svhn_layer(model, 128, 1, 'hidden8')
svhn_layer(model, 128, 1, 'hidden9')

svhn_layer(model, 192, 2, 'hidden10')
svhn_layer(model, 192, 1, 'hidden11')

model.add(Flatten())

model.add(Dense(3072))
model.add(Dense(3072))

x = Input((30,70,1))
y = model(x)

digit1 = (Dense(output_dim =11,activation = "softmax"))(y)
digit2 = (Dense(output_dim =11,activation = "softmax"))(y)
digit3 = (Dense(output_dim =11,activation = "softmax"))(y)
digit4 = (Dense(output_dim =11,activation = "softmax"))(y)
digit5 = (Dense(output_dim =11,activation = "softmax"))(y)

identifier = Model(input=x, output = [digit1, digit2, digit3, digit4, digit5])

You can play with other normalizations too, like selu and elu. My tests show they perform better than relu.
Remembering this will work with inputs like they described (images with dimension 64x64x3). Your input looks like different, so, maybe you have to remove some layers or strides.


text:
Q: Challenges with caesar-cipher: Encoding and Decoding code I am new to Java and this is what I have to do:
  Write a program that lets the user input a message and a shift value and then outputs the encoded message
Write a separate program that lets the user input a coded message using the first program and then decodes it for you and you cannot use StringBuffer or StringBuilder
What I am trying to do here is make the second part of the program but I am having some problems. When you add shift value, it only encodes it by 1 no matter what number you input and when I try to decode, it gives me an error.
public class part2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String text;
        String key;
        int shift;

        System.out.println("Enter message:");
        text = sc.nextLine();
        System.out.println("Enter encryption key:");
        key = sc.next();
        shift = key.length(); {
            System.out.println("1.Encrypt\n2.Decrypt\n3.Exit...");
            int choice = sc.nextInt();
            switch (choice) {
                case 1:
                    System.out.println("Encryptedmessage..." + encrypt(text, shift));
                    break;
                case 2:
                    //send retrived string from encrypt() method and keyLength to decrypt() method it returns 'Decrypted' string
                    System.out.println("Decrypted message..." + decrypt(encrypt(text, shift), shift));
                    break;
                case 3:
                    //exit from the program
                    System.exit(0);
                    break;
                default:
                    System.out.println("Invalid option..");
            }
        }
    }
    public static String encrypt(String text, int shift) {

        for (int i = 0; i < text.length(); i++) {
            char letter = text.charAt(i);

            // shift only letters (leave other characters alone)
            if (letter >= 'a' && letter <= 'z') {
                letter = (char)(letter + shift);

                // may need to wrap around
                if (letter > 'z') {
                    letter = (char)(letter - 26);
                } else if (letter < 'a') {
                    letter = (char)(letter + 26);
                }
            }
            System.out.print(letter);
        }
        return null;
    }

    public static String decrypt(String str, int keyLength) {
        String decrypted = "";
        for (int i = 0; i < str.length(); i++) {

            int c = str.charAt(i);

            if (Character.isUpperCase(c)) {
                c = c - (keyLength % 26);
                if (c < 'A')
                    c = c + 26;
            } else if (Character.isLowerCase(c)) {
                c = c - (keyLength % 26);
                if (c < 'a')
                    c = c + 26;
            }
            decrypted = decrypted + (char) c;
        }
        return decrypted;
    }
}

This is my code for the first part:
public static void main(String[] args) {

        Scanner console = new Scanner(System.in);
        System.out.print("Type a message you want to be coded: ");
        String message = console.nextLine();
        message = message.toLowerCase();

        System.out.print("Enter a Shift: ");
        int key = console.nextInt();
    if (key < 1 || key > 25) {
                System.out.printf(" The key must be between 1 and 25, you entered %d.\n", key);
            }
        while (key < 1 || key > 25);

        encode(message, key);
    }

    // This method encodes the given text string using a Caesar
    // cipher, shifting each letter by the given number of places.
    public static void encode(String text, int shift) {
        System.out.print("The encoded message: \n");
        for (int i = 0; i < text.length(); i++) {
            char letter = text.charAt(i);

            // shift only letters (leave other characters alone)
            if (letter >= 'a' && letter <= 'z') {
                letter = (char) (letter + shift);

                // may need to wrap around
                if (letter > 'z') {
                    letter = (char) (letter - 26);
                } else if (letter < 'a') {
                    letter = (char) (letter + 26);
                }
            }
            System.out.print(letter);
        }
    }

This is the code for first part and it works perfectly. Just need help with the second part

A: You have a couple of problems here.
First, you are not quite done with the first part, like you think. Let's look at your encrypt method:
public static String encrypt(String text, int shift) {

    for (int i = 0; i < text.length(); i++) {
        char letter = text.charAt(i);

        // shift only letters (leave other characters alone)
        if (letter >= 'a' && letter <= 'z') {
            letter = (char)(letter + shift);

            // may need to wrap around
            if (letter > 'z') {
                letter = (char)(letter - 26);
            } else if (letter < 'a') {
                letter = (char)(letter + 26);
            }
        }
        System.out.print(letter); // <- This is part of your problem
    }
    return null; // <- This is part of your problem
}

When we call this, we output the encoded string to the console, but look at the last line: we return null. You need to figure out a way to store the encoded message and then return it. Otherwise, you will always get a NullPointerException on this line in your main method:
System.out.println("Decrypted message..." + decrypt(encrypt(text, shift), shift));

The second problem is that you may be misunderstanding your assignment. Looking at that line above, once you have encrypt working, you still have a useless decrypt option: it will always give you back the message you enter. What I think you want to be doing is to just decrypt the message, with the user passing in an already encrypted message. But, that's just my hunch, and you might want to check with your instructor on that.


text:
Q: SQL Server: BACKUP MASTER KEY produces different output every time I ran this on a new DB:
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '27c381e5-27cf-483f-81bf-143845911a5f';

BACKUP MASTER KEY TO FILE = 'c:\temp\key1.key'
ENCRYPTION BY PASSWORD = '27c381e5-27cf-483f-81bf-143845911a5f'

BACKUP MASTER KEY TO FILE = 'c:\temp\key2.key'
ENCRYPTION BY PASSWORD = '27c381e5-27cf-483f-81bf-143845911a5f'

However, the backups are different:
C:\Windows\system32>type c:\temp\key1.key | md5sum
702f95c38ea9b740ebaa7e186b9c12ec *-

C:\Windows\system32>type c:\temp\key2.key | md5sum
31906913d9d7c15fc1ba90a9635fee52 *-

I did hex-dumps, too, and the files aren't remotely similar.
Can someone explain this behavior? I'm trying to do a backup and restore and I can't seem to figure out how this process is supposed to work. The restores are failing and it appears that I can't even figure out what's going on with the backup.

A: TL;DR:
It is normal for cipher text to be different on each encryption, all other things being equal. I believe this is intentional "randomisation" of the output in order not to make password guessing easier. (The signature, however, will always be the same.)
If you will look at your DMK backup files' contents side by side, you will see that the first 40-60 bytes have almost identical structure (same amounts of spaces in the same places, for instance); only some data differ. This is a header where the salt, among other things, is located. Salt doesn't need to be hidden; it only needs to be random.

Now about the errors you receive during the restore which, for some reason, cannot be made known. I have created the test environment and two DMK backups just as you did. In addition, in order to make things a bit more realistic, I created a certificate without specifying the encryption password:
create certificate [TestCert] authorization [dbo]
    with subject = 'DMK Restore Test certificate';

This means that the certificate private key will be encrypted using the DMK, so now we have some encrypted data. If I try to restore the DMK from its first backup:
restore master key from file = 'D:\Tests\Key1.dmk'
    decryption by password = 'asdfdgkjh98hvio'
    encryption by password = 'nmbneknfownoih';

SSMS outputs the following message (not an error, mind you):

The old and new master keys are identical. No data re-encryption is required.

The key is currently open, because it's a default behaviour, and no differences are detected. Trying to create a signature using our cert proves that data encrypted by DMK (cert's private key) is accessible:
select signbycert(cert_id('TestCert'), 'ASDfgh');

(You will see some varbinary(128) output for the above).
However, if I turn off the key auto-opening by removing its copy from the master, which is a common scenario when you restore the database backup:
alter master key drop encryption by service master key;

and then try to restore using the same restore master key statement as above, there will be an error, indeed:

Msg 15329, Level 16, State 30, Line 1
The current master key cannot be decrypted. If this is a database
  master key, you should attempt to open it in the session before
  performing this operation. The FORCE option can be used to ignore this
  error and continue the operation but the data encrypted by the old
  master key will be lost.

The keys (existing and the one being restored) are still the same, but this time SQL Server can't see it - the DMK is closed. Trying to sign using the cert returns NULL for the same reason. Note the mentioning of the FORCE option. If I add it:
restore master key from file = 'D:\Tests\Key1.dmk'
    decryption by password = 'asdfdgkjh98hvio'
    encryption by password = 'nmbneknfownoih'
    force;

the result is, again, just an informational message:

The current master key cannot be decrypted. The error was ignored
  because the FORCE option was specified.

The only thing left to get your data back is to either explicitly open the DMK, or turn its auto-opening back on:
open master key decryption by password = 'nmbneknfownoih';
go
-- And if you need it to be always available in the future
alter master key add encryption by service master key;
go

After that, certificate signing starts to work again (and will return exactly the same binary data as it did the first time).


text:
Q: Java. Странное поведение Calendar Я использую такой синтаксис:
 System.out.println(calendar.get(Calendar.DAY_OF_MONTH));

И все работает верно выводит 21 и сегодня 21е число.
Но когда я посылаю:
System.out.println(calendar.get(Calendar.MONTH));

Мне печатает 11 хотя сейчас 12-ый месяц.
Почему это происходит, как исправить? Помогите пожалуйста.

A: Попробуйте использовать GreagorianCalendar, наследника от Calendar


text:
Q: Change the visibility of a react component Hi the following code should modify the visibility of a react component depending on whether or not a button is clicked, this when a button is clicked the first element  must disappear and I have to appear the second, but this does not happen what is this due to?
React code:
import React from "react";
import styled from "styled-components";
import image from "../../assets/img/calc.png";
import CalculatorContainer from "./CalculatorDraggable/index";

class DraggableCalculator extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isCalculatorVisible: false };
  }
  enable() {
    console.log("Make calculator visibile");
    this.setState({
      isCalculatorVisible: true,
    });
  }
  render() {
    return (

        {this.state.isCalculatorVisible == true ? (
          <CalculatorContainer />
        ) : (

        )}
        <Container onClick={this.enable}>

        </Container>

    );
  }
}

export default DraggableCalculator;

const Container = styled.div`
  border-radius: 25px;
  border: 2px solid #73ad21;
  padding: 20px;
  width: 200px;
  height: 200px;

  /* background-color: var(--cLight2);
  border: 5px solid var(--cMain); */
  border-radius: 50%;
  margin-left: auto;
  margin-top: 30px;
  margin-right: auto;
  cursor: pointer;

  // @MEDIA TABLET LANDSCAPE
  @media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
    width: 100px;
    height: 100px;
  }

  img {
    max-width: 100%;
    max-height: 100%;
  }
`;

A: It looks like the enable function doesn't have the this of the class component bound to it, it throws an error TypeError Cannot read properties of undefined (reading 'setState').
Either bind this to it in the constructor
constructor(props) {
  super(props);
  this.state = { isCalculatorVisible: false };
  this.enable = this.enable.bind(this); // <--
}

or convert to an arrow function so it happens automatically
enable = () => {
  console.log("Make calculator visible");
  this.setState({
    isCalculatorVisible: true,
  });
}

A: Your code is not working because "this" is undefined inside the enable() function. It so because React component (DraggableCalculator, in your case) does not auto-bind its methods to itself.
Hence you have to bind any method yourself inside the constructor, like this for your case:
constructor(props) {
    super(props);
    this.state = { isCalculatorVisible: false };

    this.enable = this.enable.bind(this);
}


text:
Q: java reflection getFields for private member| accessing object name value dynamically I want to print all of the class's properties with their name and values.  I have used reflection, but getFields give me length of 0.
RateCode getMaxRateCode = instance.getID(Integer.parseInt((HibernateUtil
            .currentSession().createSQLQuery("select max(id) from ratecodes")
            .list().get(0).toString())));
for (Field f : getMaxRateCode.getClass().getFields()) {
            try {
                System.out.println(f.getGenericType() + " " + f.getName() + " = "
                        + f.get(getMaxRateCode));
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
}

RateCode.java
    private Integer rateCodeId;
    private String code;
    private BigDecimal childStay;
    private DateTime bookingTo;
    private Short minPerson;
    private Boolean isFreeNightCumulative = false;
    private boolean flat = false;
    private Timestamp modifyTime;

A: Class.getFields() only gives you public fields.  Perhaps you wanted the JavaBean getters?
BeanInfo info = Introspector.getBeanInfo(getMaxRateCode.getClass());
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
    System.out.println(pd.getName()+": "+pd.getReadMethod().invoke(getMaxRateCode));

If you want to access the private fields, you can use getDeclaredFields() and call field.setAccessible(true) before you use them.
for (Field f : getMaxRateCode.getClass().getDeclaredFields()) {
    f.setAccessible(true);
    Object o;
    try {
        o = f.get(getMaxRateCode);
    } catch (Exception e) {
        o = e;
    }
    System.out.println(f.getGenericType() + " " + f.getName() + " = " + o);
}

A: getFields only returns public fields.  If you want all fields, see getDeclaredFields


text:
Q: Google Maps API v2 displaying maps only on one device We are using the same API key in the manifest file, which is obtained from the the SHA-1 fingerprint but it is displaying map only on one device(the first device to run it) and not on other devices. We are also using FragmentActivity. So what could be the problem. Please help guys

A: Change your max sdk ver to 18 (android 4.3). I suppose this is the device that fail.
An other option - If you use the developers SHA-1 (the one you generate from adb) and you  instaled the app on the devices from the difrent computers computer, then I assume you need to get the SHA-1 fingerprint for the other computer.


text:
Q: Retrieving a variable number of rows using a table join This is an addition layer of complexity on another question I asked here: Using GROUP BY and ORDER BY in same MySQL query
Same table structure and problem, except this time imagine that the past_election table is now set up as...
| election_ID | Date       | jurisdiction   | Race          | Seats |
|-------------|------------|----------------|---------------|-------|
| 1           | 2016-11-08 | federal        | president     | 1     |
| 2           | 2016-11-08 | state_district | state senator | 2     |

(last record has seats set as 2 instead of 1.)
I want to use the Seats number to grab different numbers of records, ordered by the number of votes, for each group. So in this case with the following additional tables...
candidates
| Candidate_ID | FirstName | LastName | MiddleName |
|--------------|-----------|----------|------------|
| 1            | Aladdin   | Arabia   | A.         |
| 2            | Long      | Silver   | John       |
| 3            | Thor      | Odinson  | NULL       |
| 4            | Baba      | Yaga     | NULL       |
| 5            | Robin     | Hood     | Locksley   |
| 6            | Sherlock  | Holmes   | J.         |
| 7            | King      | Kong     | Null       |

past_elections-candidates
| ID | PastElection | Candidate | Votes |
|----|--------------|-----------|-------|
| 1  | 1            | 1         | 200   |
| 2  | 1            | 2         | 100   |
| 3  | 1            | 6         | 50    |
| 4  | 2            | 3         | 75    |
| 5  | 2            | 4         | 25    |
| 6  | 2            | 5         | 150   |
| 7  | 2            | 7         | 100   |

I would expect the following output:
| election_ID | FirstName | LastName | votes | percent |
|-------------|-----------|----------|-------|---------|
| 1           | Aladdin   | Arabia   | 200   | 0.5714  |
| 2           | Robin     | Hood     | 150   | 0.4286  |
| 2           | King      | Kong     | 100   | 0.2857  |

I've tried setting a variable and using that with a LIMIT statement but variables don't work in limits. I've also tried using ROW_NUMBER() (I'm not using MySQL 8.0 so this won't work but I'd be willing to upgrade if it did) or a related workaround like @row_number := IF ... and then filtering based on the row number but nothing has worked.
Last tried query:
SELECT pe.election_ID as elec,
       pe.Seats as s,
       pecs.row_num,
       c.FirstName,
       c.LastName,
       pecs.max_votes AS votes,
       pecs.max_votes / pecs.total_votes AS percent
FROM past_elections pe
JOIN `past_elections-candidates` pec ON pec.PastElection = pe.election_ID
JOIN (SELECT PastElection,
             Candidate,
             @row_num := IF(PastElection = @current_election, @current_election + 1, 1) as row_num,
             MAX(Votes) AS max_votes,
             SUM(Votes) AS total_votes,
             @current_election := PastElection
      FROM `past_elections-candidates`
      GROUP BY PastElection) pecs ON pecs.PastElection = pec.PastElection AND pecs.row_num <= pe.Seats
JOIN candidates c ON c.Candidate_ID = pec.Candidate

A: Use MySQL 8 regardless ;)
Use ROW_NUMBER to order the past elections:
SELECT *, ROW_NUMBER() OVER(PARTITION BY pastelection ORDER BY votes DESC) as rown
FROM `past_elections-candidates`

Join this to past_elections as a subquery (this is just the bit you're stuck on with the "using pe.seats to vary the number of rows returned per election" and doesn't include the percent bits:
SELECT *
FROM
  past_elections pe
  INNER JOIN
  (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY pastelection ORDER BY votes DESC) as rown
    FROM `past_elections-candidates`
  ) pecr
  ON pecr.pastelection = pe.electionid AND
     pecr.rown <= pe.seats

If you want to test things out on 8 before you upgrade, loads of the db fiddle sites support v8
ps; percent-y stuff can be done at the same time as the ROW_NUMBER with eg:
votes/SUM(votes) OVER(PARTITION BY past_election)

eg for election ID 1 that sum will be 200+100+50, giving 200/350 = ~57%
SELECT *, votes/SUM(votes) OVER(PARTITION BY past_election) as pcnt, ROW_NUMBER() OVER(PARTITION BY pastelection ORDER BY votes DESC) as rown
FROM `past_elections-candidates`

You need to calc it before filtering

A: I don't have the right fields listed but this is as close as I'll probably get tonight... I've gotten the rows I need but need to join the candidate table to get the name out...
Using Dense_Rank seems to work for this...
SELECT * FROM (
  SELECT pec.PastElection,
         c.FirstName,
         c.LastName,
         pec.Votes,
         pecs.totalVotes,
         pe.Seats as s,
         DENSE_RANK() OVER(PARTITION BY PastElection ORDER BY Votes DESC) as rank_votes
  FROM `past_elections-candidates` pec
  JOIN (SELECT PastElection,
               Max(Votes) as maxVotes,
               Sum(Votes) as totalVotes
        FROM `past_elections-candidates`
        GROUP BY PastElection) pecs ON pecs.PastElection = pec.PastElection
  JOIN `past_elections` pe ON pec.PastElection = pe.election_ID
  JOIN candidates c ON c.Candidate_ID = pec.Candidate
) t WHERE rank_votes <= s;

This results in
| PastElection | FirstName | LastName | Votes | totalVotes | s | rank_votes |
|--------------|-----------|----------|-------|------------|---|------------|
| 1            | Aladdin   | Arabia   | 200   | 350        | 1 | 1          |
| 2            | Robin     | Hood     | 150   | 350        | 2 | 1          |
| 2            | King      | Kong     | 100   | 350        | 2 | 2          |

I guess it's just kind of messy having the rank_votes and s columns in the data, but that's honestly fine with me if it gets the results I need.


text:
Q: Criptografar uma string em python Gostaria de saber se existe algum algoritmo de criptografia onde é possivel escolher qual a chave ou parte dela que sera usada para criptografar/descriptografar a mensagem
Um exemplo:
mensagem = 'string qualquer'

chave = 'chave escolhida'

mensagem_encriptada = encrypt(mensagem, key = chave)

print(mensagem_encriptada)

mensagem_recuperada = decrypt(mensagem_encriptada, key = chave)

print(mensagem_recuperada)

Saida esperada seria essa:
(uma string qualquer como dfg1tre*vf2d3jnh&&^/vfdfhgf34@@cfr%ws76z!)string qualquer

A: Você pode usar alguma biblioteca para fazer a criptografia. Tem várias bibliotecas, como a pycrypto, cryptocode e etc. Tem dezenas de bibliotecas por aí.
Um exemplo simples desse seu mesmo programinha usando a biblioteca cryptocode:
import cryptocode

chave = "423338233093093"
mensagem = "Esta eh a minha mensagem! :)"

MensagemCriptografada = cryptocode.encrypt(mensagem, chave)
print("Sua mensagem criptografada: " + MensagemCriptografada)

MensagemDescriptografada = cryptocode.decrypt(MensagemCriptografada, chave)
print("Sua mensagem descriptografada: " + MensagemDescriptografada)

A saída será:

Sua mensagem criptografada: gSjdIssy9DOYfPnACctSaoNn4/VcTRzlLYh4PQ==*dv9iN+Uwsad+v8QMBUgF7A==*4G2FKJ2n+WJxwak9LpyaWw==*lvCp3brLC0nJVd1g4lf3Vg==
Sua mensagem descriptografada: Esta eh a minha mensagem! :)

A: Depende da criptografia  simétrica ou assimétrica.
Há bibliotecas que auxiliam a criar uma boa criptografia  usando AES e a RSA.
um simples exemplo usando a função xor:
Quanto maior a chave mais segura sera, quanto menor  mais fácil sera para identificar a mensagem
import string
import random

chave = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits + '^!\$%&/()=?{[]}+~#-_.:,;<>|\\') for _ in range(0, 1024))

print(chave)

mensagem = 'python'

print("Msg: " + mensagem + '\n')

def str_xor(s1, s2):
    return "".join([chr(ord(c1) ^ ord(c2)) for (c1, c2) in zip(s1,s2)])

secreta = str_xor(mensagem, chave)

print("Mensagem secreta :"+secreta + "\n")

recuperando_mensagem_secreta = str_xor(secreta, chave)
print("Mensagem descriptografada " + "\n" + recuperando_mensagem_secreta + "\n")

A cada vez que o código for iniciado uma nova criptografia sera criada


text:
Q: Add track points in layer I have a shape file and I want to add a layer which includes the track points (x coordinate , Y - coordinate for the attribute table). I need the tracks for identifying the buidlings and for calculations.

This is what it looks like.
And the following picture shows what I need, the red dots are the track points. I got them from OSM by adding tracks and track points out of a GPX. The other file wasn't a GPX and I couldn't select adding track points as I added this layer.

A: You can use Extract vertices tool to get the corner points of the polygon shapefile, then use Add geometry attributes to add the x and y coordinates of the corner points.
Extract vertices tool is located in Processing toolbox -> Vector geometry -> Extract vertices tool. Add Add geometry attributes tool is located from Vector main menu -> Geometry tools -> Add geometry attributes.
Please note that using extract vertices tool you will get 5 vertices for each polygon, the first and fifth vertices are same in order to close the polygon shapefile. If you want to remove the duplicate points, you need to use Remove duplicate vertices tool from Processing toolbox -> Vector geometry -> Remove duplicate vertices


text:
Q: Angular directive to load JS files for the other directives I'm trying to minimize js/css/html footrpint for the user and to load only the files really needed. I've utilized RequireJS for that.
For my templates I'm trying to implement someting similar to
using section in C# or ///< reference path='...' > in TypeScript
But somehow depending on my template content it does or doesn't instantiate depends-on directive depending on template I have:
Works:
<depends-on path="..\..\test"></depends-on>
<login-form></login-form>

Doesn't work:
<depends-on path="..\..\test"></depends-on>
<login-form></login-form>
<other-directive></other-directive>

Doesn't work:
  <div>
     <depends-on path="..\..\test"></depends-on>
     <login-form></login-form>
  </div>

I'm obviously missing the way Angular parses and processes templates.
Is there a way to achieve what I'm trying to do?

A: OK, the problem was that it didn't wait until all directive template depends on are loaded. To ensure dependencies are loaded, dependent code should be in callback passed to require function.


text:
Q: MSDOS API serial port only reading last sent character I've been playing with the MSDOS API in assembler for some time and I'm trying to build an application to read/write from the serial port. I'm currently using VMware Workstation 11 + VSPE (http://www.eterlogic.com/Products.VSPE.html) to emulate the serial port communication.
One thing I noticed is that if I send let's say "asdfgh" into the serial port and then read it in MSDOS (Using interrupt 21h function 03h, but I also tried interrupt 14h function 02h), it only returns the last character read: "h"
According to some documentation I read, if an application sends data faster than I can process it, characters will be lost, which means that either there is another way to make MSDOS save bytes to a buffer (controlling flow) or I have to write a driver that does this (or maybe a TSR program that manages this I dunno).
So the question is, do I have to write a driver or is there another way to do this?

A: I managed to write a program that turns on the 16550 FIFO buffer and now It works using the DOS API.
So it was just the FIFO buffer
No need to slow down the baud rate or whatsoever. Nonetheless, if one happen to have a 8250 it's probably either that or implement a communications driver on top of it
Also, this helped a lot:
https://en.wikibooks.org/wiki/Serial_Programming/8250_UART_Programming#UART_Registers


text:
Q: loading a SWC asset by variable name I am trying to load assets from an SWC into a SWF at compile time, in as3. I'm getting the information about which assets to load from a JSON file. I can do so statically, but when I try to define the names dynamically, I'm running into problems.
So for example I can do this:
onemech[+ tmpObj.id] = new mech3 as MovieClip;

And it loads the asset named mech3. But what I would like to be able to do is something like
var mechtype:String = "mech" + mechtypenumber;
onemech[+ tmpObj.id] = new mechtype as MovieClip;

Obviously, that doesn't work.
I looked around a bit and I found this here, which seems to be angling toward what I need, but I can't figure out how to apply what's said there to my specific situation.
For the record, I have control over both the JSON format and the naming schema within the asset SWC, if there's an easier solution there.
Thanks in advance for any assistance.

A: you just need something like this:
var s:Class = getDefinitionByName("Symbol") as Class;
addChild(new s());


text:
Q: Return a list if entries who exist and not exist I have a list of network-devices in a database-table. Users can get misc information about those devices using a web-interface (ends up in the query as WHERE hostname IN('hostname1','hostname2',...)). Let's say one of the five given entries is wrong because of a misspelling. So normally i get four answers from the database-query, the wrong one will be still ignored. I need to detect that not existing entry to give the user a hint like:
hostname1 exist -> requested Information
hostname2 exist -> requested Information
hostname3 NOT EXIST
hostname4 exist -> requested Information
hostname5 exist -> requested Information

I ran out of ideas with the EXISTS Option. Thanks in Advance!

A: I find only one solution after create a temporary table "search", suppose to containts one column named "hostname" with value. I do not find a way to convert a list of values ('hostname1' , 'hostname2', 'hostname4') into a list of record. So a temporary table of one column here:
table "search" column "hostname"
hostname1
hostname2
hostname4

Here the creation of the "search" table:
CREATE TEMPORARY TABLE IF NOT EXISTS search AS  SELECT 'hostname1' as hostname from host union SELECT 'hostname2' as hostname  from host union  select 'hostname4' as hostname  from host

Then a left join on a column:
CREATE TEMPORARY TABLE IF NOT EXISTS search AS  SELECT 'hostname1' as hostname from host union SELECT 'hostname2' as hostname  from host union  select 'hostname4' as hostname  from host; select * from search left join host ON host.hostname = search.hostname;

This is the output columns (hostname,id,hostname):
hostname1   1   hostname1
hostname2   2   hostname2
hostname4   NULL    NULL

In my case, hostname4 does not exist into the initial table host so that a way to detect an incorrect value with the id column of the result for example.


text:
Q: Unchecking a Previously Selected Checkbox when another checkbox is checked My form has 3 checkboxes available to the User. When the User mistakenly checks one Checkbox and realizes the mistake then checks the correct Checkbox, I need the incorrect checked Checkbox to Uncheck automatically.
I have diligently searched the web but have been unable to find any sites that offer answers for VB 2010. Mostly they provide solutions for HTML, Excel, Java, etc.
Private Sub BeginnerForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    StartupForm.Close()

    If Me.CheckBox1.Checked Then
        Me.CheckBox2.Checked = False
        Me.CheckBox3.Checked = False
    ElseIf Me.CheckBox2.Checked Then
        Me.CheckBox1.Checked = False
        Me.CheckBox3.Checked = False
    ElseIf Me.CheckBox3.Checked Then
        Me.CheckBox1.Checked = False
        Me.CheckBox2.Checked = False
    End If
End Sub

The results of this code is that it does not uncheck the Checkbox(es). I get no error code, it just does not UNCHECK the Checkbox(es). I have also tried other code entries such as Me.Checkbox2.CheckState.Checked = CheckState.Unchecked to no avail. Trusting you can steer me in the right direction to UNCHECK a Checkbox when another Checkbox is CHECKED.

A: First of all, as mentioned by daShier, you place the code in the wrong event handler. Since you want to uncheck the other checkboxes when one is being checked, you must put the code in the either Click or CheckChanged event handler of all your checkboxes that take part in this selection logic. I would suggest to put in the CheckChanged event since it will be triggered even when your checkbox check state is changed through code in addition to through mouse or keyboard actions.
' declare variable to keep track of the previous selected checkbox
Dim prevSelectedCheckBox As CheckBox

' all checkboxes to be controlled are handled by this event handler
Private Sub CheckBoxes_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, CheckBox3.CheckedChanged
    ' first, identify which checkbox is triggering this event
    Dim this As CheckBox = DirectCast(sender, CheckBox)

    ' if this event is triggered when this checkbox is being checked
    If this.Checked Then
        ' if there is a checkbox previously selected/checked
        If prevSelectedCheckBox IsNot Nothing Then
            prevSelectedCheckBox.Checked = False ' uncheck it
        End If

        ' now this checkbox is currently the checked one, save it to the variable
        prevSelectedCheckBox = this

    ' if event is triggered by unchecking this checkbox, and this checkbox is the previously checked checkbox
    ElseIf this.Equals(prevSelectedCheckBox) Then
        ' clear the variable since now, there is no checkbox is being checked
        prevSelectedCheckBox = Nothing

    End If
End Sub

However, if user can only select one option among the options represented by the checkboxes, you better use radio button instead.

A: It appears you are processing the code in the wrong handler. You are changing things when closing the form. Try moving the code to the CheckBoxx.CheckedChanged handlers:
    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        If CheckBox1.Checked Then
           CheckBox2.Checked = False
           CheckBox3.Checked = False
    End Sub

UPDATE: I realize that your original code that I copied and pasted would cause a loop since the changing of the checkbox states would trigger the other routines. It's not necessary since you only need clear the other boxes if the box your user is clicking is checked.
You will need to add similar code to CheckBox2.CheckedChanged and CheckBox3.CheckedChanged as well.
Also, I should point out that you are trying to make checkboxes act as radio buttons. Why not replace the checkbox controls with radio buttons instead so that VB handles the one-only behavior for you?


text:
Q: Disabled highlighting and copy content from HTML page, except the content in textfield? I would like to prevent copy function in html page.
And I see this topics already.
Now, I am Done and complete  it.
This is code I have used
<script type='text/javascript'>
    document.ondragstart = function() { return false; };

</script>
<style type='text/css'>
body
{
    -webkit-touch-callout: none;
    -webkit-user-select: none; /* Webkit */
    -moz-user-select: none;    /* Firefox */
    -ms-user-select: none;     /* IE 10  */
    /* Currently not supported in Opera but will be soon */
    -o-user-select: none;
    user-select: none;
}
</style>

This code can disabled  copy content from all element and working well in IE,Chrome and FF
But, my client still want to copy content from any input filed (type=text,textarea)
So
1 ) How to make text field ,textarea only be able to copy content ?  And other element still disabled copy content function
Thank you.
And Sorry, for my bad skill in english.

A: Advise your client that once content is served up on the browser, there is no way to protect it. Once it's on the client, it's completely vulnerable. All the suggested prevention measures are silly and futile. Even if you wrap it in a .swf and obfuscate the ActionScript, anybody who wants it can get it.
The answer is to stop and guide your client not bend at their ignorant will.
No offense.


text:
Q: How do I simplify this fraction? if i have ${X^{5/2}}$ all over $\dfrac{5}{2}$, how do I simplify? I have tried a couple of different ways but for the life of me I cannot get past this one. I would really appreciate any help given, sorry for the poor format of the question.

A: Recall that $a\div b=a\cdot \frac{1}{b}$ so that you have:
$$\frac{x^{2.5}}{5/2}=x^{2.5}\div\frac{5}{2}={x^{5/2}}\cdot\frac{2}{5},$$
leaving $\dfrac{2x^{5/2}}{5}$. Is this clear?


text:
Q: Optimizing database queries in unit testable code So let's say you're writing software for some company. Best practices, as I understand them, would dictate that for dev purposes, you populate your DB with fake data. There are a number of benefits to this.

*

*If you're going to be using, say, Vagrant to manage your dev environment, most of the pre-built images have HDD's of a limited size. Like let's say production has 100's of GB of data. Your Vagrant box isn't likely going to be that big. Also, if you're doing continuous integration testing, you're probably not gonna want to do it with a production size DB.

*In theory, developers ought not have personally identifiable info of real world customers and this facilitates that.
One big problem I see with this, however, is...  let's say your dev DB is, all together, maybe 1MB in size, whilst production is 100's of GB in size. A developer might write a query that JOINs tables together on unindexed columns. Maybe with 1MB of data it works great but with 100's of GB of data?
How is one supposed to deal with this problem?
(for that matter, there can sometimes be an excessive amount of red tape to cut through to get production data to accurately reproduce an issue specific to a customer, but that's an organizational problem - not a technical one)

A: This question has nothing in common with "unit testing", it is not caused by unit testing, cannot be detected and obviously not solved by "unit testing".
Having applications facing bigger data sets in production than expected during development is a really old problem (I guess >50 years old). It is in no way restricted to databases and database queries, and the same is true for the tactics to deal with it:

*

*Make proper planning and estimation for the data you expect in production.

*Profile with smaller datasets and extrapolate for the bigger ones you expect (and make sure you do not extrapolate in a linear fashion when the order of growth is quadratic or worse).

*Test properly and make sure your program can give you also profiling information  when it runs in production.

*Make sure you do not pick an architecture which brings you into a dead end for the expected amount of data.

*Optimize as needed - start with optimizing when you have indicators for performance problems, but not earlier. Make sure your devs know what "premature optimization" means and that they do not optimize the wrong parts of the code "just in case".

*Make sure you have educated, experienced devs and/or db experts working on the critical parts of the application. Writing good software is not a beginners game.

A: In an ideal world:
You let database administrators deal with that. They have the tools and the background to make the right decisions about what and what not to index.
In a less then ideal world there are a few things you can do, among those:
1: Be sensible.
Don't use a "select *" and if you do a "select personid from persons where somecondition = x", you may find an index on somecondition good, unless of course if you do 10.000 insert/second on the table.
2: Let your application do the profiling.
SQL server for instance has some nice ways to find missing indexes and database performance in general.
SQL server for instance has built in functionality to find missing indexes and it's on by default: Find missing indexes in SQL server.

A: How is one supposed to deal with this problem?
Build out a performance test environment.  Populate a database with 100s of GBs of test data.  Use bulk load techniques to populate the database quickly.  Then performance test your application.  Verify the indexes and queries are performing correctly with this amount of data.  If not, add or re-organize your indexes appropriately.
Always take a look at how much data your system will have [N] years from now.  Develop a purge/pruning strategy.  Test your queries against your planned high water marks to avoid potential performance problems in the future.

A: *

*Build Tests  Ideally, you shouldn't be pushing out code live if it hasn't passed some type of build test, and the build test should be smart enough to detect massive changes in performance.

*Get a DB Admin  Database Administrators will know how to make smart indexes on tables.

*Good Code Practices  Companies with large datasets should be implementing some type of code standards or practices for exactly this type of reason.

A: Stored Procedures
If you are at a stage where you have a critical db which can be taken out by bad queries then you need to get a bit more professional than just putting the sql into the code.
Having all DB queries use SProcs gives you that extra layer of abstraction which is required to allow you to tweak your queries for performance as your database evolves.


text:
Q: how do I get curl to save a file to a specified directory? I'm trying to get curl, using a script, to download a file and save it to a certain directory. I got it to download but I dont know how to get it to a certain directory from a script. It usually just saves it to the current working directory.

A: curl http://google.com > /path/to/dir/index.html

A: Let curl and the shell each do what they do well:
(cd TARGET_DIRECTORY && curl ...)

Also there may be things that interest you in the description of the -o option in the manual.

A: CORRECTION:
You can use
-o, --output FILE    Write output to instead of stdout
curl --url https://google.com --output /any/file-location


text:
Q: Javascript changing several divs classes, tabbed content I am making some tabbed content, I have the tabs inline and overlapping each other slightly, meaning they have three states: inactive tab ("it" class), active tab ("at" class) and trailing tab ("tt" class) which follows the active tab. In the code sample below, tab three is active and tab four is the trailing tab as it comes after it.

Tab One

Tab Two

Tab Three

Tab Four

Tab Five

I'm a total newbie to JavaScript I'd like each tab when clicked to:
1. change all the other tabs classes to "it",
2. change the current, clicked tab class to "at" and
3. change the next tabs class to "tt" if one exists.
From research on the net, I understand that these are the functions I want roughly:
document.getElementById('tab').nextSibling;
document.getElementById('tab').className = "it";

I just don't know how to call a function and stich it up together. Sorry for the complicatedness of this, if it's impossible to call the next div/tab and change its class solely then don't worry, could you just help me change the selected tabs class and all the others please? Thanks in advance.

A: See http://jsfiddle.net/E7jnq/1/ for a jQuery implementation, or http://jsfiddle.net/ryMH3/ for a vanilla JS implementation.
jQuery:
$(document).ready(function()
{
    $('#tabnest a').click(function()
    {
        $(this).parent().parent().find('div').removeClass('at').removeClass('tt').addClass('it'); // Set everything to 'it'
        $(this).parent().addClass('at'); // Set this div to 'at'
        if ($(this).parent().next('div').length > 0)
        {
            $(this).parent().next('div').addClass('tt');
        }
    });
});

Vanilla JS:
var tabNest = document.getElementById('tabnest');
var tabs = getElementsByClassName('tab');

for (i = 0; i < tabs.length; i++)
{
    addEventListener(tabs[i], 'click', function ()
    {
        for (i = 0; i < tabs.length; i++)
        {
            if (tabs[i] == this)
                this.className = 'tab at';
            else if (tabs[i - 1] == this)
                tabs[i].className = 'tab tt';
            else
                tabs[i].className = 'tab it';
        }
        this.className = 'tab at';

    }, false);
}

function getElementsByClassName(classname, node)
{
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))
            a.push(els[i]);
    return a;
}

function addEventListener(element, eventType, handler, capture)
{
    if (element.addEventListener)
        element.addEventListener(eventType, handler, capture);
    else if (element.attachEvent)
        element.attachEvent("on" + eventType, handler);
}

A: First, you cannot re-use an id.  An element id must be unique.  Use class for that.  I would suggest giving each tab a class of tab always.  Then give the active tag an additional class of "active" and for the trailing tab, use the adjacent sibling selector (+).  Ie, .active + .tab.
This is a great place to use jQuery.  The jQuery syntax would be:
$(function() {
    $(".tab").click(function () {
        $(".tab.active").removeClass("active");
        $(this).addClass("active");
    });
});

Drop that code into any script tag, and it'll just work.  If you don't want jQuery:
window.onload = function() {
    var tabNest = document.getElementById("tabNest");
    var tabs = tabNest.children;
    for (var i = 0; i < tabs.length; i++) {
        tabs[i].onclick = tabClick;
    }
    function tabClick (e) {
        for (var i = 0; i < tabs.length; i++) {
            tabs[i].className = tabs[i].className.replace(/\bactive\b/, "")
        }
        this.className += " active";
    }
};

A: Try this :
HTML :

Tab One

Tab Two

Tab Three

Tab Four

Tab Five

Javascript:
var atags = document.getElementsByName('tab'); //returns the array of all the element with tab as the name

for(var x=0; x<atags.length; x++){ // loops throught all the element with the name = tab
  // some code
  atags[x].className = "it";
}


text:
Q: Inverse Laplace Transform with squared irreducible quadratic in denominator using convolution theorem Please help me find the inverse Laplace transform of
$$F(s) = \dfrac{4}{(s^2+2s+5)^2}.$$
The answer I got is $\frac 1 5 (e^t - e^{-t}) \cos 2t - \frac 1 2 (e^t + e^{-t}) \sin 2t$.
I first applied the convolution theorem, then had to do integration by parts and the solution turned out to be too long is there any shorter solution for this problem, and is my answer correct??
Any help would be highly appreciated. Thanks.

A: First observe that $$F(s)=\frac{4}{\left[(s+1)^2+2^2\right]^2}$$
Let $\mathcal{L}^{-1}\left\{F(s)\right\}=f(t)$, then from the First Shifting Theorem we have
$$\mathcal{L}\left\{e^tf(t)\right\}=F(s-1)=\frac4{\left(s^2+2^2\right)^2}=\left(\frac2{s^2+2^2}\right)^2\tag{1}$$
Applying the Inverse Laplace Transform to the last equation we get, from the Convolution Theorem,
\begin{align*}
e^tf(t)&=\mathcal{L}^{-1}\left\{\frac2{s^2+2^2}\cdot\frac2{s^2+2^2}\right\}\\[4pt]
&=\int_0^t\sin 2\tau\sin 2(t-\tau)d\tau\\[4pt]\tag{2}
&=\int_0^t\frac12\left\{\cos\left[2\tau-2(t-\tau)\right]-\cos\left[2\tau+2(t-\tau)\right]\right\}d\tau\\[4pt]
&=\int_0^t\frac12\left[\cos(4\tau-2t)-\cos(2t)\right]d\tau\\[4pt]
&=\left.\frac18\sin(4\tau-2t)\right|_0^t-\frac12t\cos (2t)\\[4pt]
&=\frac18\sin(4t-2t)-\frac18\sin(-2t)-\frac12t\cos (2t)\\[4pt]
&=\frac14\sin(2t)-\frac12t\cos (2t)
\end{align*}
In the equation $(2)$ the identity $\color{red}{\sin x\sin y=\frac12\left[\cos(x-y)-\cos(x+y)\right]}$ have been used.
Then $$\boxed{\color{blue}{f(t)=\frac{e^{-t}(\sin 2t-2t\cos 2t)}{4}}}$$


text:
Q: Print out xml tags from named template I have input xml such as:
<XML>
    <A1>50</A1>
    <A2>20</A2>
    <A3>70</A3>
    <A4>90</A4>
    <A5>5</A5>
    <A6>45</A6>
    <A7>35</A7>
    <A8>25</A8>
    <A9>80</A9>
</XML>

And XSLT rule to work with it:
<xsl:template name="summfunc">
    <xsl:param name="summ"/>
    <xsl:param name="summands"/>
    <xsl:param name="output-text"/>
    <xsl:param name="output-node"/>
    <xsl:if test="format-number($summ, '#.##') !=format-number(sum($summands), '#.##')">
        <ERROR>
            30
            <TEXT><xsl:value-of select="$output-text"/></TEXT>
            <PROBLEMNODE>
                <xsl:value-of select="$output-node"/>
            </PROBLEMNODE>
        </ERROR>
    </xsl:if>
</xsl:template>

<xsl:template match="/XML">

<xsl:variable name="tests">
    <xsl:call-template name="summfunc">
        <xsl:with-param name="summ" select="//A3"/>
        <xsl:with-param name="summands" select="//A1 | //A2"/>
        <xsl:with-param name="output-text">abrakadabra</xsl:with-param>
        <xsl:with-param name="output-node" select="//A3"/>
    </xsl:call-template>

</xsl:variable>

<xsl:value-of select="$tests"/>
</xsl:template>

Summary I want to print:
        <ERROR>
            30
            <TEXT>some text</TEXT>
            <PROBLEMNODE>
                some text, containing node
            </PROBLEMNODE>
        </ERROR>

As many times, as template "summfunc" had errors. That is why I just print $tests as it is, if there were no errors, it would be empty (but maybe that is not good solution).
But it don't prints tags! I receive "30some text"  as text if there were errors, it don't print tags. When I try to put tags to xsl:text, it don't work, even if I use " or '.
How to print it right way? It perfectly prints tags if I put them between value-of select="$tests" and /xsl:template, but somehow it don't print tags if they are in named template. How to solve it?

A: If you want to "print tags", use xsl:copy-of instead of xsl:value-of
So, all you need to do is this
<xsl:copy-of select="$tests"/>

xsl:value-of is for outputting the text values of items.


text:
Q: XML Parser returns last item, not the rest my XML Content: (FileName: sku.xml)
<skus>
<id>p1</id>
<id>test</id>
<id>aa</id>
<id>bb</id>
<id>cc</id>
<id>dd</id>
<id>ee</id>
<id>ff</id>
<id>gg</id>
<id>hh</id>
<id>ii</id>
<id>jj</id>
<id>kk</id>
<id>ll</id>
</skus>

my SAX XML PARSER Class:
public class SAXXMLParser {
public static List<XMLSetAdd> parse(InputStream is) {
    List<XMLSetAdd> setAdds = null;
    try {
        // create a XMLReader from SAXParser
        XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
                .getXMLReader();
        // create a SAXXMLHandler
        SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
        // store handler in XMLReader
        xmlReader.setContentHandler(saxHandler);
        // the process starts
        xmlReader.parse(new InputSource(is));
        // get the News list`
        setAdds = saxHandler.getIds();

    } catch (Exception ex) {
        Log.d("XML", "SAXXMLParser: parse() failed");
        ex.printStackTrace();
    }

    // return News list
    return setAdds;
}

}
My SAX XML HANDLER:
public class SAXXMLHANDLER extends DefaultHandler {

    private List<XMLSetAdd> setAdds;
    private String tempVal;
    // to maintain context
    private XMLSetAdd setAdd;

    public SAXXMLHANDLER() {
        setAdds = new ArrayList<XMLSetAdd>();
    }

    public List<XMLSetAdd> getIds() {
        return setAdds;
    }

    // Event Handlers
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // reset
        tempVal = "";
        if (qName.equals("skus")) {
            setAdd = new XMLSetAdd();
        }
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        tempVal = new String(ch, start, length);
    }

    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (qName.equals("skus")) {
            setAdds.add(setAdd);
        } else if (qName.equals("id")) {
            setAdd.setId(tempVal);
        }
    }

}

my XML SetAdd:
public class XMLSetAdd {

    public String getId() {
        return Id;
    }

    public void setId(String Id) {
        this.Id = Id;
    }

    private String Id;
}

My Async Class:
private class GetXMLTask extends AsyncTask<String, Void, List<XMLSetAdd>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<XMLSetAdd> news) {

            try
            {
                for (int i = 0; i < IdsL.size(); i++)
                {
                    skusList.add(IdsL.get(i).getId());
                    Log.d("XML content",IdsL.get(i).getId());
                }

                skusQuery = new Bundle();
                skusQuery.putStringArrayList("ITEM_ID_LIST", skusList);

                GetAllSkusAsync runner = new GetAllSkusAsync();//Some Async to run after
                runner.execute();
            }
            catch (Exception ex)
            {
                Log.d("Error Reading XML: ", ex.toString());
                Toast.makeText(
                        getApplicationContext(),"Connection Error!"
                        Toast.LENGTH_SHORT).show();
            }
        }

        /*
         * uses HttpURLConnection to make Http request from Android to download
         * the XML file
         */
        private String getXmlFromUrl(String urlString) {
            StringBuffer output = new StringBuffer("");
            try {
                InputStream stream = null;
                URL url = new URL(urlString);
                URLConnection connection = url.openConnection();

                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();

                    BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
                    String s = "";
                    while ((s = buffer.readLine()) != null)
                        output.append(s);
                }
            } catch (Exception ex) {
                Log.d("Error in asyncTask XML: ", ex.toString());
                ex.printStackTrace();
            }
            return output.toString();
        }

        private List<XMLSetAdd> IdsL;

        @Override
        protected List<XMLSetAdd> doInBackground(String... urls) {
            IdsL = null;
            List<XMLSetAdd> myList = null;
            String xml = null;
            for (String url : urls) {
                xml = getXmlFromUrl(url);

                InputStream stream = new ByteArrayInputStream(xml.getBytes());
                IdsL = SAXXMLParser.parse(stream);

                myList = SAXXMLParser.parse(stream);
            }
            // stream.close();
            return IdsL;
        }
    }

The code which I use to call Async Class:
String URL = "http://someaddress/php/sku.xml";
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });

Now When I run this code and Log the result ,my list returns the last xml child which based on my xml file is "ll" and the rest of xml is not added to the file.
The list should return all of the ids but returns the last one.

A: Check following code. Edited SAX XML HANDLER.
public class SAXXMLHANDLER extends DefaultHandler {

private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;

public SAXXMLHANDLER() {

}

public List<XMLSetAdd> getIds() {
    return setAdds;
}

// Event Handlers
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
    // reset
    tempVal = "";
    if (qName.equals("skus")) {
        setAdds = new List<XMLSetAdd>();

    }else if(qName.equals("id")){
         setAdd = new XMLSetAdd();
     }
}

public void characters(char[] ch, int start, int length)
        throws SAXException {
    tempVal = new String(ch, start, length);
}

public void endElement(String uri, String localName, String qName)
        throws SAXException {
    if (qName.equals("skus")) {

    } else if (qName.equals("id")) {
        setAdd.setId(tempVal);
        setAdds.add(setAdd);
    }
}

}

A: The reason is because you are only adding items to the list when endElement is skus. You should be adding one element for each id as follows:
 public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals("skus")) {
            // setAdds.add(setAdd); // dont add here..
        } else if (qName.equals("id")) {
            setAdd.setId(tempVal); // if ending with id
            setAdds.add(setAdd); // then add id to the list
        }
 }

Update
 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // reset
        tempVal = "";
        if (qName.equals("id")) {
            setAdd = new XMLSetAdd(); // new item for each id
        }
 }

A:    @Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
    super.startElement(uri, localName, qName, attributes);
    curentElement=localName;

    if(qName.equals("skus")){
       setAdd = new XMLSetAdd();
    }
}

 @Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
    super.characters(ch, start, length);

    String value = new String(ch, start, length);
    if(curentElement.equals("id")){
        tempVal=value;
}

   @Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    super.endElement(uri, localName, qName);
    curentElement = "";
    if (localName.equals("id")) {
      setAdd.setId(tempVal);
    }else if(localName="skus"){
             setAdds.add(setAdd);
}

A: Try this way
Update your parse
public class SAXXMLHANDLER extends DefaultHandler {

    private List<XMLSetAdd> setAdds;
    private String tempVal;
    // to maintain context
    private XMLSetAdd setAdd;

    public SAXXMLHANDLER() {
        setAdds = new ArrayList<XMLSetAdd>();
    }

    public List<XMLSetAdd> getIds() {
        return setAdds;
    }

    // Event Handlers
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // reset
        if (qName.equals("id")) {
            tempVal = "";
            setAdd = new XMLSetAdd();
        }
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        tempVal = new String(ch, start, length);
    }

    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals("id")) {
            setAdd.setId(tempVal);
            setAdds.add(setAdd);
        }
    }


text:
Q: Manipulating the legend of scale_fill_gradient2 I have data which comes from a statistical test (gene set enrichment analysis, but that's not important), so I obtain p-values for statistics that are normally distributed, i.e., both positive and negative values:
The test is run on several categories:
set.seed(1)
df <- data.frame(col = rep(1,7),
                 category = LETTERS[1:7],
                 stat.sign = sign(rnorm(7)),
                 p.value = runif(7, 0, 1),
                 stringsAsFactors = TRUE)

I want to present these data in a geom_tile ggplot such that I color code the df$category by their df$p.value multiplied by their df$stat.sign (i.e, the sign of the statistic)
For that I first take the log10 of df$p.value:
df$sig <- df$stat.sign*(-1*log10(df$p.value))

Then I order the df by df$sig for each sign of df$sig:
library(dplyr)
df <- rbind(dplyr::filter(df, sig < 0)[order(dplyr::filter(df, sig < 0)$sig), ],
            dplyr::filter(df, sig > 0)[order(dplyr::filter(df, sig > 0)$sig), ])

And then I ggplot it:
library(ggplot2)
df$category <- factor(df$category, levels=df$category)

ggplot(data = df,
       aes(x = col, y = category)) +
  geom_tile(aes(fill=sig)) +
  scale_fill_gradient2(low='darkblue', mid='white', high='darkred') +
  theme_minimal() +
  xlab("") + ylab("") + labs(fill="-log10(P-Value)") +
  theme(axis.text.y = element_text(size=12, face="bold"),
        axis.text.x = element_blank())

which gives me:

Is there a way to manipulate the legend such that the values of df$sig are represented by their absolute value but everything else remains unchanged? That way I still get both red and blue shades and maintain the order I want.

A: I'm not sure I did understood what you're looking for. Do you meant that you wan't to change the labels within legends? If you want to change labels manipulating breaks and labels given by scale_fill_gradient2() shall do it.
ggplot(data=df,aes(x=col,y=category)) +
  geom_tile(aes(fill=sig)) +
  scale_fill_gradient2(low='darkblue',mid='white',high='darkred',
                       breaks = order(unique(df$sig)),
                       labels = abs(order(unique(df$sig)))) +
  theme_minimal()+xlab("")+ylab("")+labs(fill="-log10(P-Value)") +
  theme(axis.text.y=element_text(size=12,face="bold"),axis.text.x=element_blank())

For what you're looking for maybe you could display texts inside the figure to show the values, try stacking stat_bin_2d() like this:
ggplot(data=df,aes(x=col,y=category)) +
      geom_tile(aes(fill=sig)) +
      scale_fill_gradient2(low='darkblue',mid='white',high='darkred',
                           breaks = order(unique(df$sig)),
                           labels = abs(order(unique(df$sig)))) +
      theme_minimal()+xlab("")+ylab("")+labs(fill="-log10(P-Value)") +
      stat_bin_2d(geom = 'text', aes(label = sig), colour = 'black', size = 16) +
      theme(axis.text.y=element_text(size=12,face="bold"),axis.text.x=element_blank())

You might want to give the size and colour arguments some tries.

A: If you check ggplot's documentation, scale_fill_gradient2, like other continuous scales, accepts one of the following for its labels argument:

*

*NULL for no labels

*waiver() for the default labels computed for the transofrmation object

*a character vector giving labels (must be same length as breaks)

*a function that takes the breaks as input and returns labels as output
Since you only want the legend values to be absolute, I assume you're satisfied with the default breaks in the legend colour bar (-0.1 to 0.4 with increments in 0.1), so all you really need is to add a function that manipulates the labels.
I.e. instead of this:
scale_fill_gradient2(low = 'darkblue', mid = 'white', high = 'darkred') +

Use this:
scale_fill_gradient2(low = 'darkblue', mid = 'white', high = 'darkred',
                     labels = abs) +


text:
Q: How to get pyplot to put multiple lines in one figure I'm trying to replace plt.hold() which accumulates lines in a figure.
Research: Several posted suggestions to this issue say to use multiple
plt.plot(x,y) commands followed by plt.show(). On my system (Python 3.6) that
prints only the content of the last plt.plot() call.
import matplotlib.pyplot as plt
import numpy as np
t = np.linspace(0, 2*np.pi, 400)
a = np.sin(t)
b = np.cos(t)

plt.plot(t, a, 'b')
plt.show()

Adding another plt.plot() call clears the first line
plt.plot(t, a, 'b')
plt.plot(t, b, 'g')
plt.show()

A method that works is to put them all in one plt.plot() call.
plt.plot(t, a, 'r--', t, b, 'b')
plt.show()

But I have five lines with labels to plot so this would be a long, hard-to-read
argument list.
How can I define each of the lines individually for one figure?


text:
Q: Xcode enforcing App extension API only, but I'm not writing an extension or using extension features I've been working on an app since iOS 7, and updated it from 7->8 without a problem, now I'm going to 9 and Xcode is telling me I'm using methods not allowed in an app extension but I'm not writing something constricted to an app extension api.
'sharedApplication' is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead.
I've had the app running on simulator and device for iOS 9.  This just randomly happened the other day.
Ideas?

A: If you don't have any app extensions, just uncheck "Allow app extension API only" box under Deployment Info in the General tab of the project settings for your target.
It's odd that it got checked in the first place though. I wonder what happened.


text:
Q: Retrieve one record for each column irrespective of number records in the table I want to select one record with two joins.
I have following query:
$this->db
        ->select('vehicle.idvehicle, vehicle.mark, vehicle.model, vehicle.type, vehicle.author_id, users.nick, photos.name')
        ->from('xxxxxsld_auto.vehicle')
        ->join('users', 'vehicle.author_id = users.userid')
        ->join('photos', 'vehicle.idvehicle = photos.vehicle_id')
        ->get()
        ->result_array();

It works fine, but if I have more photos in DB, I get more more records, it depends of photos record.
What should I do to receive one record for each vehicle irrespective of number record in photos table?
Edit: LIMIT and DISTINCT didn't work.

A: You can use GROUP_CONCAT and SUBSTRING_INDEX to pick one photo, if you want all the photos you can just use GROUP_CONCAT(photos.name) AS photo and you can get all the photos name by comma seperated list ,i have used ->group_by('vehicle.idvehicle'); so for one vehicle group all the photos will be merged by comma but as in your question you stated you need the one photo so i used the SUBSTRING_INDEX  you can also get the latest photo by using the ORDER by in GROUP_CONCAT if photo id is auto incremented like SUBSTRING_INDEX(GROUP_CONCAT(photos.name ORDER BY photo.id DESC),',',1) AS photo
$this->db
        ->select("vehicle.idvehicle, vehicle.mark,
         vehicle.model, vehicle.type, vehicle.author_id, users.nick,
         SUBSTRING_INDEX(GROUP_CONCAT(photos.name),',',1) AS photo,",FALSE)
        ->from('xxxxxsld_auto.vehicle')
        ->join('users', 'vehicle.author_id = users.userid')
        ->join('photos', 'vehicle.idvehicle = photos.vehicle_id')
        ->group_by('vehicle.idvehicle');
        ->get()
        ->result_array();

Or just use group by
$this->db
        ->select("vehicle.idvehicle, vehicle.mark,
         vehicle.model, vehicle.type, vehicle.author_id, users.nick,
         photos.name,",FALSE)
        ->from('xxxxxsld_auto.vehicle')
        ->join('users', 'vehicle.author_id = users.userid')
        ->join('photos', 'vehicle.idvehicle = photos.vehicle_id')
        ->group_by('vehicle.idvehicle');
        ->get()
        ->result_array();

Edit From the comments you stated you need all photos so be aware of that fact the GROUP_CONCAT has a default limit of 1024 characters to concatenate but this can be increased by following the manual


text:
Q: bad interaction between stat_smooth and geom_ribbon I was answering this question, which required plotting smooth areas, but removing 'useless' area. To do that on a simple geom_area (not smooth), i'd just use geom_ribbon with aes(ymax=y, ymin=min(y)). But turning a stat_smooth(geom="area") into a stat_smooth(geom="ribbon", aes(ymax=y, ymin=min(y))) does not yield the expected result.
geom_area to geom_ribbon (dummy data at the end):
ggplot(df, aes(x=x, y=y)) + geom_area() to ggplot(df, aes(x=x, y=y)) + geom_ribbon(aes(ymax=y, ymin=min(y)))

Now the smooth version:
ggplot(df, aes(x=x, y=y)) + stat_smooth(geom="area") to ggplot(df, aes(x=x, y=y)) + stat_smooth(geom="ribbon", aes(ymax=y, ymin=min(y)))

The output that i wanted is something like this:

I found some solutions that involved making a new data frame with "smoothed data", and then plotting that normally with a geom_ribbon, but that applied only when you had a known function and could easily generate more observations. Another try was to set the y limits to ylim(min(y), max(y)), but ggplot doesn't plot any geom that is "caught" in a limit, so maybe if there's a way to change that feature it'd be a way to solve my problem.
Dummy data:
df <- data.frame(
  x = 1:7,
  y = c(12.44, 11.98, 11.40, 12.15, 13.14, 11.99, 12.17))

A: Do you mean something like this? If you want to use a calculated variable in your mapping, you need to wrap it with after_stat(). after_stat(y) means "use the y value calculated by the stat, not the y value in the original data frame."
library(ggplot2)

df <- data.frame(
  x = 1:7,
  y = c(12.44, 11.98, 11.40, 12.15, 13.14, 11.99, 12.17)
)

ggplot(df, aes(x=x, y=y)) +
  geom_point() +
  stat_smooth(
    geom="ribbon",
    aes(ymax = after_stat(y), ymin = after_stat(min(y))),
    fill = "skyblue"
  )
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2020-10-28 by the reprex package (v0.3.0)


text:
Q: Washed out colors in PictureBox When I show a specific image in a PictureBox (or Cyotek's ImageBox in my case, doesn't matter), the color gets a little washed out. Most images displays correctly but some few images gets washed out.
Here's what it looks like:
The original image
Opened in Windows Photo Viewer
Opened in my application
I tried loading the image in 3 different ways, but same result:
Image image = GetImage(OPEN);
imgBox.Image = image;

public Image GetImage(string path)
        {
            Image image = null;
            //image = Image.FromFile(@"D:\Visual Studio\pictures\pokemon.jpg");  // washed out colors
            try
            {
                using (FileStream file_stream = new FileStream(path, FileMode.Open, FileAccess.Read))  // washed out colors
                {
                    MemoryStream memory_stream = new MemoryStream();
                    file_stream.CopyTo(memory_stream);
                    image = Image.FromStream(memory_stream, false, false);
                    file_stream.Dispose();
                }
            }
            catch
            {
                try
                {
                    FIBITMAP picture = FreeImage.LoadEx(path);  // washed out colors
                    Bitmap bitmap = FreeImage.GetBitmap(picture);
                    image = bitmap;
                    FreeImage.Unload(picture);
                }
                catch { }
            }
            return image;
        }

Anyone know why this is? Maybe some specific tag in this image that Windows and PictureBox handles differently?

A: You should use Image.FromStream() and pass true for the useEmbeddedColorManagement argument to ensure that any metadata for color management is used.


text:
Q: One or more APIs that are required for game services to work have been turned off in the API console I had implemented leaderboard in google play store console.  But after implementing when I see the play store console it shows:

One or more APIs that are required for game services to work have been turned off in the API console. We recommend to turn them on again to ensure your game is working properly.

Also the leaderboard not working.

A: I had this same issue, and when I clicked the Turn APIs button back on, it would show the error again after a page refresh.
I got in contact with Google and they said that a few other developers were experiencing this issue and that they would email me back once they had made progress finding out what's wrong
Now then - because this all happened around the time I was re-linking a project into Google Play Games Services, I thought I had messed something up. Being restless I decided just now to create a new keystore file, and generate a fresh SHA-1 fingerprint. I was able to enter the newly generated code on the API Manager console, under the Credentials tab.
For some reason, it worked; I am now able to sign via Google and access the high-scores page.
Might be worth a try?


text:
Q: How to hide folder
Possible Duplicate:
How can I hide directories without changing their names?

How can I hide a folder and only see it when Ctrl+H is pressed?
I have checked in Properties and couldn't find it.

A: It is very simple. Just put a dot before the folder name you want to hide.
.folder


text:
Q: Python 'str' object is not callable I have a nasty error in my code which I can't figure out on my own. Here is my code:
    accounts = open('usernames.txt').read().splitlines()
    my_accounts = random.choice(accounts)
    for x in my_accounts(starting_account, ending_account, 1):
        payload = { 'user_key': get_user_key(),
                    'terms': 'true',
                    'action': 'edit',
                    'page': 'simple',
                    'flow': 'TestA',
                    'dob': '1987-22-01',
                    'gender': 'f',
                    'name': str(x),
                    'password': create_password()}
        r = requests.post(CONST_URL + end_point, headers=headers, cookies=cookies, data=payload, allow_redirects=False, verify=False)

        if r.status_code == 302:
            accounts_output = 'accounts.txt'
            f = open(accounts_output, 'w')
            user_output = (str(r.status_code) + ' Account created succesfully: ' + str(x) + ' ' + create_password())
            f.write(user_output)
            f.close()
        else:
            print(str(r.status_code) + ' Unable to connect to the server :/')
            print(r.content)

When I try to run this I get the following error:
Traceback (most recent call last):
  File "C:/Users/Google Drive/testing/moreTesting.py",              line 66, in <module>
ms = accountCreator().account_creator(0, 5)
  File "C:/Users/Pieperloy/Google Drive/testing/moreTesting.py",      line 43, in account_creator
    for x in my_accounts(starting_account, ending_account, 1):
TypeError: 'str' object is not callable

Also, yes I did try lookup the issue but didn't found anything that could help me with my particular case. Thanks in advance, have a great day

A: my_accounts is a string:
accounts = open('usernames.txt').read().splitlines()
my_accounts = random.choice(accounts)

but you are trying to use it as a function:
my_accounts(str(starting_account), str(ending_account), 1)

if you also have a function using that exact same name, you'll have to rename one or the other, you can't use the same name for a variable and a function.

A: accounts = open('usernames.txt').read().splitlines()
my_accounts = random.choice(accounts)
for x in my_accounts(starting_account, ending_account, 1):

splitlines() returns a list of strings. So your my_accounts variable will have a random string from your accounts list.
Hence, when you call my_accounts() in the for loop, you get the error that str objects are not callable.
Read more on splitlines().


text:
Q: Merge axis in numpy array I want to convert X,Y,Z numpy array to (X*Z)*Y numpy array.
Code(Slow):
 def rearrange(data):
        samples,channels,t_insts=data.shape
        append_data=np.empty([0,channels])
        for sample in range(0,samples):
            for t_inst in range(0,t_insts):
                channel_data=data[sample,:,t_inst]
                append_data=np.vstack((append_data,channel_data))
        return append_data.shape

I am looking for a better vectorized approach if possible

A: You can use np.transpose to swap rows with columns and then reshape -
data.transpose(0,2,1).reshape(-1,data.shape[1])

Or use np.swapaxes to do the swapping of rows and columns and then reshape -
data.swapaxes(1,2).reshape(-1,data.shape[1])