text:
Q: Making images repaint faster I have a working code where you can control the movement of a goldfish with the arrow keypad. When you press the up key, the goldfish swim up. When you press the down key, the goldfish swim down. When you press the left key, the goldfish swim left. And when you press the right key, the goldfish swim right. I made it so that the goldfish's pixel increase or decrease by exactly 1 pixel every time it moves in a new direction, but when you do it like that the goldfish swims very slowly. I know that if you increase the pixel by more than 1 the goldfish seems to be swimming faster, but then that way it wouldn't paint every pixel, and the goldfish swimming won't look as smooth. So my question is, is there a way to repaint the goldfish to go faster without increasing the pixels it paints by? Here's my code:
public class Fishy extends Panel implements KeyListener, MouseMotionListener {
static int x1;// first x location of the shape.
static int x2;// second x location of the shape
static int y1;// first y location of the shape
static int y2;// second y location of the shape
static int shapeWidth;// width of the shape
static int shapeHeight;// height of the shape
static final int left = 37;
static final int right = 39;
static final int down = 40;
static final int up = 38;
static boolean leftPress;
static boolean rightPress;
static boolean upPress;
static boolean downPress;
static int speed = 1;
static int x;
static int y;
static int size = 50;
static String facingDirection = "RIGHT";
int enemyX1;
int enemyY1;
int enemyX2;
int enemyY2;
int enemySpeed;
int enemySize;

static Image LimageFishy = new ImageIcon("F://Picture//Lfish.png").getImage();
static Image RimageFishy = new ImageIcon("F://Picture//Rfish.png").getImage();
static BufferedImage bufferedImageFishy;

Fishy enemyFish[] = new Fishy[20];

static JFrame frame = new JFrame("Fishy");

// TREE method of extending classes[]

static Fishy fishy = new Fishy(1000, 500, 9);

Fishy(int width, int length, int minusBy) {
    super(width, length, minusBy);
}

/* Graphics goes here */
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLUE);
    g.fillRect(0, 0, 1000, 500);

    // size++;
     if (facingDirection.equals("RIGHT")) {
     g.drawImage(RimageFishy, x1, y1, size, size, null);
     }
     if (facingDirection.equals("LEFT")) {
     g.drawImage(LimageFishy, x1, y1, size, size, null);
     }

    g.drawString(DraggingShapes.mousePointerLocation, 50, 50);

}

public static void main(String args[]) throws IOException, InterruptedException {

    frame.addKeyListener(fishy);
    fishy.addMouseMotionListener(fishy);

    frame.add(fishy);
    Frame.showFrame(frame, false);

    /*while (true) {
        Thread.sleep(1);
        if (x1 < 1000) {
            x1++;
        } else {
            x1 = 0;
        }
        frame.repaint();
    }*/

}

@Override
public void keyPressed(KeyEvent e) {

    if (up == e.getKeyCode()) {

        upPress = true;
    }
    if (down == e.getKeyCode()) {

        downPress = true;
    }
    if (left == e.getKeyCode()) {

        leftPress = true;
        facingDirection = "LEFT";
    }
    if (right == e.getKeyCode()) {

        rightPress = true;
        facingDirection = "RIGHT";
    }

    /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

    if (upPress == true && leftPress == false && rightPress == false) {
        fishy.y1 -= speed;
    }
    if (downPress == true && leftPress == false && rightPress == false) {
        fishy.y1 += speed;
    }
    if (leftPress == true && upPress == false && downPress == false) {
        fishy.x1 -= speed;
    }
    if (rightPress == true && upPress == false && downPress == false) {
        fishy.x1 += speed;
    }

    /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

    if (leftPress == true && upPress == true) {
        fishy.x1 -= speed;
        fishy.y1 -= speed;
    }
    if (leftPress == true && downPress == true) {
        fishy.x1 -= speed;
        fishy.y1 += speed;
    }
    if (rightPress == true && upPress == true) {
        fishy.x1 += speed;
        fishy.y1 -= speed;
    }
    if (rightPress == true && downPress == true) {
        fishy.x1 += speed;
        fishy.y1 += speed;
    }

    System.out.println("PRESSING (Left:" + leftPress + ") (Right:" + rightPress + ") (Up:" + upPress + ") (Down:" + downPress + ")");
    repaint();

}

@Override
public void keyReleased(KeyEvent e) {

    if (up == e.getKeyCode()) {
        upPress = false;

    }
    if (down == e.getKeyCode()) {
        downPress = false;

    }
    if (left == e.getKeyCode()) {
        leftPress = false;

    }
    if (right == e.getKeyCode()) {
        rightPress = false;

    }

}

@Override
public void mouseMoved(MouseEvent e) {
    DraggingShapes.showPointerLocation(e.getX(), e.getY());
    repaint();

}

/*** METHODS THAT WE'RE NOT GOING TO USE ***/
@Override
public void keyTyped(KeyEvent e) {

}

@Override
public void mouseDragged(MouseEvent e) {

}

}

Also, I notice that when you're not controlling the image with keyboard input, and just telling it to repaint using Thread.sleep(millisecond), when you're telling it to Thread.sleep(1 millisecond), the image repaints really fast, even if you're only increasing it by 1 pixel, and I'm wondering why it isn't the same with keyboard input.

A: If the key is held, the KeyListener will fire every n milliseconds (this may be OS dependent, but on my Windows system n ~ 33ms). So the repaint will be called every ~ n milliseconds. Relative to the Thread.sleep(1) method, this is ~ n times slower (note this is approximate as repaint is a request for the EDT to paint, and speed it actually works may depend upon the repaint queue and the painting itself). As a result, at 33ms your object is only traveling ~30 pixels/second.
I wouldn't necessary recommend trying to increase the rate of repainting to speed it up, rather to speed it up by increasing the rate at which it moves (eg the speed variable). Along these same lines, you can use a Swing timer to provide the animation loop.
javax.swing.Timer timer = new javax.swing.Timer(60, new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent arg0) {
        repaint();
    }

});
timer.start();

This gives you finer control over how fast animation occurs. You change the model with the UI listener elements (or otherwise), and rely on this timer for the animation. A descent rule of thumb might be to have the timer fire every 60ms. Note this would not speed things up - just give you finer control over the animation process.

A: Im not sure if this is exactly what your looking for but this might be the reason why there was some discrepancy between you using sleep(1) vs using the keyboard to move the fish. I refactored your code by adding a HashMap, as it allows for much easier updating and using that to update the direction variables.
public class Fishy extends Panel implements KeyListener, MouseMotionListener {

    // here is the map declaration for the data structure
    // that will map the key, which was an integer, to
    // (up,down,right,left)press, which was a boolean.

    static Map<Integer, Boolean> map = new HashMap<>();

    static int x1;// first x location of the shape.
    static int x2;// second x location of the shape
    static int y1;// first y location of the shape
    static int y2;// second y location of the shape
    static int shapeWidth;// width of the shape
    static int shapeHeight;// height of the shape
    static final int left = 37;
    static final int right = 39;
    static final int down = 40;
    static final int up = 38;
    static boolean leftPress;
    static boolean rightPress;
    static boolean upPress;
    static boolean downPress;
    static int speed = 1;
    static int x;
    static int y;
    static int size = 50;
    static String facingDirection = "RIGHT";
    int enemyX1;
    int enemyY1;
    int enemyX2;
    int enemyY2;
    int enemySpeed;
    int enemySize;

    static Image LimageFishy = new ImageIcon("F://Picture//Lfish.png").getImage();
    static Image RimageFishy = new ImageIcon("F://Picture//Rfish.png").getImage();
    static BufferedImage bufferedImageFishy;

    Fishy enemyFish[] = new Fishy[20];

    static JFrame frame = new JFrame("Fishy");

    // TREE method of extending classes[]

    static Fishy fishy = new Fishy(1000, 500, 9);

    Fishy(int width, int length, int minusBy) {
        super(width, length, minusBy);
    }

    /* Graphics goes here */
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.BLUE);
        g.fillRect(0, 0, 1000, 500);

        // size++;
         if (facingDirection.equals("RIGHT")) {
         g.drawImage(RimageFishy, x1, y1, size, size, null);
         }
         if (facingDirection.equals("LEFT")) {
         g.drawImage(LimageFishy, x1, y1, size, size, null);
         }

        g.drawString(DraggingShapes.mousePointerLocation, 50, 50);

    }

    static void buildMap() {
        map.put(up, false);
        map.put(down, false);
        map.put(left, false);
        map.put(right, false);

    }

    public static void main(String args[]) throws IOException, InterruptedException {

        buildMap();

        frame.addKeyListener(fishy);
        fishy.addMouseMotionListener(fishy);

        frame.add(fishy);
        Frame.showFrame(frame, false);

        /*while (true) {
            Thread.sleep(1);
            if (x1 < 1000) {
                x1++;
            } else {
                x1 = 0;
            }
            frame.repaint();
        }*/

    }

    @Override
    public void keyPressed(KeyEvent e) {

        // using the hashmap, we can refactor away the if statements
        map.put(e.getKeyCode(), true);

        /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

        // It is possible to refactor away the following if statements
        // but that requires further surgery on the code.

        for (Map.Entry<Integer, Boolean> entry: map.entrySet()) {
            if (entry.getValue()) {
                if (entry.getKey() == up) {
                    fishy.y1 -= speed;
                }
                else if (entry.getKey() == down) {
                    fishy.y1 += speed;

                }
                else if (entry.getKey() == right) {
                    fishy.x1 += speed;

                }
                else if (entry.getKey() == left) {
                    fishy.x1 -= speed;

                }
            }
        }

        System.out.println("PRESSING (Left:" + leftPress + ") (Right:" + rightPress + ") (Up:" + upPress + ") (Down:" + downPress + ")");
        repaint();

    }

    @Override
    public void keyReleased(KeyEvent e) {

        // got rid of the unnecessary if statements
        // and directly accessed the hashmap to update the value
        map.put(e.getKeyCode(), false);

    }

    @Override
    public void mouseMoved(MouseEvent e) {
        DraggingShapes.showPointerLocation(e.getX(), e.getY());
        repaint();

    }

    /*** METHODS THAT WE'RE NOT GOING TO USE ***/
    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void mouseDragged(MouseEvent e) {

    }

    }


