text:
Q: Javascript, textarea, best way to detect line been changed I'm trying to make something like adding WYSIWYG editing sigins on images.
So, I got textarea for text.  I generate (in real time) <svg> text there. Text can be inside <svg><rect>. On every line break its a new line and new <rect>. I set rect size (witdth, height) depends on what returns text.getBBox() function, storing data about each rect sizes in some array by index.
Now, if I change some text in middle line, i want to change size of rectangle where this text is placed.
How should i detect, which line has been changed by it size?
Ofc I can store old textarea data, compare with changed data every time on textinput, find changed line etc but seems like its a bad solution
UPD:
I assume there is workaround to redraw ALL text I got in <textarea>, line by line, every time it changes, but it looks like not good solution too


text:
Q: Logic error resulting in missing/incorrect output possibly relative to for-loop The PrimeDetector class shown below has documentation which describes the uses of each method. The tester class creates an object of the PrimeDetector class and attempts to print a set of generated integer values from an ArrayList returned from the hasPrime() method. I do not see my error, as I have created a procedural version of it which works just fine. It prints only the first 3 prime numbers, and returns as having only detected 3 prime numbers--leading me to believe that the issue lies within the PrimeDetector class, somewhere within the for-loop, though I can't be certain, as it is nearly the same structure as my procedural version--so far as I can tell. I will include the single procedural  class, as well as the OOP version and its tester.
/**
 * The PrimeDetector class detects prime numbers within a user's
 * given set [0,n] where n is a user-given upper limit.
 *
 * @author A. Mackey
 * @version 06/05/14
 */
import java.util.*;
public class PrimeDetector {
    private int n;
    private int primeCounter;
    private ArrayList<Integer> primeList = new ArrayList<Integer>();

    /**
     * Constructor for objects of class PrimeDetector
     * @param n is the upper limit in the set [0,n] tested with the hasPrime() method.
     */
    public PrimeDetector(int n) {
        this.n = n;
    }

    /**
     * @return an ArrayList of type Integer containing all prime values within the set [0,n].
     */
    public ArrayList<Integer> hasPrime() {
        primeCounter = 0;
        for (int i = 1; i <= n; i++) {
            boolean isPrime = true;
            for (int j = 2; j <= i / 2; j++) {
                if (i % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                primeCounter++;
                primeList.add(i);
            } else {
                break;
            }
        }
        return primeList;
    }

    /**
     * @return primeCounter variable which holds and integer value equivalent to the number of prime values in
     * the [0,n] set evaluated in the hasPrime() method.
     */
    public int getPrimeCounter() {
        return primeCounter;
    }
}

Tester:
/**
 * The PrimeDetectorTest class tests the PrimeDetector class, which detects prime numbers within a user's
 * given set [0,n] where n = a user-given upper limit.
 *
 * @author A. Mackey
 * @version 06/05/14
 */
import java.util.*;
public class PrimeDetectorTest
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a positive integer you wish to find primes up to: ");
        int n = in.nextInt();
        System.out.println("The following list is prime within the range [0, " + n + "]: ");
        PrimeDetector list = new PrimeDetector(n);

        ArrayList<Integer> primeList = list.hasPrime();

        for (int s : primeList)
        {
            System.out.println(s + " is prime.");
        }

        System.out.println(list.getPrimeCounter() + " prime numbers within this set.");
    }
}

Procedural version:
import java.util.*;
public class PrimeDetectorV1
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter a positive integer you wish to find primes up to: ");
        int n = in.nextInt();
        int primeCounter = 0;
        System.out.println("The following list is prime within the range [0, " + n + "]: ");

        for(int i = 0; i <= n; i++)
        {
            while (i>0)
            {
                boolean isPrime = true;
                for (int j = 2; j <= i/2; j++)
                {
                    if(i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    System.out.println(i + " is prime.");
                    primeCounter++;
                    break;
                }
                else
                {
                    break;
                }
            }
        }
        System.out.println("There are " + primeCounter + " prime numbers within this set.");
    }
}

A:   if (isPrime) {
      primeCounter++;
      primeList.add(i);
  } else {
       break;
  }

Remove the else{break;} here. Because if you found a number that is not prime, you still need to check the next one. Currently your program will stop when it founds a number that is not prime.
Also 1 is not a prime number so you should start your first loop at 2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use actuators to control a free joint in mujoco_py? I am using mujoco_py to build a simulation for a hand. I have some some floating fingers that I want to control using actuators. How do I control a free joint that has 7 DOF (x,y,z, rotation quaternion) with acuators?
Thanks for the help!


text:
Q: Good architecture for consuming a REST web service in an MVVM app for Windows Phone 7? I'm having a bit of trouble deciding on the best way to get the data from the web service to the UI.
Given the asynchronous nature of WebClient how would you build this?

*

*Model uses WebClient to talk to webservice

*ViewModel asks model for data

*View is databound to ViewModel

On the Async complete event I need to get that data back out of the model to the ViewModel, these are the things I've thought about.

*

*I could fire an event in the Model that the ViewModel subscribes to.

*I could perhaps do something with passing around callbacks?

*Or should I be doing a second level of INotifyPropertyChanged events between the ViewModel and the Model?

*Or am I very confused and completely misunderstanding MVVM?

A: It depends on how purist you want to be about MVVM.
You could treat the API itself as your Model, in which case the ViewModel has the WebClient and on Async completed you'd set your properties (and they would in turn fire PropertyChanged from within their setters).
Or you can have a local Model that has the WebClient code in it (as it sounds like you have). In this case, my personal approach would to have a "ModelUpdated" event that fires from the Async complete event. (Your option 1).
Your ViewModel can listen for this event, and either fire a PropertyChanged(null) to have the View ask for ALL properties, or fire multiple PropertyChanged events. Remember you're not restricted to firing PropertyChanged from within your setters. There's nothing stopping you from having a method like
private void FireMultipleProperties(){
NotifyPropertyChanged("Property1");
NotifyPropertyChanged("Property2");
NotifyPropertyChanged("Property3");
}

So you could call that method when the Model finishes populating, and your UI will call update each property when they are fired. You'd only need to do this if you have a ton of properties and don't want to fire them all at once with PropertyChanged(null).

A: I think you need to introduce a new layer into your architecture; a service layer.  Usually, I pass in my relevant services to my ViewModel and the ViewModel does the handling of the async calls and showing busy states and all that fun stuff.
For instance, if you have a Product Model, and ProductListViewModel with a collection of products and maybe a search command, then you would introduce a ProductSearchService (Or ProductLoadService that loads all products).  I would then pass that ProductSearchService into your ProductListViewModel constructor (dependency injection) and let your ViewModel control the retrieval of the Products (your model objects) by calling the relevant service methods and loading the response.

*

*ProductListService Returns Product (Model) List

*ProductListViewModel uses ProductListService to get Products

*ProductListView binds to ProductList ObservableCollection in ProductListViewModel.

This pattern essentially resembles Model-View-Controller, where the ViewModel takes more of the Controller responsibilities.
Since you mention REST based web services, I have an example blog post of using MVC 2 JSON results as a service layer for a Win Phone 7 app: Data Driven Win Phone 7 Apps with MVC 2 JSON services


text:
Q: Mongoose handle duplicate entries with implicit error I want to check if the email or name is already in use, when i enter an already existing email and an existing name only the data from the matching email is return and no data from the name.
req.body.email is bob@gmail.com
req.body.name is hansel
Account.find({$or: [ {user_email: req.body.email}, {display_name: req.body.name}]})
            .exec((err, user) => {
                if(err) {
                    res.status(500).json({message: 'Internal Server Error', type: 'error'});
                }

                if(user) {
                     //  Only the data from the email match result is logged and no data for the already existing name
                     console.log(user)
                    // Response
                    res.json({
                        message: 'Account email address or Display name is already in use',
                        type: 'error'
                    })
                } else {
                    next();
                }
            });
        }

I am also lost how can i send a response with explicit error like
The display name is already in use or The account email address is already in use instead of the current response which is implicit
This is from the console.log(user) it only shows the match email and not the match display name
[ { _id: 5ae6cd68e1f3b32237494792,
    user_email: 'bob@gmail.com',
    display_name: 'Tetris',
    registration: 2018-04-30T08:01:44.095Z,
    __v: 0 } ]

Account schema
 const AccountSchema = new Schema({
        user_email: {
            type: String,
            required: true,
        },
        password: {
            type: String,
            required: true,
            select: false
        },
        display_name: {
            type: String,
            required: true,
        },
        registration: {
            type: Date,
            required: true,
        },
    });

