text:
Q: Turn off touchpad, point stick I just installed 18.04.2 on an HP 8460W.  Typically on laptops I like to:

*

*Turn off the touchpad when a USB mouse is connected

*Turn off the little joystick in the middle of the keyboard (and its buttons nr the spacebar) forever
How do I do either/both of these things in Ubuntu?  If it matters, I took the default Gnome-based desktop.
Out put of xinput
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ PS/2 Generic Mouse                        id=11   [slave  pointer  (2)]
⎜   ↳ SynPS/2 Synaptics TouchPad                id=12   [slave  pointer  (2)]
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Sleep Button                              id=8    [slave  keyboard (3)]
    ↳ HP HD Webcam [Fixed]: HP HD Web           id=9    [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=10   [slave  keyboard (3)]
    ↳ HP WMI hotkeys                            id=13   [slave  keyboard (3)]

Output of xinput --list-props 11
    Device 'PS/2 Generic Mouse':
    Device Enabled (148):   1
    Coordinate Transformation Matrix (150): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Natural Scrolling Enabled (283):   0
    libinput Natural Scrolling Enabled Default (284):   0
    libinput Scroll Methods Available (285):    0, 0, 1
    libinput Scroll Method Enabled (286):   0, 0, 1
    libinput Scroll Method Enabled Default (287):   0, 0, 1
    libinput Button Scrolling Button (288): 2
    libinput Button Scrolling Button Default (289): 2
    libinput Middle Emulation Enabled (290):    0
    libinput Middle Emulation Enabled Default (291):    0
    libinput Accel Speed (292): 0.000000
    libinput Accel Speed Default (293): 0.000000
    libinput Accel Profiles Available (294):    1, 1
    libinput Accel Profile Enabled (295):   1, 0
    libinput Accel Profile Enabled Default (296):   1, 0
    libinput Left Handed Enabled (297): 0
    libinput Left Handed Enabled Default (298): 0
    libinput Send Events Modes Available (268): 1, 0
    libinput Send Events Mode Enabled (269):    0, 0
    libinput Send Events Mode Enabled Default (270):    0, 0
    Device Node (271):  "/dev/input/event5"
    Device Product ID (272):    2, 1
    libinput Drag Lock Buttons (299):   <no items>
    libinput Horizontal Scroll Enabled (300):   1

Output of xinput --list-props 12
Device 'SynPS/2 Synaptics TouchPad':
    Device Enabled (148):   1
    Coordinate Transformation Matrix (150): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Tapping Enabled (301): 1
    libinput Tapping Enabled Default (302): 0
    libinput Tapping Drag Enabled (303):    1
    libinput Tapping Drag Enabled Default (304):    1
    libinput Tapping Drag Lock Enabled (305):   0
    libinput Tapping Drag Lock Enabled Default (306):   0
    libinput Tapping Button Mapping Enabled (307):  1, 0
    libinput Tapping Button Mapping Default (308):  1, 0
    libinput Natural Scrolling Enabled (283):   1
    libinput Natural Scrolling Enabled Default (284):   0
    libinput Disable While Typing Enabled (309):    1
    libinput Disable While Typing Enabled Default (310):    1
    libinput Scroll Methods Available (285):    1, 1, 0
    libinput Scroll Method Enabled (286):   1, 0, 0
    libinput Scroll Method Enabled Default (287):   1, 0, 0
    libinput Accel Speed (292): 0.000000
    libinput Accel Speed Default (293): 0.000000
    libinput Left Handed Enabled (297): 0
    libinput Left Handed Enabled Default (298): 0
    libinput Send Events Modes Available (268): 1, 1
    libinput Send Events Mode Enabled (269):    0, 0
    libinput Send Events Mode Enabled Default (270):    0, 0
    Device Node (271):  "/dev/input/event6"
    Device Product ID (272):    2, 7
    libinput Drag Lock Buttons (299):   <no items>
    libinput Horizontal Scroll Enabled (300):   1

Output of xinput --list-props 13
Device 'HP WMI hotkeys':
    Device Enabled (148):   1
    Coordinate Transformation Matrix (150): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
    libinput Send Events Modes Available (268): 1, 0
    libinput Send Events Mode Enabled (269):    0, 0
    libinput Send Events Mode Enabled Default (270):    0, 0
    Device Node (271):  "/dev/input/event8"
    Device Product ID (272):    0, 0

A: *

*to Turn off the touchpad when a USB mouse is connected run the below command
gsettings set org.gnome.desktop.peripherals.touchpad send-events 'disabled-on-external-mouse'
to reset the above command run the below command
gsettings reset org.gnome.desktop.peripherals.touchpad send-events

*To turnoff the little joystick.. you need to find out what is the ID for this joystick from xinput output and perhaps its required to disable meaningful ID's and see which one is the rite one..

from your xinput output it seems to be id 11 for joystick..
to disable this joystick run the below command
xinput --disable 11

above command will disable the joystick until you logout or reboot only..
to permanently disable it, add the command xinput --disable 11 command in your startup application preferences list..


text:
Q: php form create 2 posts somebody tried to create a plugin to display a form on the front, wich can add post . To fill it, user must create an account or login. When he create his account, he have to fill 2 field only for the database (not displayed in the backend).
When the form is submitted, it create a new post. But the problem is it create it twice, not only one. I don't understand why.
Could you help me ?
This is the code :
public function write_your_story_form() {

  if(is_user_logged_in() === false){
    echo do_shortcode('[theme-my-login]');
  }
  if(is_user_logged_in() === true) {
    global $current_user;
    $user_id = $current_user->ID;
    $initial_elle = get_user_meta($user_id, 'lk_initial_elle', true);
    $initial_lui = get_user_meta($user_id, 'lk_initial_lui', true);

    $content = '';
    $initial_ecriture = '';
    //Traitement du formulaire
    if(!empty($_POST['content']) &&
check_admin_referer('ajout_lettre_'.$user_id, 'champ-securite')) {
        $erreur = '';

        //Récupérer les champs obligatoires
        $content = sanitize_text_field($_POST['content']);
        $initial_ecriture = sanitize_text_field($_POST['initial_ecriture']);

         $post_id= wp_insert_post(array(
        'post_author' => $user_id,
        'post_content' => $content,
        'post_content_filtered' => $initial_ecriture,
        'post_title' => $letter_title,
        'post_status' => 'draft',
        'post_type' => 'post',
        'comment_status' => 'closed',
        'ping_status' => 'closed',
            ), true);

        if($post_id = 0){
            $erreur .= 'Erreur technique lors de l\'enregistrement de la lettre. ';
        } else {

                //Envoi de l'e-mail
                /*if(!empty($this->options['email-moderation'])){
                    $body = 'Une histoire a été postée .

                    Vous pouvez la publier en vous rendant dans votre
interface d\'administration';
                    $headers = array('Content-Type: text/html; charset=UTF- 8');
                    wp_mail($this->options['email-moderation'], 'Une annonce
a été postée', $body, $headers );
                }*/

                //Message de confirmation
                return '

Demande envoyée

Merci d\'avoir envoyer votre lettre. Celle-ci sera publiée après modération
Merci de votre compréhension.

';
        }
  }

ob_start();
?>

Écrire votre histoire

<?php if(!empty($erreur)){ ?>

<?php echo $erreur; ?>

    <?php } ?>
<form class="write-your-story-form" action="" method="post">
  <?php wp_nonce_field('ajout_lettre_'.$current_user->ID, 'champ-securite'); ?>
  Écrire votre lettre
  <textarea id="content" name="content" required></textarea>
  Écrire en tant que :
  <select id="initial_ecriture" name="initial_ecriture"required>
    <option value="<?php echo $initial_elle ?>"><?php echo $initial_elle ?></option>
    <option value="<?php echo $initial_lui ?>"><?php echo $initial_lui ?></option>
  </select>
  <input name="submit" id="submit" value="Envoyer ma lettre" type="submit">
</form>

<?php
$html = ob_get_contents();
    ob_end_clean();

    return $html;
  }
}

initial_il and initial_elle are only value for custom field in the database, these values are variables for an other script.
I tried with only one but the result is the same.
Thanks a lot for your help !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unsafe entailment with Haskell constraints I'm playing around with the constraints package (for GHC Haskell). I have a type family for determining if a type-level list contains an element:
type family HasElem (x :: k) (xs :: [k]) where
  HasElem x '[] = False
  HasElem x (x ': xs) = True
  HasElem x (y ': xs) = HasElem x xs

This works, but one thing it doesn't give me is the knowledge that
HasElem x xs   entails   HasElem x (y ': xs)

since the type family isn't an inductive definition of the "is element of" statement (like you would have in agda). I'm pretty sure that, until GADTs are promotable to the type level, there is no way to express list membership with a data type.
So, I've used the constraints package to write this:
containerEntailsLarger :: Proxy x -> Proxy xs -> Proxy b -> (HasElem x xs ~ True) :- (HasElem x (b ': xs) ~ True)
containerEntailsLarger _ _ _ = unsafeCoerceConstraint

Spooky, but it works. I can pattern match on the entailment to get what I need. What I'm wondering is if it can ever cause a program to crash. It seems like it couldn't, since unsafeCoerceConstraint is defined as:
unsafeCoerceConstraint = unsafeCoerce refl

And in GHC, the type level is elided at runtime. I thought I'd check though, just to make sure that doing this is ok.
--- EDIT ---
Since no one has given an explanation yet, I thought I would expand the question a little. In the unsafe entailment I'm creating, I only expect a type family. If I did something that involved typeclass dictionaries instead like this:
badEntailment :: Proxy a -> (Show a) :- (Ord a)
badEntailment _ = unsafeCoerceConstraint

I assume that this would almost certainly be capable of causing a segfault. Is this true? and if so, what makes it different from the original?
--- EDIT 2 ---
I just wanted to provide a little background for why I am interested in this. One of my interests is making a usable encoding of relational algebra in Haskell. I think that no matter how you define functions to work on type-level lists, there will be obvious things that aren't proved correctly. For example, a constraint (for semijoin) that I've had before looked like this (this is from memory, so it might not be exact):
semijoin :: ( GetOverlap as bs ~ Overlap inAs inBoth inBs
            , HasElem x as, HasElem x (inAs ++ inBoth ++ inBs)) => ...

So, it should be obvious (to a person) that if I take union of two sets, that it contains an element x that was in as, but I'm not sure that it's possible the legitimately convince the constraint solver of this. So, that's my motivation for doing this trick. I create entailments to cheat the constraint solver, but I don't know if it's actually safe.

A: I don't know if this will suit your other needs, but it accomplishes this particular purpose. I'm not too good with type families myself, so it's not clear to me what your type family can actually be used for.
{-# LANGUAGE ...., UndecidableInstances #-}
type family Or (x :: Bool) (y :: Bool) :: Bool where
  Or 'True x = 'True
  Or x 'True = 'True
  Or x y = 'False

type family Is (x :: k) (y :: k) where
  Is x x = 'True
  Is x y = 'False

type family HasElem (x :: k) (xs :: [k]) :: Bool where
  HasElem x '[] = 'False
  HasElem x (y ': z) = Or (Is x y) (HasElem x z)

containerEntailsLarger :: proxy1 x -> proxy2 xs -> proxy3 b ->
                          (HasElem x xs ~ 'True) :- (HasElem x (b ': xs) ~ 'True)
containerEntailsLarger _p1 _p2 _p3 = Sub Dict

An approach using GADTs
I've been having trouble letting go of this problem. Here's a way to use a GADT to get good evidence while using type families and classes to get a good interface.
-- Lots of extensions; I don't think I use ScopedTypeVariables,
-- but I include it as a matter of principle to avoid getting
-- confused.
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, UndecidableInstances #-}
{-# LANGUAGE TypeFamilies, TypeOperators #-}
{-# LANGUAGE DataKinds, PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE GADTs #-}

-- Some natural numbers
data Nat = Z | S Nat deriving (Eq, Ord, Show)

-- Evidence that a type is in a list of types
data ElemG :: k -> [k] -> * where
  Here :: ElemG x (x ': xs)
  There :: ElemG x xs -> ElemG x (y ': xs)
deriving instance Show (ElemG x xs)

-- Take `ElemG` to the class level.
class ElemGC (x :: k) (xs :: [k]) where
  elemG :: proxy1 x -> proxy2 xs -> ElemG x xs

-- There doesn't seem to be a way to instantiate ElemGC
-- directly without overlap, but we can do it via another class.
instance ElemGC' n x xs => ElemGC x xs where
  elemG = elemG'

type family First (x :: k) (xs :: [k]) :: Nat where
  First x (x ': xs) = 'Z
  First x (y ': ys) = 'S (First x ys)

class First x xs ~ n => ElemGC' (n :: Nat) (x :: k) (xs :: [k]) where
  elemG' :: proxy1 x -> proxy2 xs -> ElemG x xs

instance ElemGC' 'Z x (x ': xs) where
  elemG' _p1 _p2 = Here

instance (ElemGC' n x ys, First x (y ': ys) ~ 'S n) => ElemGC' ('S n) x (y ': ys) where
  elemG' p1 _p2 = There (elemG' p1 Proxy)

This actually seems to work, at least in simple cases:
*Hello> elemG (Proxy :: Proxy Int) (Proxy :: Proxy '[Int, Char])
Here

*Hello> elemG (Proxy :: Proxy Int) (Proxy :: Proxy '[Char, Int, Int])
There Here

*Hello> elemG (Proxy :: Proxy Int) (Proxy :: Proxy '[Char, Integer, Int])
There (There Here)

This doesn't support the precise entailment you desire, but I believe the ElemGC' recursive case is probably the closest you can get with such an informative constraint, at least in GHC 7.10.


text:
Q: Can a pair of pointers to different functions taking different types of parameters be compatible? Can we put a function address of a particular signature into a function pointer which is defined to have some other signature and use it seamlessly?
For example, the following code
#include <stdio.h>

void print_n(int *pn) {
    printf("%d\n", *pn);
}

void print_n_wrapper(void *p) {
    print_n(p);
}

int main(void) {
    int n = 123;
    void (*f)(void *) = print_n_wrapper;
    f(&n);
    f = print_n;
    f(&n);
    return 0;
}

gets compiled and runs fine in my machine. Am I invoking undefined behavior somehow?

A: Yes, it is undefined behaviour.
Quoting C11, chapter §6.3.2.3, Pointers, (emphasis mine)

A pointer to a function of one type may be converted to a pointer to a function of another
  type and back again; the result shall compare equal to the original pointer. If a converted
  pointer is used to call a function whose type is not compatible with the referenced type,
  the behavior is undefined.

and regarding the "function whose type is not compatible" part, the definition of compatibility goes like

For two function types to be compatible, both shall specify compatible return types.(146)
  Moreover, the parameter type lists, if both are present, shall agree in the number of
  parameters and in use of the ellipsis terminator; corresponding parameters shall have
  compatible types.

That means, void * and int * should have been the same types, but they are not. So, the functions are also not of compatible type.

A: The call to print_n(p) in print_n_wrapper is defined since all you're doing is converting a void* which was originally an int* to an int*
The assignment f = print_n; will give you trouble. Although the assignment is defined, the behaviour on the subsequent call f(&n) is undefined.


text:
Q: R - Shiny - Where can we find the .tar.gz file of the master version of DT package? I need to install the version 0.1.40 of the DT package (https://github.com/rstudio/DT) on a Linux server which is not connected to internet. Thus I can't use the statement devtools::install_github('rstudio/DT').
Thus I need to get the DT_0.1.40.tar.gz file to install this development version of DT.
Where can I find the tar.gz file of the version 0.1.40 of DT ?
Thanks.

A: If you are fine with the version on CRAN, you can go to DT's page on CRAN to download the package tarball. There is a link beside the text "Package source:". Here's the link for linux.
However, it looks like you want the development version that is currently not the version found on CRAN. You can actually download the source from github as a tarball using this link:
https://github.com/rstudio/DT/archive/master.tar.gz
then just transfer it to your linux box and install the package from source.
install.packages("/path/to/master.tar.gz", repos = NULL, type = "source")


text:
Q: How to change WebProjectOutputDir default location? Does anybody know, on a per project basis, whether you can set the WebProjectOutputDir in Visual Studio. I want to be able to have it so that when i hit Ctrl + Shift + B it automatically builds my web project to a specific directory, but I also need to be able to override this in my build script.

A: I ran into this when using Visual Studio for Mac, compiling an Umbraco project. Building would issue the following error:

Error MSB4044: The "KillProcess" task was not given a value for the
  required parameter "ImagePath"

It was returning an empty value for WebProjectOutputDir when compiling Rosyln, etc. Only the web project in the solution was compiling these items, so I edited the web project csproj file manually, and added the following to the global  at the top of the file:
    ...
    <WebProjectOutputDir>.\</WebProjectOutputDir>
</PropertyGroup>

Problem solved.

A: It is unnecessarily awkward to correctly do this based on the way that Microsoft.WebApplications.targets defines the _CopyWebApplication target and how Microsoft.Common.targets treats the OutDir and OutputPath properties.
If you want to change that in the project file itself then you should:

*

*Declare the property WebProjectOutputDir after the import to Microsoft.WebApplications.targets

*Declare the property OutDir before the import to Microsoft.WebApplications.targets
There are a few reasons why you have to do this.
Microsoft.WebApplications.targets will override any declaration of WebProjectOutputDir if it is declared before the import statement. Therefore it has to come after.
Also inside of Microsoft.WebApplications.targets the _CopyWebApplication is defined as follows:
<Target Name="_CopyWebApplication" Condition="'$(OutDir)' != '$(OutputPath)'" >
  ....
</Target>

Taking a look at the condition you will see that the target will not be executed if OutDir and OutputPath are equal to the same value. You cannot just change OutputPath because OutDir is based on OutputPath, so you have to change OutDir and make sure that it is before the import to that file because other properties are built based on that property.
Less than ideal, but hopefully that helps you.


text:
Q: Multiplication matrix vector with Python 3.x, numpy e multiprocessing I'm writing a benchmark to show the differences in time, cost, speed up, efficiency and effective of a sequential and parallel algorithm that calculate a system of linear equations using Python 3.5, but when i calculate with different processes, the calculation is not performed correctly because the result of the calculation in sequential (and with numpy) is different from that done in parallel. I also noticed that about half of the matrix, each time increasing the number of processes, does not calculate but sets to 0 the i-th position. What am I doing wrong? Where is the mistake and why? This is my code:
import random
import sys
import time
import multiprocessing
import math, numpy as np
from numpy import linalg
import argparse, sys, os

def creaMatrici(n):
    A = [[random.random() for x in range(n)] for x in range(n)]
    B = [random.random() for x in range(n)]
    #A^(-1)
    A = np.linalg.inv(A)
    return A,B

def np_moltiplica(a, b):
    c = np.dot(a,b)
    return c

def moltiplica_seriale(A,b,n):
    c = [0 for x in range(n)]
    for i in range(0,len(A)):
        for j in range(0,len(A)):
            c[i] += A[i][j] * b[j]
    return c

def moltiplica_parallelo(result_queue, worker_index, chunk_boundary, A,b):
    n = len(A)
    result = []
    for m in range(n):
        output = moltiplica_seriale(
                A[chunk_boundary[0]:chunk_boundary[1],:],b,n)
        result.append(output)

    result_queue.put((worker_index, result))

###########################################################################

def divisione_lavoro(nWorkers, A,b):
    def calcola_partizionamento_lavoro(l, n):
        c = int(math.ceil(len(l)/float(n)))
        return c

    sizePartizionamento = calcola_partizionamento_lavoro(A, nWorkers)
    limitiMatriciDivise = [(i, i+sizePartizionamento) for i in range(0, (len(A)), sizePartizionamento)]

   if nWorkers != len(limitiMatriciDivise):
        return None

    result_queue = multiprocessing.Queue()
    processiFigli = []
    for worker_index in range(nWorkers):
        processiFigli.append(
               multiprocessing.Process(target=moltiplica_parallelo,
                             args=(
                                   result_queue,
                                   worker_index,
                                   limitiMatriciDivise[worker_index],
                                   A,
                                   b)
                                      )
                           )

    for c in processiFigli:
        c.start()

    results = [0 for n in range(len(A))]

    for _ in range(nWorkers):
        worker_index, result_chunk = result_queue.get(block=True)
        chunk_boundary = limitiMatriciDivise[worker_index]
        results = result_chunk[0]

    for c in processiFigli:
        c.join()
    return results

    ###########################################################################

def main(argv=None):
    if argv is None:
        argv = sys.argv

    n = int(argv[1])

    A,b = creaMatrici(n)

    #########################SERIALE##########################

    start = time.time()
    c = moltiplica_seriale(A,b,n)
    end = time.time()

    duration = (end-start) % 60
    print ('Risultato = ', c)
    print ('\nTempo seriale: %.5f s' % duration)

    #########################NUMPY############################

    start = time.time()
    c = np_moltiplica(A,b)
    end = time.time()

    duration = (end-start) % 60

    print ('\n\nRisultato = ', c)
    print ('\nTempo usando il modulo numpy: %.5f s' %duration)
    print ('\n\n')

    ######################MULTIPROCESSING#######################

    durations = []
    n_children = [1, 2, 4, 8]
    for n in n_children:
        start = time.time()
        result = divisione_lavoro(n, A, b)
        if result is None:
            continue
        duration = (time.time() - start) %60
        if n == 1:
            print ("Risultato calcolato con %s processo figlio: %s" % (n, result))
        else:
            print ("Risultato calcolato con %s processi figli: %s" % (n, result))
        print ("Tempo: %.2f s" % duration)
        print ('\n\n')
        durations.append(duration)

    costo = [n*d for n,d in zip(n_children,durations)]
    speedup = [durations[0]/d for d in durations]
    efficienza = [s/n for s,n in zip(speedup, n_children)]
    efficacia = [s/c for s,c in zip(speedup,costo)]
    for n, costo, speed, efficienza, efficacia in zip(n_children,costo,speedup,efficienza,efficacia):
        if n == 1:
            print ("costo con %s-processo figlio: %.2f" % (n,costo))
            print ("speedup con %s-processo figlio: %.2f" % (n, speed))
            print ("efficienza con %s-processo figlio: %.2f" % (n, efficienza))
            print ("efficacia con %s-processo figlio: %.2f\n" % (n, efficacia))
        else:
            print ("costo con %s-processi figli: %.2f" % (n,costo))
            print ("speedup con %s-processi figli: %.2f" % (n, speed))
            print ("efficienza con %s-processi figli: %.2f" % (n, efficienza))
            print ("efficacia con %s-processi figli: %.2f\n" % (n, efficacia))

if __name__ == "__main__":
    sys.exit(main())


text:
Q: List all values in a column in the order of another column and change the output for one of the values I have a table called fruits with fields fruit_id, fruit_name. I want to output names of all the fruits in the table in the order of the fruit_id, but for "water melon" I just want to output "melon". For all other fruits, I want to output the the entire fruit name as it is in the table.
For example, if I have this data in the table:
fruit_id | fruit_name
---------|-----------
1        | apple
2        | guava
3        | yellow mango
4        | water melon
5        | cacao
6        | coconut
7        | green mango

I want to output:
apple
guava
yellow mango
melon
cacao
coconut
green mango

How can you obtain such output?
I tried
SELECT *
FROM fruits
WHERE fruit_name
NOT IN
(
 'apple',
 'guava',
 'yellow mango',
 'water melon',
 'cacao',
 'coconut',
 'green mango'
)
ORDER BY fruit_name;

A: Since you are obviously using a subtle categorization scheme - yellow and green mangos are different but somehow a water melon is just a melon, you need to give your fruit a "category" as well as a name. Then you can select the distinct category to get just the list of categories.

A: Store the value without the 'water' part.
If that's not an option you can use PHP http://php.net/str_replace or http://www.php.net/explode to remove the first word.
A possible option:
$sql = mysql_query("SELECT * FROM `fruits`");
while($row = mysql_fetch_array($sql)){
   echo str_replace('water', '', $row[0]);
}

A: If you want all the values of a given column as they are, except change one specific value with something else, you can use the REPLACE function, which applies a simple string replacement:
SELECT REPLACE(fruit_name, 'water melon', 'melon')
FROM fruits
ORDER BY fruit_id

A few notes:

*

*REPLACE(x, y, z) searches the value of x for any occurences of the string y and replaces them with the string z.

*If you want the results to have the fruit_name column heading, you need to add AS fruit_name to the end of the first line, because if you're selecting a calculated column (i.e. the results of a function), by default the column in won't have a name. It won't automatically title the column in the results according to the name of the column to which you're applying the function. So, that would be:
SELECT REPLACE(fruit_name, 'water melon', 'melon') AS fruit_name

*Your query has ORDER BY fruit_name, but that would give you the values of the fruit_name field in alphabetical order. According to your example, you want them in the order of the ID. You can order by a column that's not part of what you're selecting (e.g. SELECT column1, column2 FROM table ORDER BY column 3), so just order by the fruit_id column.

*Your query would return no results at all from your sample table. WHERE column1 NOT IN (<list>) returns only records where the value of column1 is not equal to any of the items in the list. Since your list contains all the fruit names, you're excluding everything. If applied to a larger data set, you'd get everything except those seven fruit names. So either way, "water melon" wouldn't be in the results at all (nor would apple, guava, yellow mango, etc.).

A: select case fruit_name when 'water melon' then melon else fruit_name end
from fruits
order by fruit_id


text:
Q: What is the most general form of Hamiltonian to which MERA ansatz can be applied? As far as I understand one can only use MERA(Multiscale Entanglement Renormalization Ansatz) to find ground state for  Hamiltonians of following form(with possible simplifications due to additional symmetries):
$$H =\sum_{i} h^{[i,i+1]}$$
I can see from the article of Vidal that the whole algorithm is based on aforementioned form of Hamiltonian.
My question is whether one can still use MERA for more complicated(non-local) Hamiltonians? Or is there any principal problem which prevents us from doing that?
Suppose it is impossible. Are there any generalisations of MERA(or may be other kinds of tensor networks) which deal with non-local Hamiltonians?


text:
Q: Bind element inside of datatemplate to parent's property how can i bind an element inside of a template to a property of its parent like:
<Button Tag="rofl">
   <Button.ContentTemplate>
      <DataTemplate>
         <TextBlock Text="{ HERE I WANT TO BIND TO THE BUTTONS TAG }"/>
      </DataTemplate>
   </Button.ContentTemplate>
</Button>

Is that possible?

A: In addition to @Pedro Lamas's answer you can also perform this by the following way:
        <Button x:Name="ButtonTemplate" Tag="rofl">
            <Button.ContentTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Tag, ElementName=ButtonTemplate}"/>
                </DataTemplate>
            </Button.ContentTemplate>
        </Button>

You define a name for your control and access it's property in it's DataTemplate thanks to the ElementName feature.

A: You should be able to use a RelativeSource with the TemplatedParent to do that:
<TextBlock Text="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}"/>


text:
Q: Getting HTML instead of JSON from xmlhttp.responseText im new to AJAX and i got the following problem. I want to receive a JSON Array from my Servlet and use the JSON Objects in my JavaScript file. I think i didn't really understood the concept behind that and google did not help me very well. Here are the 2 Snippets of the Javascript and the Servlet.
Javascript:
var xmlhttp = new XMLHttpRequest();
var kaljson;
xmlhttp.onreadystatechange = function(){
   if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
      console.log(xmlhttp.responseText);
      kaljson = JSON.parse(xmlhttp.responseText);
   }
}
xmlhttp.open("GET","KalenderFaerben",true);
xmlhttp.send();

for(var i = 0; i < kaljson.length; i++){
   alert(kaljson[i].datum);
}

Servlet:
HttpSession session = request.getSession();
ArrayList<NotizBean> kalender = (ArrayList<NotizBean>) session.getAttribute("kalender");
String kalenderArray = "[";
for (int i = 0; i < kalender.size(); i++) {
    kalenderArray += "{\"datum\":\"" + kalender.get(i).getDatum()+"\"}";
    if(i < (kalender.size()-1))
        kalenderArray += ",";
}
kalenderArray += "]";
System.out.println(kalenderArray);
request.setAttribute("kalenderJson", kalenderArray);

RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/kalender.jsp");
dispatcher.forward(request, response);

Where am i wrong? Hope someone can help me.

A: Okay, i solved the problem. I just didn't understand the concept behind all of this. I was dispatching to a usual jsp file with HTML content and not to a jsp file with JSON objects only.


text:
Q: What kind of graph shows the distance between any 2 points as a measure of similarity between them? I would like to start by saying that I have looked across several sites on the StackExchange website, and have determined this would be the best to ask my question as it regards data-visualisation techniques.
I recall attending a conference several years ago. The conveners were discussing methods of data visualisation and they showed a 2-dimensional scatter graph with each point being a country. And on this graph there was a reason why there were no units on the XY-axes.
Each point encapsulated several metrics of a country such as literacy rate, GDP per capita, HDI, mortality rate, income inequality etc and hence these metrics couldn't be condensed on a 2-D axis.
Yet, their was meaning behind these scattered points. Each point's distance to another point showed how similar they were to each other. I cannot recall the underyling method of measuring 'similarity' but I'm suppose correlation or some kind of clustering method was used.
I have attached a crude example drawn to show what I mean by this.
This is purely drawn crudely, but I hope this conveys the technique used and the example case as well. Countries who's Economies are similar, such as G8 nations are closer together, and those developing such as China, Brazil and India are also closer together. Yet note the visual distance between SSA countries and G8 ones. They are far apart because they are highly distinct from each other, yet closer to developing nations such as China etc.
To summarise, the distance from any given point to another given point has meaning and is a measure of their similarity. I found this kind of graphing technique really insightful and interesting, but I just cannot remember what it is called and how to implement it for other datasets and I was wondering if anyone knows.
I hope that I have explained myself clearly, I understand that this isn't as heavy of a statistics question but I feel that this is relevant to the topics defined as suitable under this site.


text:
Q: pandas group by and find first non null value for all columns I have pandas DF as below ,
id  age   gender  country  sales_year
1   None   M       India    2016
2   23     F       India    2016
1   20     M       India    2015
2   25     F       India    2015
3   30     M       India    2019
4   36     None    India    2019

I want to group by on id, take the latest 1 row as per sales_date with all non null element.
output expected,
id  age   gender  country  sales_year
1   20     M       India    2016
2   23     F       India    2016
3   30     M       India    2019
4   36     None    India    2019

In pyspark,
df = df.withColumn('age', f.first('age', True).over(Window.partitionBy("id").orderBy(df.sales_year.desc())))

But i need same solution in pandas .
EDIT ::
This can the case with all the columns. Not just age. I need it to pick up latest non null data(id exist) for all the ids.

A: Use GroupBy.first:
df1 = df.groupby('id', as_index=False).first()
print (df1)
   id   age gender country  sales_year
0   1  20.0      M   India        2016
1   2  23.0      F   India        2016
2   3  30.0      M   India        2019
3   4  36.0    NaN   India        2019

If column sales_year is not sorted:
df2 = df.sort_values('sales_year', ascending=False).groupby('id', as_index=False).first()
print (df2)
   id   age gender country  sales_year
0   1  20.0      M   India        2016
1   2  23.0      F   India        2016
2   3  30.0      M   India        2019
3   4  36.0    NaN   India        2019

A: print(df.replace('None',np.NaN).groupby('id').first())

*

*first replace the 'None' with NaN

*next use groupby() to group by 'id'

*next filter out the first row using first()

A: Use -
df.dropna(subset=['gender']).sort_values('sales_year', ascending=False).groupby('id')['age'].first()

Output
id
1    20
2    23
3    30
4    36
Name: age, dtype: object

Remove the ['age'] to get full rows -
df.dropna().sort_values('sales_year', ascending=False).groupby('id').first()

Output
   age gender country  sales_year
id
1   20      M   India        2015
2   23      F   India        2016
3   30      M   India        2019
4   36   None   India        2019

You can put the id back as a column with reset_index() -
df.dropna().sort_values('sales_year', ascending=False).groupby('id').first().reset_index()

Output
   id age gender country  sales_year
0   1  20      M   India        2015
1   2  23      F   India        2016
2   3  30      M   India        2019
3   4  36   None   India        2019


text:
Q: Accessing multidimensional arrays in POST data in my app POST variable contains some arrays. How can I loop POST variable to get the arrays data which are keys in  POST variable in PHP. Any help is appreciated.

A: Your HTML must be:
<form action=":URL:" method="post">
    <input type="hidden" name="some[0]" value="0" />
    <input type="hidden" name="some[1]" value="1" />
    <input type="hidden" name="some[2]" value="2" />
    <input type="hidden" name="some[3]" value="3" />
    <input type="hidden" name="some[4]" value="4" />
    ...
</form>

So then in PHP you can do:
if (isset($_POST['some']))
{
    foreach ($_POST['some'] as $key => $value)
    {
        echo $key, $value;
    }
}

Here you are... hoping that it was your question.

A: This seems to answer your question, if I understand correctly you have a multidimensional array so $_POST['mypost'][$i] where $i is the key/index

A: echo "<pre>";
print_r($_POST);
echo "</pre>";
exit;

From this output you can easily find the way

A: Try:
foreach($_POST as $v)
{
    //DO SOMETHING WITH $v
    ...
}


text:
Q: Delay in Unregistering Geofences So I tried Geofencing in my app. I was able to trigger successfully my app to send a notification if my phone has entered into a Geofence. However, I noticed that even if I unregistered the Geofence already, the app takes like around 3mins at least to unregister. I was able to verify this by unregistering the Geofence via a Checkbox and closing the app. The app still notifies me that I have entered a Geofence even when it has already been unregistered.
It was only after a specific amount of time that the system finally stops notifying me that I entered a geofence. So it seems unregistering takes some times.. Has anyone noticed this? Any reasons why?
here is my code snippet to unregister. The log in my app says I was successfully able to unregister.
try {
    LocationServices
        .getGeofencingClient(mContext)
        .removeGeofences(getGeofencePendingIntent())
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.v(LOG_TAG, "Geofences unregistered");
            }
    });
} catch (SecurityException securityException) {
    Log.v(LOG_TAG, "Security Exception Error, Geofences not Unregistered. "
        + securityException.toString());
}


text:
Q: Switching from Wordpress to Drupal Search Engine Problems I have been running a WP site for a little over 6 months now and I'm beginning to run into WP limitations on post styles (yes, I know about WP3's post types).
I would like to completely change the site over to Drupal, but I'm worried about the Search Engine effects.
For instance: We have finally just put on many pages images on Google Images - we will lose all those? Will it cause the site to get blacklisted due to the change? Or will Google recognize the site's change and just reindex the images?

A: Do you mean you have referenced images in the content hosted on Google Images, or you uploaded images to Google for use in the content?
Either way, you shouldn't have any short or long term affects with SEO, as long as you institute the same SEO in your site when converting. For example, meta tags, meta keywords, description, site name etc.
Check out these modules:

*

*http://drupal.org/project/nodewords

*http://drupal.org/project/seo_checklist

*http://drupal.org/project/page_title

*http://drupal.org/project/wordpress_import

*http://drupal.org/project/contentoptimizer

*http://drupal.org/project/xmlsitemap

A: Also, Nodewords 1.13 and newer can let you add the OpenGraph meta tags, which are used with Facebook to provide the customized summary blocks when you bookmark a page.


text:
Q: How to save data when you tried to reference the schema I am trying to save information from a book that contains in its eschema auhtor and genre that I have it referenced in different files.
The problem is that when I make the reference in the main eschema. The book to have the reference of the author and the genre with the created book only keeps me the information of the book but does not make reference neither to the gender nor to the author
book.js
   const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  author: {
    type: mongoose.Schema.ObjectId,
    ref: 'Author',
  },
  numberInStock: {
    type: Number,
    default: 0,
  },
  image: {
    type: String,
    default: '/path/to/default/image.png',
  },
  genre: {
    type: mongoose.Schema.ObjectId,
    ref: 'Genre',
  },
});

module.exports = mongoose.model('Books', bookSchema);

author.js
const mongoose = require('mongoose');

const authorSchema = new mongoose.Schema({
  name: String,
  publicatons: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Book',
  }],
});

module.exports = mongoose.model('Author', authorSchema);

createBook.ejs

Add a New Book

            <form action="/books/new/create" method="post">

                             Book Name:
                            <input type="text"  class="form-control" name="name">

                            Author
                            <select class="form-control"  name="<%= author._id %>">
                            <% author.forEach(function(authors){ %>
                            <option><%= authors._id %></option>
                            <% }); %>
                            </select>

                            Genre
                            <select class="form-control"  name="<%= genre._id %>">
                            <% genre.forEach(function(genres){ %>
                            <option><%= genres.name %></option>
                            <% }); %>
                            </select>

                            Number in stock:
                            <input type="number"  class="form-control" name="numberInStock">

                            Image:
                            <input type="text"  class="form-control" name="image">

                        <button type="submit" class="btn btn-success">Success</button>

            </form>

this is the part of the front where I try to send the data to the backent, but only manage to save, the name, image, quantity but not the referenced data.
controller.js
   const create = (req, res, next) => {
  if (!req.body) {
    return res.status(400).json({
      error: 'No data',
    });
  }
  const book = new Books(req.body);
  book.save((err, result) => {
    if (err) {
      return res.status(400).json({
        error: err.message,
      });
    }

    return res.status(201).json({
      message: 'Book created succesfully',
      result,

    });
  });
};

Routes controller
const express = require('express');

const router = express.Router();
const bookController = require('../controllers/book');
const booksave = require('../controllers/create');
const authorController = require('../controllers/author');
const genreController = require('../controllers/genre');

router.get('/books/home/:page', bookController.list);

router.get('/books/new', bookController.createTemplate);
router.post('/books/new/create', booksave.create);

router.get('/books/details/:id', bookController.bookDetail);

router.get('/books/new/create/genre', genreController.createGenreTemplate);
router.post('/books/new/genre', genreController.createGenre);

router.get('/books/new/create/author', authorController.createAuthorTemplate );
router.post('/books/new/author', authorController.createAuthor);

module.exports = router;

create new book render
controller.createTemplate = (req, res) => {
  Author.find({}, (err, allAuthors) => {
    if (err) {
      console.log(err);
    } else {
      Genre.find({}, (err, allGenres) => {
        if (err) {
          console.log(err)
        } else {
          res.render('new', { author: allAuthors, genre: allGenres });
        }
      })

    }
  });
};

technically what I hope to obtain is that when I save the information of the book this has a reference to its author and to the genre and automatically the author has a references to the books that are referenced with the same

A: Change the name attribute in <select class="form-control"  name="<%= genre._id %>"> to name='author' same as in your bookSchema, and in <select class="form-control"  name="<%= genre._id %>"> to name='genre'.
The problem is your sending a post request with the following body :
{ name: /*value*/ , <%= author._id%>: /*value*/, <%= genre._id%>: /*value*/, numberInStock: /*value*/, image: /*image*/ }

The constructor of your Book model recognizes name, numberInStock and image, but not <%=author_id%> and <%=genre._id%>.
Change this also:
author: {
    type: mongoose.Schema.ObjectId,
    ref: 'Author'
  },
genre: {
    type: mongoose.Schema.ObjectId,
    ref: 'Genre'
}

to
author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: ref: 'Author'
}
genre: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Genre'
}

You also need to pass genre._id instead of genres.name, and author._idas value attributes like this :

<form action="/books/new/create" method="post">
    <select name="author">
    <% author.forEach(function(authors){ %>
      <option value="<%= authors._id %>" ><%= authors.name %></option>
    <% }); %>
    </select>
    <select name="genre">
    <% genre.forEach(function(genres){ %>
      <option value="<%= genres._id %>" ><%= genres.name %></option>
    <% }); %>
    </select>
    <button type="submit">Success</button>
</form>

A: Of the values of the front I'm just getting
{name: 'Digital Fortress', numberInStock: '', image: ''}

const create = (req, res, next) => {
  if (!req.body) {
    return res.status(400).json({
      error: 'No data received',
    });
  }
  const book = new Books(req.body);
  book.save((err, result) => {
    if (err) {
      return res.status(400).json({
        error: err.message,
      });
    }

    console.log(req.body);
    return res.status(201).json({
      message: 'Book created succesfully',
      result,

    });
  });
};


text:
Q: Basemap library using Anaconda Jupyter Notebooks - KeyError: PROJ_LIB I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error:
KeyError: 'PROJ_LIB'

After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError.
Here's what I did in my MacOS terminal:
conda create --name Py3.6 python=3.6 basemap
source activate Py3.6
conda upgrade proj4
env | grep -i proj
conda update --channel conda-forge proj4

Then in Jupyter Notebook I run the following:
from mpl_toolkits.basemap import Basemap

Can anyone tell me why this results in a KeyError?

A: The problem occurs as the file location of "epsg" and PROJ_LIB has been changed for recent versions of python, but somehow they forgot to update the init.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file:
C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share
So you have to add this path at the start of your code in spyder or whatever field you are using.
import os

os.environ['PROJ_LIB'] = r'C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share'

from mpl_toolkits.basemap import Basemap

A: Need to set the PROJ_LIB environment variable either before starting your notebook or in python with os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'
Ref. Basemap import error in PyCharm —— KeyError: 'PROJ_LIB'

A: In Windows 10 command line: first find the directory where the epsg file is stored:
where /r "c:\Users\username" epsg.*

...
c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share\epsg
...
then either in command line:
activate envname

SET PROJ_LIB=c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share

(make sure there are no leading on trailing spaces in the path!) and then
jupyter notebook

or add this to your jupyter notebook (as suggested by john ed):
import os

os.environ['PROJ_LIB'] = r'c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share'

A: If you can not locate epsg file at all, you can download it here:
https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg
And copy this file to your PATH, e.g. to:
os.environ['PROJ_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af_0\Lib\site-packages\mpl_toolkits\basemap\data\'
This is the ONLY solution that worked for me on Windows 10 / Anaconda 3.

A: Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me!


text:
Q: Add, remove input box using javascript So what i am trying to do is to have
1.add function to add an input box
2.remove function to remove the last input box in the list
3.sort function to sort the list of input texts by alphabetic order
I think my add function is working, but i am running into problem when i am trying to remove the last input box or trying to sort it.
Any idea or suggestion would be very much appreciated. thanks

<form id="mainform" >
<button onclick="add()">add</button>
<button onclick="remove()">remove</button>
<button onclick="sort()">sort</button>
</form>

<script>
    var i = 0;
    var count =0;
    function add() {
         var x= document.createElement("INPUT");
         x.setAttribute("type", "text");
         x.setAttribute("placeholder", "Name");
         i += 1;
         count=count+1;
         document.body.appendChild(x);
    }
    function remove(){
         i -= 1;
         count=count-1;
    }

    function sort(){
         var x;
         x=count;
         var strings=[]
         var t;
         var i=0;
         t=x;
         while(t!=0){
              strings.push(document.forms["mainform"].elements[i].value);
              t=t-1;
              i=i+1}

         strings=strings.sort()
         var j=0;
         var msg='';
         while(x!=0){
              var msg=msg+strings[j]+'\n';
              document.forms["mainform"].elements[j].value=strings[j];
              j=j+1;
              x=x-1;}
   }
</script>

A: Looks like your add function adds the inputs directly to the body, while your sort function is looking for elements in the form['mainform'] element.
Your remove function is just decrementing your iterator without actually affecting the form at all.

A: That would do the job:

    <form id="mainform" >
    <input type="button" value="add" onclick="add()"></input>
    <input type="button" value="remove" onclick="remove()"></input>
    <input type="button" value="sort" onclick="sort()"></input>
    </form>

    <script>
        function add() {
             var x= document.createElement("INPUT");
             x.setAttribute("type", "text");
             x.setAttribute("placeholder", "Name");
             x.setAttribute("class", "someInput");
             document.body.appendChild(x);
        }

        function remove() {
          var childs = document.body.getElementsByClassName("someInput");
          if(childs.length > 0) {
            document.body.removeChild(childs[childs.length - 1]);
          }
        }

        function sort(){
          var hash = {};
          var childs = document.body.getElementsByClassName("someInput");

          // Map each element to its value
          for(var i = 0; i < childs.length; i++) {
            var currentElement = childs[i];
            hash[currentElement.value] = currentElement;
          }

          // Remove all added elements
          for(var i = 0; i < childs.length; i++) {
            var currentElement = childs[i];
            document.body.removeChild(currentElement);
          }

          // Sort by map keys, and add all elements back sorted
          Object.keys(hash).sort().forEach(function(v, i) {
            document.body.appendChild(hash[v]);
          });
       }
    </script>

Please note that I replaced the button elements with input elements in order to prevent the form from being submitted.
Also pay attention that I marked each inserted textbox with class named "someInput". That will make our life easier when we want to query and get all the inserted textboxes.


text:
Q: How to crop multi images use list bounding box position in the file (python)? I have a dataset of images.jpg and a file csv has values bounding box position is top, left, right, bottom. I use ubuntu OS and the python language.

A: Something like this should work. It assumes a few things:

*

*that the separator in your CSV is a semi-colon, i.e. ;

*that your CSV file is called images.csv

*that you want the cropped images output to a sub-directory called output

*that you have PIL/Pillow installed, though it could easily be adapted to use pyvips, OpenCV, skimage

#!/usr/bin/env python3

import os
import re
import csv
import json
from PIL import Image

def cropImage(filename,coords):
    """Crop image specified by filename to coordinates specified."""
    print(f"DEBUG: cropImage({filename},{coords})")

    # Open image and get height and width
    im = Image.open(filename)
    w, h = im.width, im.height

    # Work out crop coordinates, top, left, bottom, right
    l = int(coords['left']  * w)
    r = int(coords['right'] * w)
    t = int(coords['top']   * h)
    b = int(coords['bottom']* h)

    # Crop and save
    im = im.crop((l,t,r,b))
    im.save("output/" + filename)
    return

# Create output directory if not existing
if not os.path.exists('output'):
    os.makedirs('output')

# Process CSV file - expected format
# heading;heading
# 00000001.jpg?sr.dw=700;{'right': 0.9, 'bottom': 0.8, 'top': 0.1, 'left': 0.2}
# 00000002.jpg?sr.dw=700;{'right': 0.96, 'bottom': 0.86, 'top': 0.2, 'left': 0.25}

with open('images.csv') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=';')
    for row in csv_reader:
        fieldA, fieldB = row[:2]

        # Ignore header lines
        if not "jpg" in fieldA:
            continue

        # Strip trailing rubbish off filename
        filename = re.sub("\?.*","",fieldA)
        print(f"DEBUG: filename={filename}")

        # Replace single quotes in JSON with double quotes
        JSON = fieldB.replace("'",'"')
        print(f"DEBUG: JSON={JSON}")
        coords = json.loads(JSON)
        print(f"DEBUG: coords={coords}")

        cropImage(filename, coords)


text:
Q: Berry phase and Wilson loop According to the definition, the Wilson loop is
\begin{equation}
W[\mathcal{C}] =\operatorname{Tr}\left[\mathcal{P} \exp\left\{i\oint _{\mathcal{C}} A_{\mu } dx^{\mu }\right\}\right]
\end{equation}
where $\mathcal{P} $ is the path ordering,  $A_{\mu }$ is the gauge field.
And closed-path Berry phase is defined as
\begin{equation*}
\gamma _{n} =\oint _{c} A\cdot dR
\end{equation*}
where A is the Berry connection
\begin{equation}
A=i\ \langle n(R)| \nabla _{R}| n(R)\rangle
\end{equation}
$| n(R)\rangle $ is the eigenstate of Hamiltonian $\hat{H}(R)$, which depends on parameter $R$.
Since they can both be viewed as holonomy , my question is under what condition could they be identical? Or when could Berry connection be interpreted as gauge field in Yang-Mills theory?

A: *

*Both the usual gauge fields ($A_\text{QFT}$) and the Berry connection ($A_$) are connections on a principal bundle.

*In usual gauge theory in QFT you have a spacetime manifold, $S$ and a Lie algebra $\mathfrak{g}$. The gauge fields are $\mathfrak{g}$-valued one-forms on $S$, $A_\text{QFT}\in\Omega^1(S;\mathfrak{g})$.

*In the Berry phase business you have a quantum mechanical theory defined on some space with a parameter space, $P$. Moreover, the underlying Lie algebra is $\mathfrak{u}(1)$. The Berry connection takes values in $A_ \in\Omega^1(P;\mathfrak{u}(1))$.

*They could be, therefore, formally identical, if the parameter space of your quantum mechanics is the spacetime manifold of an abelian gauge theory.

*A difference between them is that the Berry connection is a background gauge field; namely fixed by the system, while in gauge theories you need to path-integrate over all possible connections. Hence the word formally, above.

*You can always build an abelian gauge theory with the Berry connection as its gauge connection but you should not expect that it would be a very physical theory.

*Finally, another thing you can do, if you have a map $f:M\to P$, and a QFT defined on $M$, is that you can pull back the Berry connection along $f$, so that $f^*A_\in\Omega^1(M;\mathfrak{u}(1))$. Now $f^*A_$ behaves like a usual abelian background gauge field, which you can now couple to your physical fields.


text:
Q: How to implement comment notification? I am trying to implement notifications on comments, that is - if I comment on a post and another user comments on the same post, I'll get a notification. I've handled the notification for the post owner using this query
SELECT id, owner_id, post_id, user_id2, COUNT(user_id2) AS num, type, UNIX_TIMESTAMP(date_done) AS date
FROM notification
WHERE owner_id = '$user_id' AND user_id2 != '$user_id'
ORDER BY date_done DESC

In the table above, owner_id is the person that owns the post, the user_id2 are those that commented on the post.
How do I tell the user with id 17 that two persons (with user id 2 and 1) also commented on the post?
If I should use a second table, please tell me how the structure should be. Thanks

A: The following query gets the user(s) who have commented
SELECT   DISTINCT user_id2
FROM notification
WHERE post_id = '$post_id'

But you don't want to notify the person currently posting so...
SELECT   DISTINCT user_id2
FROM notification
WHERE post_id = '$post_id'
AND user_id2 != '$user_id'

Or am I missing something?

A: I suggest separating posts and comments into separate tables with a one to many relation
post {
  id,
  user_id,
  content,
  date
}
comment {
  id,
  post_id,
  user_id,
  comment,
  date
}
Then you can simply poll your comments via a timeout ajax call. If comments have been added by a user_id that's not your, inject a notification into the page.

A: This class that I created will give you the detail. I have done what you need to do with the method 'notify_chain'. You will need to see the other functions, so I will post the whole class for you here.
<?php

class Notification extends DatabaseObject{

public $id;
public $type;
public $post_id;
public $owner_id;
public $user_id2;
public $date_done;
public $read_or_not;
public $notifications;
public $message;
public $count;

protected static $table_name="notifier";
protected static $db_fields = array('id', 'type', 'post_id', 'owner_id', 'user_id2', 'date_done', 'read_or_not');

public function check_notification(){
    global $database;
    global $session;
    if($session->is_logged_in()) {
    $id=$session->user_id;

    $sql = "SELECT * FROM notifier WHERE owner_id={$id} AND read_or_not = 0";
    $chk = $database->query($sql);
    if(!empty($chk)){
        while($notifs = $database->fetch_assoc($chk)){
            $message="";
        $this->notifications[]  = $notifs;
        $this->id                           = $notifs['id'];
        $this->type                         = $notifs['type'];
        $this->post_id                  = $notifs['post_id'];
        $this->owner_id                 = $notifs['owner_id'];
        $this->user_id2                 = $notifs['user_id2'];
        $this->date_done                = $notifs['date_done'];
        $this->read_or_not          = $notifs['read_or_not'];
            foreach($notifs as $notif){
                $user=Member::get_name($this->user_id2, false);
                if($this->type=="comment"){
                    $message = "post_id."&ntf_clr=".$this->post_id."'>".$user." commented on your post.";
                } elseif($this->type=="reply"){
                    $message = "post_id."&ntf_clr=".$this->post_id."&cmt=Comment&rpl=CommentReply'>".$user." replied to your comment.";
                } elseif($this->type=="discussion_comment"){
                    $message = "post_id."&ntf_clr=".$this->post_id."&cmt=Comment&rpl=CommentReply'>".$user." Commented on your discussion.";
                } elseif($this->type=="discussion_reply"){
                    $message = "post_id."&ntf_clr=".$this->post_id."&cmt=Comment&rpl=CommentReply'>".$user." replied to your discussion comment.";
                } elseif($this->type=="article_comment"){
                    $message = "post_id."&ntf_clr=".$this->post_id."'>".$user." Commented on your article.";
                } elseif($this->type=="article_reply"){
                    $message = "post_id."&ntf_clr=".$this->post_id."&cmt=ArticleComment&rpl=ArticleCommentReply'>".$user." replied to your article comment.";
                } elseif($this->type=="chain_comment"){
                    $message = "post_id."&ntf_clr=".$this->post_id."'>".$user." also commented to a post.";
                } elseif($this->type=="chain_reply"){
                    $message = "post_id."&ntf_clr=".$this->post_id."&cmt=Comment&rpl=CommentReply'>".$user." also replied to a comment.";
                }
            }
            $this->message = $message_array[] = $message;
        } if(isset($message_array)){return $message_array;}
        } else{
            return false;
        }
        }
        }

        public static function mark_as_seen($notif_id){
            global $database;
            global $session;
            $me = $session->user_id;
            $sql = "UPDATE `notifier` SET read_or_not=1 WHERE owner_id = {$me} AND post_id={$notif_id}";
            $clear_notification = $database->query($sql);
        }

        public static function make_notification($post_id, $owner_id, $user_id2, $type="comment"){
            $notif = new Notification();
            $notif->type=$type;
            $notif->post_id=$post_id;
            $notif->owner_id=$owner_id;
            $notif->user_id2=$user_id2;
            $notif->date_done=strftime("%Y-%m-%d %H:%M:%S", time());
            $notif->read_or_not=0;
                $notif->create();
        }

        public static function notif_count($id){
        global $database;
        $notif_cnt = $database->query("SELECT COUNT(*) as notifs FROM notifier WHERE owner_id={$id} AND read_or_not = 0");
        $data=$database->fetch_array($notif_cnt);
        return $data['notifs'];
        }

        public static function notify_chain($post_id, $user_id2, $type="chain_comment"){
        global $database;
        global $session;
            $sql = "SELECT DISTINCT user_id2 ";
            $sql .= "FROM notifier ";
            $sql .= "WHERE post_id = {$post_id} ";
            $sql .= "AND user_id2 != {$session->user_id} ";
            $chain = $database->query($sql);
        while ($users = $database->fetch_assoc($chain)){
            $list = "";
            foreach ($users as $user){
                Notification::make_notification($post_id, $user, $user_id2, $type="chain_comment");
                $list = $user;
            }
            $list_array[] = $list;
        } return $list_array;

        }

}

$notif = new Notification();

?>

I hope that helps. check out maestrojosiah PG at facebook if you have any problems.


text:
Q: How to download a lot of remote files with a few Linux computers? Suppose I need to download a lot of small files from a remote host by HTTP and I have a list of the URLs to download. Suppose also that the remote host allows only K connections to my local network. My local network has M computers and I would like to distribute the files across them evenly. All my computers run Linux. Now I wonder how to organize the download.
Now I assume that one computer is enough to handle all K connections and store all those files in its local file system. Thus I would allocate a computer to "download" files to M folders named after M local hosts. The local hosts copy (move) files from those folders to their file systems. Does it make sense ? What is the simplest way to implement it ?

A: Your approach is fine but there is an assumption that all files are of same size and all computers have equal performance.
What happens if one computers is done with it files and other is still half way through? In this case although you have processor available but it will be sitting idle.
But to implement this you will need distributed computing which will be lot more complicated, so i would say if this is one time task or if total time take is not large then your approach shld be fine else you need to evaluate distributed approach.


text:
Q: Ruby on Rails Max Length in View So I have my index.html.erb for my /articles
and I have a list of all my articles, with its description.
So then in the show.html.erb for the articles, the description is 500 characters of length.
How do I display in the index.html.erb only 250 characters, then a read more link?

A: You can use the truncate method.
So let's say that your description is description.
In your view, you would have something like this followed by a link_to tag to your read more page.
<%= truncate(description, length: 250) %>

A: it is very simple like this,
<%= article.description[0,250] % >
it will print only first 250 character of description.


text:
Q: translate SNMP MIB into OID Plenty of posts on this subject here but none seem helpful to me. I am interested in creating a Icinga check for "sipUnregistered(19)" so we may know when SIP clients become unregistered to the gateway server. I need the OID for this task.
Here's my MIB:
CmaEndpointAlertType  ::= TEXTUAL-CONVENTION
   STATUS        current
   DESCRIPTION   "CMA endpoint alert values."
   SYNTAX        INTEGER
                 {
                    remoteControlBatteryLow(0),
                    credentialsRequired(1),
                    credentialsFailed(2),
                    httpForbidden(3),
                    notResponding(4),
                    heartbeatTimeout(5),
                    gatekeeperStatusUnknown(6),
                    gatekeeperRejected(7),
                    gatekeeperUnregistered(8),
                    directoryStatusUnknown(9),
                    directoryNotRegistered(10),
                    presenceStatusUnknown(11),
                    presenceUnregistered(12),
                    helpRequest(13),
                    mgmtUrlNotSet(14),
                    venusDisconnected(15),
                    venusSoftwareIncompatible(16),
                    sipUriNotProvided(17),
                    sipStatusUnknown(18),
                    sipUnregistered(19)
                 }

This syntax is found in the file /etc/snmp/local-mibs/polycom/POLYCOM-CMA-MIB.MIB which after dozens of fruitless attempts to translate the MIB I also copied to /root/.snmp/mibs and /usr/local/share/snmp/mibs because this doc said it may help.
It did not help.


text:
Q: Is it possible to edit QGIS features in a web client by using QGIS server? I am new to QGIS and I am trying to build an application which runs on the web by using QGIS server. Is it possible to edit features or add features on web by using QGIS server?

A: You can edit data with WFS protocol.
You can easily achieve this with Lizmap.


text:
Q: How can I get a text of element with Xpath My code return a error. How can I fix this?
(for find XPATH I copy from ctrl+shift+c exactly the element I want)
Code trials:
driver.get('https://www.facebook.com/mypage')
likes = navegador.find_element(By.XPATH, ('//*[@id="facebook"]/head/meta[4])'))

A: Presumably you are using the Selenium-Python clients but your find_element* line of code is of Selenium-Java clients.

Solution
To extract the text your effective line of code will be:
likes = navegador.find_element(By.XPATH, "//*[@id='facebook']/head/meta[4]").text

or
likes = navegador.find_element(By.XPATH, '//*[@id="facebook"]/head/meta[4]').text

Note: You have to add the following imports :
from selenium.webdriver.common.by import By


text:
Q: I'm trying to Multi-thread a MD5 Hash string method but getting the error CS0123 C# No overload for matches delegate 'ThreadStart' I have done some research and found solutions that apply to a void method, however I have been unable to replicate my code to that of a void as there is no overload for my method 'MD5' that matches the delegate 'ThreadStart', and I have been unable to convert a void to string, this programs intent is to show how multi-threading can allow for more than one process can be done at once. I intend to add additional processes on different threads, however, it is important that this works.
using System.Security.Cryptography;//Added to allow for UTF8 encoding
using System.Threading;//Added to allow for multi-threading

namespace MTSTask5
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    private void Form1_Load(object sender, EventArgs e)
    {

    }

    //MD5 Hash method
    public void MD5(string input)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        //Convert the input string to a byte array and computer the hash, return the hexadecimal
        byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
        string result = BitConverter.ToString(bytes).Replace("-", string.Empty);
        return result.ToLower();

    }

    private void btnStartHash_Click(object sender, EventArgs e)
    {
        int loopQty = Int32.Parse(txtboxLoopQty.Text);

        int i = 0;
        //Create a while loop for the MD5 method below
        while (i < loopQty)
        {
            //loop output
            string HashOutput = MD5(MD5(txtboxHashOne.Text + txtboxHashTwo.Text));
            txtboxHashOutput.Text = HashOutput + " " + i;
            Thread HashThread = new Thread(new ThreadStart(MD5));
            HashThread.Start();
            i++;
        }
    }

A: Some suggestions that may help you troubleshoot and solve your problem:
First, I believe you may be trying to return result.ToLower(), a data type of string from your method named MD5, I'm guessing you were trying to use this instead of returning void, (i.e. nothing):
//MD5 Hash method
public string MD5(string input)
{
    MD5 md5 = new MD5CryptoServiceProvider();
    //Convert the input string to a byte array and computer the hash, return the hexadecimal
    byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
    string result = BitConverter.ToString(bytes).Replace("-", string.Empty);
    return result.ToLower();
}

That may not the entire problem,  so let's check to make sure your method is working by copying the code you have in your btnStartHash_Click method into a safe place, and then replacing it with a simple message to yourself.
private void btnStartHash_Click(object sender, EventArgs e)
{
 //Convert the input string to a byte array and computer the hash, return the hexadecimal  and display it in a message box
   MessageBox.Show(MD5("abcdefg"));//parse whatever known value test
}

If you are still unsure of the hash result from your MD5 method, then start taking parts out one by one.

Build the button click up again once you're certain of desired MD5 method's output:
private void btnStartHash_Click_(object sender, EventArgs e)
{
    txtboxHashOne.Text = MD5(txtboxHashInput.Text);
    string hashOfHash = MD5(txtboxHashOne.Text);
    txtboxHashTwo.Text = hashOfHash;
}

In the above situation I'm using the MD5 method to hash the input textbox, txtboxHashInput.Text and then change the txtboxHashOne text box to reflect the change on the form.   The txboxHashOne's entire string is then hashed to make sure to make the hashOfHash string.

Instead of having each instance txtboxHashOne , txtboxHashTwo,  one may  think it could do better by just creating the text box programmatically on the form:
//lets say the loopqty input is the number of times I wanted to hash this
int numberOfTimesToHash = Int32.Parse(txtboxLoopQty.Text);

//x and y represent where you want them to start appearing on your form..
int x = 10;
int y = 100;
int howeverManyThreadsIWant = numberOfTimesToHash;

for (int i = 0; i < howeverManyThreadsIWant; i++)
{
    TextBox textBox = new TextBox();
    textBox.Location = new Point(x, y);

    //Could go into a recursive function such as` MD5(Input,recursionDepth)
    //But instead going to reprint same hash for demonstration purposes

    textBox.Text = MD5(txtboxHashInput.Text);
    //MessageBox.Show(textBox.Text);
    this.Controls.Add(textBox);
    y += 30;
}

Then, the programmer may want to try to embrace a multithreaded approach to reduce complexity we have to do a lot more.
For example, unfortunately it's not so simple to do this:
//##!!Don't do this!!
        var thread = new Thread(() =>
        {
            int x = 10;
            int y = 100;
            int howeverManyThreadsIWant = numberOfTimesToHash;
            for (int i = 0; i < howeverManyThreadsIWant; i++)
            {
                TextBox textBox = new TextBox();
                textBox.Tag = i;
                textBox.Location = new Point(x, y);

                //Could go into a recursive function such as MD5(Input,recursionDepth)
                //But instead going to simply reprint same hash
                textBox.Text = MD5(txtboxHashInput.Text);
                //MessageBox.Show(textBox.Text);
                this.Controls.Add(textBox);//<--invalid operations error
                y += 30;
            }

        });
        thread.Start();

would result in:

System.InvalidOperationException: 'Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.'<<

Strongly consider if you really need multithreading to solve this task.

Microsoft suggests:

When to Use Multiple Threads
Multithreading can be used in many common situations to significantly improve the responsiveness and usability of your application.
You should strongly consider using multiple threads to:
#Communicate over a network, for example to a Web server, database, or remote   object.
#Perform time-consuming local operations that would cause the UI to freeze.
#Distinguish tasks of varying priority.
#Improve the performance of application startup and initialization.

It is useful to examine these uses in more detail.
Communicating Over a Network
#Smart-clients may communicate over a network in a number of ways, including:
#Remote object calls, such as DCOM, RPC or .NET remoting
#Message-based communications, such as Web service calls and HTTP requests
#Distributed transactions

With that in mind, if you really need to do these things, now that you have bug free code that is hashing the way you want it, visit the Using Multiple Threads by Microsoft.
Also you may want to check out Threading in Windows Forms, this has an example that you can run with most of what you need to know.
Hopefully some of this was what you were looking for.


text:
Q: fdm & msmtp: mark messages read I have installed fdm and offlineimap to connect to our corporate Exchange server. Now I want an action that marks a message read when a pattern matches.

A: I found a way to move and mark:
action "processed"       maildir  "%h/Mails/work/INBOX.Processed"
# Found here: https://github.com/nicm/fdm/blob/master/examples/f-terbeck.conf
action "mark-read"       exec     'mf="%[mail_file]"; mv "${mf}" "${mf%%/*}/../cur/${mf##*/}:2,S"'

match "^From:.*test@xyz\.de"     in headers actions { "processed" "mark-read" }


text:
Q: File sharing in Windows 7 I have a peer-to-peer network and use Windows 7 for my workstations.
If I share a drive in Windows 7, when I want to access it I get the following error dialog:

Network Error
  Windows cannot access \USER01-PC\d
You do not have permission to access \USER01-PC. Contact your Network
  Administrator to request access.

How can I fix this problem?

A: The user you are authenticating as must have BOTH read rights to the share and read rights to the folder/files of that share. (Assuming you are sharing on an NTFS drive).
Go to the folder, and grant "Everyone" full control of the shared folder. (Later change this to "modify" if everything works)

(Grabbed image from google images; you should select "Everyone" ideally. If it's not in the list, hit "Add..." then type "Everyone". Once this works, you may want to consider limiting access to local users)

A: Try the following, but please note you make changes to the registry at your own risk:

*

*Go to your Start Menu and press 'Run'.

*

*If you do not have Run in your Start Menu you can find the Run program in your Programs folder, then select Accessories and choose Run from that list.

*Type in 'regedit' and press OK.

*Search for the following location:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa

*Double click on 'everyoneincludesanonymous' and change the value data to 1.

*Double click on 'NoLmHash' and change the value data to 0.

*Search for the following location:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\LanmanServer\Parameters

*Double click on 'restrictnullsessaccess' and change the value data to 0.

*Close the Registry Editor.

*Restart your PC.

A: Does the user you're logged in with has a password? Make sure it has one, as Windows blocks accounts with blank passwords by default.


text:
Q: VBA runs on Windows Excel but not in Mac Excel when I run a VBA on windows excel, it works. When I run the same vba on excel for Mac, it doesn't work. Then I click "debug" it highlits the following part of the macro
Selection.Replace What:="-", replacement:="/", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

A: THe SearchFormat parameter is not available on Excel for Mac:
You can remove SearchFormat and ReplaceFormat if they're not necessary, otherwise if they are necessary then use compiler directive such as:
#IF MAC THEN
    Selection.Replace What:="-", replacement:="/", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False
#ELSE
    Selection.Replace What:="-", replacement:="/", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
#END IF

This will still use the SearchFormat and ReplaceFormat on Windows OS (but not on Mac OS -- in that case you'd need to use some additional logic) and it will not raise a runtime error on the Mac OS.


text:
Q: Two definitions for a reference frame My textbook defines a reference frame in two different ways:

*

*A collection of at least 3 collinear points that are rigidly connected.

*A reference frame is defined by three orthogonal unit vectors and one point (the origin).
These two seem like two completely different definitions to me. Could someone explain what the connection is between these two definitions? The textbook attempts to explain this by writing "a reference frame is equivalent to a rigid body. Since all points of a rigid body are fixed with respect to one another, we can use them to define a reference frame", but I am still having trouble understanding the connection.

A:
If you have 3 different points on rigid body you can create orthonormal coordinate system with those equations
$$\vec Z(t)=\dfrac{\overrightarrow{R}_{13}\times \overrightarrow{R}_{12}}{\left| \overrightarrow{R}_{13}\times \overrightarrow{R}_{12}\right| }$$
$$\vec Y(t)=\dfrac{\overrightarrow{R}12}{\left| \overrightarrow{R}_{12}\right| }$$
$$ \overrightarrow{X}(t)=\vec Y\times \vec Z$$
Thus the Transformation  matrix between body system and inertial system is
$$R=[\vec X, \vec Y, \vec Z]$$
with $R^T\,R=I_3$
But you also can choose 3 euler angles to create  orthogonal transformation matrix R
Thus
$$R=R\left( \alpha ,\beta ,\gamma\right) $$
Edit
$$\overrightarrow{R}_{13}=\overrightarrow{R}_{3}\left( t\right) -\overrightarrow{R}_{1}\left( t\right) $$
$$\overrightarrow{R}_{12}=\overrightarrow{R}_{2}\left( t\right) -\overrightarrow{R}_{1}\left( t\right) $$

A: Sorry to say, but I see no connection between those two definitions. All $N$ collinear points in a rigid body by definition gives only 1 same line. However, three orthogonal vectors with origin are semantically equal to 4 non-collinear points forming vertexes of Tetrahedron :


text:
Q: How create table or append from JSON format? After process a tiny search engine with ajax-jQuery, and functions in PHP, I've a Array JSON and I want process this for append rows in table exists but I get confused.
The JSON format from query mysql is OK, but I don't know how process data to generate table or append in my exists table.
I think that is applied each for taking each element of JSON but I can not think as.
Note: My JSON Code was generate to this this way
       ...........
       $jsonSearchResults = array();
                while ($row = mysql_fetch_assoc($result)) {
                    $jsonSearchResults[] =  array(
                        'clavemat' => $row['cve_mat'],
                        'tipomat' => $row['tipo_mat'],
                        'titulomat' => $row['titulo_mat'],
                        'autormat' => $row['autor_mat'],
                        'editmat' => $row['edit_mat'],
                        'success' => 'success'
                    );
                }
         echo json_encode ($jsonSearchResults);

Table HTML
.........

Clave
Tipo
Título
Autor
Editorial

........

JSON CODE
[
{
"clavemat":"LICOELMCUS",
"tipomat":"Libro",
"titulomat":"Contabilidad",
"autormat":"Elias Flores",
"editmat":"McGraw Hill",
"success":"success"
},
{
"clavemat":"LICUDEMCNU",
"tipomat":"Libro",
"titulomat":"Curso java",
"autormat":"Deitel",
"editmat":"McGraw Hill",
"success":"success"
},
{
"clavemat":"REECMUMUNU",
"tipomat":"Revista",
"titulomat":"Eclipses",
"autormat":"Muy Interesante",
"editmat":"Muy interesante",
"success":"success"
},
{
"clavemat":"TEPLPLTENU",
"tipomat":"Tesis",
"titulomat":"Platanito Show",
"autormat":"Platanito",
"editmat":"Telehit",
"success":"success"
}
]

AJAX.JQUERY FILE
$.ajax({
            type: "POST",
            url: action,
            data: dataSearch,
            success: function (response) {

                if (response[0].success == "success") {
                    alert("Si hay datos");
                } else {
                    alert("No hay datos");
                }

            }
        });
        return false;
    });

A: This should work
$.each(response, function (index, record) {
    var row = $("
");
    $("").text(record.clavemat).appendTo(row);
    $("").text(record.tipomat).appendTo(row);
    $("").text(record.titulomat).appendTo(row);
    $("").text(record.autormat).appendTo(row);
    $("").text(record.editmat).appendTo(row);

    row.appendTo("table.busqueda");
});

The above code appends rows to an existing table with class "busqueda".

A: In your table you could add a
 element as a container for the dynamic rows:

      Clave
      Tipo
      Título
      Autor
      Editorial

And then in the ajax success callback you would render the rows:
if (response[0].success == "success") {
  // Render dynamic rows here
  var $dynamic_rows = $('#dynamic_rows');

  // clear out old rows
  dynamic_rows.html('');

  ///////
  // You can use the row building code from Rafael's answer here
  // except append to $dynamic_rows

} else {
  alert("No hay datos");
}


text:
Q: Linux - bash script to find directories with conditions I have many users under /home.
Each user has a certain amount of directories with big sizes.
I extracted the list of users created on the system into a text file without system users (uid below 1000). For example, root, ftp, and other system users are not in the usernames-list.txt
Is there a way we can allow find to search this usernames-list.txt list and access its /home/ directories based on those 2 conditions can execute rm -rf?
condition 1: list files/directories with date modified/accessed older than 6 months.
condition 2: list files/directories that have the size of +50MB in size.
execute: rm -f

A: This will list all directories with files with access time more than 180 days and size more than 50MB.
for name in $(cat usernames.txt); do
find /home/"$name" -type f -atime +180 -size +50M|sed 's/\/[^/]\+$//'|sort -u
done

To remove, I added xargs after sort.
In my own /home, I have some dirs with spaces and single quotes in the name (in my defense, some mp3 dirs:)). xargs printed a warning about and told me to add -0 option, and to fix the null character I added delimiter option -d'\n'.
for name in $(cat usernames.txt); do
find /home/"$name" -type f -atime +180 -size +50M|sed 's/\/[^/]\+$//'|sort -u|xargs -0 -d'\n' -n1 -I{} echo -rf "{}"
done

If things seem ok for you, then you can replace echo with rm in the xargs command.
Maybe rm will print error messages because some parent directory will be removed before some subdirectory.


text:
Q: Conditional INSERT INTO MySQL - WHERE NOT EXISTS I am trying to do an INSERT INTO query when the customer does not already have a record of purchasing a product.
I have tried the below SQL, but it doesn't seem to work.
$queryAddPurchase = "INSERT INTO purchase (UserID, Product, Price)
              VALUES ('$userID', '$product', '$price')
              WHERE NOT EXISTS(SELECT Product
                                       FROM purchase
                       WHERE Product = '$product'
                       AND UserID = '$userID')";

The error I am receiving is as follows:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS(SELECT Product FROM purchase ' at line 3

Any advice would be greatly appreciated!

A: On the assumption, that a user may only buy one of each product (ever and for all products).
ALTER TABLE purchase ADD UNIQUE KEY (`UserID`, `Product`); -- run this just once. this changes the table

INSERT IGNORE INTO purchase (UserID, Product, Price) VALUES ('$userID', '$product', '$price');

Be aware, that this then prevents him from buying any product multiple times, which might not be the desired outcome.

A: If possible, add a UNIQUE constraint to the table. Something like ...
alter table purchase add unique user_product (UserID, ProductID);

And your conditional insert becomes trivial:
INSERT IGNORE INTO purchase (UserID, Product, Price)
    VALUES ('$userID', '$product', '$price')

If this is not a suitable solution for you, use the selected answer here: MySQL Conditional Insert
That answer, in brief:
INSERT INTO purchase (UserID, Product, Price)
    SELECT '$userID', '$product', '$price'
    FROM dual
        WHERE NOT EXISTS (
            SELECT * FROM purchase
            WHERE UserID='$userID'
                AND ProductID='$product'
        )


text:
Q: How do find out latest clone/fetch/pull from a GitHub repo? Does GitHub make the time of a repo's latest pull/fetch/clone available (at least to those with write-access to the repo)?
The interest in this information, of course, comes from wanting to gauge how safe it would be to do a git push -f on the repo that would essentially overwrite the last few commits: if no pull/fetch/clone has happened since the earliest commit-to-be-overwritten was pushed to GitHub, then the overwrite may be OK...

Perhaps an example will clarify my question.  For simplicity, let's assume that there's only one local branch (master) and one remote branch (origin/master).  (IOW, the remote repo has only one branch, and I am tracking it with our only local branch.)
First consider a completely local scenario: I make a commit, and shortly after realize that there was a problem with this commit.  In this case, I just overwrite this commit with the correct one using git commit --amend ....
Now imagine exactly the same scenario, with the difference that, before noticing the problem with the commit, I push the faulty commit to the remote (GitHub) repo.
If I am the only user of this repo, then I can simply overwrite the commit locally as before, and then use git push -f ... to overwrite the faulty commit in the remote (GitHub) repo.
If, however, I am not the only user of this repo, the above procedure is problematic, because a different user could have cloned or fetched from the remote (GitHub) repo at some point after I pushed the faulty commit, but before I overwrote the faulty commit in the remote repo.
One way to minimize this possibility is to examine a record of all the pull, fetch, and clone operations performed on the remote repo since the time I pushed the faulty commit to it.  If this record shows at least one of such operations, then it would mean that we have precisely the problematic scenario described in the previous paragraph.
If, on the other hand, the record shows no such operation, then there is still some hope that I could overwrite the faulty commit in the remote repo without incurring in the problematic scenario described earlier.  (Of course, this is a race condition, so there's no 100% guarantee.)
All this, however, is predicated on the availability of such record of pull, fetch, and clone operations on the remote repo.  I'm question is whether GitHub makes such record available, at least to those with write-access to the repo.

A: The GitHub V3 API does return, for a user's repositories:
...
    "pushed_at": "2011-01-26T19:06:43Z",
    "created_at": "2011-01-26T19:01:12Z",
    "updated_at": "2011-01-26T19:14:43Z"
  }

The "pushed_at" field might be the time of the last commit, but not necessarily the last commit on the branch on which you are about to push --force.
However, there is no record of the latest pull, fetch of clone, especially considering that an upstream repo has no idea of how many downstream repos are accessing it and when.
See "Definition of "downstream" and "upstream"".
GitHub could record those information: it is an upstream repo, but manages its own infrastructure and access mechanism, so yes, it could record said access.
But I don't believe that kind of information is available at all for users to see.

A: Because in your issue you posted the real intent as being:

..comes from wanting to gauge how safe it would be to do a git push -f...

I think a change to your workflow would make life much easier. I'd suggest doing the following:
Don't commit non-trivial changes directly to master (basically anything that you might want to change later). Once a change has been landed in master it should never ever be touched. Here is an example:
# assuming starting on master branch
git checkout -b new_cool_idea
# commit a few things
git push origin new_cool_idea
# realize there was a bug preventing you from finishing the
# implementation of new_cool_idea
git checkout -b cool_idea_bug_fix master
# commit the bug fix
# if you have any reviewers, push to remote
git push origin cool_idea_bug_fix
# when bug fix is all good, cleanup and finish new_cool_idea
git checkout master
git merge cool_idea_bug_fix
git branch -d cool_idea_bug_fix
git push origin :cool_idea_bug_fix
git checkout new_cool_idea
git rebase master
# may possibly have conflicts, go ahead and resolve
# now finish implementing new_cool_idea
# if you only want to update one remote branch add <remote> <branch>
# otherwise all remotes will be updated
git push -f <remote> <branch>

This should help prevent needing to --rebase on master. Which again shouldn't ever happen. There is a more advanced technique that you might want to use. Say the bug_fix branch takes a little while to fix, but you also want continue developing new_idea while testing out the bug fix. So say we start with the following:
o-----o-----o             master
      |      \
      |       o-----o     bug_fix
       \
        o-----o           cool_idea

So what we want is to apply the changes from cool_idea on top of bug_fix so we can work with them in tandem. Here's how you'd do that:
git checkout cool_idea
git rebase --onto bug_fix master cool_idea

Then you're history would look like the following:
o-----o-----o                   master
             \
              o-----o           bug_fix
                     \
                      o-----o   cool_idea

If you would really consider using this method then I'll write up the steps for cleanup if you need to add a commit to or --rebase the branch bug_fix.


text:
Q: MySQL greater than or equal to operator is ignoring its or equal to obligation If a price in a row is 38.03, then the following search restrictions should all return the row containg the result.
WHERE price >= '38.02' AND price <= '38.03' (This works)
WHERE price >= '20' AND price <= '100' (This works)
WHERE price >= '38.03' AND price <= '38.03' (This doesn't work)
WHERE price >= '38.03' AND price <= '100' (This doesn't work)
WHERE price >= '38.03' (This doesn't work)
WHERE price <= '38.03' (This works)
The price is stored as a float in the DB.
So basically, <= is working whereas >= is not. Is there a reason why that could be?

A: keep in mind that float is a flawed data type when it comes to precision. If you represent 12 as float, you will get 11.99999999999998 or something.
'38.03' can be converted to decimal, or other data type that is more precise (depending on RDBMS, I am being general here), and it will differ from the float value.
float is 32 bit, low precision. Double works a lot better, being 64 bit data type. Decimal data type in some systems are 128 bit numeric data types for storing very precise numeric values, and is usually used for denominating money.
And, skip the habit of comparing using the = operator, of float values. Floats are used for approximate and fast calculations, and only comparison with a range is acceptable for checking the value of a float. That's valid for basically every single system.

A: When you use quotes (') your variables will be treated as strings. I think thats your problem.
Try: WHERE price >= 38.03 AND price <= 38.03


text:
Q: Documentation project type missing after NuGet Sandcastle Install I have installed the most current version of Sandcastle from NuGet (EWSoftware.SHFB version 2015.10.10.0), and the needed Reflection package (EWSoftware.SHFB.NETFramework version 4.6).

I read @Frank-Rem answer to Numid's question How to generate documentation using Sandcastle NuGet package (EWSoftware.SHFB)? and tried to add a new project to my solution. However, when I try to add a Sandcastle Documentation project I do not have the Documentation project type as an option.

I uninstalled the NuGet package and reinstalled it, thinking it may have been a buggy install.  But the documentation project type is still not an option, even after shutting Visual Studio down and relaunching it.
I read through the readme.txt file and saw that I will need to add some property tags to the .shfbproj file when it gets generated.  Beyond that, I don't see any other steps that I need to perform or packages to install in order to get the project type to show up. I have also gone to the GitHub project page and checked the Issues tab to make sure this isn't a known issue they are working on.
I am using Visual Studio Ultimate 2013.
Are there additional steps I need to take to get the Sandcastle project type to show up in the Add New Project list?
Thank you for any ideas!

A: I was able to resolve the issue by running the Sandcastle Help File Builder Guided Installer. This identified missing components and installed them.
I was then able to follow the instructions from @frank-rem on adding the documentation project and documentation source to the new project.

Assuming that you already have a solution with a project, add a new project of type 'Documentation' to your solution.
Right-click Documentation Sources and add a source by selecting the csproj you wish to document.
Then just build.

Additional steps I took to get a finalized help doc: I found that Sandcastle had added several TODO items, which didn't show up in the Visual Studio task list.  So I did a search on the solution for TODO and resolved them that way.
After that I followed the instructions on adding the namespace summaries provided by @davy-landman (in a comment to Davy Landman's answer) to clear up some missing flags.

This has actually changed in the latest version (currently 1.9.3.0) to Project Properties > Summaries > NameSpaceSummaries. – Ant Swift Jan 6 '12 at 9:44


text: Q: IIS 7.5 Lock my DLL after many request I have a big problem, i deployed on my web server IIS 7.0 a custom DLL that provide some data (exaclty one row per day up to maximun 365 row). This dll work fine for about 6 or 7 hours, after that IIS lock this DLL and no data return in my front-end. If i do a iisreset and app pool recycle all back to work correctly untill next dll lock. In my Application Pool have setup Regular Time Interval to recycle but iis lock equally my DLL. I'm desperate anybody can suggest me any solution??


text:
Q: How to list Currently Authorized Views in BigQuery? I want to list all the Currently Authorized Views in a dataset (projectID, datasetID, and tableID).
I have try to check using Information schema but still face the dead end. I want to gather information about projectID, datasetID, and tableID. Is there any possible way to do it?
Image of Authorized View

A: Inorder to list views in BigQuery, you can use below queries.
To Return metadata for views in a single dataset
SELECT * FROM dataset.INFORMATION_SCHEMA.VIEWS

To Return metadata for all views in a region
SELECT * FROM region-us.INFORMATION_SCHEMA.VIEWS

It's not possible to query only the authorized views using INFORMATION_SCHEMA. As per your requirement to view projectID, datasetID, and tableID details of Authorized Views in a dataset, as you have mentioned you can go to your dataset and click + Sharing > Authorize Views where you can add authorization and view the Currently Authorized Views.

For more information you can refer to this tutorial.
If you want the feature to view details of  authorized views using  INFORMATION_SCHEMA as present in BigQuery UI, you can raise a feature request on the issue tracker describing your requirement.


text:
Q: CSS animation relative to current screen position I'm trying to implement some CSS Keyframe animations on my application, which get triggered on different events.
The animation consists of a unicorn flying up from the bottom of the screen, stopping in the middle for a second, and then moving up out of the screen.  The problem comes when different users have different amounts on content on the page, making the page height bigger.
I want the animation to stop for a second relative to users position, in the middle of the users view, not relative to the page height.
This is my code so far:
 <img src="../***" v-if="aCounter === 1" class="unicornUp" alt="Unicorn">

.unicornUp {
  position:absolute;

  width:50%;
  height:50%;
  right:20%;
  opacity: 0;
  z-index:99;
  animation-name: unicornMoveUp;
  animation-duration: 3s;
   -webkit-animation-timing-function: linear;
  animation-timing-function: linear;
  animation-iteration-count: 1;
  animation-delay: 0.5s;
}
@keyframes unicornMoveUp {
  from { bottom: 0; opacity: 1;}
  20% {bottom:20%;opacity: 1;transform: rotate(5deg);}
  40% {bottom: 50%;opacity: 1;}
  60% {bottom: 50%;opacity: 1; transform: rotate(-5deg);}
  80% {bottom: 60%; opacity: 1;}
  100% {bottom: 90%; opacity: 0;}
}

I've been thinking about a sticky parent div, but I'm not sure if this is even correct and where to start. Any help would be appreciated!

A: Try  position: fixed instead, as as opposed to position: absolute which is relative to the entire document, fixed is relative to the viewport i.e. the screen