text:
Q: jquery links fade in/out I am trying to get my wordpress internal links to appear in a content div, instead of doing a normal page reload. The fade in/out is working correctly, but the div content is not changing. Firebug is showing no errors, and all internal links are now only adding "#/" to the page link, how would I make sure the link is correctly being added back in with jquery?
Thanks in advance,
P.S, I am following the "css-tricks: ajaxing a wordpress theme" video if that helps,
    $(function() {

        $(".home li.home").removeClass("home").addClass("current_page_item");
        var $mainContent = $("#content"),

            URL = '',
            siteURL = "http://" + top.location.host.toString(),
            $internalLinks = $("a[href^='"+siteURL+"']"),
            hash = window.location.hash,
            $el, $allLinks = $("a");

        if (hash) {
            $mainContent.animate({ opacity: "0.1" });
            $(".current_page_item").removeClass("current_page_item");
            $("a[href="+hash+"]").addClass("current_link").parent().addClass("current_page_item");
            hash = hash.substring(1);
            URL = hash + " #content";
            $mainContent.load(URL, function() {
                $mainContent.animate({ opacity: "1" });
            });
        }

        $internalLinks.each(function() {
            $(this).attr("href", "#" + this.pathname);
        }).click(function() {
            $mainContent.animate({ opacity: "0.1" });
            $el = $(this);
            $(".current_page_item").removeClass("current_page_item");
            $allLinks.removeClass("current_link");
            URL = $el.attr("href").substring(1);
            URL = URL + " #content";
            $mainContent.load(URL, function() {
                $el.addClass("current_link").parent().addClass("current_page_item");
                $mainContent.animate({ opacity: "1" });
            });

        });
});

A: Can you put in console.log(variableName) in your method and see if the output of the variable in firebug is what you expect?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity Prefab Script Variables are the same values I have a prefab that is instantiated at runtime and basically tracks the time that it is alive since being instantiated, the problem is is that with all of the prefabs that I create the variable time_alive is the same across all instances.
I've added the code that I've used to create the prefab as well as the definition of the prefab. What would I need to do/what am I missing?

A: Ive fixed this by not using sendmessage


text:
Q: Ansible-vault not being passed to playbook correctly I am trying to use ansible and ansible-vault to provision users. This is my current directory structure:
|-- ansible-test.out
|-- group_vars
|-- inventory
|-- roles
|   |-- bsd_sudoers
|   |   |-- tasks
|   |   |-- templates
|   |   |   `-- cde-admins
|   |   `-- vars
|   `-- bsd_users
|       |-- files
|       |-- tasks
|       |   `-- main.yml
|       |-- templates
|       `-- vars
|           `-- all.yml
|-- site.retry
|-- site.yml
`-- vars
    `-- all.yml

This is what I have for my playbook so far:
---
- name: Creating Users
  user:
    name: "{{ item.name }}"
    system : "{{ item.sudoer }}"
    shell: /bin/bash
    password: "{{ item.password }}"
    uid: "{{ item.uid }}"
    home: "{{ item.home }}"
  with_items: users

Here is a sample of what I have in ansible vault:
---
   vars:
     users:
       - name: 'foo'
         home: '/home/foo'
         key: 'ssh-rsa ....'
         password: '!!'
         bash: '/bin/bash'
         sudoer: yes
         uid: "2049"
         guid: '2049'
         group: admin

When I run the playbook, this error message is always generated:
fatal: [ansible-test]: FAILED! => {"failed": true, "msg": "The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'uid'\n\nThe error appears to have been in '/Users/ansible/playbooks/roles/bsd_users/tasks/main.yml': line 2, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n---\n- name: Creating Users\n  ^ here\n\nexception type: <class 'ansible.errors.AnsibleUndefinedVariable'>\nexception: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'uid'"}
    to retry, use: --limit @/Users/ansible/playbooks/site.retry

Why is this always happening? I was under the impression that Ansible would naturally pass the encrypted variables to my playbook but this does not seem to be the case.

A: As Konstantin mentioned before, you need to include the variable file either as -e @vars/all.yml via the command line, or by adding vars_files into the playbook. You can also add the all.yml file into the group_vars directory, and it will be picked up automatically.
Regarding the second error message you are receiving, starting with Ansible 2.4 the recommended way of providing the password at the command line is by using --vault-id. This can be anything from a path to the id file, to @prompt for Ansible to prompt you for a password, or even the path to a script that returns the password.
Prior to Ansible 2.4, you need to use --ask-vault-pass or --vault-password-file.
You can also add a variable in ansible.cfg named vault_password_file, where you can define the location of the vault password file (for example vault_password_file = /path/to/.vault_password_file), so you don't need to specify it every time you run ansible-playbook. Starting with Ansible 1.7, this path can also point to a script that returns the password as stdout.
If this helps answer your question, I would appreciate it if you could mark it as the accepted answer.

A: First:
with_items: users should be with_items: "{{ users }}".
Bare variables are not supported any more.
Second:
There's no need to define top-level vars dict in vaulted files, use:
---
users:
  - name: foo
    home: /home/foo
  - name: bar
    home: /home/bar


text:
Q: DNN binary classifier's accuracy not increasing My binary classifier DNN's accuracy seems stuck since epoch 1. I think this means that the model is not learning. Any insight on why this is happening?
Problem statement: I would like to classify a given sequence of readings for sensors (ex. [0 1 15 1 0 3]) into either 0 or 1 (0 equivalent to "idle" state, 1 equivalent to "active" state).
About the dataset: Dataset is available here
The "state" column is the target, while the rest of the columns are the features.
I've tried using SGD instead of Adam, tried using different kernel initializes, tried changing the number of hidden layers and number of neurons per layer and tried using sklearn's StandardScaler instead of the MinMaxScaler. None of these approaches seemed to change the outcome.
This is the code:
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.callbacks import EarlyStopping
from keras.optimizers import Adam
from keras.initializers import he_uniform
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import OneHotEncoder

seed = 7
random_state = np.random.seed(seed)

data = pd.read_csv('Dataset/Reformed/Model0_Dataset.csv')
X = data.drop(['state'], axis=1).values
y = data['state'].values

#min_max_scaler = MinMaxScaler()
std_scaler = StandardScaler()

# X_scaled = min_max_scaler.fit_transform(X)
X_scaled = std_scaler.fit_transform(X)

X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=random_state)

# One Hot encode targets
y_train = y_train.reshape(-1, 1)
y_test = y_test.reshape(-1, 1)

enc = OneHotEncoder(categories='auto')
y_train_enc = enc.fit_transform(y_train).toarray()
y_test_enc = enc.fit_transform(y_test).toarray()

epochs = 500
batch_size = 100
model = Sequential()
model.add(Dense(700, input_shape=(X.shape[1],), kernel_initializer=he_uniform(seed)))
model.add(Dropout(0.5))
model.add(Dense(1400, activation='relu', kernel_initializer=he_uniform(seed)))
model.add(Dropout(0.5))
model.add(Dense(700, activation='relu', kernel_initializer=he_uniform(seed)))
model.add(Dropout(0.5))
model.add(Dense(800, activation='relu', kernel_initializer=he_uniform(seed)))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
model.summary()

early_stopping_monitor = EarlyStopping(patience=25)
# model.compile(SGD(lr=.01, decay=1e-6, momentum=0.9, nesterov=True), loss='binary_crossentropy', metrics=['accuracy'])
model.compile(Adam(lr=.01, decay=1e-6), loss='binary_crossentropy', metrics=['accuracy'], )

history = model.fit(X_train, y_train_enc, validation_split=0.2, batch_size=batch_size,
                    callbacks=[early_stopping_monitor], epochs=epochs, shuffle=True, verbose=1)
eval = model.evaluate(X_test, y_test_enc, batch_size=batch_size, verbose=1)

Expected results: Accuracy increasing (and loss decreasing) with each epoch (at least for the early epochs).
Actual results: The following values are fixed throughout the entire training process:
loss: 8.0118 - acc: 0.5001 - val_loss: 8.0366 - val_acc: 0.4987

A: You are using the wrong loss, with a two-output softmax you should use categorical_crossentropy and you should one-hot encode your labels. If you want to use binary_crossentropy, then the output layer should be a one unit with a sigmoid activation.


text:
Q: xscreensaver doesn't stop fadeout correctly I have xscreensaver set to blank my screen, with a 5 second fade duration. When user input happens during this fadeout, the following happens:

*

*screen starts fading

*Image freezes, only fading updates

*user input happens

*Fading continues until finished

*Screen goes blank, then unblanks immediately

What I would expect to happen is:

*

*screen starts fading

*user input happens

*Fading stops, screen is never blanked

Is this possible using xscreensaver?

A: There is a "grace period" setting called lockTimeout which controls how long the user can interrupt once the screensaver starts (independently of fading out, it seems). Simply set it to the same as your fadeSeconds value for a less surprising user experience:
xscreensaver.fadeSeconds:   0:00:10
xscreensaver.lockTimeout:   00:00:10


text:
Q: How to use LIKE sql wild card in wpdb global variable of wordpress? <?php
global $wpdb;
global $current_user;
$review_title = isset($_GET['abc'])?$_GET['abc']:'test';
$review_titles = $wpdb->get_results( $wpdb->prepare("SELECT ch_listing.listingId,organizationName, logoUrl, organizationType,reviewId, reviewTitle,reviewDate FROM ch_listing LEFT JOIN ch_review ON ch_listing.listingId = stakeholderId WHERE (reviewTitle LIKE %s);" '%'.like_escape($review_title).'%')));
?>

Returns null. What is wrong with my code? Is there anyone who can help me on how to use LIKE sql wildcard in wpdb->get_results wordpress?

A: global $wpdb;
global $current_user;