A: Mongoose's .find always return an array. If your query matches no documents it will return an empty array.
The empty array is evaluated as true in any condition.
if ( [] ) { ... } else { // will never be called }

That's why your code block with next() is never never called.
if( user ) {
 // ^ user is either [] or [{...},...], so it's always true
} else {
     next();
}

What you can do to improve your code would be to have either a findOne query :
Account.findOne( { ... } ).then( user => {

    // user is either null or { ... }

} );

Or simply change
if ( user ) { ...

to
if ( user.length > 0 ) { ...

About knowing which condition you have matched you can check
if ( user.length > 0 ) {
    res.json( {
        message : (
            user[0].user_email === req.body.email ? "Email" : "Display Name"
        ) + " is already taken",
        error: true
    });
}

But keep in mind that this will not match a situation where the email and the display name are both used.


text:
Q: Reducing a nested loop I'm studying the Movielens dataset for a classification task, so I'm preparing my dataset as follows:
I have 3 datasets:
genome-score.cvs:

movieId
tagId
relevance

1
1
0.028749999999999998

1
2
0.0152749999

1
3
0.19627257

Genome tag:

tagId
tag

1
007

2
007 (series)

3
18th century

and movies.csv:

movieId
title

1
Toy Story (1995)

Then I have a list of tag called: GenTags, in this list there are all tag that the people used for a tagging the films.
So my task is:

*

*Insert as column in movies.csv all tag in GenTags

*For each movies insert in corresponding cell the relevance of tag for that film.

This is the output that I want:

movieId
title
007
007 (series)
18th century
1920s
.... and all tag

1
Toy Story (1995)
0.3485
0.269
0.1907499999
0.20475
0.05675

This for prepare my dataset for a classification learning:
My code:
import numpy as np
import pandas as pd

GenTags = pd.read_csv('ml-25m/genome-tags.csv', sep=',')
GenScor = pd.read_csv('ml-25m/genome-scores.csv', sep=',')
Movies = pd.read_csv('NewMovies.csv', sep=',')

for tag in GenTags["tag"]:
    Movies[tag] = np.nan

for index, row in Movies.iterrows():
    for j in GenTags["tag"]:
        k = row["movieId"]
        A = GenScor[GenScor.movieId == k]
        i = GenTags[GenTags.tag == j]["tagId"].tolist()[0]
        B = A[A.tagId == i]["relevance"].tolist()
        if len(B) == 1:
            C = A[A.tagId == i]["relevance"].tolist()[0]
            Movies.loc[index, j] = C

Movies.to_csv("prove.csv",index=False)

But this code is too computationally expensive. Is there a better way?

A: It looks to me like a merge and pivot.  Merge scores to movies, then genome to that.
This operates under the assumption that all of the tag features you want in your model will appear at least once for at least one movie.  Any movie that doesn't have that tag gets the fill_value, or you could add a custom function for imputation.
import pandas as pd

score = pd.DataFrame({'movieId': [1, 1, 1], 'tagId': [1, 2, 3], 'relevance': [0.0287499999999999, 0.0152749999, 0.19627257]})
genome = pd.DataFrame({'tagId': [1, 2, 3], 'tag': ['007', '007 (series)', '18th century']})
movies = pd.DataFrame({'movieId': [1], 'title': ['Toy Story (1995)']})

df = movies.merge(score,on='movieId')
df = df.merge(genome, on='tagId')

df =df.pivot_table(index=['movieId','title'], columns='tag', values='relevance', fill_value=0).reset_index().rename_axis(None,axis=1)

Output
   movieId             title      007  007 (series)  18th century
0        1  Toy Story (1995)  0.02875      0.015275      0.196273


text:
Q: Unknown user name in Internet Explorer properties In my Internet Explorer Properties Security box in the section Group or user names I found. Account Unknown(S-1-5-80-2375682873-768044350=35334…
What is this?

A: It means one of two things.

*

*First, the user or group might have been deleted. When you delete a user or group, Windows can't check the ACL of every object on every computer of the local domain and all trusted domains for the access control entries (ACEs) assigned to the user or group and delete such ACEs. Therefore, you end up with "orphaned" ACEs, which aren't a threat to security.

*The other possibility is that the user or group still exists but the computer was unable to connect to the appropriate domain controller (DC) to resolve the SID's name because of network problems, a failed trust relationship, or because a DC is down.

The first possibility applicable as well to a computer out of an Active Directory Domain.


text:
Q: Using tf.boolean_mask with greater_equal to slicing a tensor I am trying to use tf.boolean_mask to select certain values from a tensor.
myArray = tf.random_normal([6], mean=1, stddev=4, seed = 1)
with tf.Session() as test_a:
    myMask =  tf.greater_equal(myArray, 0.5)
    myScores = tf.boolean_mask( myArray, myMask )
    print("myArray = ", myArray.eval())
    print("myMask = ", myMask.eval())
    print("myScores = ", myScores.eval())

To which I get the following.
myArray =  [-2.24527287  6.93839502  1.26131749 -8.77081585  1.39699364  3.36489725]
myMask =  [False  True  True  True False False]
myScores =  [ 2.71667314  1.12839425  1.47780943  1.50100374]

I had expected to get
myArray =  [-2.24527287  6.93839502  1.26131749 -8.77081585  1.39699364  3.36489725]
myMask =  [False  True  True  False True True]
myScores =  [ 6.93839502  1.26131749  1.39699364  3.36489725]

How can I do this?

A: Great question! That stumped me for a minute, the answer is ultimately trivial, but an important lesson in how tensorflow operates.
First some working code:
import tensorflow as tf

myArray = tf.random_normal([6], mean=1, stddev=4, seed = 1)
myMask =  tf.greater_equal(myArray, 0.5)
myScores = tf.boolean_mask( myArray, myMask )

with tf.Session() as sess:
    print(sess.run([myArray, myMask, myScores]))

Result:
[array([-2.2452729,  6.938395 ,  1.2613175, -8.770817 ,  1.3969936, 3.3648973], dtype=float32),
 array([False,       True,       True,       False,      True,      True]),
 array([6.938395 , 1.2613175, 1.3969936, 3.3648973], dtype=float32)]

Notice that myArray is an OP, not a variable. An OP (short for operation) is computed at the time that you call sess.run (or eval in this case, but using eval made it less obvious).
A variable, such as myVar = tf.variable(...) persists from one call to sess.run to another. Since myArray is an OP it was being recomputed each time you performed any operation against the tensorflow graph. Since you called the graph on 3 separate instances you got 3 different values for myArray in each call. You only printed myArray in the first instance of course and erroneously assumed it was remaining static.
Notice with the modified code that I posted I now request all 3 variables in one sess.run call, hence they all use the same value of myArray, and all the results are as expected.


text:
Q: Change input values from select list. I have two text input boxes that will need to be populated from the same selection list but each text box may have different values. What happens is that the code I have written allows you to click and change on value but when you try to do change the second value it changes both values rather than just the second value. I have looked at bind, text with no luck.
Input Boxes:
<input type="text" id="lensStyle" size="35" class="orderinput" tabindex="12"/>
<input type="text" id="lensStyleLeft" size="35" class="orderinput" tabindex="12"/>
grabs the values in from:
<select class="longbox" size="14" id="lensStyleBox"></select>

using this Jquery
    $("#lensStyle").focus(function(){
        $("#lensStyleBox").click(function(){
            $("#lensStyle").val($("#lensStyleBox").val());
        });

    });

    $("#lensStyleLeft").focus(function(){
        $("#lensStyleBox").click(function(){
            $("#lensStyleLeft").val($("#lensStyleBox").val());
        });
    });

A: You need to unbind the click handlers as the focus changes. This should do the trick - http://jsfiddle.net/WPjgc/

A: Try below code, If you want the text box to be populated on focus with the selection you had in the drop down.
$("#lensStyle, #lensStyleLeft").focus(function(){
    $(this).val($("#lensStyleBox").val());
});

What you are doing doesn't seems correct. Let us know if this is not something you need.


text:
Q: Prove $f(z)=(z-1)^a(z+1)^b$ has a branch in $\mathbb{C}\backslash[-1,1]$ iff $a+b\in\mathbb{Z}$ Prove $f(z)=(z-1)^a(z+1)^b$ has a branch in $\mathbb{C}\backslash[-1,1]$ iff $a+b\in\mathbb{Z}$
I've tried the following
Assuming that we have a branch for $f$
$f(z)=(z-1)^{a+b}(\frac{z+1}{z-1})^{b}=(z-1)^{a+b}(1+\frac{2}{z-1})^b$, i know that if $z\notin[-1,1]$ then $(1+\frac{2}{z-1})\notin (-\infty,0]$ and we can take a branch for this and then we have a branch for$(1+\frac{2}{z-1})^b$ now i got stuck on how to show that $a+b\in\mathbb{Z}$.
I thought maybe setting $e^{(a+b)log(z-1)}=w$ and we know  that $e^z$ is $2\pi k$ periodical and therfore $(a+b)\in\mathbb{Z}$


text:
Q: Positive linear functional on a C*-algebra is bounded The following is a theorem of Murphy's C*-algebras and operator theory:
My question: I think in the proof of theorem, Murphy uses the assumption $|\tau(a)|<M$ for positive elements $a\in A_{\|.\|\leq1}$, while there is not this assumption in theorem. How does he conclude that? Please help me. Thanks.


text:
Q: 64-Bit installation only gives my a 32-bit OS I recently decided to install Ubuntu on my computer for a project I'm doing, I downloaded the 64 bit version of Ubuntu from the official website and burned it onto a DVD, however, after the installation, I noticed (through the system settings) that the OS was only 32-bit
In case I had made the mistake of accidentally downloading the 32-bit ISO, I went to the Ubuntu website and downloaded the 64-bit version and burned it to a memory stick. I then proceeded to re-install the OS, but it still gives me the "32-bit" in the system settings.
Can someone please tell me What I am doing wrong?
Although I am certain that my PC architecture is 64-bit, I'll include details of my setup, just incase you think I may have made a mistake:
Processor: AMD A6-5400K APU with Radeon(tm) HD Graphics × 2 (in other words, its a dual core)
Motherboard: Asus F2A85-M PRO
Ram: 2x Kingston 4GB DDR3
Also, I got the .ISO from this address:
http://www.ubuntu.com/download/desktop
Iso name: ubuntu-14.04.1-desktop-amd64.iso
Thank you very much in advance :)

A: Your uname output indeed indicates a 32 bit OS, It appears that you accidentally flipped the dropdown on the page you provided from 64 to 32 bit.
My uname output from the 64-bit ISO link that you provided ends with X86_64.
You should check the md5sum of your download to insure it matches before you re-burn.
You can find references to the md5sum here: MD5 hash for ubuntu .iso (14.04 through 16.10)


text:
Q: Permission denied to create a symbolic link; sudo errors out I am trying to install phalcon development tools. In the documentation they said:
Create a symbolic link to the phalcon.php script:
ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon
chmod ugo+x /usr/bin/phalcon

and after connecting to my Ubuntu server, at the step of creating symbolic link to the phalcon.php script I get an error:
ubuntu@ip-000-00-0-00:/$ sudo ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon
sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set

How can I complete the installation?
When I try without sudo I get:
ubuntu@ip-000-00-0-00:/$ ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon
ln: failed to create symbolic link '/usr/bin/phalcon': Permission denied

Documentation which I followed
I have tried all the answers from this question but still getting same errors: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set

A: Seems like /usr/bin/sudo is broken as mentioned. You can try to fix it by booting your linux machine in recovery mode and fixing it by running the commands:

*

*Change owner back to root (uid 0) chown root:root /usr/bin/sudo

*Fix permissions ONLY IF THEY ARE INCORRECT. Run ls -l /usr/bin/sudo and permissions should be -rwsr-xr-x. If they are not, fix them by running chmod 4755 /usr/bin/sudo.

If all goes well then you should have sudo back!


text:
Q: draw a box for part of a matrix in math environment
Possible Duplicate:
Highlight elements in the matrix

I have a big matrix as follows:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

    \[
\tilde{M}_{R+1,N}=
  \begin{pmatrix}
  r_{1,(1)}^{(1)},r_{1,(2)}^{(1)} \cdots, r_{1,(n)}^{(1)}, r_{2,(1)}^{(1)}, r_{2,(2)}^{(1)}, \cdots, r_{2,(n)}^{(1)}, \cdots, r_{m,(1)}^{(1)}, r_{m,(2)}^{(1)}, \cdots, r_{m,(n)}^{(1)}\\
  r_{1,(1)}^{(2)},r_{1,(2)}^{(2)} \cdots, r_{1,(n)}^{(2)}, r_{2,(1)}^{(2)}, r_{2,(2)}^{(2)}, \cdots, r_{2,(n)}^{(2)}, \cdots, r_{m,(1)}^{(2)}, r_{m,(2)}^{(2)}, \cdots, r_{m,(n)}^{(2)}\\
  \vdots \\
  r_{1,(1)}^{(R)},r_{1,(2)}^{(R)} \cdots, r_{1,(n)}^{(R)}, r_{2,(1)}^{(R)}, r_{2,(2)}^{(R)}, \cdots, r_{2,(n)}^{(R)}, \cdots, r_{m,(1)}^{(R)}, r_{m,(2)}^{(R)}, \cdots, r_{m,(n)}^{(R)} \\
  r_{1,(1)}^{(0)},r_{1,(2)}^{(0)} \cdots, r_{1,(n)}^{(0)}, r_{2,(1)}^{(0)}, r_{2,(2)}^{(0)}, \cdots, r_{2,(n)}^{(0)}, \cdots, r_{m,(1)}^{(0)}, r_{m,(2)}^{(0)}, \cdots, r_{m,(n)}^{(0)}
  \end{pmatrix}
\]

\end{document}

Resulting in:

Now I want to draw several boxes on this big matrix. The first box contains elements from the first n columns and all rows; the second box contains elements from the next n columns and all rows, and so on. When I use \boxed command, it can only take characters that are 'together'.
How can I make such boxes in the math environment that contain "non-together" characters?


text:
Q: How can I display all values of a custom field from posts with a certain value of another custom field or from certain post types? I know the question is quite ambiguous. Let me explain:
I have a page that lists all posts with a certain value of a custom field.
(Eg.: The page Rentals lists all posts with the value rental of custom field offer_type ).
I'd like to add a filtering option by city, so that only posts with a certain value of city custom field get displayed. For this I created a form using the get method that builds a custom query (in my ex. with two custom fields, 'offer_type' and 'city').
What I need is a way to list all the cities (values of city custom field) for the posts with the rental value of offer_type. Each city has to be listed once.
I tried this bit of code (note that I took all the form wrapping out):
$metakey = 'city';
   $cities = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value
           FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) );

   if ($cities) {
                 foreach ( $cities as $city ) {
                 echo $city;
            }
        }

but this lists all the values of city custom field for all the posts (so if for eg. I have a post with value of offer_type different than rental, its value of city custom field will be displayed in my list).
I know the issue revolves around sql queries and joining tables, but I really lack the skills to solve this problem.
Please help!

A: take a look at the reference docs for the WP_Query class: http://codex.wordpress.org/Class_Reference/WP_Query
something like this:
$args = array(
  //some key/value pairs...whatever
          'meta_query => array(
                          array(
                         'key' => somekey,
                         'value' => somevalue,
                         'compare' => some comparison operator
                         ),
                         array(
                         'key' => some other key,
                         'value' => some other value,
                         'compare' => some comparison operator
                         )
                     )
               )