$review_title =isset($_GET['abc'])?$_GET['abc']:'test'; $review_titles = $wpdb->get_results( $wpdb->prepare(
"SELECT
        ch_listing.listingId
        ,organizationName
        ,logoUrl
        ,organizationType
        ,reviewId
        ,reviewTitle
        ,reviewDate
 FROM
        ch_listing
         LEFT JOIN
            ch_review
          ON ch_listing.listingId = stakeholderId
 WHERE
        (reviewTitle LIKE %s);" '%'.like_escape($review_title).'%')));

Its hard tell because you have  the LIKE %s  where LIKE '%s' might help and maybe LIKE '%%%s%%'
Best way to trouble shoot this is start talking chunks of code away and see when you start to get results back. Like take away the WHERE clause

A: here is the answer!
$review_title= "example";
$review_titles = $wpdb->get_results( $wpdb->prepare("SELECT ch_listing.listingId,organizationName, logoUrl, organizationType,reviewId, reviewTitle,reviewDate FROM ch_listing LEFT JOIN ch_review ON ch_listing.listingId = stakeholderId WHERE reviewTitle LIKE  %s",'%'.$review_title.'%'));
the tricky in the above code is that: $wpdb->get_results($wpdb->prepare(argument1,argument2)) accepts two arguments like argument1 and argument2, the first one is a reference two the next one. assume i am passing a string so i should use %s, but if i want to pass argument integer, i should use %d, the lastly the value of the variable may string or integer value.
hope this will fine work for all of you are in problem of using LIKE wildcard in wordpress!!!
thanks too much.

A: $reviewers_title = $wpdb->get_results(  $wpdb->prepare("SELECT chve_users.ID, display_name,userType, reviewId, reviewTitle, reviewDate FROM chve_users RIGHT JOIN ch_review ON chve_users.ID = reviewerId WHERE display_name LIKE  %s",'%'.$reviewer_name.'%'));

works fine


text:
Q: RSS enabled web part We are rolling up content from multiple site collections and are looking for a way to allow a RSS feed from that rolled up content.  Any ideas on implementation of a RSS option for a custom webpart?  I know the Content Query Web Part has an option to subscribe to it via RSS and am looking to implement that on a custom web part.

A: As @Steve mentioned, create an Application Page in the _Layouts folder that outputs the RSS feed.  Then link to that page from your web part.  Here is an example of how to generate an RSS feed from C#: http://www.dailycoding.com/Posts/create_rss_feed_programatically_from_data_in_c.aspx

A: I think you'll need an application page (_layouts page) for this that returns the xml needed for the feed.  If you've seperated the data/business logic from your presentation layer in your webpart, then this application page should be pretty easy to write because you are just creating a new XML based presentation layer.


text:
Q: PHP if comparison when Array involved I have an IF statement that I can't seem to get right as far as it ever failing to be true.  Here is the code:
        file_put_contents('php.txt', $_POST['columns'][$i], FILE_APPEND);
        if ( $_POST['columns'][$i] != 'TimeOccurred' ) {
            if ( $sWhere == "" ) {
                $sWhere = "WHERE ";
            }
            else {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." LIKE '%".addslashes($_POST['columns'][$i]['search']['value'])."%' ";
        }

The output from my file_put_contents is as follows:
TimeOccurred.date.truetrueArray
I need to find a way to see if this is the "TimeOccurred" column and if it is filter the results in a different way.  I have tried playing with implode/explode on the periods to break this up into three strings.  I have tried converting $_POST['columns'][$i] to a string and then breaking it up.  Can anyone point me in the right direction on this?
********EDIT*********
Am I doing this correctly?  I don't get any output at all:
Tried this outside the for statement:
var_dump($_POST['columns']);

Tried this inside the for statement:
var_dump($_POST['columns'][$i]);

I don't get output from either of them.  For some reason just doing a var_dump causing a json error when the page is loading, not sure why a random var_dump in middle of a php file would have any effect on the json data coming back since it doesn't actually change anything if I understand it correctly.  I test var_dump on completely different variable that wasn't an array and it still just causes the json error and never returns a value.
******EDIT 2******
Thought it might help if I mention that the php file in question is called via AJAX and returns json encoded data. Is it trying to encode the var_dump and send it along too?
*****EDIT 3*******
I was able to get the var_export to work properly.  Here are the results.
  array (
  0 =>
  array (
    'data' => 'Action',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     1 =>
  array (
    'data' => 'TimeOccurred.date.',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     2 =>
  array (
    'data' => 'PerformedByUserName',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     3 =>
  array (
    'data' => 'IPv4From',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     4 =>
  array (
    'data' => 'ObjectAffected',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     5 =>
  array (
    'data' => 'ObjectClass',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     6 =>
  array (
    'data' => 'AttributeAffected',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     7 =>
  array (
    'data' => 'AttributeValueAdded',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     8 =>
  array (
    'data' => 'AttributeValueRemoved',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),

     9 =>
  array (
    'data' => 'AdditionalDetailRegardingSelectedAttributes',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),
     10 =>
  array (
   'data' => 'FromServer',
    'name' => '',
    'searchable' => 'true',
    'orderable' => 'true',
    'search' =>
    array (
      'value' => '',
      'regex' => 'false',
    ),
  ),
)

So I guess I really need to do something like:
if ( $_POST['columns'][$i][data] != 'TimeOccurred.date' )

Does that seem like I'm on the right path?  Going to do some of my own testing as well.

A: Once the comments to my initial question helped me figure out how to properly export the values of my array, I was able to understand how to get my IF statement to work as expected:
if ( $_POST['columns'][$i]['data'] != 'TimeOccurred.date.' ) {
            if ( $sWhere == "" ) {
                $sWhere = "WHERE ";
            }
            else {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." LIKE '%".addslashes($_POST['columns'][$i]['search']['value'])."%' ";
        }

To be clear I realize there are some SQL Injection issues here.  For now this is just an internal proof of concept, I will be concerned with closing up SQL Injection vulnerabilities it just wasn't relevant to this individual question.  If I need help with that I will create a separate post.


text:
Q: How can I find the largest value of two columns located in different sheets? I have two columns of data and I need to find the largest value without merging the columns. I tried LARGE(('Sheet 1'!A:A):('Sheet 1'!B:B);k), which works when the columns are located in the same sheet.
But LARGE(('Sheet 1'!A:A):('Sheet 2'!B:B);k) returns #VALUE

A: I suggest find the largest of each sheet individually, then the largest of those two results. Something like:
=MAX(MAX(A:A),MAX([Book1.xls]Sheet2!$B:$B))

However a shorter version should give the same result:
=MAX(A:A,Sheet2!B:B)

where I have assumed the sheets are in the same book.


text:
Q: How to arrive at this sufficient condition for convergence of Taylor Series? So I have been studying the convergence of Taylor series from Tom M Apostol. There is a theorem which states the sufficient condition for convergence of Taylor series. Quoting the theorem we've

Assume $f$ is infinitely differentiable in an open interval $I = (a -
 r, a + r)$, and assume that there is a positive constant $A$  such
   that  $$ |f^{(n)}(x)| \le A^n$$ for $n = 1, 2, 3, \dots$ and every $x$
   in $I$. Then the Taylor's series generated by $f$ at $a$ converges to
  $f(x)$ for each $x$ in $I$.

My question is how to arrive at $|f^{(n)}(x)| \le A^n$ deductively ? I tried looking it up on the internet but haven't found anything that solves my issue.
Thanks!

A: The assertion
$$
|f^n(x)| \le A^n
$$
is a hypothesis in this theorem. You can't "arrive at it deductively" in general. When it happens to be true for any particular function $f$ then you can conclude something about the Taylor series for that function.
For example, the $n$th derivatives of $\sin$ are $\sin$ and $\cos$. Their absolute values are always at most $1$. This theorem then implies that the Taylor series for $\sin$ converges everywhere to the value of the function.


text:
Q: python - deleting element at index i from heap I am trying to write a delete function for a heap. I am given a head class and heapify functions to work with, I just need to implement delete. I want to implement it in O(log n) time. This is what I've tried:
from heap import *
class heap_delete(heap):
    def delete(self, i):
        self.A[i] = self.A[-1] #put the bottom rightmost element in i
        self.min_heapify(i)

but when I run it with the provided test code, it says 'failed'. Reading the AssertionError statement it seems that nothing is happening to the index I am trying to manipulate. Here is the heap code I am importing:
def parent(i):
    return int(i/2)
def left(i)
    return 2*i
def right(i):
    return 2*i+1
class heap:
    def __init__(self):
        self.A = [None] #to make it 1 based, None is stuck at 0
    def __getitem__(self, i):
        return self.A[i]
    def min_heapify(self, i):
        l = left(i)
        r = right(i)
        smallest = i
        if l <= self.heapsize and self.A[l] < self.A[i]:
            smallest = l
        if r <= self.heapsize and self.A[r] < self.A[smallest]:
            smallest = r
        if smallest != i:
            self._swap(i, smallest)
            self.min_heapify(smallest)
    def _swap(self, index1, index2):
        self.A[index1], self.A[index2] = self.A[index2], self.A[index1]

There are other functions, such as decrease_key, extract_min, and insert. I can add them to the post if necessary but I believe everything I need is here. The AssertionError I am recieving is as follows:
    self.assertEquals(h.A, [None])
AssertionError: Lists differ: [None, 5] != [None]

and
    self.assertEquals(h.A, [None])
AssertionError: Lists differ: [None, 15] != [None]

the former AssertionError is from the test function I am supposed to run my code with. It calls h.insert(5) and h.delete(1), followed by self.assertEquals(h.A, [None]). The ladder, also in the test function, calls insert on 5,15,10,and 0 which is followed by h.delete(h.A.index(10)) and then the same assertEquals statement as before.
From this I am lead to believe that my delete function isn't deleting anything. I have tried using del and the _swap provided but perhaps did not use them correctly. Again I am looking for O(log n) time so if anyone could point me in the right direction that would be great.

A: def delete(self, i):
    self.A[i] = self.A[-1] #put the bottom rightmost element in i
    del self.A[-1]         # <--- shrink the list
    self.min_heapify(i)

A: When you delete from your heap, then your array size should go down. That is currently not happening in your delete function :).


text:
Q: Mismo nivel de dos elementos en linea con distinto tamaño de letra Tengo este html

Canciones

Inicio

Canciones

y la letra de #icono es de 20px y la lista de 16px.¿Cómo podría hacer para que se quedará al mismo nivel al dar un alto al header? Lo he intentado con margin y padding pero no se queda bien.

A: Puedes hacerlo con padding o margin, pero es conveniente que alinees verticalmente ambos arriba.
Aquí dejo un ejemplo:

Canciones

Inicio

Canciones

Puedes ver cómo queda aquí.


text:
Q: How to express this function efficiently int f(int n, int mul) {
    if (abs(n)%mul == 0) return n;
    else return f(n - 1, mul);
}

So it rounds down to the next mul. But obviously isn't good for large values of n. How can it be expressed safely and efficiently?

A: That's relatively simple, you just evaluate the changing expression while adjusting the variable until the result fulfills the right condition:
while (abs(n) % mul != 0) --n;

Notes:

*

*While this answers your question, the code is still bad but for different reasons:

*

*There are functions that round numbers. Instead of reinventing the wheel, using one of them should be the first, instinctive approach.

*abs() looks innocent, but what if you give it the smallest possible integer in a twos-complement system? There simply is no absolute value that could be represented as such an integer.

*Similarly, decrementing n could underflow, causing undefined behaviour (and surprising results).

*Also, what if mul is not positive? The code doesn't handle this case in any way, while the function signature allows it.

*Last but not least, writing a loop in the first place is stupid. A modulo operation will give you the distance of the first operand to the next multiple of the second operand! Make sure you understand how this works on negative numbers though. Also, I wouldn't be surprised if modulo caused undefined behaviour when used with some values. Getting this 99% right is easy, the remaining percent is tricky.

*Compilers that optimize tail end recursion might generate the same code, so it's not guaranteed to give you any advantage.

A: Re

" How can [the recursive function] be expressed safely and efficiently?

For non-negative n and mulyou can just do
return n - n%mul;

I leave the possible adjustments for negative values, and how to handle a zero mul, to the reader.
This is about as efficient as you can get; it's what Euclid would have used, were he alive today and using C++ instead of [1]COBOL.

An alternative is
return mul*(n/mul);

Whether that is more or less efficient than the first, depends.
But offhand I would think that any difference would be too small measure.

You're not asking for most efficient, but merely "efficient". Which implies just reasonable efficiency. Still I recommend measuring, whenever efficiency is a concern.
Measuring needs not require great effort.
In many cases, just observing that the program performs reasonably well, can be a good enough measurement (of very low resolution and precision, but often good enough).

[1] Not sure exactly why, but I always think of Euclid as a COBOL guy.

A: If you are worried about StackOverflow ... then don't!
Following function is basically a tail recursive function, compilers like GCC automatically convert it into an iterative function for you!
int f(int n, int mul) {
    if (abs(n)%mul == 0) return n;

    return f(n - 1, mul);  //Tail recursion
}

REF:

*

*Tail recursion in C++

*http://32leav.es/?p=674
Hope this helps!

A: It would only round to a 100 if your second parameter was so. An iterative implementation follows. If you provide further detail I may look at it again.
     int f(int n, int mul)
     {
         while(n%mul != 0)
         {
           n--;
         };

     return n;
     }

A: What other users have suggested more or less work for limited cases of n.
Where is a solution for the general case:
if (abs(n) % mul == 0)
    return n;
else if (n >= 0)
    return n - abs(n) % mul;
else
    return mul - abs(n) % mul;

or if a oneliner is preferred
return abs(n) % mul == 0 ? n : n - (n >= 0 ? abs(n) % mul : mul - abs(n) % mul);


text:
Q: Flink SQL create something from nothing Earlier I asked if Flink could create something from nothing and the answer is yes. Now I am looking more into the capabilities of Flink SQL specifically.
In SQL this type of challenge is sometimes easy (e.g. SELECT 1 works in regular engines such as MySQL) but also it sometimes is impossible, for example Apache Pig cannot create something from nothing.
I am not sure about Flink SQL, the idea is of course that with the ability to create something from nothing, it eliminates any hard dependencies on other solutions when you want to run a quick test or build a portable example.
For sake of simplicity:
Assume I want to generate at least 1 message per second, and don't mind what is inside.

My first thoughts:

*

*A simple select statement will not do the trick, as you do not get any output when there is nothing to select.

*Conceptually a count(*) over a time window could work, but I did not get it working yet. Perhaps it is a feature that if there is nothing to count the output will be nothing (rather than 0).

Other than windowing I do not see anything in Flink SQL that has the concept of time, so outside that I suspect it will not be possible.
What am I Not looking for:

*

*Starting with one message and making more with it. Suppose I have a kafka topic and a message enters, then it is likely trivial to keep looping it back and creating infinity messages. But my question is more about how to start when kafka is empty.

*Flink code that is not SQL, or even other tooling.

A: Even better than the datagen connector is flink-faker, which has been used is many of the examples in the Flink SQL Cookbook. I think you'll find these examples especially interesting.
Flink SQL has powerful support for working with both event time and system time, including watermarking. For example, Flink SQL uses watermarks to determine which records can be expired from Flink state when handling streaming event time windows and interval joins.
For some additional Flink SQL operations that leverage time, see time versioned tables, pattern detection, temporal joins, and time-based lookup joins.

A: You might find the "datagen" connector useful for this.
https://ci.apache.org/projects/flink/flink-docs-release-1.12/dev/table/connectors/datagen.html
For example:
CREATE TABLE Orders (
order_number BIGINT,
price        DECIMAL(32,2),
buyer        ROW<first_name STRING, last_name STRING>,
order_time   TIMESTAMP(3)
) WITH (
  'connector' = 'datagen'
)


text:
Q: Gruntjs copy subdirectories I'm not sure on the right Gruntjs command for grunt-contrib-copy.
Initially, I had a directory with fonts in it and I needed to copy them all from the app/styles/fonts directory into a build/fonts directory so I used this:
{expand: true, flatten: true, src: ['app/styles/fonts/*'], dest: 'build/fonts'}

and it worked well.
I've now added a couple of sub-directories (inside app/styles/fonts) with more font files in them but when I run the command it will copy the files and the folders but put the contents of the new directories into the build/fonts. I want them to remain in their respective folders.
How can I fix this?

A: {
 expand: true,
 flatten: true, //use only if you want to copy all files in destination folder without their respective folders
 src: ['app/styles/fonts/**'],
 dest: 'build/fonts'
}

try this it will copy all files and directories of fonts. but if you use faltten:true then it will copy all files into build/fonts and will break the directory structure.
So for keeping the same structure don't use flatten option.


text:
Q: How to generate end tag for empty element in XML using JAXB I'm generating XML using JAXB. But JAXB is generating an empty Tag closing it self. But my client want separate empty tag. I know both are equals but he is not agree with me. please any one suggest the solution. Thanks.
Sample code:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "currencyCode",
    "discountValue",
    "setPrice",
    "spendLowerThreshold",
    "spendUpperThreshold",
    "discountApportionmentPercent",
    "discountApportionmentValue"
})
@XmlRootElement(name = "countryData")
public class CountryData {
    protected String currencyCode;
    protected String discountValue = "";
    protected String setPrice = "";
    protected String spendLowerThreshold = "";
    protected String spendUpperThreshold = "";
    protected String discountApportionmentPercent = "";
    protected String discountApportionmentValue = "";

    // Setters and Gettres
}

Actual Output:
<currencyCode>GBP</currencyCode>
<discountValue/>
<setPrice/>
<spendLowerThreshold/>
<spendUpperThreshold/>
<discountApportionmentPercent>0.0</discountApportionmentPercent>
<discountApportionmentValue/>

Expected Output:
<currencyCode>GBP</currencyCode>
<discountValue></discountValue>
<setPrice></setPrice>
<spendLowerThreshold></spendLowerThreshold>
<spendUpperThreshold></spendUpperThreshold>
<discountApportionmentPercent>0.0</discountApportionmentPercent>
<discountApportionmentValue></discountApportionmentValue>

Code for Marshalling:
try {
    Marshaller marshaller = JAXBContext.newInstance(CountryData.class).createMarshaller();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    marshaller.marshal(countryData , os);
    log.debug("The PPV request raw XML -> " + os.toString());
} catch (JAXBException e) {
    // nothing to do
}

I'm Using JDK 6.0

A: If you have generated Classes from XSD then you would also generated ObjectFactory class. If don't please refer here about how to generate ObjectFactory class.
After that, your code would be like--
JAXBContext context;
            context = JAXBContext.newInstance(*yourClass*.class);

final ObjectFactory objFactory = new ObjectFactory();

            final JAXBElement<YourClass> element = objFactory
                    .*autoGeneratedmethodfromObjectFactorytogetelement*;

Marshaller marshaller;
            marshaller = context.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            final StringWriter stringWriter = new StringWriter();

            marshaller.marshal(element, stringWriter);
          String message = stringWriter.toString();

This will give you desired output.

A: This behaviour is implementation dependant. I stumbled into opposite problem (I needed self-closing tag) and I resolved in this way.You can try using this version of marshal() or modifying code from linked answer.

A: Problem solved,
To force a closing tag, just add an empty String as the value of this tag !
You can do it using @XmlValue :
public class closedTag {

    @XmlValue
    private String content;

    public closedTag() {
        this.content = "";
    }

}


text:
Q: multiple virtual host working only for 2 subdomain in apache centos 6 Hi below is the content of httpd.conf file. I create 5 subdomain inside this file 2 subdomain are working. I mention after virtual host which are working and which are not working
NameVirtualHost *:80
<VirtualHost *:80>
ServerName 88.198.133.25
DocumentRoot "/home/developer/public_html"
<Directory /home/developer/public_html>
Options FollowSymLinks
AllowOverride All
</Directory>

# this is for default acees of apache
# working

</VirtualHost>
<VirtualHost *:80>
ServerName bioad.log.com
DocumentRoot "/home/developer/public_html/subdomain/bio/bioad"
<Directory /home/developer/public_html/subdomain/bio/bioad>
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

#not working

<VirtualHost *:80>
DocumentRoot /home/developer/public_html/gecautonew
ServerName gec.log.com
ServerAlias gec.log.com
<Directory /home/developer/public_html/gecautonew>
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

#not working

<VirtualHost *:80>
DocumentRoot /home/developer/public_html/obb/public
ServerName obb.log.com
<Directory /home/developer/public_html/obb/public>
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

# working

<VirtualHost *:80>
DocumentRoot /home/developer/public_html/subd/bio/api
ServerName biopi.log.com
<Directory /home/developer/public_html/subd/bio/api>
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

#working

<VirtualHost *:80>
DocumentRoot /home/developer/public_html/biouser
ServerName biou.log.com
<Directory /home/developer/public_html/biouser>
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>

#not working

I am unable to identify what is the actual problem in this config file

A: Depending on which apache version you may need to add the NamedVirtualHost directive to the apache configuration and reload apache.
Please confirm you have the following in /etc/httpd/config/httpd.conf :
NameVirtualHost *:80


text:
Q: AutoITLibrary = Automating Simple Windows GUI Application could anybody please help me in automating the GUI/UI of a simple Windows application using the Robot Framework AutoITLibrary? I've done it using just the AutoIT tool, but can't seem to get it to work using the AutoITLibrary.
I've tried my syntax below, but no luck. Essentially, all I want to do is launch the application, and go Next >> Next >> Finish. Any help would be very appreciated. Thanks.
*** Settings ***
| Library | AutoItLibrary

*** Variables ***
| ${P4Vx64} | C:\\Temp\\setup.exe
| ${Title} | Sample Application

*** Test Cases ***
| Install
| | AutoItLibrary.Run | ${P4Vx64}
| | Control Click | ${Title} | &Next | Button6
| | Control Click | ${Title} | &Next | Button5
| | Control Click | ${Title} | &Finish | Button3

A: Why don't you use pywinauto? The script should look very simple and readable:
from pywinauto.application import Application

app = Application()
app.start_("C:\\Temp\\setup.exe")
mainWindow = app.SampleApplication
mainWindow.Wait('ready')
mainWindow['&Next'].ClickInput()
mainWindow['&Next'].ClickInput()
mainWindow['&Finish'].ClickInput()
mainWindow.WaitNot('visible')


text:
Q: How to wrap existing functions (including aggregates) into a new one in Postgres? I'm using Postgres 9.2 to generate some JSON data. For each nested table I'm doing this nested set of functions:
SELECT array_to_json(
  coalesce(
    array_agg(
      row_to_json(foo)),
    ARRAY[]::json[])
)
FROM foo

The effect is to create a json array with each row being the json collection for the row. The coalesce ensures that I get an empty array rather than nil if the table is empty. In most cases foo is actually a subquery but I don't think that is relevent to the question.
I want to create a function table_to_json_array(expression) such that this has the same effect as above:
SELECT table_to_json_array(foo) FROM foo

I need to use this lots so I was planning to create a Postgres function to have the effect of the combination of these calls to clean up my queries. Looking at the documentation it seems as if I need to create an aggregate rather than a function to take a table argument but those look like I would need to reimplement array_agg myself.
Have I missed something (possibly just the type a function would need to take)? Any suggestions?

A:
In most cases foo is actually a subquery but I don't think that is
  relevent to the question.

Unfortunately, it is. You can create a function with regclass argument:
create or replace function table_to_json(source regclass)
returns json language plpgsql
as $$
declare
    t json;
begin
    execute format ('
        SELECT
            array_to_json(
                coalesce(array_agg(row_to_json(%s)),
                ARRAY[]::json[]))
        FROM %s', source, source)
        into t;
    return t;
end $$;

select table_to_json('my_table');
select table_to_json('my_schema.my_view');

But in context:
select table_to_json_rec(arg)
from (select * from my_table) arg

the argument arg is of type record. PL/pgSQL functions cannot accept type record. The only way to get this is a C function, what I guess is not an option. The same goes for aggregates (you must have a function to define an aggregate).

A: Postgres 9.3 adds a json_agg function which simplifies the specific query I need although this isn't a general solution to the aggregate functions issue. It still needs a coalesce function to ensure the empty set is properly returned.
SELECT coalesce( json_agg(foo), json'[]')
FROM foo

And it works even when foo is a subquery.


text:
Q: How to exactly add up 2 values with PHP that are output from a WordPress shortcode For a personal project, I have 2 gravity forms. I am using this plugin that allows me to add a shortcode with form parameters which adds up all values in every form entry that have been entered in a specific field and gives me a grand total https://wordpress.org/plugins/gravitywp-count/ so I have 2 figures (one from each form)
What I want to do now is use PHP to add them together.
<?php
    $first_number = do_shortcode("[gravitywp_count formid='1' number_field='3']");
    $second_number = do_shortcode("[gravitywp_count formid='2' number_field='3']");
    $sum_total = $first_number + $second_number;

    $direct_text = 'The two variables added together = ';

    print ($direct_text . $sum_total);
?>

The current value of formid='1' is 10,969.39 and the value of formid='2' is 4,582.92 so the total should be 15,552.31 but my code is only giving me the answer as 14. So I guess it is only adding up the 10 and the 4 so the thousand figures before the first comma.
Can anyone advise?

A: This can be achieved by the PHP str_replace() Function
You can remove the comma from the result you get from the shortcode and store the value in a new variable.
Finally making the code like this:
$first_number = do_shortcode("[gravitywp_count formid='1' number_field='3']");
$second_number = do_shortcode("[gravitywp_count formid='2' number_field='3']");
$first_number_sep = str_replace( ',', '', $first_number );
$second_number_sep = str_replace( ',', '', $second_number );

if( is_numeric( $first_number_sep &&  $second_number_sep) ) {
    $first_number = $first_number_sep;
    $second_number = $second_number_sep;
}

$sum_total = $first_number_sep + $second_number_sep;
$sum_total = $first_number_sep + $second_number_sep;
$total_formatted = number_format($sum_total, 2, '.', ','); //formats the number back to the comma state

echo 'The two variables added together = ' . $total_formatted;


text:
Q: FullPageJS - fixed header z-index hides section's content Using FullPageJS for a current project with a fixed top menu that changes its height according to viewport size.
A narrow screen will stack the menu items on top of each other and a wider one will have the menu items next to each other resulting in a different height of the menu.
Looking at the Fixed Elements demo from FullPageJS if I for example inspect the "Fixed elements" h1 with dev tools in Firefox and go up two elements till I reach .fp-tableCell and there I deselect vertical-align:middle one can observe the text moving under the fixed header.
Well it is not actually moving but going to the top border of its container. This means the sections are always 100% of the viewport height and this means that content in sections that is not vertically aligned in the middle in a table cell element will be hidden by fixed elements such as a fixed navigation.

What I am trying to get is indeed a fixed header or fixed footer but not have the sections "go under" the fixed elements but actually stop at the border of the fixed element to not hide the section's content.
One way would be to inject a placeholder element with the height of the current height of the fixed element and place that under the fixed element on the same flow as the current section and therefore limit the section "sliding under" the fixed element.
Waypoints Sticky Elements does this for dynamically created sticky or fixed elements:

A wrapper is created around your element.
This wrapper remains in a static position on the page, acting as an
  empty placeholder for that element in the document flow while the real
  element gains and loses fixed positioning.
This wrapper element is the actual element that is used in the
  underlying Waypoint.
The wrapper height is set. This ensures the wrapper is the same height
  as the element it wraps, even when that element becomes fixed. This
  prevents the page layout from shifting when it does.
Adds a class to the sticky element when it hits the top of the window.
  This class is what you must style using CSS to give the sticky element
  fixed positioning.

A: You are overthinking this.
1) Give your content container a class and put a margin-top on that content container with the same amount of height as your header. In your case, that's about 60px. If it's a variable height (which your example on JSFiddle is not), look into using calc() in your CSS.
HTML:

CSS:
.content-area {
  margin-top: 60px;
  padding: 0 60px 60px;
}

2) Your header had three different position declarations on it! If you want a fixed header, it's just position:fixed; The code would look like this:
header {
    width: 100%;
    height: 50px;
    background-color: hsla(0, 0%, 20%, 1);
    box-shadow: 0px 2px 8px #222;
    position: fixed;
    top: 0;
}

3) The height of your menu items does not have an effect on the header size when I tested it. It also didn't even need a z-index declaration to work correctly. You might want to look at your example again.
I updated your code for you. It works now but your question is all over the place so I'm not 100% sure on this: http://jsfiddle.net/yaJyK/98/

A:
The approach with using a placeholder for the fixed element that gets lifted from the flow was correct.
Prepend a div, e.g. dummy-buffer or placeholder to the .fp-tableCell class with the height of the fixed element's height. In this example navHeight is the total height of the fixed element.
By giving the placeholder the same height as navHeight the rest of the content from the .section doesn't get cover up by the fixed element any more. In the image you can see the placeholder element while the .section is in transition.
note: I have also changed the default fullPage.css rule for this to work since I prefer to have the content of the section aligned at the top of the section.
.fp-tableCell {
  vertical-align:top !important;
}

$('.fp-tableCell').prepend($('
DUMMY BUFFER
'));

var navHeightUpdate = function(){
    var navHeight = $('.navigation').outerHeight();
    console.log('Navigation Height = '+navHeight);
    $('.dummy-buffer').css('height',navHeight);
};

navHeightUpdate();

https://jsfiddle.net/gvsasrnw/


text:
Q: How can I write vigenere cryptanalysis of persian text? How can I write Vigenere cryptanalysis for persian language?
Is there any sample source code for persian?

A: I was unable to find a Persian-language version of Vignere cryptanalysis.
You could try one of the solutions here and adapt the alphabet used to the persian alphabet. (You'll need persian-language letter usage statistics, it won't work with english ones.) I recommend the python but that's just personal taste.


text:
Q: How to update each custom tableview cell data at the same time? I am using Xcode 8.2.1 with Swift 3. I have one custom UITableViewCell containing a UITextView. When I type into the textView, the custom cell automatically grows. This part is working fine. I also want to update my other cells with the same data when I type in a specific cell. For example:
When I type text into the 5th cell, automatically enter the same data in the 11th, 15th and 18th cells. Those cells must be grown automatically as well. I've added data to the specific indexes of the array. But it doesn't get reflected in the tableView. How do I achieve this functionality?
Please go through following code I've implemented so far. This updateCellHeight method is a custom delegate method. This method is called when the user types in the textView.
func updateCellHeight(indexPath: IndexPath, comment: String) {

    let currentCellLyricVal = self.traduzioneArray[indexPath.row]["rics"]
    tempIndexArray.removeAll()

    for (index,element) in traduzioneArray.enumerated() {

        let lyricVal = element["rics"]
        if currentCellLyricVal == lyricVal {
            tempIndexArray.append(index)
        }
    }
    for index in tempIndexArray {
        self.traduzioneArray[index]["ione"] = comment
        self.lyricsTableView.beginUpdates()
        self.lyricsTableView.endUpdates()
    }
}

func textViewDidChange(_ textView: UITextView) {
    self.delegate.updateCellHeight(indexPath: self.cellIndexPath, comment: textView.text)
}

A: Once you update the data set with the new data. Reload the particular cells with the updated data set.
func updateCellHeight(indexPath: IndexPath, comment: String) {
        DispatchQueue.main.async {
            let currentCellLyricVal = self.traduzioneArray[indexPath.row]["rics"]
            tempIndexArray.removeAll()

            for (index,element) in traduzioneArray.enumerated() {

                let lyricVal = element["rics"]
                //You have to skip the current cell. by checking index != indexPath.row
                if currentCellLyricVal == lyricVal, index != indexPath.row {
                    tempIndexArray.append(index)
                }
            }

            for index in tempIndexArray {
                self.traduzioneArray[index]["ione"] = comment

                let updatedIndexPath = IndexPath(row: index, section: indexPath.section)
                  if let visibleCellIndexPaths = tableView.indexPathsForVisibleRows  {
                       if visibleCellIndexPaths.contains(updatedIndexPath) {
                            tableView.reloadRows(at: [updatedIndexPath], with: .automatic)
                       }
                  }
            }
        }
    }

NOTE: If the modified data set cells are visible then only we have to reload the particular cells.

A: Firstly, from storyboard or in your tableView Cell class set the textviews NumberOfLines = 0 .
In the height for row delegate have
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

In your viewdidLoad add these lines:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140

In the tableViewController
 func updateCellHeight(indexPath: IndexPath, comment: String) {

    let currentCellLyricVal = self.traduzioneArray[indexPath.row]["rics"]
    tempIndexArray.removeAll()

    for (index,element) in traduzioneArray.enumerated() {

        let lyricVal = element["rics"]
        if currentCellLyricVal == lyricVal {
            tempIndexArray.append(index)
        }
    }
    for index in tempIndexArray {
        self.traduzioneArray[index]["ione"] = comment
    }
      tableView.reloadRows(at: [IndexPath(row: 11, section: 1),IndexPath(row: 13, section: 1)], with: UITableViewRowAnimation.none)
}

By having the lines set to 0 and auto dimension height the cells automatically resize. Please also verify that you set your custom cells delegate to self in yourcellForRowmethod.

A: I think the issue with automatic data entering is the fact that reloading of cells results in resignFirstResponder() call.
This seems quite logical as on data reloading you actually give up some cells and ask the table view for new ones through cellForRowAt:. The old ones might not be the same so they resignFirstResponder().
One way to update the text of a cell is to directly alter the cell contents. You can do this for text view contents. Unfortunately for cell height there is no way to directly alter the cell without triggering heightForRowAt:.
UPDATE2: There IS a solution for iOS 8+ combining direct cell manipulation and AutomaticDimension on the table view.
Working flawlessly for UITextView. Check updates below. This is how the final result looks like:

UPDATE1: Code example for direct cell manipulation added
Use simple model to hold table view data:
// Simple model, for the example only
class Model {
    // The value of the text field
    var value: String?
    // The type of the cell
    var type: CustomCell.CellType = .typeA

    init(value: String) {
        self.value = value
    }

    init(value: String, type: CustomCell.CellType) {
        self.value = value
        self.type = type
    }
}

// Init the model.
var tableData = [
    Model(value: "Cell Type A", type: .typeA),
    Model(value: "Cell Type B", type: .typeB),
    Model(value: "Cell Type B", type: .typeB),
    Model(value: "Cell Type A", type: .typeA),
    Model(value: "Cell Type B", type: .typeB)]

And delegate like this:
// Delegate to update visible cells in the table view when text field value change.
protocol TextChangeDelegate {
    func textChangedAtCell(_ cell: CustomCell, text: String?)
}

Then init your custom cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // Will crash if identifier is not registered in IB
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomCell

    // For this to work you need to update the model on each text field text change
    cell.textValue.text = tableData[indexPath.row].value
    cell.index = indexPath.row
    cell.type = tableData[indexPath.row].type
    cell.textChangeDelegate = self

    return cell
}

In the Custom Cell:
class CustomCell: UITableViewCell {

    // The type of the cell. Cells with same type will be updated simultaneously.
    enum CellType {
        case typeA
        case typeB
    }

    // Very simple prototype cell with only one text field in it
    @IBOutlet weak var textValue: UITextField!

    // Default type
    var type = CellType.typeA
    // Index in the model. Not optional (or other special assumptions on initial value)
    // for simplicity of the example.
    var index = 0
    var textChangeDelegate: TextChangeDelegate?
}

extension CustomCell: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        // Assume we will return true. Any logic could appear here.
        // If we need to return false, don't call the delegate method.
        let result = true

        if result {
            let nsString = textField.text as NSString?
            let newString = nsString?.replacingCharacters(in: range, with: string)
            print("New: \(newString ?? "(nil)")")

            textChangeDelegate?.textChangedAtCell(self, text: newString)
        }

        return result
    }
}

This is how to implement the TextChangeDelegate in the view controller with direct cell access, i.e. without reloading data:
extension ViewController: TextChangeDelegate {

    func textChangedAtCell(_ cell: CustomCell, text: String?) {

        // Only visual update. Skip the cell we are currently editing.
        for visibleCell in tableView.visibleCells where visibleCell != cell {
            if let currentCell = visibleCell as? CustomCell,
                tableData[currentCell.index].type == cell.type {
                    currentCell.textValue.text = text
            }
        }

        // Update the model (including invisible cells too)
        for (index, data) in tableData.enumerated() where data.type == cell.type {
            tableData[index].value = text
        }

        // Avoid reloading here, as this will trigger resignFirstResponder and you will
        // have issues when jumping from text field to text field across cells.
    }
}

You now have simultaneous text update on all cells with same CellType. This example use UITextField (check UPDATE2 for UITextView).
UPDATE2 goes here. Cell with UITextView with simultaneous text AND height adjustment.
Use the model and controller from previous example (minor changes as you will use new cell).
Utilize UITableViewCell and put UITextView inside. In AutoLayout set constraints to text view:

Remember to disable scrolling and bounces to the text view (otherwise you will not have auto-height).
Don't forget to link textView's delegate to the UITextViewCell subclass.
Then in the cell, use
func textViewDidChange(_ textView: UITextView) {
    self.textChangeDelegate?.textChangedAtCell(self, text: textView.text)
}

Then, super important, in the ViewController's viewDidLoad, add this two settings
tableView.estimatedRowHeight = 50
tableView.rowHeight = UITableViewAutomaticDimension

and register the cell:
tableView.register(UINib(nibName: "CustomTextViewCell", bundle: nil),
                   forCellReuseIdentifier: "customTextViewCell")

Finally, add this code to TextChangeDelegate implementation from UPDATE1 to do the actual height update trick:
func textChangedAtCell(_ cell: UITableViewCell, text: String?) {

    <code from UPDATE 1 goes here>

    tableView.beginUpdates()
    tableView.endUpdates()
}

Enjoy!

A: every time you need update cell use this code:
func updateCellHeight(indexPath: IndexPath, comment: String) {

  //update dataModel according to new text
  ...
  //then reload visible tableview rows
  //pay atttention to beginUpdates endUpdates methods.
  //This do the trick)

  tableView.beginUpdates()
  tableView.reloadRows(at: indexPathsForVisibleRows ?? [], with: .none)
  tableView.endUpdates()

 }


text:
Q: Any simple way to require an EditTextPreference value to not be blank in Android? I have a number of EditTextPreference which must be a number 0-9. I can prevent other characters but not backspace. Backspace + Okay = an empty value. An empty value means when the it is retrieved and parsed into a number it will crash.
At the moment I check when a preference changes, if it has certain keys and no length, and if so, I re-save with a "0". Is there a simpler built in way to do this? A "require value" property, or at least something more automatic like being able to get the digits of the changed preference? (if digits is "0123456789" then it must not be empty).
So far in the settings activity I have:
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    //Prevent EditText from being non number
    String type = this.findPreference(key).getClass().getSimpleName();
    if( type.equals("EditTextPreference")
        //Put key of any allowed to be blank here...
                && prefs.getString(key, "0").length()==0 ){
            this.findPreference(key).setSummary("0");

        SharedPreferences.Editor prefedit = prefs.edit();
        prefedit.putString(key, "0");
        prefedit.commit();
    }
    updateSummaries();
}

(Set summary isn't working --^. Being able to check the android:digits="0123456789" property would make it so I wouldn't need to put keys of any that should be blank.)
Or in the main activity I can put all of the numerical prefs into Strings, check the string, set it to 0 if no good, then parse each string. As I use more of them this feels less appealing, not automatic.
String sTT = prefs.getString("mykey", "0");
>> x10
if(sTT.length()==0){ sTT="0"; }
>> x10
tt = Long.parseLong( sTT );
>> x10, different types

(This may still be the best way...?)

A: You can apply a TextWatcher to the EditTextPreference's underlying EditText. This allows you to intercept any changes to the text, and modify it in any way you want, by forcing it to contain a default digit (0) for example.
Although, I think it would make more sense overall for you to just cope with an empty input when you parse the data.

A: You could always make a simple preferences class, which takes an EditText with android:inputType = "number"

A: Really old, but just in case there;s someone having issues with this, This is what I usually do in such case,
have your Application class implemnt OnSharedPreferenceChangeListener,
it'll look like this:
public class MyAppApplication extends Application implements
        OnSharedPreferenceChangeListener

Put this in oncreate, so you can actively keep watch on Menu updates anytime;
preference = PreferenceManager.getDefaultSharedPreferences(this);
        preference.registerOnSharedPreferenceChangeListener(this);

and you can do this in any suitable part in your Application class,
if (preference.getString("prefkey", "").compareTo("") == 0) {
            SharedPreferences.Editor temp = preference.edit();
            temp.putString("prefkey", defaultServerAddress);
            temp.apply();
        }

I do this in my OnCreate tho, so I whenever the app starts, the preference item in question is, always reverted.
You can also do smart moves in public void onSharedPreferenceChanged, to keep track of the possibility that the preference item has become blank.

A: A really easy way to is to simply override EditTextPreference like this.
public class SafeEditTextPreference extends EditTextPreference {

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SafeEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public SafeEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public SafeEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SafeEditTextPreference(Context context) {
        super(context);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        boolean valid = this.getEditText().getText().toString().length() > 0;
        super.onDialogClosed(valid);
    }

}

Then use that instead of EditTextPreference. It will only save to preferences if the text string is at least 1 long, however you can change that validity check to be whatever you need it to be.
You could add a TextWatcher to give the user a more dynamic response.


text:
Q: BeautifulSoup (bs4) XML parser removes html entities look at this example:
# xml parser
bs4.BeautifulSoup('<price>£4</price>', 'xml')

# prints:
<?xml version="1.0" encoding="utf-8"?>
<price>4</price>

# html (lxml) parser
bs4.BeautifulSoup('£4', 'lxml')

# prints:
£4

Notice the £ sign. Why the XML parser removes it? What should I do to have it in the output? I need xml parsing, because the document contains some paired tags which are wrongly parsed by lxml parser (e.g. <link>).

A: The £ is not a standard XML entity - use for example £ instead. £ is a HTML entity, and can't be used without declaring (or embedding) them in a DTD.
Edit: See for example How do I define HTML entity references inside a valid XML document?


text:
Q: I got stuck on cycles to get the path of a sql directed graph I've got a table where I keep couples of numbers, to indicate arcs of a directed Graph, where every node is identified by an integer value:
CREATE TABLE graph (
n2 INTEGER NOT NULL,
n1 INTEGER NOT NULL,
PRIMARY KEY (id_area_possesso, id_area_utente)
CONSTRAINT CK CHECK (n1 <> n2)
)

Where n1 points n2, and so on; so, for instance, when I will insert
INSERT INTO graph VALUES (3,4)
INSERT INTO graph VALUES (9,3)
INSERT INTO graph VALUES (12,9)

I will obtain this graph: 4->3->9->12.
I use this query to get the list of the arcs (the path) starting from a node:
WITH tmp (n2,n1) AS (
SELECT G.n2 , G.n1
FROM Graph AS G
WHERE n1=3
UNION ALL

SELECT n2 , n1
FROM Graph AS G JOIN tmp ON (G.n1=tmp.N2)

)

SELECT * FROM tmp
GO

As result of this query I would obtain the arcs:

*

*(9,3)

*(12,9)

This query works fine, but when there are cycles on the graph:
INSERT INTO graph VALUES (0,1)
INSERT INTO graph VALUES (2,0)
INSERT INTO graph VALUES (1,2)

it goes on an infinite loop, and I get the error message:

The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

I can't use or create other tables in my project, so I will have to do everything on temporary ones. How can I fix my query in order to get the right path, avoiding to get stuck in cycles?

A: you will need to store each path/arc in a temp table.
then check that temp table on each pass to see if the path has already been saved before proceeding.

A: You can build a string with id's as you go and test if the id already is in.
;WITH tmp (n2,n1,nx) AS
(
  SELECT G.n2,
         G.n1,
         cast('/'+cast(G.n1 as varchar(10))+'/' as varchar(max))
  FROM Graph AS G
  WHERE n1=1
  UNION ALL
  SELECT G.n2,
         G.n1,
         tmp.nx+cast(G.n1 as varchar(10)) +'/'
  FROM Graph AS G
    JOIN tmp
      ON (G.n1=tmp.N2) and
         tmp.nx not like '%/'+cast(G.n1 as varchar(10))+'/%'
)

SELECT * FROM tmp


text:
Q: PostgreSQL Full Outer Join Using Position Why is it that in PostgreSQL you cannot use:
FULL OUTER JOIN
 . . .
ON POSITION(table1.column1 IN table2.column1) <> 0,
But you can accomplish the same thing with a left join and a right join and then using a union all to join the results. It's the same exact result set that I want and I feel it should be possible since it's possible to just do the right and left join manually. I can live with having to do it, but it'd be a lot simpler to write with just using a Full Outer Join.


text:
Q: How would I go about refactoring this view? So when I originally designed this view I did not take into account a desire to make changes later down the road...
Here my design...

And the the .h file...
#import <UIKit/UIKit.h>
@interface RegisterView : UITableViewController <UITextFieldDelegate>
@end

What I want to do is create a view and place all of the elements that I already have inside of it...
Is there a way that I can accomplish this, but not have to essentially re-write the entire .m file? Its around 400 lines, nothing tough but very laborious.
Thoughts?


text:
Q: Randomly missing nodes in html when scraping with GuzzleClient I'm dealing here with an issue on scrape because of the inconsistency of the child elements, that sometimes are present and other times missing.
Since I'm saving state referencing the $values[] array, what I found was that sometimes $value[18] is the email address, other times it can be the phone or fax.
The sample array of three iterations is as follows:
[0] => [
    [1] => Firm: The Firm One Name
    [2] => Firm:
    [3] => The Firm One Name
    [4] => Office: 5th Av. 18980, NY
    [5] => Office:
    [6] => 5th Av. 18980, NY
    [7] => City: New York
    [8] => City:
    [9] => New York
    [10] => Country: USA
    [11] => Country:
    [12] => USA
    [13] => Tel: +123 4 567 890
    [14] => Tel:
    [15] => +123 4 567 890
    [16] => Email: person.one@example.com
    [17] => Email:
    [18] => person.one@example.com
],
[1] => [
    [1] => Firm: The Firm Two Name
    [2] => Firm:
    [3] => The Firm Two Name
    [4] => Office: 5th Av. 342680, NY
    [5] => Office:
    [6] => 5th Av. 342680, NY
    [7] => City: New York
    [8] => City:
    [9] => New York
    [10] => Country: USA
    [11] => Country:
    [12] => USA
    [13] => Tel: +123 4 567 890
    [14] => Tel:
    [15] => +123 4 567 890
    [16] => Fax: +123 4 567 891
    [17] => Fax:
    [18] => +123 4 567 891
    [19] => Email: person.two@example.com
    [20] => Email:
    [21] => person.two@example.com
],
    [2] => [[1] => Firm: The Firm Three Name
    [2] => Firm:
    [3] => The Firm Three Name
    [4] => Office: 5th Av. 89280, NY
    [5] => Office:
    [6] => 5th Av. 89280, NY
    [7] => Country: USA
    [8] => Country:
    [9] => USA
    [10] => Fax: +123 4 567 899
    [11] => Fax:
    [12] => +123 4 567 899
    [13] => Email: person.three@example.com
    [14] => Email:
    [15] => person.three@example.com
]

As it might be noticeable, when I iterate and save $values[15] of the last array, which is the email address, on the first [0][15] corresponds to a Tel. number.
My question is, is there a simpler way than doing a 'crazy loop' over the fields and always save the email as an email and not as a phone number?
I'm using GuzzleClient() along with $node->filterXPath() and/or $node->filter() depending on what I have to grab.
The html structure I'm working on is very short and simple as the example below, sometimes there are nodes missing...:

Firm:

            Person One

Office:

            <address>
                5th Av.
18980,
NY
            </address>

City:

New York

Country:

USA

Tel:

+123 4 567 890

Fax:

+123 4 567 891

Email:

            person.one@example.com

A: I have dealt with the same situation before and the only solution for this situation is Regular Expression because Html elements changes every time and you can't keep track on values until you use regex, Here is your fix
$re = '/
Email:<\/div>

            (.*)<\/a>/';
$str = '

Firm:

            Person One

Office:

            <address>
                5th Av.
18980,
NY
            </address>

City:

New York

Country:

USA

Tel:

+123 4 567 890

Fax:

+123 4 567 891

Email:

            person.one@example.com

';

preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);

// Print the entire match result
var_dump($matches);

In the same way you have to prepare regex for other values and you are ready to go, the code above looks messy but you can remove spaces from string and also from regex to make it clean.

A: This can be easily done by regular expression, I dont have much exposure with PHP, but for regular expression:
you can use following command for key:
class="abc-u first">(.*):

& for value:
class="abc-u">(.*?)</

A: After taking some rest and thinking freshly about the problem, I found the solution that gets the data sanitised as needed. After all it's just a matter of filtering the results and get the correct values in the correct place in the array.
Here's what I make and works for any case (when adapted to ones needs):
$crawler->filterXPath('//*[@id="profiledetails"]/div')->each(function($node) use ($data, $start, $i) {

    // get the values
    foreach($node->filter('div') as $k => $v) {
        $values[] = trim($v->nodeValue);
    }

    // sanitise the data
    $sanitised = [];
    foreach($values as $k => $v) {
        trim($v); // trim to make sure there's no spaces
        if($v == 'Firm:') {
            $sanitised['firm_name'] = $values[$k + 1]; // Note: the +1 is to get the next node where the value is set
        }
        if($v == 'Office:') {
            $sanitised['address'] = $values[$k + 1];
        }
        if($v == 'City:') {
            $sanitised['city'] = $values[$k + 1];
        }
        if($v == 'Country:') {
            $sanitised['country'] = $values[$k + 1];
        }
        if($v == 'Tel:') {
            $sanitised['phone'] = $values[$k + 1];
        }
        if($v == 'Fax:') {
            $sanitised['fax'] = $values[$k + 1];
        }
        if($v == 'Email:') {
            $sanitised['email'] = $values[$k + 1];
        }
    }

    $data['firm_name'] = !empty($sanitized['firm_name']) ? $sanitized['firm_name'] : null;
    $data['address'] = !empty($sanitized['address']) ? nl2br($sanitized['address']) : null;
    $data['city'] = !empty($sanitized['city']) ? $sanitized['city'] : null;
    $data['country'] = !empty($sanitized['country']) ? $sanitized['country'] : null;
    $data['phone'] = !empty($sanitized['phone']) ? $sanitized['phone'] : null;
    $data['fax'] = !empty($sanitized['fax']) ? $sanitized['fax'] : null;
    $data['email'] = !empty($sanitized['email']) ? $sanitized['email'] : null;

    // Save the data
    ProfileModel::where('id', $i)->update($data);
    // just a console log to know where we are in case it fails on timeout
    echo "Done for profile id " . $i . PHP_EOL;
});

The result will always, for each iteration, be a correct array even when empty or missing nodes are found. It looks like this:
[
    ['firm_name'] = 'Firm Name One';
    ['address'] = '5th Av.
18980,
NY';
    ['city'] = 'New Yok';
    ['country'] = 'USA';
    ['phone'] = '+123 4 567 890';
    ['fax'] = null;
    ['email'] = 'person.one@example.com';
]

And now every single row on the DB gets the data (or NULL ) in the right columns.


text:
Q: Send SMS with Amazon SNS I am trying to send SMS through the AWS SNS using the SDK for php.
I already configure the user in IAM (created a user to do this), grant full access to SNS service and check the keys many many times.
I am using the code that was posted in this topic for testing link and receiving this message error

Fatal error: Uncaught exception 'Aws\Sns\Exception\SnsException' with message 'Error executing "Publish" on "https://sns.us-east-1.amazonaws.com"; AWS HTTP error: Client error: POST https://sns.us-east-1.amazonaws.com resulted in a 403 Forbidden response:   Sender SignatureDo (truncated...) SignatureDoesNotMatch (client): The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details

Anyone knows what I am doing wrong? I am not able to find the solution


text:
Q: need to list the item from facts output I need to save the target host's IP addresses to a file using set_fact. Below is my playbook, but it's giving output as a list.
  hosts:  all
  tasks:
    - set_fact:
        data:  "{{ ansible_all_ipv4_addresses }}"
    - set_fact:
        ip: "{{ data.split(',')  }}"

    - name: Show the devices
      shell: echo {{ item }} >> /tmp/ips
      with_items: "{{  ip  }}"

output:
ok: [system1] => {
    "data": [
        "172.19.0.1",
        "172.18.0.1",
        "172.20.0.1",
        "172.17.0.1",
        "172.16.108.124",
        "10.0.41.117"
    ]
}
cat /tmp/ips
[u'172.19.0.1', u'172.18.0.1', u'172.20.0.1', u'172.17.0.1', u'172.16.108.124', u'10.0.41.117']

Desired o/p is
 172.168.1.21
 172.168.1.22

A: Instead of
shell: echo {{ item }} >> /tmp/ips
with_items: "{{  ip  }}"

Use template.
template:
  src: ips.j2
  dest: /tmp/ips

with template ips.j2
{% for item in ip %}
{{ item }}
{% endfor %}

A: ansible_all_ipv4_addresses is already an array so you don't need to split it:
- copy:
    dest: /tmp/ips
    content: "{{ ansible_all_ipv4_addresses | join('\n') }}"

This will produce the desired output.


text:
Q: Is it valid to simplify $\sqrt{(t-7)^3}$ to $(t-7)^2$? $\lim\limits_{t \to 7^+} \dfrac{\sqrt{(t-7)^3}}{t - 7}$
Can you simplify the top of the quotient to   $(t-7)^2$ ?

Or a more general question, does the square root of exponent 3 simplify to exponent 2?

A: $\sqrt{(t-7)^3}=(t-7)^{\frac{3}{2}}=(t-7)(t-7)^{\frac{1}{2}}$.

A: i would say $\sqrt{(x-7)^3}=(x-7)\sqrt{x-7}$ for $x>7$

A: If $t \to 7^+$, the value of $t - 7$ will be always positive, since if $t$ is approaching $7$ from the right side, $t$ will always be a little bigger than $7$, and thus $t - 7$ will always be a little bigger than $0$ (i.e., positive).
So simplifying the limit:
$\lim \limits_{t \to 7^+} \dfrac{\sqrt{(t-7)^3}}{t-7}$
$\lim \limits_{t \to 7^+} \dfrac{\sqrt{(t-7)^2}\sqrt{(t-7)}}{t-7}$
$\lim \limits_{t \to 7^+} \dfrac{|t-7|\sqrt{t-7}}{t-7}$
Since $t-7$ will always be positive, $|t-7|=t-7$, and they cancel out from the numerator and the denominator, leaving:
$\lim \limits_{t \to 7^+} \sqrt{t-7}= 0$


text:
Q: Show that FACTORING $\le_P$ SPLITTING I want to show that FACTORING $\le_P$ SPLITTING. First let us recall the definitions:

FACTORING: Given an integer $n \ge 2$ find its prime factorisation.
SPLITTING: Given an integer $n \ge 2$ find two non-trivial factors of it.

The core idea for FACTORING $\le_P$ SPLITTING is easy: Suppose we have an algorithm $\mathcal{A}$ that solves SPLITTING. We can use $\mathcal{A}$ to find two non-trivial factors, say $a$ and $b$, of $n$. We can then use the AKS-test on $a$ and $b$ to test them for primality in polynomial time. If both are prime we are done. Otherwise we can recursively use $\mathcal{A}$ on them to find  non-trivial factors of $a$ and $b$ and repeatedly test them for primality with the AKS-algorithm until we found the prime factorisation of $n$.
But how can I estimate the runtime of the above scheme? Could you help me?

A: Consider a number as a list of prime factors. Each time you call split this list is partitioned in two parts and you recurse on both parts. The base case is a list of length 1 - a prime.
It should be obvious that the worst case performance happens when each split is as imbalanced as possible - only 1 prime is separated per split. In that case our performance is $O\left(l \cdot \left(s(n)+p(n)\right)\right)$ where $l$ is the length of our list and $s(n)$ is the time taken to split a number $n$ and $p(n)$ the time taken to check for primality.
But since each element in the list of prime factors must be at least two, we know that $2^l \leq n$ and thus $l \leq \log_2(n)$, and thus our total runtime is $O\left(\log n \cdot \left(s(n)+p(n)\right)\right)$.


text:
Q: Processing circle in webpages In Most of the web sites we see the common one 'Processing cricle' for indicating page loading /image loading etc.. and making the main(parent ,back) page faded..  I would like to know what are those concepts and how could I implement those

A: The circle probably indicates that there is a pending AJAX call.
Have a look at the AJAX Tutorial at w3schools for an introduction.
The "loading animations" can be generated at http://ajaxload.info/

A: @aioobe has a good answer, but as you didn't provide any example pages, I'll offer other reasons for progress indicators:

*

*Ajax calls may be in progress

*Very long page loads can use an animated gif during the load before the load event has fired

*Flash content may be loading (similar to AJAX as it's an asynchronous HTTP request)

*multi-threaded JavaScript may be executing.

Each situation has its own implementation, and you may want to either ask a new question in regard to each method, or turn this question into a community wiki.


text:
Q: How to manipulate data in list view that is populated by custom cursor adapter I have populated a list view using the custom cursor adapter, That listview consists of a checkbox and button in the below manner.
checkbox1 button1
checkbox2 button2
.
.
.

Now I want to navigate to another activity when click on the button in list view now my issue here is when I click on the button1 then I want to see the data in checkbox1 and similarly for other rows as well.
Now I am confused on how to maintain a sync between the checkbox and button and how to achieve the click functionality. How can I achieve this?

A: You will need to find your corresponding view in the list view implementing the onclickListener
For eg
    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

            Button b = (Button)v.findViewById(R.id.button);
                            b.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                                  Intent i=new Intent(this,SecondActivity.Class)
                                   startActivity(i);
                           }
            });
                            //Similarly for the checkbox
        }
    });

A: You can do the following on the Button's onClickListener if the Button and CheckBox share the same parent
boldButton.setOnClickListener(new OnClickListener()
{

    @Override
    public void onClick(View view)
    {
       View parentView = (View) view.getParent();
       CheckBox checkBox = (CheckBox) parentView.findViewById(R.id.check);
    }
});

This will give you the CheckBox corresponding to the clicked Button

A: Use a ViewHolder class in adapter class and use that in getView(), Then within getView
viewHolder.yourButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(viewHolder.checkbox.isChecked())
                                // toggle the check and do your work here
        }
    });

You can learn ViewHolder pattern here its very simple
Another example link

A: This Selectable ListView Tutorial link should help in your solution.

A: Check this post might help.
You have to preserve the state of row in listview so row can be populated with its state.

Android how to identify item in listview with checkbox


text:
Q: How can I determine a score result based on the goal count in mysql? Maybe this question is super specific but I can't really find a way to do it.
A bit of background. I'm studying, and In order to learn this I'm playing around counting stats from our Wednesday football matches with my friends.
Now in order to make data as normalized as possible and calculate everything programmatically, I have a table called matches and a table called goals.
Matches
+----+------------+
| id | date       |
+----+------------+
| 1  | 05-01-2022 |
+----+------------+
| 2  | 12-01-2022 |
+----+------------+