$my_query = new WP_Query( $args );

//some code to do something with the results of the query

A: this is not a direct answer to your question but a line of code you would use as reference to work onto.
here is a copy of what i use to search thru my table,
i search between a data range and then limit it to only display instances of an entered usr_id
 $this->items = $wpdb->get_results($wpdb->prepare("SELECT  *  FROM $table_name WHERE `datec` BETWEEN CAST('$start_date' AS DATE) AND CAST('$end_date' AS DATE) AND `usr_id`= $usr_id"), ARRAY_A);

hope this helps :)


text:
Q: Htaccess and PHP Direction or routing The URL I want to achieve: https://example.com/VdnbzeHfua/ep1_mp4
Note : My page (index.php) is located in root folder
when I access this URL https://example.com/VdnbzeHfua/ep1_mp4 it should not look forward for sub folders
i will get and use the values in the URL with PHP (index.php in root folder) like this
<?php

$url      = $_SERVER['REQUEST_URI'];
................
...........
?>

How to achieve this with php and .htaccess?
Please anyone help me solving this.

A: You require a standard front-controller pattern, which can be achieved with a  single directive in .htaccess:
FallbackResource /index.php

Any request that would otherwise trigger a 404 is passed to /index.php instead.
An alternative method (which is perhaps more commonly seen) is to use mod_rewrite instead. For example:
RewriteEngine On

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

Although this alone doesn't do anything more than the FallbackResource directive does above.
Both methods would require the DirectoryIndex to be set correctly, if not already (this will usually be set to index.php in the server config). For example, at the top of your .htaccess, before the existing directives:
DirectoryIndex /index.php

You seem to already have the PHP part resolved. ie. check the value of $_SERVER['REQUEST_URI'] in order to examine the requested URL, which incidentally will also contain the query string.
You can then include the necessary PHP files as required. For example, this could be something simple like:
if ($url == '/about') {
    include('content/about.php');
}

But can be made as complex as you like. Obviously an if construct won't scale to 1000s of pages.


text:
Q: JS DOM checkbox not working I have to enable/ disable a textarea based on whether the person clicks on a checkbox or not. I feel like I got the code right but for some reason it still isn't working. Am I calling the js file wrong in the script tag?
The javascript file name is task2.js.
Code in the html file:
<!DOCTYPE html>

 Order Information

  Select color:
  <select name="color">
    <option selected="selected">White</option>
    <option>Black</option>
    <option>Red</option>
    <option>Green</option>
    <option>Blue</option>
  </select>

  Select shirt size:
  <select name="sizeandprice">
    <option>Small - $9.99</option>
    <option>Medium - $10.99</option>
    <option selected="selected">Large - $11.99</option>
    <option>X-Large - $13.99</option>
  </select>

  Is this a gift? <input type="checkbox" name="gift" id="check">

  Write your gift message here:

  <textarea disabled rows="5" cols="50" name="message" id="text">Type your message here.
  </textarea>

This is the code in the javascript file:
document.getElementById("check").addEventListener('click', function(){
    var textArea = document.getElementById("text");
    textArea.disabled = !textArea.disabled;
});


text:
Q: How can a QR Scanner retrieve data from remote database? Firstly, I am currently using Android Studio and ZBAR lib to develop a QR Scanner.
1) QR Code will contain the unique id for example the vehicle number.
2) When the QR code are scanned, the result will not only show the vehicle number but also for example name of vehicle, owner of vehicle etc
In conclusion, i am trying to retrieve data from the remote database through unique ID when qr code scanner are activated. I know i can use JSON parse but i am not sure of how and where to input JSON parse in the codes. I would appreciate if someone can guide me or recommend a good tutorial. Please do take note i am a beginner in coding. Thank you very much for your help.
QRScanner.java
    package com.example.namirah.eparking.Activity;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import com.example.namirah.eparking.R;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

public class QRScanner extends Activity {
public static final String TAG = QRScanner.class.getSimpleName();

private Camera mCamera;
private CameraPreview mPreview;
private Handler autoFocusHandler;

private Button scanButton;
private ImageScanner scanner;

private boolean barcodeScanned = false;
private boolean previewing = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.qr_scanner);

    initControls();

}

private void initControls() {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    autoFocusHandler = new Handler();
    mCamera = getCameraInstance();

    // Instance barcode scanner
    scanner = new ImageScanner();
    scanner.setConfig(0, Config.X_DENSITY, 3);
    scanner.setConfig(0, Config.Y_DENSITY, 3);

    mPreview = new CameraPreview(QRScanner.this, mCamera, previewCb,
            autoFocusCB);
    FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
    preview.addView(mPreview);

    scanButton = (Button) findViewById(R.id.ScanButton);

    scanButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (barcodeScanned) {
                barcodeScanned = false;
                mCamera.setPreviewCallback(previewCb);
                mCamera.startPreview();
                previewing = true;
                mCamera.autoFocus(autoFocusCB);

            }
        }
    });
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        releaseCamera();
    }
    return super.onKeyDown(keyCode, event);
}

/**
 * A safe way to get an instance of the Camera object.
 */
public static Camera getCameraInstance() {
    Camera c = null;
    try {
        c = Camera.open();
    } catch (Exception e) {
    }
    return c;
}

private void releaseCamera() {
    if (mCamera != null) {
        previewing = false;
        mCamera.setPreviewCallback(null);
        mCamera.release();
        mCamera = null;
    }
}

private Runnable doAutoFocus = new Runnable() {
    public void run() {
        if (previewing)
            mCamera.autoFocus(autoFocusCB);
    }
};

public Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {
    public void onPreviewFrame(byte[] data, Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        Camera.Size size = parameters.getPreviewSize();

        Image barcode = new Image(size.width, size.height, "Y800");
        barcode.setData(data);

        final int result = scanner.scanImage(barcode);

        if (result != 0) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();

            SymbolSet syms = scanner.getResults();
            for (Symbol sym : syms) {

                Log.i("<<<<<<Asset Code>>>>> ",
                        "<<<<Bar Code>>> " + sym.getData());
                final String scanResult = sym.getData().trim();

                Intent intent = new Intent(QRScanner.this, QRCodeDetails.class);
                intent.putExtra("result", scanResult);
                startActivity(intent);

              /*  Toast.makeText(BarcodeScanner.this, scanResult, Toast.LENGTH_SHORT).show();*/

                barcodeScanned = true;

                break;
            }

        }

    }
};

    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };

};

qrcodedetails.php
<?php
 //open connection to mysql db
$connection =mysqli_connect("localhost","dbname","passsword") or die("Error " . mysqli_error($connection));

//fetch table rows from mysql db
$vehicleno = $_GET['vehicle_no'];
$sql = "SELECT * FROM parkingsession where vehicle_no = '$vehicleno' ";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result)) //row contain result
{
    $emparray[] = $row;
}
echo json_encode($emparray);

//close the db connection
mysqli_close($connection);
?>

A: You need to make a http request from the android application to your php server with the scanned ID in the request string (just as if you had typed the request string into the browser's url bar).
Given that you understand that this is what you want to do, take a look at Make an HTTP request with android which outlines how you can do it.


text:
Q: Why doesn't the newly created thread obtain its tid through pthread_create() return argument but pthread_self() This is the sample code for thread creation from "Advanced Programming in the Unix Environment". As for thread creation, err = pthread_create(&ntid, NULL, thr_fn, NULL); can the newly created thread just use ntid to print its own threadID, rather than calling pthread_self()?
#include "apue.h"
#include <pthread.h>

pthread_t ntid;

void
printids(const char *s)
{
    pid_t       pid;
    pthread_t   tid;

    pid = getpid();
    tid = pthread_self();
    printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid,
      (unsigned int)tid, (unsigned int)tid);
}

void *
thr_fn(void *arg)
{
    printids("new thread: ");      /* for the newly created thread,can it
                                    * print its own threadID just using ntid,
                                    * instead of calling pthread_self()
                                    */
    return((void *)0);
}

int
main(void)
{
    int     err;

    err = pthread_create(&ntid, NULL, thr_fn, NULL);
    if (err != 0)
        err_quit("can't create thread: %s\n", strerror(err));
    printids("main thread:");
    sleep(1);
    exit(0);
}