Goals
+----+--------------+
| id | match | team |
+----+--------------+
| 1  |   1   |  A   |
+----+--------------+
| 2  |   1   |  B   |
+----+--------------+
| 3  |   1   |  B   |
+----+--------------+
| 4  |   2   |  A   |
+----+--------------+
| 5  |   2   |  A   |
+----+--------------+

So my objective here is to count the goals for each team in each match, compare both values to determine the winner and come up with a result like this:
Results
+-------+------------+
| match | result     |
+-------+------------+
| 1     | B          |
+-------+------------+
| 2     | A          |
+-------+------------+

I'm currently doing this fairly straightforward using laravel on my app, but I'm trying to get it done through SQL queries only.
I also know that this would be much easier, if i simply added a goals_team_a, goals_team_b, result columns to my Matches table. If this is the actual correct solution is super easy to add, I just though at some point goals may differ from the score because of a typo or something and this is the way to be extra sure. Probably an overkill

A: The current structure of matches and goals is definitely flawed. If a given match id has no goals scored by either side there is no record of who played. By simply adding home and away teams to the match you have a more meaningful match entity and it becomes simple to query for the result.
Matches

id
kick_off
home_team_id
away_team_id

1
2022-01-05 10:00:00
1
2

2
2022-01-12 14:30:00
2
1

Teams

id
name

1
A

2
B

Additionally, if your goals table is as simple as suggested, it serves no purpose but I suspect this was simplification for the sake of providing an example.  Assuming there is a player and time goal scored as part of the goal table, it has obvious value.
Goals

id
match_id
team_id
player_id
time_scored

1
1
1
1
10:01:23

2
1
2
2
10:17:38

3
1
2
2
11:02:44

4
2
1
1
15:42:53

5
2
1
1
15:47:18

With the teams identified in the match you can then use something like -
select m.id as match_id,
  case
    when count(distinct hg.id) > count(distinct ag.id) then ht.name
    when count(distinct hg.id) < count(distinct ag.id) then at.name
    else 'draw'
  end as `result`
from matches m
join teams ht on m.home_team_id = ht.id
join teams at on m.away_team_id = at.id
left join goals hg on m.home_team_id = hg.team_id and m.id = hg.match_id
left join goals ag on m.away_team_id = ag.team_id and m.id = ag.match_id
group by m.id

to get -

match
result

1
B

2
A

Here's a db<>fiddle to play around with.


text:
Q: Access sql query help - football database I need to create a query that shows the average attendance by conference when at least one team played in a game.
I can get average for team1 no problem. Relationships screenshot

SELECT Conference.ConferenceName, AVG(Game.Attendance) AS AVG_ATT
FROM (Conference INNER JOIN School ON Conference.[ConferenceID] = School.[ConferenceID])
INNER JOIN Game ON School.[SchoolID] = Game.[Team1]
GROUP BY Conference.ConferenceName;

The problem I am having is adding Team2 to the equation.

A: You can use more complicated JOIN expressions than Table1.Field1 = Table2.Field2 in Access SQL, but note that you won't be able to edit the query in the Query designer.
SELECT Conference.ConferenceName, AVG(Game.Attendance) AS AVG_ATT
FROM (Conference INNER JOIN School ON Conference.[ConferenceID] = School.[ConferenceID])
INNER JOIN Game ON (
       School.[SchoolID] = Game.[Team1]
    OR School.[SchoolID] = Game.[Team2]
  )
GROUP BY Conference.ConferenceName;

A: I changed to a team table and it made the queries very easy.  I liked having Team1 and team2 inside the game table i might try your method to see how well it works.
game and  team screenshot


text:
Q: Opening a shared file in C++ without root previliges I am working on a Red-Hat machine without root prevliges.
I have some shared files that I can access using smb:// with username and password. Since I don't have root previliges, I can't mount the share (or at least, I haven't been able to find out how).
What I need is to open the file for reading\writing from a C++ code.
Is there any way to do so?

A: you can use libsmbclient library to do normal file access like smbc_open, smbc_fstat, smbc_lseek, smbc_read.