A: Let's check spec:
http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html
pthread_create(pthread_t *restrict thread,

Upon successful completion, pthread_create() shall store the ID of the created thread in the location referenced by thread.
The calling thread can obtain the ID of the created thread through the return value of the pthread_create() function, and the newly created thread can obtain its ID by a call to pthread_self().

The problem is: ntid is variable of calling function;  even if it is global, the reading of this global variable from thread doesn't scale to two created threads or more.
Other problem is timing and order of execution. pthread_create writes thread id to ntid after new thread is created:

Upon successful completion, pthread_create() shall store the ID of the created thread in the location referenced by thread.

So, it is unsafe to read ntid from created thread without synchronization, new thread may do read before actual value will be written to global.
So, you should use pthread_self: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_self.html

The pthread_self() function shall return the thread ID of the calling thread.
The pthread_self() function provides a capability similar to the getpid() function for processes and the rationale is the same: the creation call does not provide the thread ID to the created thread.


text:
Q: Can't add config transforms I have created a build configuration but the "Add Config transforms" option doesn't show up for me. I've tried currently being on that build configuration or not. I've tried to add the file manually, but then it doesn't stack with the original Web.config file.

A: Install "Configuration Transform" extension. And this option will show up.
Tools -> Extension and updates... -> (select "Online" and type "transform" into search box)


text:
Q: Refreshing Page After Delete With Ajax in ASP.NET MVC I'm trying to refresh the page after I delete a record from the database. I managed to hack the behaviour I want by reloading the windows inside the ajax 'error' but I'm not quite sure why I can't return success to ajax from my controller.
I've tried the following:
Different return types in the controller (RedirectToRoute, RedirectToAction("Index"), Action Result (Return Ok()), plus using POST and GET as the AJAX type (and changing the controller accordingly).
Everything I do (other than reloading inside the error block) deleted the record from the db but never refreshes the page with the new table.
View:
@model todo.ViewModels.TodoViewModel

        Id
        Name

    @foreach (var t in Model.TodoList)
    {

            @t.Id
            @t.Name
            <input type="submit" class="btn btn-danger" value="Delete" onClick="deleteTodo(@t.Id)" />

    }

js:
function deleteTodo(i)
{

    $.ajax({
        url: 'Todo/Delete',
        type: 'GET',
        dataType: 'json',
        data: {
            id: i
        },
        success: function() {
            alert('success');
        },
        error: function() {
            alert('fail');
            window.location.reload();
        }
    });
}

Controller
 public IActionResult Index()
        {
            var tdlvm = GetAllTodos();
            return View(tdlvm);
        }

        [HttpGet]
        public RedirectToActionResult Delete(int id)
        {
            using (var connection =
                   new SqlConnection("Server=(localdb)\\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Todo"))
            {
                using (var tableCmd = connection.CreateCommand())
                {
                    connection.Open();
                    tableCmd.CommandText = $"DELETE from todo WHERE Id = '{id}'";
                    int rowCount = tableCmd.ExecuteNonQuery();
                }
            }

            return RedirectToAction("Index");
        }

        internal TodoViewModel GetAllTodos()
        {
            List<Todo> todoList = new();

A: You are trying to redirect from Controller which is not really best done using AJAX. AJAX is used to update a portion of the page and is generally not used to redirect to some other page. In your case you can do the following:
You need to return Json from your Controller method. You can do that by defining your method to be JsonResult which will return Json to your AJAX call.
You can also use ActionResult if there are multiple return types possible deriving from ActionResult, like ViewResult, FileResult, JsonResult, etc.
Since you are doing a GET action and MVC defaults to DenyGet to protect you against a very specific attack involving JSON requests, you need to allow it explicitly. If it were a POST action, then you do not need to bother with setting the JsonRequestBehavior.
[HttpGet]
public JsonResult Delete(int id)
{
    int rowCount=0;
    using (var connection =
           new SqlConnection("Server=(localdb)\\MSSQLLocalDB;Integrated Security=true;Initial Catalog=Todo"))
    {
        using (var tableCmd = connection.CreateCommand())
        {
            connection.Open();
            tableCmd.CommandText = $"DELETE from todo WHERE Id = '{id}'";
            rowCount = tableCmd.ExecuteNonQuery();
        }
    }

    if(rowCount > 0)
    {
      return Json(new {status="true", msg= "Successfully deleted"}, JsonRequestBehavior.AllowGet);
    }
    else
    {
      return Json(new {status="false", msg= "Could not delete"}, JsonRequestBehavior.AllowGet);
    }
}

And you can handle this in your AJAX like this:
function deleteTodo(i)
{

    $.ajax({
        url: 'Todo/Delete',
        type: 'GET',
        dataType: 'json',
        data: {
            id: i
        },
        success: function(data) {
          if(data.status=="true")
          {
            var urlToRedirect= '@Url.Action("Index","Home")';
            window.location.href = urlToRedirect; //Redirect here
          }
          else if(data.status=="false")
          {
            alert(data.msg)
          }
        },
        error: function() {
            alert('fail');
            window.location.reload();
        }
    });
}

A: when you are using ajax redirect inside of the controller action is not working. Try this
 success: function() {
   alert('success');
   window.location.href= "/home/index";
},


text:
Q: flash.utils.getDefinitionByName vs. ApplicationDomain's class definition methods What's the difference between these two method groups in terms of the set of classes they work with (i.e. ApplicationDomain's class definition set vs the set of class definitions getDefinitionByName uses)?

*

*ApplicationDomain. getDefinition / hasDefinition / getQualifiedDefinitionNames (Flash Player 11.3+ only, undocumented)

*getDefinitionByName
It's clear that there's an application domain hierarchy and that definitions may be visible in some app domains and not others.  For example, would ApplicationDomain.getDefinition return a definition that is not defined in the given app domain but is accessible from it? (e.g. if the domain is a child domain and we're looking up a definition defined in the parent?)  The documentation for ApplicationDomain just says "Loaded classes are defined only when their parent doesn't already define them." but it also says "(ApplicationDomains) allow multiple definitions of the same class to exist and allow children to reuse parent definitions."
The documentation also indicates that getDefinitionByName returns class definitions, whereas ApplicationDomain.getDefinition will return namespace and function definitions in addition to class definitions.
Assuming I'm only interested in class definitions, what ApplicationDomains does getDefinitionByName search? (e.g. all domains, the current/caller domain only, or any domains accessible to the caller?)
This initial test is confusing:
import flash.system.ApplicationDomain;
var d:ApplicationDomain = new ApplicationDomain( ApplicationDomain.currentDomain ); //child of current domain
trace(ApplicationDomain.currentDomain.hasDefinition("flash.display.DisplayObject")); //true
trace(ApplicationDomain.currentDomain.getQualifiedDefinitionNames().length); //1 (the main timeline class definition only: Untitled_fla::MainTimeline)
trace(d.hasDefinition("flash.display.DisplayObject")); //false

In the above test, on the one hand, getQualifiedDefinitionNames reports that only the main timeline class is defined in the current app domain, yet getDefinition returns true for DisplayObject, indicating it reports the existence of definitions in the parent (system) domain, yet the final trace on the grandchild domain contradicts that by returning false.
ApplicationDomain.currentDomain.parentDomain also returns null, which directly contradicts the following documentation statements: "The system domain contains all application domains, including the current domain..." and "Every application domain, except the system domain, has an associated parent domain. The parent domain of your main application's application domain is the system domain."
The contradiction is very apparent here, where currentDomain has the definition, but when you create a child domain and access the parent, which should be currentDomain, it suddenly reports that it doesn't contain the definition:
trace(ApplicationDomain.currentDomain.hasDefinition("flash.display.DisplayObject")); //true
trace((new ApplicationDomain( ApplicationDomain.currentDomain )).parentDomain.hasDefinition("flash.display.DisplayObject")); //false! why?

A: This page is quite comprehensive: http://www.senocular.com/flash/tutorials/contentdomains/?page=2  I've managed to solve a couple mysteries, but the basic question outlined above (particularly concerning the scope of getDefinitionByName) still stands.  I just wanted to post an answer for what I was able to resolve.
Retreiving the parentDomain returns null if the parent is the system domain.  So although the parentDomain is the system domain, the parentDomain property returns null anyway.  That's just the way it is.  Unfortunately, that makes the system domain inaccessible, for example, for class enumeration through getQualifiedDefinitionNames.
Concerning my initial test, it seems that constructing a new ApplicationDomain creates a dead object until a SWF is actually loaded under that domain.  For example, creating a child domain of the current domain and calling hasDefinition on it will return false, but if you assign that very same instance to a loader context an pass it to Loader.load, once the load completes, you can call hasDefinition on the instance that originally returned false, and it will return true instead.  So you can construct an ApplicationDomain with a parent, but it won't really function until it's being actively used.
var d:ApplicationDomain = new ApplicationDomain( ApplicationDomain.currentDomain ); //child of current domain
trace(d.hasDefinition( "flash.display.DisplayObject" )); //false for now...
var l:Loader = new Loader();
l.load(new URLRequest( "any.swf"), new LoaderContext( false, d ) );
l.contentLoaderInfo.addEventListener( Event.COMPLETE, completed, false, 0, true );
function completed(e:Event ):void
{
    trace(d.hasDefinition( "flash.display.DisplayObject" ); //...and now it's true.
}

So it would seem that ApplicationDomain.getDefinition does report classes in the parent, grandparent, etc. domains, but it will only do so after the new ApplicationDomain instance has been activated through loading something into it.
Also, ApplicationDomain instances may refer to the same application domain, but they cannot be directly compared.  For example, (ApplicationDomain.currentDomain == ApplicationDomain.currentDomain) is false.


text:
Q: Bash / xargs trick to open all files that changed in git HEAD I open files from Terminal in Sublime Text and do so using a shortcut like this:
$ subl <filename>
...what I'm hoping to do is open all files that changed in my last git commit.
I can see all files that changed like so:
$ git show --name-only HEAD
commit b2c891f64daab0dc67df5cde9608602c7cde2f7b
Author: Jacob
Date:   Fri Jun 9 16:52:05 2017 -0700

    start doing some cool stuff; ref 12345

python/deep/hot/Classes.py
python/shallow/cold/features.tmpl
javascript/utility_master.js

... but this command shows more info besides the filenames themselves.
I want to do something like:
$ git show --name-only HEAD | <get the lines out that aren't filenames> | xargs -i subl {}
Does this require awk? Or a different git flag that I can't find?

A: Use diff: git diff --name-only HEAD~
subl `git diff --name-only HEAD~`

A: git show --pretty= --name-only HEAD should do the trick


text:
Q: Number of non singular matrices over a finite field of order 2 I have to find out the number of $3×3$ non singular matrices over a field of order $2$.
I tried in the following way.
First to find out a non singular matrix $A,$ clearly any row of $A$ can't be full of $0$s.
So the first row (say) can be filled up by $(8-1)$ ways.
Once the row is filled up,the next row can't be the same and also can't be full of zeros,so we can fill the next row by $
(8-2)$ ways.
And at last the third row also can't be full of zeros,same as the first row,and same as the second row also.So we have
 $(8-3)$ choices.
Hence the number of non singular matrices seems to be $7×6×5=210$.
Am I right? Or there are more non singular matrices ? May be less also.
Please correct me if I am wrong.
Thank you.

A: Here field of order 2 is $\mathbb{F}_2$ = $\mathbb{Z}_2$ = $\{0,1\}$. The result is actually the number of elements in the General Linear Group $GL_3(\mathbb{F}_2)$ or $GL_3(\mathbb{Z}_2)$.
To count the number of non-singular matrices of order 3 with 0 and 1 as its elements only, we have to make sure that all the rows are linearly independent and non-zero.
For the first row we have $(2^3 – 1)$ choices.
For the second row we have $(2^3 – 1) – 1 $ = $(2^3 – 2)$ choices. Because we cannot count the vector already has been used in first row.
For the third row we have $(2^3 – 1) – 2 – 1 $ = $(2^3 – 2^2)$ choices. Because we have to omit 2 vectors from the count that already have been used in first and second row. And we have to omit one more vector that can be the linear combination of the first and second rows.
So, in total we can have $(2^3 – 1)(2^3 – 2)(2^3 – 2^2)$ = $7\times6\times4$ = $168$ matrices.


text:
Q: LINQ query doesn't give any results (finding which interval a number belongs to) I have a property class which looks like this
ZipStart | ZipEnd | Acode

10000    | 13999  | BEK

14000    | 14999  | ATE

Now, I have a value, for example 11332 and I want to look up which Acode that number belongs to, for this I've the following code:
           var res = from o in ListOfDataClass
                  where iCode >= o.ZipStart && o.ZipEnd <= iCode
                  select o;

            var c = res.FirstOrDefault();
            return c.Acode;

However this results in  null from time to time, I haven't been able to find a pattern yet though, but since the issue arises in this method I've been able to deduct from the debugger that the iCode IS actually 11332 but that the LINQ-query doesn't yield any results.
Any ideas?

A: Your condition is incorrect.
The second part has to be o.ZipEnd >= iCode or iCode <= o.ZipEnd.

A: I think you have to move your condition about a little:
where iCode >= o.ZipStart && iCode <=  o.ZipEnd


text:
Q: Getting value of checkbox from dropdown I'm really stuck here & I think I'm missing something really obvious. Kindly help me out(I'm a beginner in html,javascript)
I have made a dropdown containing a un-ordered list of items that I'm getting populated from JSON.Here'e the code for populating the list:
    var oldJSON = null;
    setTimeout(function main_func() {
            var counter=0;
            $.getJSON('mydata.json', function(data) {
                    if(JSON.stringify(oldJSON) != JSON.stringify(data)){
                        //$(".dropdown").html("");
                        //$("#notifications").append("<option style=display:none></option>")
                        $.each(data.items, function(i, v) {
                                counter++;
                                document.getElementById('test').innerHTML=counter ;
                                $('.dropdown').append('
<input type="checkbox" value="'+counter+'"id="'+ counter +'">
' + v.type +'
'+'
' +v.text +'
'+'
'+v.pnr+'
'+ '
');
                                ;});
                    }
                    oldJSON = data;
            });
            setTimeout(main_func,2000);
    });

Now,my dropdown(consider it a facebook type notification) contains checkbox(for mark as read-haven't implemented it yet). I need to get the values from the checkbox. Right now I'm getting blank values. Could someone please point me in the right direction?
Here's my html:

& here's the javascript to go along with it(which is not working):
$('.dropdown input[type="checkbox"]').on('click', function () {
    var title = $(this).closest('.dropdown').find('input[type="checkbox"]').val(),
    title = $(this).val() + ",";
    if ($(this).is(':checked')) {
        $('.selected_item').append(title);
    }
});

Kindly do edit the question if you can frame it better ;) . If its any help,I've pasted my code here for html css json

A: try this demo
$('.dropdown input[type="checkbox"]').on('click', function () {
    var title = "";
    $('.dropdown input[type="checkbox"]').each(function(){
    if ($(this).is(':checked')) {
        if(title != "")
            title = title + ',';

        title = title + $(this).val();
    }
    $('#selected_item').html(title);
    });
});


text:
Q: Arcs of longitude not displaying correctly with MiKTeX (as opposed to with MacTeX) I have a problem when rendering the following code with MiKTeX (it renders fine with MacTeX). My arcs of longitude are not displaying correctly (pushed to the edges of the ball instead of towards the middle). I think the problem might be the PGF version I am using (3.0 on MiKTeX and 2.10 on MacTeX). Reading this post http://latex-community.org/forum/viewtopic.php?f=45&t=25293 it makes me wonder whether the problem is a bug in the PGF/TikZ version mention in this post, but it's been two years since this post. I've tried replacing .estyle by .style to no avail.
I have to get the code working with MiKTeX, is there any way to do that? I appreciate your advice!
\documentclass{article}
\usepackage{tikz}

\newcommand\pgfmathsinandcos[3]{%
  \pgfmathsetmacro#1{sin(#3)}%
  \pgfmathsetmacro#2{cos(#3)}%
}
\newcommand\LongitudePlane[3][current plane]{%
  \pgfmathsinandcos\sinEl\cosEl{#2} % elevation
  \pgfmathsinandcos\sint\cost{#3} % azimuth
  \tikzset{#1/.estyle={cm={\cost,\sint*\sinEl,0,\cosEl,(0,0)}}}
}
\newcommand\DrawLongitudeCircle[2][1]{
  \LongitudePlane{\angEl}{#2}
  \tikzset{current plane/.prefix style={scale=#1}}
   % angle of "visibility"
  \pgfmathsetmacro\angVis{atan(sin(#2)*cos(\angEl)/sin(\angEl))} %
  \draw[color=blue,current plane] (\angVis:1) arc (\angVis:\angVis+180:1);
  \draw[color=blue,current plane,dashed] (\angVis-180:1) arc (\angVis-180:\angVis:1);
}

\begin{document}
\begin{tikzpicture}
    \def\R{2} % sphere radius
    \def\angEl{5} % elevation angle
    \def\meridian{-100}
    \fill[ball color=white!20] (0,0) circle (\R);
    \DrawLongitudeCircle[\R]{\meridian}
\end{tikzpicture}
\end{document}

A: Replace .estyle by .style, as described in the post that you cite, resulting in the line
\tikzset{#1/.style={cm={\cost,\sint*\sinEl,0,\cosEl,(0,0)}}}

The following image was typeset with the TeXLive 2016 distribution, tikz/pgf 2015/08/07 v3.0.1a. If the code below results in a different image, you maybe have to upgrade to the most recent version.

\documentclass{article}
\usepackage{tikz}

\newcommand\pgfmathsinandcos[3]{%
  \pgfmathsetmacro#1{sin(#3)}%
  \pgfmathsetmacro#2{cos(#3)}%
}
\newcommand\LongitudePlane[3][current plane]{%
  \pgfmathsinandcos\sinEl\cosEl{#2} % elevation
  \pgfmathsinandcos\sint\cost{#3} % azimuth
  \tikzset{#1/.style={cm={\cost,\sint*\sinEl,0,\cosEl,(0,0)}}}
}
\newcommand\DrawLongitudeCircle[2][1]{
  \LongitudePlane{\angEl}{#2}
  \tikzset{current plane/.prefix style={scale=#1}}
   % angle of "visibility"
  \pgfmathsetmacro\angVis{atan(sin(#2)*cos(\angEl)/sin(\angEl))} %
  \draw[color=blue,current plane] (\angVis:1) arc (\angVis:\angVis+180:1);
  \draw[color=blue,current plane,dashed] (\angVis-180:1) arc (\angVis-180:\angVis:1);
}

\begin{document}
\begin{tikzpicture}
    \def\R{2} % sphere radius
    \def\angEl{5} % elevation angle
    \def\meridian{-100}
    \fill[ball color=white!20] (0,0) circle (\R);
    \DrawLongitudeCircle[\R]{\meridian}
\end{tikzpicture}
\end{document}


text:
Q: iOS: how to stop text animation in partial curl I'm using a partial curl modal in my iOS application. Please see this video:
http://vimeo.com/38643030
During the partial curl transition, the text in the round rect buttons is moving too. How can I stop this?

A: Put [self.view layoutIfNeeded] in the -viewDidLoad implementation for the view controller that's being shown via the curl animation. This makes the buttons & their contents lay out once before the animation starts instead of trying to do its layout (and redo it as things change around it) during the animation.

A: Just to add to rickster's answer, I had a similar problem with a UITableViewController and it was necessary to add
[self.view layoutIfNeeded];
[self.tableView layoutIfNeeded];

in the -viewDidLoad. Neither of the above statements worked on their own.


text:
Q: Laravel 8 Mix npm run development error with vue.js I've laravel Vue js project. I need to make changes to our project but when I try to use npm run development to reflect my changes but I got the below-mentioned error in Mac System.
fleetcart@ dev /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com
> npm run development

> fleetcart@ development /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js

Browserslist: caniuse-lite is outdated. Please run:
  npx browserslist@latest --update-db
  Why you should do it regularly: https://github.com/browserslist/browserslist#browsers-data-updating
/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/Themes/Storefront/node_modules/webpack/lib/NormalModule.js:207
            throw new TypeError(
            ^

TypeError: The 'compilation' argument must be an instance of Compilation
    at Function.getCompilationHooks (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/Themes/Storefront/node_modules/webpack/lib/NormalModule.js:207:10)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/Themes/Storefront/node_modules/mini-css-extract-plugin/dist/index.js:394:103
    at SyncHook.eval [as call] (eval at create (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:7:1)
    at SyncHook.lazyCompileHook (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.newCompilation (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:631:26)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:667:29
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:4:1)
    at AsyncSeriesHook.lazyCompileHook (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.compile (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:662:28)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:321:11
    at Compiler.readRecords (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:529:11)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:318:10
    at eval (eval at create (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:9:1)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/CachePlugin.js:50:13
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:5:1)
    at AsyncSeriesHook.lazyCompileHook (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/Hook.js:154:20)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:315:19
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:13:1)
    at AsyncSeriesHook.lazyCompileHook (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.run (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack/lib/Compiler.js:312:24)
    at processOptions (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack-cli/bin/cli.js:353:14)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack-cli/bin/cli.js:364:3
    at Object.parse (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack-cli/node_modules/yargs/yargs.js:576:18)
    at /home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack-cli/bin/cli.js:49:8
    at Object.<anonymous> (/home/virtual/vps-e25466/2/2c563f2522/staging.pnutso.com/node_modules/webpack-cli/bin/cli.js:366:3)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fleetcart@ development: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fleetcart@ development script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/virtual/vps-e25466/2/2c563f2522/.npm/_logs/2022-11-11T12_21_33_478Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fleetcart@ dev: `npm run development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the fleetcart@ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/virtual/vps-e25466/2/2c563f2522/.npm/_logs/2022-11-11T12_21_33_490Z-debug.log

Below is my package.json file:
{
    "name": "fleetcart",
    "private": true,
    "scripts": {
        "rtlcss": "rtlcss",
        "postinstall": "lerna bootstrap",
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "@babel/preset-env": "^7.19.4",
        "cross-env": "^6.0.2",
        "eslint": "^8.26.0",
        "eslint-config-spatie": "^2.0.3",
        "eslint-plugin-import": "^2.26.0",
        "glob": "^7.2.3",
        "laravel-mix": "^6.0.49",
        "laravel-mix-merge-manifest": "^0.1.2",
        "lerna": "^6.0.2",
        "rtlcss": "^4.0.0",
        "sass": "^1.56.0",
        "sass-loader": "^8.0.2",
        "vue-template-compiler": "^2.7.13",
        "webpack-shell-plugin": "^0.5.0"
    },
    "dependencies": {
        "webpack": "^5.74.0"
    }
}

Earlier when I run npm run dev cmd then getting some strange error related to the library version mismatch error so I updated Laravel-Mix lib to 6.0.12 and try to run but after too much research, not get any results.
I removed the node_modules, package.json file from the root folder and then again reinstalled it, but nothing happened.
I used the below-mentioned command in the development script:
cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --config=node_modules/laravel-mix/setup/webpack.config.js

Please let me know if anyone has an idea to reflect my changes to live server after npme run dev command.
Thank You in advance.


text:
Q: URL rewriting page load loops I am using Intelligencia UrlRewriter to apply URL Rewriting.
I took page1.aspx and used the OnClick event of a button and did a Response.Redirect to page2.aspx. Everything works fine if I test with these two sample pages.
Then I applied some styles and javascript to page2.aspx. When I click the same button on page1.aspx and put a break point on page2.aspx.cs page_load function, what I observed is that page_load function is looped for multiple times and it loops and loads all the database calls multiple times.
Applying IsPostback didn't help. Then I removed the CSS and JS then everything is fine.Need answer why this page_load function repeats multiple times.

A: I had this problem too.  Like the others have touched on, it can be caused by relative paths inside your page.
I was rewriting:
domain.com/article/12345/title-here

To become:
domain.com/article.aspx?ID=12345

Problem was, there were 2 images with relative paths:
  EG. images/fb.jpg
      images/tw.jpg

By logging the value in Request.RawUrl.ToString(), I was able to see that the browser was requesting following images:
 domain.com/article/12345/images/fb.jpg

 domain.com/article/12345/images/tw.jpg

Although these files don't exist, the URL still satisfied the redirect rule.
Thus, rewriting the URL to:
domain.com/article.aspx?ID=12345

Which explains why my page loaded three times.  Once for the HTML, and once for each image.
Changed the image src values to an absolute path and the problem was solved.

A: You have to set rewrite rules for CSS and JS directory. Your page calling again and again because on request of css and JS files your page serve. set rewrite rules for your CSS and JS according to your directory system.
Edit
not sure may be work
<rewrite url="^(/.+(\.gif|/.+\.png|\.jpg|\.ico|\.pdf|\.css|\.js|\.asmx|\.axd|\.flv|\.swf)(\?.+)?)$" to="$1" processing="stop" />

A: Page load loops occur using the out of the box ASP.Net implementation as well. One oe the ways you can check for and reduce processing overhead is to check the httpContext object to see what the currently requested object is. If the object is not what you expect - an image, .js file, stylesheet, etc, bail out of the page processing.


text:
Q: Error in is.constant(y) : (list) object cannot be coerced to type 'double' I have a sample file that I am using to forecast as a panel series.
 The steps followed are
library(plm)
library(Formula)
library(forecast)
library(timeDate)
library(zoo)

df1 <- read.csv("full panel Test Input.csv", header=TRUE, sep=",")
pdf1 <- plm.data(df1,index=c("state","time"))
fmodel1 <- plm(M4~M1+M2+M3,data=pdf1,model="within")
fcast <- forecast(fmodel1,data=pdf1)

I get the error stated in the subject exactly at step nine. The process and the data is fine since we have checked it in stata.
Any help is appreciated.
M1  M2  M3  M4  state   time
466 63  14  10  AZ  2013w31
0   63  0   0   AZ  2013w32
480 63  77  270 AZ  2013w33
0   63  0   0   AZ  2013w34
10  0   742 40  AZ  2013w35
0   0   0   0   AZ  2013w36
0   0   210 10  AZ  2013w37
1049    28  168 30  AZ  2013w38
1148    35  203 20  AZ  2013w39
5130    182 21  10  AZ  2013w40
8667    427 0   10  AZ  2013w41
460000  10731   14  20  AZ  2013w42
1000000 27608   0   120 AZ  2013w43
0   27608   0   0   AZ  2013w44
18494   1344    7   30  AZ  2013w45
15775   1176    21  10  AZ  2013w46
15516   1197    0   40  AZ  2013w47
0   1197    0   0   AZ  2013w48
0   1197    0   0   AZ  2013w49
11280   700 0   30  AZ  2013w50
6320    336 14  50  AZ  2013w51
765 35  0   20  AZ  2013w52
230 0   0   10  AZ  2014w1
0   0   0   0   NJ  2013w31
0   0   0   0   NJ  2013w32
6   0   0   10  NJ  2013w33


text:
Q: NVIDIA drivers installed, but nvidia-smi not working on CentOS I have an NVIDIA driver installed, verified by the output of cat /proc/driver/nvidia/version:

NVRM version: NVIDIA UNIX x86_64 Kernel Module  390.30  Wed Jan 31 22:08:49 PST 2018
  GCC version:  gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC)

However, running nvidia-smi gives the following error: bash: nvidia-smi: command not found...
More info: I am running CentOS 7, and trying to a) get nvidia-smi working and b) then install CUDA.

A:
Asked 3 years, 1 month ago

you stated  I have an NVIDIA driver installed however you did not describe how you installed it.  Be aware the nvidia driver is a kernel module and it is often lost after doing a yum update when a kernel update happens;  the nvidia kernel module is not preserved (unless you have DKMS installed) so nvidia functionality will then cease.
However that does not explain why /usr/bin/nvidia-smi says command not found which is another matter, but that is where nvidia-smi should be and /usr/bin should obviously be in your PATH.  Simply reinstalling nvidia via the nvidia.run file will fix that...
Below is my preferred method for doing NVIDIA install (and cuda) under RHEL/CentOS 7.x which has served me well (for about the last 3 years)

*

*download NVIDIA-Linux-x86_64-460.67.run from  nvidia  {get the correct one for your graphics card}  approx 150mb

*download cuda_11.2.2_460.32.03_linux.run from nvidia {whatever the latest version is, over 2gb}

*su to root; copy both to /root;  chmod 700 on both;

*systemctl set-default multi-user.target

*reboot or systemctl isolate multi-user.target or init 3

*run /root/NVIDIA-Linux-x86_64-460.67.run  {and observe the building kernel module part}

*after successful install, /usr/bin/nvidia-smi should be present and work;

*then do a systemctl isolate graphical.target  or  init 5 and if a graphical console works then log in, and set back to systemctl set-default graphical.target if you prefer.

*ideally do one last reboot to validate everything is working

The CUDA install is basically the same process.
The bundled nvidia graphics driver within the cuda.run file is not always the latest.
The latest nvidia.run driver will (should) always work with whatever cuda version.
You are not required to install the bundled nvidia graphics driver within the cuda.run file, so my preference is to uncheck that when installing cuda.

A: I run an HPC cluster at work and we have the cuda-driver RPM installed. It provides nvidia-smi, but its in the $INSTALL_ROOT/libs/440.64.00/bin directory. $INSTALL_ROOT might vary from system to system, so you'll have to find that first.
After I remembered we'd used an RPM named cuda-driver and not one with nvidia in the name, I found the nvidia-smi tool like this:
rpm -qa | grep -i cuda | xargs rpm -ql | grep -i nvidia-smi
Which gave me three pathnames (you can see my INSTALL_ROOT here)
/cm/local/apps/cuda-driver/libs/440.64.00/bin/nvidia-smi
/cm/local/apps/cuda-driver/libs/440.64.00/share/doc/NVIDIA_GLX-1.0/html/nvidia-smi.html
/cm/local/apps/cuda-driver/libs/440.64.00/share/man/man1/nvidia-smi.1.gz
And then I used rpm -qf on one of those to get the name of the RPM.
Hope that helps!

A: Usually, when working on a new system - if you have sudo access then:
First, try

sudo apt-get install nvidia-cuda-toolkit OR

sudo yum install nvidia-cuda-toolkit

depending on the system you are working with.
If that doesn't work, then try other solution.
For no sudo access machines - download drivers from the official website and then install nvidia-driver first and then cuda for the same driver version.
nvidia-smi is part of the nvidia-utils package which you need to install for corresponding driver version.
For example: for nvidia-driver 440 you will need to install sudo apt install nvidia-utils-440


text:
Q: SQL Server 2005: Update rows in a specified order (like ORDER BY)? I want to update rows of a table in a specific order, like one would expect if including an ORDER BY clause, but SQL Server does not support the ORDER BY clause in UPDATE queries.
I have checked out this question which supplied a nice solution, but my query is a bit more complicated than the one specified there.
UPDATE TableA AS Parent
SET Parent.ColA = Parent.ColA + (SELECT TOP 1 Child.ColA
    FROM TableA AS Child
    WHERE Child.ParentColB = Parent.ColB
    ORDER BY Child.Priority)
ORDER BY Parent.Depth DESC;

So, what I'm hoping that you'll notice is that a single table (TableA) contains a hierarchy of rows, wherein one row can be the parent or child of any other row.  The rows need to be updated in order from the deepest child up to the root parent.  This is because TableA.ColA must contain an up-to-date concatenation of its own current value with the values of its children (I realize this query only concats with one child, but that is for the sake of simplicity - the purpose of the example in this question does not necessitate any more verbosity), therefore the query must update from the bottom up.
The solution suggested in the question I noted above is as follows:
UPDATE messages
SET status=10
WHERE ID in (SELECT TOP (10) Id
    FROM Table
    WHERE status=0
    ORDER BY priority DESC
);

The reason that I don't think I can use this solution is because I am referencing column values from the parent table inside my subquery (see WHERE Child.ParentColB = Parent.ColB), and I don't think two sibling subqueries would have access to each others' data.
So far I have only determined one way to merge that suggested solution with my current problem, and I don't think it works.
UPDATE TableA AS Parent
SET Parent.ColA = Parent.ColA + (SELECT TOP 1 Child.ColA
    FROM TableA AS Child
    WHERE Child.ParentColB = Parent.ColB
    ORDER BY Child.Priority)
WHERE Parent.Id IN (SELECT Id
    FROM TableA
    ORDER BY Parent.Depth DESC);

The WHERE..IN subquery will not actually return a subset of the rows, it will just return the full list of IDs in the order that I want.  However (I don't know for sure - please tell me if I'm wrong) I think that the WHERE..IN clause will not care about the order of IDs within the parentheses - it will just check the ID of the row it currently wants to update to see if it's in that list (which, they all are) in whatever order it is already trying to update... Which would just be a total waste of cycles, because it wouldn't change anything.
So, in conclusion, I have looked around and can't seem to figure out a way to update in a specified order (and included the reason I need to update in that order, because I am sure I would otherwise get the ever-so-useful "why?" answers) and I am now hitting up Stack Overflow to see if any of you gurus out there who know more about SQL than I do (which isn't saying much) know of an efficient way to do this.  It's particularly important that I only use a single query to complete this action.
A long question, but I wanted to cover my bases and give you guys as much info to feed off of as possible. :)
Any thoughts?

A: You cannot succeed this in one query, because your updates are correlated (ie. level N depends on the updated value of level N+1). Relational engines frown on this very explicitly because of the Halloween Problem. The query plan will go out of its way to ensure that the updates occur as if they had two stages: one in which the current state was read, and then one in which the updated state was applied. If necessary, they'll spool intermediate tables just to preserve this apparent execution order (read all->write all). Since your query, if I understand correctly, tries to break this very premise I don't see any way you'll succeed.

A: UPDATE statements will be executed as a single query, not as a step by step result.
You need to either use a while loop/cursor (uhhgg) or maybe make use of a CTE expression view to achieve what you are trying, which gives you the recursice possibility.
Have a look at

*

*Using Common Table Expressions

*Recursive Queries Using Common Table
Expressions

A: Here is a one line SQL solution. If you ever relax the requirement that it need be one update statement you can factor out some of the complexity
CREATE TABLE [TableA](
    [ID] [int] NOT NULL,
    [ParentID] [int] NULL,
    [ColA] [varchar](max) NOT NULL,
    [Priority] [varchar](50) NOT NULL,
    [Depth] [int] NOT NULL)
go

INSERT TableA
SELECT 1, NULL, 'p', 'Favorite', 0 UNION ALL
SELECT 2, 1, 'm', 'Favorite', 1 UNION ALL
SELECT 3, 1, 'o', 'Likeable', 1 UNION ALL
SELECT 4, 2, 'v', 'Favorite', 2 UNION ALL
SELECT 5, 2, 'v', 'Likeable', 2 UNION ALL
SELECT 6, 2, 'd', 'Likeable', 2 UNION ALL
SELECT 7, 6, 'c', 'Red-headed Stepchild', 3 UNION ALL
SELECT 8, 6, 's', 'Likeable', 3 UNION ALL
SELECT 9, 8, 'n', 'Favorite', 4 UNION ALL
SELECT 10, 6, 'c', 'Favorite', 3 UNION ALL
SELECT 11, 5, 'c', 'Favorite', 3 UNION ALL
SELECT 12, NULL, 'z', 'Favorite', 0 UNION ALL
SELECT 13, 3, 'e', 'Favorite', 2 UNION ALL
SELECT 14, 8, 'k', 'Likeable', 4 UNION ALL
SELECT 15,4, 'd', 'Favorite', 3

;WITH cte AS (
SELECT a.i, a.Depth, a.maxd, a.mind, a.maxc, a.di, a.ci, a.cdi, a.ID, a.y, CAST('' AS varchar(max))z
FROM(
    SELECT DISTINCT i = 1
    ,p.Depth
    ,maxd = (SELECT MAX(Depth) FROM TableA)
    ,mind = (SELECT MIN(Depth) FROM TableA)
    ,maxc = (SELECT MAX(c) FROM (SELECT COUNT(*) OVER(PARTITION BY ParentID) FROM TableA)f(c))
    ,di   = (SELECT MIN(Depth) FROM TableA)
    ,ci   = 1
    ,cdi  = (SELECT MIN(Depth) FROM TableA)
    ,p.ID
    ,CAST(p.ID AS varchar(max)) + p.ColA + SPACE(1) + CASE WHEN g IS NULL THEN '' ELSE '(' END
                                     + ISNULL(g,'') + CASE WHEN g IS NULL THEN '' ELSE ')' END y
    FROM TableA p
    LEFT JOIN TableA c ON (c.ParentID = p.ID)
    CROSS APPLY (SELECT SPACE(1) + CAST(c2.ID AS varchar(max)) + ColA + SPACE(1)
                 FROM TableA c2 WHERE ParentID = p.ID
                 ORDER BY Priority
                 FOR XML PATH(''))f(g)
    )a
UNION ALL
SELECT r.i, r.Depth, r.maxd, r.mind, r.maxc, r.di, r.ci, r.cdi, r.ID
,CASE WHEN di = cdi
      THEN REPLACE(r.y,LEFT(r.z,CHARINDEX(SPACE(1),r.z,2)), r.z)
      ELSE r.y END [y]
,r.z
FROM(
    SELECT i = i + 1
    ,Depth
    ,[maxd]
    ,[mind]
    ,[maxc]
    ,CASE WHEN ci = maxc AND cdi = maxd
          THEN di + 1
          ELSE di
          END [di]
    ,CASE WHEN cdi = [maxd]
          THEN CASE WHEN ci + 1 > maxc
                    THEN 1
                    ELSE ci + 1
                    END
          ELSE ci
          END [ci]
    ,CASE WHEN cdi + 1 > maxd
          THEN mind
          ELSE cdi + 1
          END [cdi]
    ,id,y
    ,CAST(ISNULL((SELECT y FROM(
        SELECT p.Depth,p.ID
        ,SPACE(1) + CAST(p.ID AS varchar(max)) + p.ColA + SPACE(1) +
        CASE WHEN g IS NULL THEN '' ELSE '(' END + ISNULL(g,'')
      + CASE WHEN g IS NULL THEN '' ELSE ')' END y
        ,r1 = DENSE_RANK() OVER(ORDER BY p.ID) --child number
        ,r2 = ROW_NUMBER() OVER(PARTITION BY p.ID ORDER BY p.ID) --DISTINCT not allowed in recursive section
        FROM TableA p
        JOIN TableA c ON (c.ParentID = p.ID)
        CROSS APPLY (SELECT SPACE(1)+CAST(c2.ID AS varchar(max))+ColA+SPACE(1)
                     FROM TableA c2
                     WHERE ParentID = p.ID
                     ORDER BY Priority
                     FOR XML PATH(''))f(g)
        WHERE p.Depth = cdi AND cdi < di AND p.ID <> cte.ID
        )v
    WHERE r1 = ci
    AND r2 = 1
    AND cte.y LIKE '%' + LEFT(v.y,CHARINDEX(SPACE(1),v.y,2) ) + '%'),'') AS varchar(max)) z
FROM cte
WHERE [di]<[maxd] or [ci]<[maxc] or [cdi]<[maxd]
)r
)--cte
UPDATE t
SET ColA = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE
        (y,SPACE(1),''),'1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''),'8',''),'9',''),'0','')
FROM cte
JOIN TableA t ON (t.ID = cte.ID)
WHERE di = (SELECT MAX(Depth) FROM TableA)
AND cdi  = (SELECT MAX(Depth) FROM TableA)
AND ci   = (SELECT MAX(c) FROM (SELECT COUNT(*) OVER(PARTITION BY ParentID) FROM TableA)f(c))
OPTION(maxrecursion 0)

SELECT * FROM TableA
DROP TABLE TableA

A: JMTyler-
1 What kind of data is in ColA? What does it look like?
2 How is/should that column be originally populated? I ask this because you would only be able to run the update once since the value in that column would be modified from a previous run. Any additional runs would just concatenate more data. Which makes me believe there is another ColC with the original value for ColA (a person's name?)
3 Will a row ever be deleted orphaning it's children? If yes what should their ParentColB then point to? NULL? Does their depth then get set to 0 so they are now at the top of the hierarchy?
If you can answer this I can give you a solution
Thanks


text:
Q: How to self join on date calculation and other fields in Redshift Got a query that gets bookings data grouped by date, operator, source, route and I want to self join it so that I have the same data against it but joined on the previous year's date (add 1 day to align the weekday).
For example, if we had
date      |num|
----------|---|
2017-01-01|300|
2017-01-02|301|
2017-01-03|302|
2017-01-04|303|
2017-01-05|304|
2017-01-06|305|
2017-01-07|306|
2017-01-08|307|
2017-01-09|308|
2017-01-10|309|
...
2018-01-01|501|
2018-01-02|502|
2018-01-03|503|
2018-01-04|504|
2018-01-05|505|
2018-01-06|506|
2018-01-07|507|
2018-01-08|508|
2018-01-09|509|
2018-01-10|510|
...

Then I would want result to be
date      |num| date      |num|
----------|---| ----------|---|
2017-01-01|300| null      |null|
2017-01-02|301| null      |null|
2017-01-03|302| null      |null|
2017-01-04|303| null      |null|
2017-01-05|304| null      |null|
2017-01-06|305| null      |null|
2017-01-07|306| null      |null|
2017-01-08|307| null      |null|
2017-01-09|308| null      |null|
2017-01-10|309| null      |null|
...
2018-01-01|501| 2017-01-02|301|
2018-01-02|502| 2017-01-03|302|
2018-01-03|503| 2017-01-04|303|
2018-01-04|504| 2017-01-05|304|
2018-01-05|505| 2017-01-06|305|
2018-01-06|506| 2017-01-07|306|
2018-01-07|507| 2017-01-08|307|
2018-01-08|508| 2017-01-09|308|
2018-01-09|509| 2017-01-10|309|
2018-01-10|510| 2017-01-11|...|

What I've got so far
select

a.date          as date1
,a.source       as source1
,a.operator     as operator1
,a.route        as route1
,a.sum          as bookings1

,b.date         as date2
,b.source       as source2
,b.operator     as operator2
,b.route        as route2
,b.sum          as bookings2

from

(select
date
,source
,operator
,route
,sum(record_count)
from booking
where transaction_date >= dateadd(year, -2, current_date)
group by 1,2,3,4) a

full outer join

(select
date
,source
,operator
,route
,sum(record_count)
from booking
where date between dateadd(year, -3, current_date) and dateadd(year, -1, current_date)
group by 1,2,3,4) b

on

b.date                          = dateadd(day, 1, dateadd(year, -1, a.date))
and a.source                    = b.source
and a.outbound_operator_name    = b.outbound_operator_name
and a.outbound_route_name       = b.outbound_route_name

;

The problem with the above query is that it show's the correct 2018 results but not the correct 2017 results. I presume there's something wrong with either the join type or something within the on clause e.g. the date calculation attempt...
Any help would be much appreciated


text:
Q: Read a variable with multiple occurrences from a file using AWK I want to get the value (usually a string) of var1 in a file my_file.dat and save this value to x.
I managed to do this using the following command:
x = `awk '$1 == "var1" {print $2}' my_file.dat`

It now turns out that there can be several occurrences of var1 in my_file.dat, e.g.:
Series1
var1 = temp/data/
Series2
var1 = lost/oldfiles/

My question is then how can I get only the value of the 'var1' which is located right after the line 'Series1', such that 'x' returns 'temp/data/'?

A: Given the sample you posted all you need is:
x=$(awk 'prev=="Series1" {print $NF} {prev=$0}' file)

but more robustly:
x=$(awk '
    { name=value=$0; sub(/[[:space:]]*=.*/,"",name); sub(/[^=]+=[[:space]]*/,"",value) }
    (prev=="Series1") && (name=="var1") { print value }
    { prev=$0 }
' file)

A: What about a two state machine to solve the problem:
#!/bin/awk

BEGIN {
    state = 0;
}

{
    if( state == 0 )
    {
        if( index( $1, "Series" nseries ) )
        {
            state = 1
        }
    }
    else
    {
        if( index( $1, "Series" ) > 0 )
        {
            exit
        }

        if( index( $1, "var1" ) > 0 )
        {
            idx = index( $0, "=" )
            str = substr( $0, idx + 1 )
            gsub(/^[ \t]+/, "", str )
            print str
            exit
        }
    }
}

# eof #

Test file:
Series1
var1 = temp/data/

Series2
var1 = lost/oldfiles/

Series3
var1 = foo/bar/

Series4
var1 = alpha/betta/

Series5
var1 = /foo/this=bad

Series6
var1 = /foo/Series/

Reading var1 from Series1:
x=$(awk -v nseries=1 -f solution.awk -- ./my_file.dat)
echo $x
temp/data/

Reading var1 from Series5:
x=$(awk -v nseries=5 -f solution.awk -- ./my_file.dat)
echo $x
/foo/this=bad

Reading var1 from Series6:
x=$(awk -v nseries=6 -f solution.awk -- ./my_file.dat)
echo $x
/foo/Series/

Hope it Helps!


text:
Q: an if statements blanks the output I am trying to show a list of symbolized items and letting the user choose one to be deleted.

*

*I write the info to a txt file.

*I store the contents of the file in an array.

*I print out the array.

*The user inputs (L101 for example) and it will get deleted from
the file.

The problem is in step (1)
I want the file to be written, if and only if the file didn't exist.
so I precede the while loop which will write to the file with
if(file.isFile() ==false).

This however seems to blank the output, as if the reader isn't able to read the file and store it in the array. why?
P.S if I don't put an if and else statements the output is ok, it's just that it writes the file again, which I don't want to happen, I want ti to show everything except what the user typed.
Here's the code
public static void main (String args[]) throws IOException
{
    //Declaring the file
     File tempFile = new File("D:\\myTempFile.txt");
    //Declaring the writer
     BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
    int n=0;
    int L=1;
    //Writing to the file if it did not exist
    if(tempFile.isFile()==false)
    {

    while(n<15 && L<3)
        {
        n++;
        writer.write("L"+L+"0"+n);
        writer.newLine();
        L++;
        writer.write("L"+L+"0"+n);
        writer.newLine();
        L++;
        writer.write("L"+L+"0"+n);
        writer.newLine();
        L=1;
        //}

    }
     writer.close();
     freeParkingSpaces();
    }
    //read the and store to array if the file exists
    else if(tempFile.isFile()==true)
    {
        freeParkingSpaces();
    }

}

public static void freeParkingSpaces() throws IOException
   {
     File tempFile = new File("D:\\myTempFile.txt");
   //using try and catch to handle errors and print propriet message instead.
    try{
        Scanner readSpaces; // declare scanner variable.
//reading from file that contains the available spaces and storing them into an array.
System.out.println("Please choose one of the following parking spaces: ");
System.out.println(" ");
String [] freeSpaces= new String[45]; // declaring the array.
int i=0;

//getting input from file that contains the available spaces and storing them into an    array.
readSpaces=new Scanner(new File("D://myTempFile.txt"));
System.out.print("\t\t");

//Display the values of the array which are the available spaces.
while(i<15 && readSpaces.hasNext()){
freeSpaces[i]=readSpaces.nextLine();
System.out.print("   "+freeSpaces[i]);
i++;
}
System.out.println(" ");
System.out.print("\t\t");
while(i>=15&&i<30&&readSpaces.hasNext()){
freeSpaces[i]=readSpaces.nextLine();
System.out.print("   "+freeSpaces[i]);
i++;
}
System.out.println(" ");
System.out.print("\t\t");
while(i>=30&&i<45&&readSpaces.hasNext()){
freeSpaces[i]=readSpaces.nextLine();

System.out.print("   "+freeSpaces[i]);
i++;
}
System.out.println(" ");
readSpaces.close();

//create scanner object to hold the input of a user which is a park space.
Scanner holder5=new Scanner(System.in);
System.out.print("Your choice:  ");
String spaceName=holder5.nextLine();

//declaring files

File inputFile=new File("D://Temporary.txt");

// creating object to read from Free_ParkingSpaces file
BufferedReader reader=new BufferedReader(new FileReader(tempFile));
// creating object to write to the tempFile
BufferedWriter writer0=new BufferedWriter(new FileWriter(inputFile));
String currentLine;

while((currentLine = reader.readLine()) != null){
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(spaceName)) continue;//leave the required space by the user.
writer0.write(currentLine);   //write the lines to the tempFile.
writer0.newLine();   // start from new line.
}

writer0.close(); //close BufferedWriter Object

reader.close(); //close BufferedReader Object
tempFile.delete();  // Delete the old available spaces file.
inputFile.renameTo(tempFile); // Naming the temp file myTempFile.

System.out.println("Registration has completed successfuly");}

                                    catch(Exception e){
                        System.out.println("\n\t\t\t\tSorry, there's something     wrong try again!");}
                   }
}

A: isFile() checks if its a file (not a directory)
exists() checks if the file exists.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
Change it.  Also, always make sure you read the docs about the method and know exactly its purpose before using it.
Note, if statements take a boolean, so if(file.exists()){} or if(file.isFile()){} is the right way
Edit:
Since you are still having problems getting the data into the file here is what you should do.
First, handle the IOException.  When you do throws IOException you are, basically, saying that you will handle the exception at a higher level, but main also declares that, so the exception is never caught (One of the problems when learning using an IDE and auto-corrections).
To make that happen you need to do:
1) Remove all throws IOException
2) Change the catch to be
 try{
    //...
 } catch(IOException ioe){
     ioe.printStackTrace();
 } catch(Exception e){
     System.out.println("\n\t\t\t\tSorry, there's something     wrong try again!");
     System.out.println("\n\t\t\t\tReason:"+e.getMessage());
 }

Doing this will show if there are any IO exceptions thrown.
You can also comment tempFile.delete(); to inspect if the file actually has any data.  If you want to delete it all the time an create a new one do
public static void main (String args[])  {
   //Declaring the file
   File tempFile = new File("D:\\myTempFile.txt");

   if(!tempFile.exists()){
       tempFile.createNewFile();
   }

Edit 2
Here is a working example
    public static void main(String[] args){
        try{

           File tempFile = new File("c:/testing/temp.txt");
           tempFile.getParentFile().mkdirs();
           tempFile.createNewFile();

           writeToFile(tempFile);
           //readFromFile();
           //deleteFile();

        } catch(IOException ioe){
           ioe.printStackTrace();
        }
    }

    public static void writeToFile (File file) throws IOException{

        //Declaring the writer
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));

        int n=0;
        int L=1;

        //Writing to the file if it did not exist
        while(n<15 && L<3) {
            n++;
            writer.write("L"+L+"0"+n);
            writer.newLine();
            L++;
            writer.write("L"+L+"0"+n);
            writer.newLine();
            L++;
            writer.write("L"+L+"0"+n);
            writer.newLine();
            L=1;
        }

        writer.close();
   }


text:
Q: Net Core Middleware acting on failed requirements Using Core 3.1
Have an authorization handler that gets invoked through an authorization filter (i.e. effects all controllers):
var builder = new AuthorizationPolicyBuilder();
builder.Requirements.Add(new MySpecialRequirement(...));
var policy = builder.Build();

services.AddSingleton<IAuthorizationHandler, MySpecialAuthorizeHandler>();

services
  .AddControllers(options => options.Filters.Add(new AuthorizeFilter(policy)))
  .AddControllersAsServices();

When the handler doesn't call succeed on then the filter fails returning a standard 403 without a response message.  Is it possible from Core Middleware to see what requirements failed?  If possible then the response message could be adjusted correspondingly.  This would also open for looking at the collection of requirements that didn't pass rather than a specific.


text:
Q: Long-run fraction Markov Chains A machine has three critical parts (1,2,3) but can function as long as two of these parts are functional. When two are broken, they are replaced and the machine is functional the next day.
The state space is the parts that are broken {0,1,2,3,12,13,23}.
Parts 1,2, and 3 fail with probabilities 0.01, 0.02, and 0.04, respectively, but no two parts fail on the same day.
What is the number of parts of types 1,2, and 3 we will use if the machine operates for 1800 days.
So I understand that the transition probability is given by (where $p(i,j)$ is the probability of going from state $i$ and day $n$ to state $j$ on day $n+1$):
$$\begin{matrix}
 \quad& 0\quad & 1 \quad& 2\quad&3\quad&12\quad &13\quad&23\\
 \\
0\quad & 0.93\quad & 0.01\quad &0.02\quad&0.04\quad&0\quad&0\quad&0 \\
\\
1\quad & 0\quad & 0.94\quad&0\quad&0\quad&0.02\quad&0.04\quad&0\\
\\
2\quad&0\quad&0\quad&0.95\quad&0\quad&0.01\quad&0\quad&0.04\\
\\
3\quad&0\quad&0\quad&0\quad&0.97\quad&0\quad&0.01\quad&0.02\\
\\
12\quad&1\quad&0\quad&0\quad&0\quad&0\quad&0\quad&0\\
\\
13\quad&1\quad&0\quad&0\quad&0\quad&0\quad&0\quad&0\\
\\
23\quad&1\quad & 0 \quad& 0\quad&0\quad&0\quad &0\quad&0
\end{matrix}$$
So, I know by the convergence theorem, $p^n(x,y)\rightarrow \pi (y)$ as $n\rightarrow \infty$ if $p$ is irreducible and aperiodic. However, for $p$ to be aperiodic, all states $x$ must have
$p(x,x)>0$, which is not the case for states 12,13, and 23. So I am lost at what to do.

A: You have misunderstood. For large enough values of $n$, you will find that $p^n(x,x)>0$ for states 12, 13 and 23.
Look at this: https://www.probabilitycourse.com/chapter11/11_2_4_classification_of_states.php


text:
Q: Java returning a variable I am trying to use a method below to return a variable "charges"
public static double billingM(double income, int min, double rate) {
    double charges;
    if (income <= 25000 && min <= 30)
        charges = 0;
    if (income <= 25000 && min > 30)
        charges = rate * 0.4;
    if (income > 25000 && min <= 20)
        charges = 0;
    if (income > 25000 && min > 20)
        charges = rate * 0.7;
    return charges;
} //End of Billing Method

How do I get it to return the variable charges??? It won't how I have it right now.

A: double charges; is a local variable. You need to initialize it since your if statements do not cover all possibilities.

A: You need to initialize your local variables, so try to do:
double charges = 0.0;

A: When i try to execute this program, i observed few things
1)Local variable charges is not at all initialized before usinng.
so all local variables must be initialized before you use them.
or else you will get compile time error like "local variable may not have been initialized"
2)if you want to return variable along with the value , you cant return multiple values directly so use map with key as variable name and value as map value.