text:
Q: Problems with nested functions in Python I'm having a simple problem using Python functions.
I'll try to be clear:
I have to write two functions:
The first one, returns a dictionary where the keys are names, associated to lists of 5 random numbers.
{'John': [25, 27, 30, 14, 15], 'Mary': [15, 26, 14, 31, 12], 'Saray': [27, 15, 19, 14, 39]}

This is an example of the output of the first function.
The second function, should return me a dictionary with the same keys, and the average of the five numbers of the lists. expected output:
{'John': [21.8], 'Mary': [19.6], 'Saray': [22.8]}

The problem is that, I don't know how the second function should take as input the results of the first one. I tried with something like that:
def First_Function(a):
    d={}
    [...]
    x=list(d.keys())
    y=list(d.values())
    return d

def Second_Function(a=x,b=y):

But the progrm says that x and y are not defined. What can i do?

A: x and y are valid variables only inside the first function.
Your first function is returning dictionary, pass that into second one.
Example:
def ex2(d):
    x = list(d.keys())
    y = list(d.values())
    # What ever your function does.

result = ex1(a)
ex2(d=result)  # I gave myself a freedom to name parameter d

A: Assuming you have dictionary generated by the first function
 import numpy as np

 def func_(a):
     for key, value in a.items():
        a[key] = [np.mean(a[key])]
     return a

func_(a)
#op
{'John': [22.2], 'Mary': [19.6], 'Saray': [22.8]}

A: If you're writing two separate functions. that is not nesting.
With two separate functions, this would be a valid way to do it:
def first_function(a):
    d={}
    [...]
    return d

def second_function (d: dict):
    result = {}
    for key in d:
        my_list = d[key]
        result[key] = sum(my_list)/len(my_list)
    return result

Output:
>>> second_function({'John': [25, 27, 30, 14, 15], 'Mary': [15, 26, 14, 31, 12], 'Saray': [27, 15, 19, 14, 39]})

{'John': 22.2, 'Mary': 19.6, 'Saray': 22.8}

You may want to modify the code to suit your expected output. However, I couldn't help but notice the average calculated for the "John" key in your question is wrong.
To nest the second function into the first one and have it be executed as a part of the first function, you can use this syntax:
def first_function(a):

    def second_function (d: dict):
        result = {}
        for key in d:
            my_list = d[key]
            result[key] = sum(my_list)/len(my_list)
        return result

    d={}
    [...]
    return second_function(d)


text:
Q: getting php session variable in js file I have a php file with a php if statement that generates a php session variable for a mySQL table name. I need to access this table name is a javascript file demo.js. Any ideas would be great.
PHP Code Snip-it:
$fcyclestartdate = $_POST['CycleStartDate'];
$fcycleenddate = $_POST['CycleEndDate'];
$_SESSION["paycycletable"] = "PCR_".str_replace("-", "", $fcyclestartdate)."_".str_replace("-", "", $fcycleenddate);

js file code Snip-it:
function DatabaseGrid()
{
    this.editableGrid = new EditableGrid("demo", {//Variable table name must go where "demo" is
        enableSort: true,
        // define the number of row visible by page
        pageSize: 50,
        // Once the table is displayed, we update the paginator state
        tableRendered:  function() {  updatePaginator(this); },
        tableLoaded: function() { datagrid.initializeGrid(this); },
        modelChanged: function(rowIndex, columnIndex, oldValue, newValue, row) {
            updateCellValue(this, rowIndex, columnIndex, oldValue, newValue, row);
        }
    });
    this.fetchGrid();
}

A: Save the table name in JS global space.
In your php code:
echo "<script> paycycletable='" . $_SESSION["paycycletable"] . "'</script>";

Now you have this variable anywhere in your JS
this.editableGrid = new EditableGrid(paycycletable, {...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Behavior of static blocks with inheritance I am trying to use static blocks like this:
I have a base class called Base.java
public class Base {

    static public int myVar;

}

And a derived class Derived.java:
public class Derived extends Base {

    static
    {
        Base.myVar = 10;
    }
}

My main function is like this:
public static void main(String[] args)  {
    System.out.println(Derived.myVar);
    System.out.println(Base.myVar);
}

This prints the out put as 0 0 where as I expected 10 0. Can somebody explain this behavior? Also, if I want my derived classes to set the values for a static variable how can I achieve that?

A: Static initializer-blocks aren't run until the class is initialized. See Java Language Specification paragraphs 8.7 (Static initializers) and 12.4.1 (When initialization occurs):

A static initializer declared in a class is executed when the class is
  initialized (§12.4.2). Together with any field initializers for class
  variables (§8.3.2), static initializers may be used to initialize the
  class variables of the class.

Here's a similar example straight out of JLS 12.4.1:
class Super {
  static int taxi = 1729;
}
class Sub extends Super {
  static { System.out.print("Sub "); }
}
class Test {
  public static void main(String[] args) {
    System.out.println(Sub.taxi);
  }
}

This program prints only:

1729

because the class Sub is never initialized; the reference to Sub.taxi
  is a reference to a field actually declared in class Super and does
  not trigger initialization of the class Sub.

A: As I understand. You don't call any Derived properties (myVar belongs to Base, not to Derived). And java is not running static block from Derived. If you add some static field to Derived and access it, then java executes all static blocks.
class Base {

    static public int myVar;

}

class Derived extends Base {

    static public int myVar2;

    static
    {
        Base.myVar = 10;
    }
}

public class Main {
    public static void main( String[] args ) throws Exception {
        System.out.println(Derived.myVar2);
        System.out.println(Base.myVar);
    }
}

From java specification, when class is initialized (and static block got executed):

12.4.1 When Initialization Occurs A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
• T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static  field  declared  by T  is  used and  the  field  is  not  a  constant  variable (§4.12.4).
  • T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

A: There is a single copy of myVar and both parent and child class will share the same.
Untill and unless child class get initilized.

A: When we do
class Base {

    public static int myVar = 0;
    static {
        System.out.println("Base");
    }
}

class Derived extends Base {

    static {
        System.out.println("Derived");
        Base.myVar = 9;

    }
}

public class StaticBlock {

    public static void main(String[] args) {

        System.out.println(Base.myVar);
        System.out.println(Derived.myVar);
    }
}

The Output will be
Base
0
0
That means derived class's static block not executing..!!

A: Here is the link to the Java Specification - section 8.7 talks about static initializers. It gives good details about how they should function and the order in which they get called. http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.7


text:
Q: Find the probability (normal + exponential) Let $X$ be normal with mean $0$ and variance $1/2$, Y exponential with mean $1$. $X$ and $Y$ are independent. Find $\mathbb{P}(Y>X^2)$

*

*$\mathbb{P}(Y>X^2)=\int\limits_{-\infty}^{\infty}\mathbb{P}(Y>X^2|X=x)f_{X}(x)dx= ...=\sqrt{2}/2$

*Second approach. Since $2X^2$ is $\Gamma(1/2,1/2)$, then $2\cdot2X^2$ is $\Gamma(1,1/2)$ which is exponential with mean $2$. Thus $\mathbb{P}(Y>X^2)=P(4Y>4X^2)=P(Y>0.25T)=a\neq\frac{\sqrt{2}}{2}$, where $T$ is exponentially distributed, indepedent of $Y$.
The question is: where am I wrong? I suspect the second approach is wrong, but why?

A: More generally: given $X$~$N(\mu,\sigma^2)$ and $Y$~Exponential(1), with $X$ and $Y$ independent, their joint pdf is $f(x,y)$:

Here is a quick check of the probability you seek, using the mathStatica add-on to Mathematica:

Then, for your given parameter values, the correct solution is:

which is approximately 0.7.

Finally, a quick Monte Carlo check to confirm we haven't made any mistakes ... (the following sets $\mu=0$ and $\sigma = \sqrt\frac12$):
datax = RandomReal[NormalDistribution[0, Sqrt[1/2]], 100000];
datay = RandomReal[ExponentialDistribution[1], 100000];
Count[datay - datax^2, x_ /; x > 0] /100000.

0.70418

:)

OP wrote:  - Second approach. "Since $2X^2$ is $\Gamma(1/2,1/2)$ ..."
Correctly: Since $\sqrt{2}X$ ~ $N(0,1)$, and the square of a standard Normal is Chisquared(1), it follows that: $2X^2$ ~ Chisquared(1) ... which is: Gamma$(\frac12,2)$ ... not Gamma$(\frac12,\frac12)$.


text:
Q: Two foreign keys for 1 column? I am trying to design a database , but I have difficulties in setupping the foreign keys. I use InnoDB and phpMyAdmin.
I have 3 tables:
1) orders
- order_id
- order_details
- files_id

2) contacts
- contact_id
- contact_details
- files_id

3) files
- filе_id (not primary key, just index)
- filename

The idea is the following: a contact and an order can have 0 or more files attached to them. I am trying to setup the foreign keys so when I delete a contact or an order, it automatically deletes all the files referenced (CASCADE on DELETE).
As you might see I need to attach files.file_id with 2 foreign keys - contacts.files_id, orders.files_id. I don't see how to do that or if it is even possible. Any ideas?

A: You can do this instead:
1) orders

*

*order_id

*order_details

2) contacts

*

*contact_id

*contact_details

3)orders_Files

*

*order_id

*file_id

4) contacts_Files

*

*Contact_id(FK),

*file_id

5) files

*

*filе_id (primary key,)

*filename

A: An alternative to @MahmoudGamal's answer is to consider orders and contacts to be more specific types of a generic object:
CREATE TABLE object (
  object_id       SERIAL
);

CREATE TABLE orders (
  order_id        SERIAL,
  order_details   TEXT,
  object_id       BIGINT UNSIGNED NOT NULL,
  UNIQUE (object_id),
  FOREIGN KEY (object_id) REFERENCES object (object_id) ON DELETE CASCADE
);

CREATE TABLE contacts (
  contact_id      SERIAL
  contact_details TEXT,
  object_id       BIGINT UNSIGNED NOT NULL,
  UNIQUE (object_id),
  FOREIGN KEY (object_id) REFERENCES object (object_id) ON DELETE CASCADE
);

Then files are associated with those objects:
CREATE TABLE files (
  file_id         SERIAL,
  filename        TEXT
  object_id       BIGINT UNSIGNED NOT NULL,
  FOREIGN KEY (object_id) REFERENCES object (object_id) ON DELETE CASCADE
);

Now, when you delete an object, the relevant order or contact together with all associated files will all be deleted.

A: Those tables will not allow having multiple files per order or contact.
You will need two additional mapping tables for order_id+files_id and contact_id+files_id,
and you should make files.file_id and primary key.


text:
Q: Parse JSON to CSV Twitter Data KeyError: 'user' I am trying to parse some tweets data I collected in a JSON file right now. The problem is some of the tweets don't have 'user' or 'place' in them. As a result, I get messages like:
  File "<stdin>", line 18, in <module>
  KeyError: 'user'

So I tried to add an if-else statement, but it is still giving me the error message. What is the next step?
for line in lines:
    try:
            tweet = json.loads(line)

            # Ignore retweets!
            if tweet.has_key("retweeted_status") or not tweet.has_key("text"):
                    continue

            # Fetch text from tweet
            text = tweet["text"].lower()

            # Ignore 'manual' retweets, i.e. messages starting with RT
            if text.find("rt ") > -1:
                    continue

            tweets_text.append( text )
            # I added an if-else statement, but it's still having be the error message
            if tweet['user']:
                    tweets_location.append( tweet['user']['location'] )
            else:
                    tweets_location.append("")

    except ValueError:
            pass

A: Use dict.get.
        if tweet.get('user'):
                tweets_location.append(tweet['user'].get('location', ''))
        else:
                tweets_location.append("")

See Why dict.get(key) instead of dict[key]?

A: You are getting a KeyError. If you want to check whether the key is in the dictionary, do:
if 'user' in tweet:
    tweets_location.append( tweet['user']['location'] )

Or you could embed it in a try..except:
try:
    tweets_location.append( tweet['user']['location'] )
except KeyError:
    tweets_location.append('')

Alternatively, you may use the get method of dict, as suggested by XrXrXr. The get method gives you a convenient way of providing a default value, i.e., so you can do it all in one line:
tweets_location.append( tweet.get('user', '').get('location', '') )

This defaults to the empty string if 'user' is not a key in tweet, and also to the empty string if the 'location' is not a key of tweet['user']

A: By doing tweet['user'] in the if statement you are assuming the key user exist, which raises the KeyError. You can test if the key is in the dict by doing if 'user' in tweet. Alternatively, you can handle the KeyError similar to how to handle ValueError
try:
    ....
    try:
        tweets_location.append( tweet['user']['location'] )
    except KeyError:
        tweets_location.append("")
except ValueError:
        pass


text:
Q: Cleaning up a varied list that contains strings and tuples with unicode I have a list that is taken from  id3. tags from an .mp3. When i print the list, its a mixture of strings and tuples with unicode.
I get the following from  a straight print out of the list.
[('album', [u'Singles']), ('artist', [u'Led Zeppelin']), ('title', [u'Kashmir'])]

I want to have this:
album  Singles, artist Led Zeppelin, title Kashmir
I have tried to use the following:
nvar = filter(lambda x: x!="[u'" and x!="(" and x!=")" and x!="]", var)

which prints:
[('album', [u'Singles']), ('artist', [u'Led Zeppelin']), ('title', [u'Kashmir'])]

I can use:
>>> nvar = filter(lambda x: x!="[" and x!="'" and x!="(" and x!=")" and x!="]", str(var))
>>> nvar
'album, uSingles, artist, uLed Zeppelin, title, uKashmir'

but I am left with the u from unicode. If I use x!="u", then any word with a u in it will wrong after that function runs.
Also this seems to be the hard way to do things.
Any ideas? Thanks in advance.

A: Assuming that tags is indeed a Python list containing 2-tuples of (str, list), then:
tags = [('album', [u'Singles']), ('artist', [u'Led Zeppelin']), ('title', [u'Kashmir'])]
print ', '.join('{} {}'.format(el[0], el[1][0]) for el in tags)
# album Singles, artist Led Zeppelin, title Kashmir

A: Something like below should work. Since the 'u' is between the '(' and "'" it will not affect the 'real' data.
    def Plain(self, U_String) :
          P_String = str(U_String)
          m=re.search("^\(\u?\'(.*)\'\,\)$", P_String)
          if (m) :  #Typical unicode
             P_String = m.group(1).decode("utf8")
          return P_String


text:
Q: EF6: How create a predicate which checks if a property is contained in the property of a list of objects I have the following case:
I have a function which I have to call:
class WorkobjectRepository...
public async Task<IList<WorkobjectView>> FindAllMatchingAsync(Expression<Func<WorkobjectView, bool>> whereExpression)
{
    return await this.WorkobjectContext.WorkobjectViews.AsNoTracking().Where(whereExpression).ToListAsync();
}

The Class WorkobjectView has among other properties the following two properties:
1. StatusDetailedDisplayName
2. AssignedSubteamId

Now I want all WorkobjectViews where StatusDetailedDisplayName == StatusDetailedDisplay.activeOpen and AssignedSubteamId is contained in a list of objects UserAccountSubteam where UserAccountSubteam has the property Id.
The following code works successfully for me:
// List<UserAccountSubteam> caredTeams, which is given
String[] teams = new string[caredTeams.Count];
for (int i = 0; i < caredTeams.Count; i++)
{
    teams[i] = caredTeams[i].Id;
}
return await this.WorkobjectRepository.FindAllMatchingAsync(w => w.StatusDetailedDisplayName == StatusDetailedDisplay.activeOpen && teams.Contains(w.AssignedSubteamId));

Now, I wanted to optimize the code using LINQ or using collection functions.
Option 1: The first one was using LINQ and Exists method:
var results =  await this.WorkobjectRepository.FindAllMatchingAsync(w => w.StatusDetailedDisplayName == StatusDetailedDisplay.activeOpen && caredTeams.Exists(team => team.Id == w.AssignedSubteamId));

But this failed and I received the following error message:
LINQ to Entities does not recognize the method 'Boolean Exists(System.Predicate`1[Backend.DomainLayer.UserAccountSubteam])' method, and this method cannot be translated into a store expression.

Option 2: Then, I tried to use Any:
var results =  await this.WorkobjectRepository.FindAllMatchingAsync(w => w.StatusDetailedDisplayName == StatusDetailedDisplay.activeOpen && caredTeams.Any(team => team.Id == w.AssignedSubteamId));

which failed, too:
Unable to create a constant value of type 'Backend.DomainLayer.UserAccountSubteam'. Only primitive types or enumeration types are supported in this context.

Option 3: Last, but not least I tried the following which failed too:
var results =  await this.WorkobjectRepository.FindAllMatchingAsync(w => w.StatusDetailedDisplayName == StatusDetailedDisplay.activeOpen && caredTeams.Select(c => c.Id).Contains(w.AssignedSubteamId));

Error message:
Unable to create a constant value of type 'Backend.DomainLayer.UserAccountSubteam'. Only primitive types or enumeration types are supported in this context.

How is the correct way to achieve this? And please note that I am not able to change the basic function FindAllMatchingAsync.

A: First option with Contains is correct way but can be simplified.
var teams = caredTeams.Select(t => t.Id);

return await this.WorkobjectRepository
   .FindAllMatchingAsync(w => w.StatusDetailedDisplayName == StatusDetailedDisplay.activeOpen
      && teams.Contains(w.AssignedSubteamId));


text:
Q: Why orientation on $S^1$ is the one that counter-clockwise-pointing vectors are positive. I am totally disoriented by orientation..
So in the text, it says

The closed unit vall $B^2$ in $\mathbb{R}^2$ inherits the standard orientation from $\mathbb{R}^2$. The induced orientation on $S^1$ is the one for which the counter-clockwise-pointing vectors are positive.

So according to my understanding, $S^1$ is oriented by $\{n_x, v_1\}$, where $n_x$ is the outward unit normal, and $v_1$ is a basis vector for $S^1$. Is this right? What is $v_1$? just $(1)$ as the standard basis?
Then, how can I get the conclusion that the orientation on $S^1$ is the one for which the counter-clockwise-pointing vectors are positive? We suppose to exam whether the determinant of linear transformation between standard basis $\{(1,0),(0,1)\}$ and $\{n_x, v_1\}$ is positive right? But how can I compute it, since I don't really understand the numerical representation of $\{n_x, v_1\}$ - therefore I can't carry out the computation.
Very much confused, sorry if the statement does not make much sense...
According to Guillemin and Pollack's Differential Topology
Definition: Orientation of $V$, a finite-dimensional real vector space: Let $\beta, \beta^\prime$ be ordered basis of $V$, then there is a unique linear isomorphism $A: V \to V$ such that $\beta = A \beta^\prime$. The sign given an ordered basis $\beta$ is called its orientation.
Definition: Orientation of $X$, a manifold with boundary: A smooth choice of orientations for all the tangent space $T_x(X).$

A: It should help to write the general element of $S^1$ as $x = (\cos\theta, \sin\theta)$, and view this as a unit normal $n_x$ at $x$. The counterclockwise tangent vector at $x$ (a unit basis for the tangent line $T_x S^1$) is $v_1 = (-\sin\theta, \cos\theta)$....

A: @AndrewD.Hwang answered my question. To confirm my understanding is correct, here's the complete solution following Andy's answer.
To write the general element of $S^1$ as $x = (\cos\theta, \sin\theta)$, and view this as a unit normal $n_x$ at $x$. The counterclockwise tangent vector at $x$ (a unit basis for the tangent line $T_x S^1$) is $v_1 = (-\sin\theta, \cos\theta)$, hence we want to verify that the determinant of linear transformation between $\{(1,0),(0,1)\}$ and $\{(\cos \theta, \sin \theta), (-\sin \theta, \cos \theta)\}$ is positive.
Remember the basis is ordered, to solve
$$A\begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} \cos \theta \\ \sin \theta \end{pmatrix}$$
We obtain
$$A = \begin{pmatrix} \cos \theta & * \\ \sin \theta & *  \end{pmatrix},$$
* means anything, which we will be determined by second condition that
$$A\begin{pmatrix} 0 \\ 1 \end{pmatrix} = \begin{pmatrix} - \sin \theta \\ \cos \theta \end{pmatrix}.$$
We obtain
$$A = \begin{pmatrix} \cos \theta & -\sin \theta \\ \sin \theta & \cos \theta  \end{pmatrix}.$$
Clearly, $\det A = 1$.


text:
Q: Using reflection to retrieve a value from a list I have a simple method which retrieves a table from an azure mobile service.
public static async List<T>GetDataFromListTable<T>()
{
    var data = await MobileService.GetTable<T>().ToListAsync();
    return data.Count != 0 ? data : null;
}

This works fine.
What I am trying to do is have another method that takes a parameter name which is returned from the service and return the value of that parameter. So far I have this
public static async Task<T> GetDataFromTable<T>(string paramName)
    {
        var k = Activator.CreateInstance(typeof(T));
        var members = typeof(T).GetProperties().Select(t=>t.Name).ToList();
        if (!members.Contains(paramName))
            return (T)k;
        var mn = typeof(T).GetProperties()[members.IndexOf(paramName)];
        var data = GetDataFromListTable<T>();
        var retval = data.Select(t => t.mn);
    }

The issue is obviously that I can't do the Linq query as T doesn't contain mn. I can also not use
var retval = data.Select(t=>t.paramName);

as paramname is a just a string representation of a member within a class.
In a nutshell...
method 1 has the parameter name, grabs a list from method 2. From the returned list in method 2, find the parameter name and return the associated value.
Is there a way to do what I'm trying to do?

A: You can do:
var retval = data.Select(t => mn.GetGetMethod().Invoke(t, null));

or
var retval = data.Select(t => mn.GetValue(t, null));

You can also simplify your code with something like this (not tested, sorry):
public static async Task<T> GetDataFromTable<T>(string paramName)
{
    var k = Activator.CreateInstance(typeof(T));
    var mn = typeof(T).GetProperty(paramName);

    if (mn == null)
        return (T)k;

    var data = GetDataFromListTable<T>();
    var retval = data.Select(t => mn.GetGetMethod().Invoke(t, null));

    ...
}

A: I think using expression trees would be more convenient since you're working with collections. Your method signature needs to incorporate the types T and TResult since it is using Select which returns an IEnumerable<TResult>.
public static async Task<IEnumerable<TResult>> SelectData<T, TResult>(
    string propertyName
)
{
    if(string.IsNullOrWhiteSpace(propertyName))
    {
        return Enumerable.Empty<TResult>();
    }

    var dataTask = GetTableData<T>();

    var tType = Expression.Parameter(typeof(T), "t");
    var property = Expression.Property(tType, propertyName);
    var selectExpression =
        Expression.Lambda<Func<T, TResult>>(property, tType)
                  .Compile();
    return (await dataTask).Select(selectExpression);
}

A: Isn't it possible to do this
 var retval =  data.Select(t => mn.GetValue(t, null));


text:
Q: grails run-app on localhost:8080 instead of :8080/appName? Is there a way to get grails run-app to launch on localhost:8080/ instead of localhost:8080/${appName}?
In Config.groovy,, setting grails.serverUrl has absolutely no effect - it only seems to affect absolute url generation of different grails methods.
In production, I use apache virtualhosts to mask site.com:8080/appName as site.com. I want to make my test configuration match production.

A: If you are running Grails 3.1.1 you can add the following line to your
grails-app/conf/application.yml file to bring back the http://localhost:8080/appName functionality:
server:
    'contextPath': '/appName'

Replace appName with your application's actual name (i.e. the folder name that the grails-app folder is in).

A: How about
grails.app.context = "/"

in Config.groovy, as per this jira discussion?

A: With recent versions of Grails this can also be set in application.properties:
app.context=/


text:
Q: How can I find the font "Proxima N W15 Reg" I have seen a font that I really like on the sendgrid.com site. The font is:
"Proxima N W15 Reg"
Here's a link to a page that uses it:
An example page using the font
But I cannot find out anything about this font with google. Does anyone have any ideas where I could search for this font?

A: They are available on MyFonts, TypeKit, Fonts.com and a myriad of other websites, as a quick search will show.
Slightly more edgy, they are downloaded along the webpage you're directing to, as woff files, as the Web Inspector of your web browser will show you.


text:
Q: Why this MySQL Query Not working? I have wrote MySQL query to check any rows between given start and finish time, but it doesn't work, please someone help me to find this error?
query:
SELECT *
FROM users
WHERE user_id='".$input['guard']."'
AND (start_time >= '".$startDateTime."' OR finish_time <= ".$finishDateTime."'

error:
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3 (SQL: SELECT * FROM users WHERE user_id='13' AND (start_time >= '2014-10-20 10:30:00' OR finish_time <= '2014-10-20 21:30:00' )

A:   $guard=$input['guard'];
  $sql="SELECT *FROM users WHERE user_id='$guard' AND (start_time >='$startDateTime' OR finish_time <='$finishDateTime')";


text:
Q: jQuery DatePicker how to disable auto day selection while browsing calendar? In jQuery DatePicker there is one annoying thing, if you using it as a calendar and depend on selected date. While navigating from month to month it keep selected day activated for all months. I know that this issue exist for more than 6 months and I have reported it to jQuery Team.However I would like to know is there any workarounds or how to disable this behaviour?
Calendar example can be found here

A: here's a workaround I figured out.
$(function() {

    $("#datepicker").datepicker({
        onChangeMonthYear: function(year, month, inst) {
            var bMonth = (new Date(this.value)).getMonth() != month - 1;
            var bYear = (new Date(this.value)).getFullYear() != year;
            if (bMonth || bYear) {
            setTimeout(function() {
                $('.ui-state-active').removeClass('ui-state-active');
            }, 5);
            }
        }
    });
});

crazy demo

A: Include this script after you've included jQuery UI. You can include it inline, or put it in its own file.
edit: This hack fixes your issue for version 1.8.5 of jQuery UI. I have tested a number of usage cases in FF 3.6.10 and IE 8. It is entirely possible that this hack does not work under all possible circumstances. If I notice any, I'll probably try to fix them, but for now, it is provided as is.
I've thrown together a demo. Shows it's working with jQuery 1.8.4, too. Just to be clear... my solution is not a quick and dirty workaround, it's an actual fix of the bug in the datepicker code. It's so long, because it overwrites an original method (and thus contains the original code in its entirety). The fix itself is a change in just one line. But I've provided the fix as a script that can just be included without having to edit the original code at all, for convenience.
$.extend(
    $.datepicker,
    {
        _generateHTML:
            function(inst) {
                if (!inst.dpuuid)
                {
                    for(attr in window)
                    {
                        if(/^DP_jQuery_/.test(attr))
                        {
                            inst.dpuuid = attr.replace(/^DP_jQuery_([0-9]+)/, '$1');
                        }
                    }
                }
                var dpuuid = inst.dpuuid;
                var today = new Date();
                today = this._daylightSavingAdjust(
                    new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
                var isRTL = this._get(inst, 'isRTL');
                var showButtonPanel = this._get(inst, 'showButtonPanel');
                var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
                var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
                var numMonths = this._getNumberOfMonths(inst);
                var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
                var stepMonths = this._get(inst, 'stepMonths');
                var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
                var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
                    new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
                var minDate = this._getMinMaxDate(inst, 'min');
                var maxDate = this._getMinMaxDate(inst, 'max');
                var drawMonth = inst.drawMonth - showCurrentAtPos;
                var drawYear = inst.drawYear;
                if (drawMonth < 0) {
                    drawMonth += 12;
                    drawYear--;
                }
                if (maxDate) {
                    var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
                        maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
                    maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
                    while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
                        drawMonth--;
                        if (drawMonth < 0) {
                            drawMonth = 11;
                            drawYear--;
                        }
                    }
                }
                inst.drawMonth = drawMonth;
                inst.drawYear = drawYear;
                var prevText = this._get(inst, 'prevText');
                prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
                    this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
                    this._getFormatConfig(inst)));
                var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
                    '' + prevText + '' :
                    (hideIfNoPrevNext ? '' : '' + prevText + ''));
                var nextText = this._get(inst, 'nextText');
                nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
                    this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
                    this._getFormatConfig(inst)));
                var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
                    '' + nextText + '' :
                    (hideIfNoPrevNext ? '' : '' + nextText + ''));
                var currentText = this._get(inst, 'currentText');
                var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
                currentText = (!navigationAsDateFormat ? currentText :
                    this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
                var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
                    '.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
                var buttonPanel = (showButtonPanel) ? '
' + (isRTL ? controls : '') +
                    (this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
                    '.datepicker._gotoToday(\'#' + inst.id + '\');"' +
                    '>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '
' : '';
                var firstDay = parseInt(this._get(inst, 'firstDay'),10);
                firstDay = (isNaN(firstDay) ? 0 : firstDay);
                var showWeek = this._get(inst, 'showWeek');
                var dayNames = this._get(inst, 'dayNames');
                var dayNamesShort = this._get(inst, 'dayNamesShort');
                var dayNamesMin = this._get(inst, 'dayNamesMin');
                var monthNames = this._get(inst, 'monthNames');
                var monthNamesShort = this._get(inst, 'monthNamesShort');
                var beforeShowDay = this._get(inst, 'beforeShowDay');
                var showOtherMonths = this._get(inst, 'showOtherMonths');
                var selectOtherMonths = this._get(inst, 'selectOtherMonths');
                var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
                var defaultDate = this._getDefaultDate(inst);
                var html = '';
                for (var row = 0; row < numMonths[0]; row++) {
                    var group = '';
                    for (var col = 0; col < numMonths[1]; col++) {
                        var selectedDate = this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.selectedDay));
                        var cornerClass = ' ui-corner-all';
                        var calender = '';
                        if (isMultiMonth) {
                            calender += '
 1)
                                switch (col) {
                                    case 0: calender += ' ui-datepicker-group-first';
                                        cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
                                    case numMonths[1]-1: calender += ' ui-datepicker-group-last';
                                        cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
                                    default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break;
                                }
                            calender += '">';
                        }
                        calender += '
' +
                            (/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
                            (/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
                            this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
                            row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
                            '

' +
                            '
';
                        var thead = (showWeek ? '' + this._get(inst, 'weekHeader') + '	' : '');
                        for (var dow = 0; dow < 7; dow++) { // days of the week
                            var day = (dow + firstDay) % 7;
                            thead += '= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
                                '' + dayNamesMin[day] + '	';
                        }
                        calender += thead + '

';
                        var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
                        if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
                            inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
                        var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
                        var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
                        var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
                        for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
                            calender += '
';
                            var tbody = (!showWeek ? '' : '' +
                                this._get(inst, 'calculateWeek')(printDate) + '	');
                            for (var dow = 0; dow < 7; dow++) { // create date picker days
                                var daySettings = (beforeShowDay ?
                                    beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
                                var otherMonth = (printDate.getMonth() != drawMonth);
                                var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
                                    (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
                                tbody += '= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
                                    (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
                                    ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
                                    (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
                                    // or defaultDate is current printedDate and defaultDate is selectedDate
                                    ' ' + this._dayOverClass : '') + // highlight selected day
                                    (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
                                    (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
                                    (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day
                                    (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
                                    ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
                                    (unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' +
                                    inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions
                                    (otherMonth && !showOtherMonths ? ' ' : // display for other months
                                    (unselectable ? '' + printDate.getDate() + '' : '' + printDate.getDate() + '')) + '	'; // display selectable date
                                printDate.setDate(printDate.getDate() + 1);
                                printDate = this._daylightSavingAdjust(printDate);
                            }
                            calender += tbody + '
';
                        }
                        drawMonth++;
                        if (drawMonth > 11) {
                            drawMonth = 0;
                            drawYear++;
                        }
                        calender += '

' + (isMultiMonth ? '
' +
                                    ((numMonths[0] > 0 && col == numMonths[1]-1) ? '

' : '') : '');
                        group += calender;
                    }
                    html += group;
                }
                html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
                    '' : '');
                inst._keyEvent = false;
                return html;
            }
    }
);

A: Here's the ticket:
http://dev.jqueryui.com/ticket/5984
It includes the fix and a workaround for the compressed version.
I think you can modify your copy of jQuery UI safely. The issue is already solved so it should show up in next stable release.


text:
Q: How can i select from 2 tables some relationed fields in django? Im new in python-django and i really need some help. This is my first question here. I´ve searched a lot on similar questions here but didnt find my needs. I am working on a restaurant website, developing in python and django and im facing very difficulties to make the restaurant menu. This data of the menu stays in a mysql db.
I searched for select_related and prefetch related a lot, i imagine one of these will help, but its not working.
So, i have 2 tables, category_menu and menu. I have to list all categories and all the items of these categories.
I have 2 models, category_menu and menu:
class category_menu(models.Model):
    name_category = models.CharField(max_length=50, null=False)

    class Meta:
    default_related_name = 'categories'

    def __str__(self):
    return self.name_category

    def get_absolute_url(self):
    return reverse('category_menu_edit', kwargs={'pk': self.pk})

class menu(models.Model):
    item = models.CharField(max_length=50, null=False)
    description = models.CharField(max_length=300, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.ForeignKey(category_menu,related_name='categories', null=True, on_delete=models.CASCADE)

class Meta:
    default_related_name = 'menus'

def __str__(self):
    return self.item

def get_absolute_url(self):
    return reverse('menu_edit', kwargs={'pk': self.pk})

Im my views, i have the following:
query = category_menu.objects.prefetch_related('categories').all().distinct
datamenu = {'object_list': query}

return render(request, template_name, datamenu)

In my html, just the categories are listing, but the relationed items of the menu are not.
Could you help me?

A: I am not focusing on the answer here, but it may be a step to solution at least.
on menu model, could you please change the field:
category = models.ForeignKey(category_menu, related_name='categories', null=True,
to this one:
category = models.ForeignKey(category_menu, related_name='menus', null=True)

A: You have used "categories" in both category.Meta.default_related_name and in menu.category.related_name. That could be causing some problems.
Try removing related_name='categories' from menu.category so that it looks like this:
category = models.ForeignKey(category_menu, null=True, on_delete=models.CASCADE)

Fix the indentation of your menu model. Meta, __str__() and get_absolute_url() should all be indented the same as they are on the category_menu model, e.g.:
class menu(models.Model):
    item = models.CharField(max_length=50, null=False)
    description = models.CharField(max_length=300, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    category = models.ForeignKey(category_menu, null=True, on_delete=models.CASCADE)

    # These have been indented
    class Meta:
        default_related_name = 'menus'

    def __str__(self):
        return self.item

    def get_absolute_url(self):
        return reverse('menu_edit', kwargs={'pk': self.pk})

Migrate the database, then attempt getting your queryset without prefetch:
query = category_menu.objects.all()

In your template, you can use nested for tags to list the categories and menu items within each category. Something like this:
{% for category in object_list %}

{{ category }} ({{ category.menus.count }})

{% for item in category.menus.all %}

{{ item }}

{{ item.description }}

${{ item.price }}

{% endfor %}
{% endfor %}

If it works, try prefetching using the default_related_name on your menu model:
query = category_menu.objects.prefetch_related('menus').all()


text:
Q: DT bug : Retain previous selected rows when data changes In shiny, DT retains the previous selected rows when data source changes. In the code below, when you select rows from the table and then change drop down value, it still returns index of previous selected rows (from previous drop down value). This seems to be a bug in DT library. I am clueless in fixing it. I want to store all the selected rows and then show sum in the valueboxoutput based on the selected rows. Is also there an option to keep rows selected as it is in blue?
library(shiny)
library(shinydashboard)
library(DT)
library(dplyr)

# FETCH DATA
mydata = mtcars
mydata$id = 1:nrow(mydata)

#Dashboard header carrying the title of the dashboard
header <- dashboardHeader(title = "My Dashboard")

######################
# Dashboard Sidebar
######################

sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
    selectInput(
      "hyp",
      "Select:",
      list(
        'All','drat','wt'
      ) ,
      selected =  "All", selectize = TRUE)
  )
)

# Dashboard Body

frow1 <- fluidRow(
  valueBoxOutput("value1")
)

frow2 <- fluidRow(
  box(DT::dataTableOutput("mytable"), width = 12)
)

# combine the two fluid rows to make the body
body <- dashboardBody(frow1, frow2)

####################
# Dashboard Page
###################
ui <- dashboardPage(title = 'Model', header, sidebar, body, skin='purple')

####################
# SERVER
###################

d = data.frame(stringsAsFactors = F)
server <- function(input, output, session) {
  dd = reactiveValues(select = NULL, select2 = NULL)

  # Render Table
  output$mytable = DT::renderDataTable({
    DT::datatable(test(), rownames= FALSE, extensions = c('FixedHeader'),
                  filter = 'top',
                  selection=list(mode = 'multiple'),
                  options = list( autoWidth = TRUE,
                                  scrollX = TRUE,
                                  orderClasses = TRUE,
                                  pageLength = 50,
                                  fixedHeader = TRUE,
                                  dom = 'Bfrtip'
                  ),escape=F)
  }
  )

  proxy = DT::dataTableProxy('mytable')

  test <- reactive({
    if(input$hyp == 'All') {
      result = mydata
    } else {
      result = mydata %>% dplyr::filter(UQ(as.name(input$hyp)) <= 3)
    }
    return(result)
  })

  mt = reactiveValues(ndt = NULL)

  observe({
    if (length(input$mytable_rows_selected) >0) {
    mt$ndt<- test()[input$mytable_rows_selected,]
    }
  })

  observeEvent(input$hyp, {freezeReactiveValue(input, "mytable_rows_selected")})

  proxy = DT::dataTableProxy('mytable')
  observe({print(input$mytable_rows_selected)})
  observe({print(mt$ndt)})

  #creating the valueBoxOutput content
  output$value1 <- renderValueBox({
    c_a = sum(mydata[mt$ndt[["id"]],"mpg"], na.rm = T)
    valueBox(
      formatC(c_a, format="d", big.mark=',')
      ,'Total MPG'
      ,icon = icon("th",lib='glyphicon')
      ,color = "purple")
  })
}

runApp(list(ui = ui, server = server), launch.browser = TRUE)

Update
I managed to fix it partially. Issues I am facing now - When I unselect row, it does not change the sum calculation. Also I want all the selected rows remain highlighted.
  mt = reactiveValues(ndt = NULL)
  ft = reactiveValues(pa = NULL)

  observeEvent(input$mytable_rows_selected, {
    mu = data.frame(n = input$mytable_rows_selected, stringsAsFactors = F)
    mt$ndt<- test()[as.numeric(mu$n),]
    ft$pa = rbind(ft$pa, mt$ndt)
    ft$pa <- distinct(ft$pa, .keep_all = TRUE)
  }
  )

  #creating the valueBoxOutput content
  output$value1 <- renderValueBox({
    c_a = sum(ft$pa[,"mpg"], na.rm = T)
    valueBox(
      formatC(c_a, format="d", big.mark=',')
      ,'Total MPG'
      ,icon = icon("th",lib='glyphicon')
      ,color = "purple")
  })
}

A: Overall you need to clear ft$pa if no rows is selected now, for this your observer need to react for NULL values in input$mytable_rows_selected (this argument ignoreNULL = FALSE will help). I do simple changes to your observeEvent
observeEvent(input$mytable_rows_selected, ignoreNULL = FALSE, {
    mu = data.frame(n = input$mytable_rows_selected, stringsAsFactors = F)
    mt$ndt<- test()[as.numeric(mu$n),]
    ft$pa = rbind(ft$pa, mt$ndt)
    ft$pa <- distinct(ft$pa, .keep_all = TRUE)

    #clear reactive dataframe
    if (is.null(input$mytable_rows_selected))
      ft$pa <- ft$pa[-1,]
  })


text:
Q: rich:inplaceinput text color issue i have a problem with rich:inplaceInput
when i focus on a cell and unfocus the text of the inPlaceInput component turns gray
How to do to keep the text Black ?
please Help Me
Thank you

A: From what you write, i think that you using the blueSky skin and you are talking about the default text that is shown in the box in case it is not changed.
There is a css class (rf-ii-dflt-lb) for the default text that in blueSky it shows text in gray. You need to override this class in your page like
.rf-ii-dflt-lbl {
    color: black;
}

You can also check all css classes available for inplaceInput here


text:
Q: Javascript images error in wordpress After moving to Wordpress the images of weather cannot be retrieved even though the JavaScript code runs fine. Here is the code that I am using to retrieve images in custom.js. The code:
$('#weather').openWeather({
    city: 'New York, US',
    placeTarget: '.weather-place',
    iconTarget: '.weather-icon',
    customIcons: 'files/img/icons/weather/'
});

There is something wrong with
'files/img/icons/weather/'

Well firstly when using html the javascript was in files/js/custom.js and the images were in files/img/weather/ it worked but now with wordpress it does'nt work
Your help would be appreciated.
The files folder is in the root directory.

A: If your files directory branches off the root, then try adding a slash before the word "files", like so: customIcons: '/files/img/icons/weather/'
Else, you may need to provide the entire path http://www.mydomain.com/files/...
ALSO, you're not providing a file name /files/img/icons/weather/icon.jpg

A: If you moved to wordpress, the paths might have changed. Where do you keep your javscript library?
I would use the debug console from your browser to see what happens and which icons your script is trying to get and then modify the path. (press F12 and click on the "network" tab, reload the page and check for 404 errors)


text:
Q: Pipe data from Writable to Readable I am working on getting files from an SFTP server and piping the data to Box.com using their sdk. The Box sdk takes a readable stream as as parameter for uploading a file. The code that I have written to fetch the files from the sftp server uses the npm module ssh2-sftp-client.
The issue I am having is that a writable stream is "the end of the line" with streams unless you are using something like a Transform which is a Duplex and implements both read and write. Below is the code that I am using. Because I am working on this for a client I am intentionally leaving out some stuff that is not necessary.
Below is the method on the sftp class
async getFile(filepath: string): Promise<Readable> {
  logger.info(`Fetching file: ${filepath}`);
  const writable = new Writable();
  const stream = new PassThrough();
  await this.client.get(filepath, writable);
  return writable.pipe(stream);
}

The implementation of getting a file and attempting to pipe to box which is an instance of an authorized BoxSDK client.
try {
  for (const filename of filenames) {
    const stream: Readable = await tmsClient.getFile(
      'redacted' + filename,
    );

    logger.info(`Piping ${filename} to Box...`);
    await box.createFile(filename, 'redacted', stream);
    logger.info(`${filename} successfully downloaded`);
  }
} catch (error) {
  logger.error(`Failed to move files: ${error}`);
}

I am not super well versed in streams but based on my research I think this should work in theory.
I have also tried this implementation where the ssh client returns a buffer and then I try and pipe that buffer as a readable stream. With this implementation though I keep getting errors from the Box sdk that the stream ended unexpectedly.
async getFile(filepath: string): Promise<Readable> {
  logger.info(`Fetching file: ${filepath}`);
  const stream = new Readable();
  const buffer = (await this.client.get(filepath)) as Buffer;
  stream._read = (): void => {
    stream.push(buffer);
    stream.push(null);
  };
  return stream;
}

And the error message: 2020-02-06 15:24:57 error: Failed to move files: Error: Unexpected API Response [400 Bad Request] bad_request - Stream ended unexpectedly.
Any insight is greatly appreciated!

A: So after doing some more research into this it turns out that the issue is actually with the Box sdk for Node. The sdk is terminating the body of the stream before it is actually done. This is because under the hood they are using the request library which requires a content-length header to send large payloads. Without that in place it will continue to terminate the stream before the payload is sent.
On the Box community forum they suggest adding properties to the stream prototype to pass stuff to the underlying request library. I STRONGLY disagree with this because it is not the correct way to go about it. The Box sdk needs to provide a way to pass in the length of the content in Bytes. As the user of their API I should not have to manipulate their underlying dependencies. I am going to open an issue with their sdk and hopefully get this fixed.
Hope this is useful to someone else!


text:
Q: jQuery draggable leaving cloned html behind I am using jQuery UI; Draggable http://jqueryui.com/demos/draggable invoked like this:
$(document).ready(function(){

    $("#side_bar").sortable({
        revert: true
    });

    $(".draggable").draggable({
                              containment: 'parent',
                              hascroll: true,
                              handle: 'div.box_header',
                              scrollSensitivity: 100,
                              scrollSpeed: 100,
                              axis: 'y',
                              connectToSortable: '#side_bar',
                              helper: 'clone',
                              opacity: 0.35
                              }); });

You can see the html structure on http://www.sarsclan.co.uk (right side bar area).
It seems to create a transparant clone as your dragging, but when you drop it puts the draggable div in the right place, but leaves the original div in it's place and just appends the dom with a clone of that original div in its new place.

A: The demos on jqueryui Sortable show no extra draggable call, as far as I can see: http://jqueryui.com/demos/sortable/. Have you tried to do with a sortable call only?
EDIT: I can see that your code is similar to the "Draggable + Sortable" example on the jqueryui site. However, that example always clones the element at the top and inserts the clone into the sortable list, so that's not what you want to achieve.

A: Do you really mean to have " helper: ' clone' " ? What happens if you remove it?


text:
Q: How to extract the elements of a deep nested tuple and put them in a list in python? I've been playing with Python, and wrote the following code that finds all prime numbers in a given range as following:
def get_primes(x):
    primes = []

    def is_prime(x):
        if x == 0:
            return
        else:
            for i in range(2, int(x)):
                if (x % i) == 0:
                    return is_prime(x - 1)
            else:
                return x, is_prime(x - 1)

    primes.append(is_prime(x))
    return primes

print(get_primes(int(input("Enter the range: 0 - "))))

And the output is: (enter 100 for example)
Enter the range: 0 - 100
[(97, (89, (83, (79, (73, (71, (67, (61, (59, (53, (47, (43, (41, (37, (31, (29, (23, (19, (17, (13, (11, (7, (5, (3, (2, (1, None))))))))))))))))))))))))))]

that looks so ugly.
So, I need a way to flatten the recursive tuple structure:
[97, 89, 83, 79, 73, 71, 67, 61, 59, 53, 47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2, 1]

i used the following code to do so:
x = get_primes(100)
arr = []
arr.append(x[0][0])
arr.append(x[0][1][0])
arr.append(x[0][1][1][0])
arr.append(x[0][1][1][1][0])
arr.append(x[0][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
arr.append(x[0][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][1][0])
print(arr)

But of course, this is not a professional method.
So, what i want is to know how can i make this one:
 [97, 89, 83, 79, 73, 71, 67, 61, 59, 53, 47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2, 1]
from this one:
[(97, (89, (83, (79, (73, (71, (67, (61, (59, (53, (47, (43, (41, (37, (31, (29, (23, (19, (17, (13, (11, (7, (5, (3, (2, (1, None))))))))))))))))))))))))))]

I found the answer here How to flatten a tuple in python but the code there was for python 2, so, i modified it a bit.

and used this code:
def flatten(T):
    if type(T) is not tuple:
        return (T,)
    elif len(T) == 0:
        return ()
    else:
        return flatten(T[0]) + flatten(T[1:])

A: You can adapt your function to be a generator pretty easily:
def is_prime(x):
    if x != 0:
        for i in range(2, int(x)):
            if (x % i) == 0:
                yield from is_prime(x - 1)
                return
        else:
            yield x
            yield from is_prime(x - 1)

Then to get all of the primes up to 100 you can pass that generator to list to get a list containing the values from that generator:
print(list(is_prime(100)))
# [97, 89, 83, 79, 73, 71, 67, 61, 59, 53, 47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2, 1]

Recursion isn't a great approach to this though, I would suggest looking up the Sieve of Eratosthenes for a better approach.
The yield from syntax is only available in newer versions of Python (>= 3.3).  You can replace
yield from x

with
for y in x:
    yield y

if necessary.

A: If you create a nested tuple, then the only way to flatten it is by unpacking. Best way to not deal with that is just not creating one.
Here goes an alternative version of your code:
def get_primes(limit):

    def is_prime(x):
        if x in (2, 3):
            return True
        if (x % 2 == 0) or (x % 3 == 0):
            return False
        i, w = 5, 2
        while i**2 <= x:
            if x % i == 0:
                return False
            i += w
            w = 6 - w
        return True

    return [x for x in range(2, limit + 1) if is_prime(x)]

print(get_primes(int(input("Enter the range: 0 - "))))


text:
Q: How to make foundation5 JS work with iron-router in meteor Tried all smart packages of foundation that I could find on atmosphere, but I just can't make foundation javascripts work with iron-router.
Does anyone know how to do make it work ? On first page load but also after routing to a new page.
The problem is that normally you have to call
$(document).ready(function () {
    // Enable FastClick
    if(typeof FastClick !== 'undefined') {
      FastClick.attach(document.body);
    }
    $(document).foundation(function (response) {
        console.log(response.errors);
    });
});

But this can't work with the router

A: I succeeded by adding $(document).foundation() on each Template.'name'.render function.
I  haven't seen any better solution yet.


text:
Q: why does python not return all the test cases at once? why does the last test case could only be displayed after I pressed enter again? THE INPUT:
4
4
1 -2 3 -4
3
0 0 0
5
1 -1 1 -1 1
6
40 -31 -9 0 13 -40

THE OUTPUT when first run the code:
YES
[1, -2, 3, -4]
NO
YES
[1, -1, 1, -1, 1]

THE OUTPUT when pressing enter again:
YES
[40, -31, -9, 0, 13, -40]

THE CODE:
numberOfTestCase = int(input())

for i in range(numberOfTestCase):

    listLength = int(input())
    aList = [int(x) for x in input().split()]
    sumList = 0
    for x in range(listLength):
        sumList = aList[x] + sumList

    if sumList == 0:
        print("NO")
    else:
        print("YES")
        print(aList)

so what does this program do?
This program is intended to calculate whether or not the sum of the list is equal or not equal to zero and return the list if its not equal to zero.
input explanation
first line: indicates how many test cases there is
second line: indicates how many number is in the first list
third line: the first testcase/list
fourth.....n: repeating second and third line for different test cases
my question: why does python not return all the test cases at once? why does the last test case could only be displayed after I pressed enter again?

A: Python is not returning all test cases at once because the if statement that checks the sum and prints "YES" or "NO" is inside the for loop. In each loop iteration, your code does the following:

*

*Take the list length as input

*Take the list values as input

*Sum the list values in sumList

*Check if sumList == 0

*Print "NO" or "YES" and the list

So, if I understood correctly, a way to solve your problem could be to create two for loops which iterate in range(numberOfTestCase). The first takes all the inputs and stores them in listLength and aList. The second checks if the condition is met and prints the outcome.
numberOfTestCase = int(input())

listLength = []
aList = []

for i in range(numberOfTestCase):

    listLength.append(int(input()))
    tmpList = [int(x) for x in input().split()]
    aList.append(tmpList)

for i in range(numberOfTestCase):
  sumList = 0
  for x in range(listLength[i]):
      sumList = aList[i][x] + sumList

  if sumList == 0:
      print("NO")
  else:
      print("YES")
      print(aList)


text:
Q: JS Grid not showing data in table I forced to change my nearly finished project developed on Filemaker to Open Source due to licensing issues. So I have to learn PHP, Javascript and all that stuff while programming. I am struggling now for 2 weeks with this issue. I have a php file with my JS Grid table which is also visible:
My code for the table:
$(document).ready(function() {
$('#contacts_table').jsGrid({

    width: "100%",
    height: "457px",

    pageLoading: false,
    filtering: true,
    inserting: true,
    editing: true,
    sorting: true,
    paging: true,
    autoload: true,
    pageSize: 10,
    pageButtonCount: 2,
    confirmDeleting: true,
    noDataContent: "Not found",

    deleteConfirm: "Do you really want to delete data?",

    controller: {

        loadData: function (filter) {
            return $.ajax({
                type: "GET",
                url: "fetch_contacts_supplier_JS_Grid.php",
                data: filter,
                dataType: "json"
            });
        },
    },

    fields: [
        {name: "Id",        type: "number",     width: 10,  visible: false},
        {name: "SupplierId",type: "number",     width: 10,  visible: false},
        {name: "Title",     type: "text",       width: 10,  validate: "required"},
        {name: "Name",      type: "text",       width: 30,  validate: "required"},
        {name: "Surname",   type: "text",       width: 30,  validate: "required"},
        {name: "Position",  type: "text",       width: 20,  validate: "required"},
        {name: "Phone",     type: "text",       width: 30},
        {name: "Mobile",    type: "text",       width: 30},
        {name: "Fax",       type: "text",       width: 30},
        {name: "Email",     type: "text",       width: 30},
        {name: "Active",    type: "checkbox",   width: 10,  validate: "required"},
        {                   type: "control",    width: 10}
    ]

});
});

My code for the DB select (which works) fetch_contacts_supplier_JS_Grid.php:
 if($method == 'GET') {
    If ($statement = $link->prepare("SELECT * FROM suppliers_contacts WHERE _fk_SuppliersID = 1")) {
        if ($statement->execute()) {
            $result = $statement->get_result(); // fetchAll(PDO::FETCH_ASSOC);
            while($row = $result->fetch_assoc()) {
                $new_array[] = array(
                    'Id' => $row['_pk_SuppliersContactsID'],
                    'SupplierId' => $row['_fk_SuppliersID'],
                    'Title' => $row['Title'],
                    'Name' => $row['Name'],
                    'Surname' => $row['Surname'],
                    'Position' => $row['Job_Position'],
                    'Phone' => $row['PhoneFixed'],
                    'Mobile' => $row['PhoneCell'],
                    'Fax' => $row['PhoneFax'],
                    'Email' => $row['Email'],
                    'Active' => $row['Active']
                );
            }
        }
        header("Content-Type: application/json");
        echo json_encode($new_array);
    } ELSE {
        echo $link->error;
    }
 }

The array I get in the console:

[{"Id":1,"SupplierId":1,"Title":"Mr.","Name":"Jens","Surname":"Dietzel","Position":"Owner","Phone":"145754","Mobile":"86868","Fax":"4368843","Email":"jens@jd-sd.com.na","Active":"checked"},{"Id":2,"SupplierId":1,"Title":"Mrs.","Name":"Karen","Surname":"Mann","Position":"Manager","Phone":"24525","Mobile":"745754","Fax":"544","Email":"karen@test.de","Active":"checked"}]

But the table shows not found. What am I doing wrong?


text:
Q: Using URLFetchService / URL - Google appengine for java I'm using URL Fetch Java API
http://code.google.com/appengine/docs/java/urlfetch/overview.html#Fet...
to get information from graph.facebook.com, however, i keep getting
the error:
java.lang.IllegalArgumentException
        at java.net.URI.create(URI.java:842)
...
Caused by: java.net.URISyntaxException: Illegal character in query at
index 58: https://graph.facebook.com/me?access_token=...
Any idea?

A: The error message pretty much says it all: the URI you are attempting to fetch contains an illegal character at index 58. I also get the exception with your URL:
public static void main(String[] args) throws Exception {

    String s = "https://graph.facebook.com/me?access_token=593172238640599|e2a5e8bb8625b56358fe6219.1-530295086|zt7TYKmSF4e3WLWbF8jc7_P8MK8";

    URI uri = new URI(s);

}

throws:

Exception in thread "main"
  java.net.URISyntaxException: Illegal
  character in query at index 58:
  https://graph.facebook.com/me?access_token=593172238640599|e2a5e8bb8625b56358fe6219.1-530295086|zt7TYKmSF4e3WLWbF8jc7_P8MK8   at
  java.net.URI$Parser.fail(URI.java:2809)
    at
  java.net.URI$Parser.checkChars(URI.java:2982)
    at
  java.net.URI$Parser.parseHierarchical(URI.java:3072)
    at
  java.net.URI$Parser.parse(URI.java:3014)
    at java.net.URI.(URI.java:578)

The character at position 58 is the "|" character. You need to URL encode this character (and its other occurances).


text:
Q: Can only install some R-Packages (Ubuntu 14.04 server) I am trying to install the FastRWeb package for R on this Ubuntu server. I updated sources.list with:
deb http://ftp.heanet.ie/mirrors/cran.r-project.org/bin/linux/ubuntu trusty/

I have tried both:
sudo apt-get install r-cran-FastRWeb

and, from inside R as an administrator:
install.packages(FastRWeb)

Neither work, I get the following output:

Reading packages list... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package r-cran-FastRWeb

However, I have been able to install some packages (eg: RServe installed fine). Help! Please!

A: Following along the instructions at http://cran.r-project.org/bin/linux/ubuntu/README.
I added a the file /etc/apt/sources.list.d/r.list with the following contents:
deb http://cran.cnr.Berkeley.edu/bin/linux/ubuntu trusty/

ran:
gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys E084DAB9
gpg -a --export E084DAB9 | sudo apt-key add -

then:
sudo apt-get update
sudo apt-get install r-base

Finally running R as root (sudo R) I installed FastRWeb with install.packages() by picking it from the list.


text:
Q: Magento 2 : Layered Navigation Filters, tag  and SEO link juice we're using Magento 2.2.1 with custom theme, which inherits Magento's default Layered navigation filters, which contains tag  with filtering attributes, what is not SEO friendly:

is there any solution (module, extension) which can help to solve this problem? or maybe some workaround?

A: You may check about using the PRG Pattern to fix link juice and SEO issues caused by the endless number of unique URLs created by Layered Navigation.
Simply said, it's about replacing the GET request to a layered navigation/filter URL with a POST request (which search engine crawlers do not follow) before redirecting the user to the original layered navigation/filter URL.
This works like a charm, i. e. not changing the UX regarding Layered Navigation and 100% reliable in terms of preventing crawlers from wasting crawl budget on useless duplicate content URLs.
For further details and reading, please see

*

*Detailed explanation incl. sample request flow

*Why robots.txt, rel=nofollow etc. are no satisfying solutions here

*PRG Pattern Magento 2 Extension

*PRG Pattern Demo


text:
Q: Wine and Cyrillic Fonts Run Wine under Linux Mint 17.2. Cyrillic names of programs, menu items names, text files - all are unreadable.
Some exceptions do exist. For example, I can see Cyrillic text in CoDeSys IDE, but all my keyboard input is "????" on a screen. And Cyrillic program names are still weird...
Searched in Russian sites, but all receipts are of such kind: "I've tried so and so and this helped". Some of advice I managed to use but to no avail.
One example. I added files ru and ua in /var/lib/locales/supported.d/ and inserted
uk_UA.CP1251 CP1251
uk_UA.KOI8-R KOI8-R
ru_RU.CP1251 CP1251
ru_RU.KOI8-R KOI8-R
in file local. Then executed locale-gen and rebooted.
Another way is to edit Wine registry. I changed Codepages=1252,437 to 1251,866 - but this change gave no result. More of it, the changes are not remembered - reentering regedit shows old Codepages.
And yes, I've added old Windows XP ttf fonts - it was the very 1-st attempt on the problem.
Now I'm at a loss. Any help appreciated, but most of all - to understand the way Wine handles fonts. If it is possible for a dummy.

A: In some cases (for example if you need to type in Solo app) you might need to:

*

*reconfigure your locales
sudo dpkg-reconfigure locales && sudo update-locale
In locales to be generated choose (using space key) ru_RU.CP1251 CP1251

*Run it using
LC_ALL="ru_RU.CP1251" wine "/home/$USER/.wine/drive_c/Program Files/Solo/Solo.exe"

P.S. install corefonts if you've not done it yet

winetricks corefonts

A: For some applications it's important to have proper ansi codepage set, I know for sure that classic Delphi 5/6/7 applications suffer from this. All you need is to run them with LANG set accordingly. Like this:
LANG=ru_RU.UTF-8 wine program.exe

Of course you need to have this locale present on your system, normally you don't need to reboot after enabling new locale data.


text:
Q: How to make an 'add' function using n-1 and n+1 I have two functions: n = n-1 and n = n+1.
How could I make an add function using these definitions by using recursion, if-then-else, ==?

A: inc :: Int -> Int
inc n = n + 1

dec :: Int -> Int
dec n = n - 1

add :: Int -> Int -> Int
add n 0 = n
add n m = add (inc n) (dec m)

So you just increase one of the numbers every time you decrease the other. If you recurse you basically repeat this process until you hit some edge condition. This is when the decreased number drops to 0 (notice: works just for natural numbers, not negative integers). You could extend it to negative numbers using if-then-else and comparison with 0 (<, >).
In logic you would probably have a function s. Then you would axiomatize function add for example as:
add(x,y) = add(y,x)
add(x,0) = x
add(x,s(y)) = add(s(x),y)

A: Assuming inc and dec are your functions:
add x y | y > 0     = add (inc x) (dec y)
add x y | y < 0     = add (dec x) (inc y)
add x y | otherwise = x

And similarly for subtract.


text:
Q: Custom listView repeating values and changing them on scrolling I have made a listview with a custom adapter. There are five textviews, 1 checkbox and one button.
-------------------------------------
    <TextView>
    <TextView>   <checkbox>
    <TextView>
    <TextView>    <button>
    <TextView>
-------------------------------------

The arraylists that I am using to populate the textviews in the list has proper unique data. But the listview takes only four to five values of the begining and repeates it in the rest of the list.
Also when I scroll the values displayed change automatically. For example item A was displayed at first position. So when I scroll down and then come up again, item C or item D is displayed.
It is really confusing me! Please help!
Custom Adapter code
protected class MyCustomAdapter extends ArrayAdapter<String>
{
    int len;
    private SparseBooleanArray mCheckStates;
    private SparseBooleanArray favourites;

    ArrayList<String> myMake, myModel, myVer, myPrice, myPlace, sellr_pos;
    int count = 0;
    ViewHolder holder = null;
    Boolean status;

    public MyCustomAdapter(Context context, int textViewResourceId,

    ArrayList<String> car_make, ArrayList<String> car_model,
            ArrayList<String> car_version, ArrayList<String> car_price,
            ArrayList<String> car_place, ArrayList<String> sellr_pos) {
        super(context, textViewResourceId);

        mCheckStates = new SparseBooleanArray(car_model.size());
        favourites = new SparseBooleanArray(car_model.size());

        myMake = car_make;
        myModel = car_model;
        myVer = car_version;
        myPrice = car_price;
        myPlace = car_place;

    }

    private class ViewHolder {
        TextView txt1, txt2, txt3, txt4, txt5;
        CheckBox chkbox;
        Button btn_fav;
    }

    @Override
    public int getCount() {
        return myMake.size();
    }

    @Override
    public View getView(final int position, View convertView,
            ViewGroup parent) {

        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.text_adaptr, null);
            holder = new ViewHolder();

            holder.txt1 = (TextView) convertView.findViewById(R.id.text1);
            holder.txt2 = (TextView) convertView.findViewById(R.id.text5);
            holder.txt3 = (TextView) convertView.findViewById(R.id.text3);
            holder.txt4 = (TextView) convertView.findViewById(R.id.text4);
            holder.txt5 = (TextView) convertView.findViewById(R.id.text2);

            System.out.println("ListView position: " + position);

            holder.txt1.setText(myMake.get(position));
            holder.txt2.setText(myModel.get(position));
            holder.txt3.setText(myVer.get(position));
            holder.txt4.setText(myPrice.get(position));
            holder.txt5.setText(myPlace.get(position));

            holder.chkbox = (CheckBox) convertView
                    .findViewById(R.id.checkBox1);
            holder.btn_fav = (Button) convertView.findViewById(R.id.fav);

            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.chkbox.setTag(position);

        holder.chkbox.setChecked(mCheckStates.get(position, false));

        if (favourites.get(position, false)) {

            holder.btn_fav.setBackgroundResource(R.drawable.star);

        } else {
            holder.btn_fav.setBackgroundResource(R.drawable.star_grey);

        }

        len = fav_ids.size();

        System.out.println("FAV_IDS len:" + len);

        for (int t = 0; t < len; t++) {

            String pos_id = pos.get(position).trim();
            String fav_id = fav_ids.get(t).trim();

            if (pos_id.equals(fav_id)) {

                holder.btn_fav.setBackgroundResource(R.drawable.star);

                break;

            } else {

                holder.btn_fav.setBackgroundResource(R.drawable.star_grey);
            }

        }

        holder.chkbox.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            // Do something

            }
        });

        holder.btn_fav.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Do something

            }
        });

        return convertView;
    }
}

A: Set Values to the TextView at
if (convertView == null) {
....code...
........../.

/*
you are setting values here
remove it from here
*/
 holder.txt1.setText(myMake.get(position));
            holder.txt2.setText(myModel.get(position));
            holder.txt3.setText(myVer.get(position));
            holder.txt4.setText(myPrice.get(position));
            holder.txt5.setText(myPlace.get(position));
}
else
{
....code...
}

/*
Set values here
it will solve the problem
*/
holder.txt1.setText(myMake.get(position));
            holder.txt2.setText(myModel.get(position));
            holder.txt3.setText(myVer.get(position));
            holder.txt4.setText(myPrice.get(position));
            holder.txt5.setText(myPlace.get(position));

It solves  my problem


text:
Q: How to create a nav with a drop-down that overlaps the main content I have been trying to create a sub-menu in my nav. I have created a second <ul> in my <li>. As I hover over the <li> this gets a bigger width (no clue why) and the second problem I have is, this sub-menu is inside my nav itself. So my just gets a bigger height.
This is what I get:

What I am trying to achieve (made with paint):

I have made a jsfiddle, this is the demo

A: just have to add position: absolute; on your #dropdown rule in the css. I've updated the jsfiddle with a couple of minor changes to your #dropdown
EDIT: updated jsfiddle to include your second request just had to add a rule on hover for #overOns (see blow), no need for jquery/javascript. Since the #dropdown is inside the overOns element, this is all you need
#overOns:hover {
  background-color: #bd003a;
}

https://jsfiddle.net/qp0k7rsu/3/

A: Building on the solution by @philr, the fiddle linked to below also keeps the "Over Ons" header with the active background while the user hovers over the sub-menu.
Some JavaScript was required to achieve that functionality, but not much.  All I added were two event listeners.
https://jsfiddle.net/freginold/zr7vsp3z/
var dropdown = document.getElementById('dropdown');
var overOns = document.getElementById('overOns');

dropdown.addEventListener('mouseover', function() {
    overOns.style.backgroundColor = "#bd003a";
});

dropdown.addEventListener('mouseout', function() {
    overOns.style.backgroundColor = "#da0043";
});


text:
Q: Woocommerce variable I created 2 Attributes in WooCommerce.(sale & color)
The sales Attribute consists of 2 variations. (single sale & wholesale)
I want the user who chose the (single sale) variable to be able to choose the colors.(This part has no problem)
This is the problem > I want when the user selects a (wholesale), Disable the color variable and the user can not choose the color scheme.
I put the site link and screenshots below. Thanks
screenshot
product single page


text:
Q: Can I setup Eclipse to show code changes I have used Netbeans before with Subversion (SVN), and I liked how it showed me what I had changed since last commit, using the coloring in the left margin.
Can Eclipse do the same? I have installed Subclipse.

A: Visit Window -> Preferences -> General -> Editors -> Text Editors -> Quick Diff, and enable

*

*Enable quick diff

*Show differences in overview ruler

A: SubVersive and Subclipse can both show changed files in the project explorer and differences between versions in the history.  I currently use Subversive and am happy with it (although installing it was painful the first time.)

A: Had a similar problem. It turn out that the SVN Label decorations in eclipse weren't enable.
   Preferences: General/Appearance/Label Decorators

This post helped me out:
SVN-connected project not showing version info in eclipse


text:
Q: How to compute aggregations on a range of thresholds? Let's say I have the following dataframe:
df = pd.DataFrame([[0.1,0],[0.2,1],[0.3,1],[0.4,0]], columns = ['score', 'correct_pred'])

     score  correct_pred
0    0.1             0
1    0.2             1
2    0.3             1
3    0.4             0

And I would like for each row to compute the proportion of lines with score below and the proportion of correct_pred with score equal or above.
That is, for the second row for instance, 25% of the rows have a score below 0.2 and 66% of rows equal or above 0.2 have a correct pred. The output would then look like:
threshold    percentage_filtered    percentage_correct_pred
0.1          0                      0.5
0.2          0.25                   0.66
0.3          0.5                    0.5
0.4          0.75                   0

So far I do it using this piece of code:
out = pd.DataFrame(columns = ['threshold', 'percentage_filtered', 'percentage_correct_pred'])
for threshold in df.score:
    threshold_mask = df.score < threshold
    out.loc[len(out)] = [threshold,
                         np.mean(threshold_mask),
                         df[~threshold_mask].correct_pred.mean()]

Which works, but it is terribly slow on a real-size dataframe. So I need a faster version, I suspect there is a more vectorized method, maybe using numpy.cumsum or something?

A: I will assume that score may have repeated values, but if it does not it would also work (although it could be simpler). This is a way to get that result:
import pandas as pd
import numpy as np

df = pd.DataFrame([[0.1, 0], [0.2, 1], [0.3, 1], [0.4, 0]],
                  columns=['score', 'correct_pred'])
# Group by scores and count occurrences and number of correct predictions
df2 = (df.sort_values('score')
       .groupby('score')['correct_pred']
       .agg(['count', 'sum'])
       .reset_index())
# Percentage of values below each threshold
perc_filtered = df2['count'].shift(1).fillna(0).cumsum() / df2['count'].sum()
# Percentage of values above each threshold with correct prediction
perc_correct_pred = df2['sum'][::-1].cumsum()[::-1] / df2['count'][::-1].cumsum()[::-1]
# Assemble result
result = pd.concat([df2['score'], perc_filtered, perc_correct_pred], axis=1)
result.columns = ['threshold', 'percentage_filtered', 'percentage_correct_pred']
print(result)
#    threshold  percentage_filtered  percentage_correct_pred
# 0        0.1                 0.00                 0.500000
# 1        0.2                 0.25                 0.666667
# 2        0.3                 0.50                 0.500000
# 3        0.4                 0.75                 0.000000

Performance:
np.random.seed(123)

df = pd.DataFrame({'score': np.arange(0, 1, 0.0005),
                   'correct_pred':np.random.choice([1,0], size=2000)
                   })

print (df)
       score  correct_pred
0     0.0000             1
1     0.0005             0
2     0.0010             1
3     0.0015             1
4     0.0020             1
     ...           ...
1995  0.9975             0
1996  0.9980             0
1997  0.9985             1
1998  0.9990             1
1999  0.9995             1

[2000 rows x 2 columns]

In [208]: %timeit do_it_jdehesa()
9.57 ms ± 317 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [209]: %timeit do_it()
5.83 s ± 181 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [210]: %timeit do_it1()
3.21 s ± 203 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [211]: %timeit do_it2()
92.5 ms ± 1.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: Lets improve the runtime by a factor of 10.
For reference:
df = pd.DataFrame([[0.1,0],[0.2,1],[0.3,1],[0.4,0]], columns = ['score', 'correct_pred'])

def do_it():
    out = pd.DataFrame(columns = ['threshold', 'percentage_filtered', 'percentage_correct_pred'])
    for threshold in df.score:
        threshold_mask = df.score < threshold
        out.loc[len(out)] = [threshold,
                             np.mean(threshold_mask),
                             df[~threshold_mask].correct_pred.mean()]

%timeit do_it()

13 ms ± 607 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Firstly, we take all call of pandas methods out of the loop such as:
def do_it1():

    score_values = df.score.values
    score_list = list(set(score_values))

    correct_pred = df.correct_pred.values

    out = pd.DataFrame(columns = ['threshold', 'percentage_filtered', 'percentage_correct_pred'])

    for threshold in score_list:
        mask = score_values < threshold
        out.loc[len(out)] = [threshold,
                             np.mean(mask),
                             np.mean(correct_pred[~mask])]

%timeit do_it1()

9.67 ms ± 331 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Then we also create the dataframe only after getting the results
def do_it2():

    score_values = df.score.values
    score_list = list(set(score_values))

    correct_pred = df.correct_pred.values

    result = []
    for threshold in score_list:
        mask = score_values < threshold
        result.append((threshold,np.mean(mask),np.mean(correct_pred[~mask])))

    out = pd.DataFrame(result, columns = ['threshold', 'percentage_filtered', 'percentage_correct_pred'])

%timeit do_it2()

960 µs ± 16.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
EDIT:
To take jdehesas answer into account:
df = pd.DataFrame([[0.1, 0], [0.2, 1], [0.3, 1], [0.4, 0]],
                  columns=['score', 'correct_pred'])
def do_it_jdehesa():
    # Group by scores and count occurrences and number of correct predictions
    df2 = (df.sort_values('score')
           .groupby('score')['correct_pred']
           .agg(['count', 'sum'])
           .reset_index())
    # Percentage of values below each threshold
    perc_filtered = df2['count'].shift(1).fillna(0).cumsum() / df2['count'].sum()
    # Percentage of values above each threshold with correct prediction
    perc_correct_pred = df2['sum'][::-1].cumsum()[::-1] / df2['count'][::-1].cumsum()[::-1]
    # Assemble result
    result = pd.concat([df2['score'], perc_filtered, perc_correct_pred], axis=1)
    result.columns = ['threshold', 'percentage_filtered', 'percentage_correct_pred']

%timeit do_it_jdehesa()

13.5 ms ± 997 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
EDIT2: Just optimizing the cuntion a little more - yet no where near as fast as jdehesas answer
def do_it5():

    dfarray = df.values
    n = dfarray.size
    score_values = dfarray[:,0]
    score_list = np.unique(score_values)
    correct_pred = dfarray[:,1]

    result = []
    for threshold in score_list:
        mask = score_values<threshold
        result.append((threshold, np.count_nonzero(mask)/n, np.count_nonzero(correct_pred[~mask])/n))

    result =  pd.DataFrame(result, columns = ['threshold', 'percentage_filtered', 'percentage_correct_pred'])


text:
Q: Extract floats from list of list of strings [['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]

How to extract what's in between the parentheses as floats.
The output should be something like this:
[[25, 32], [24.2, 31.5], [22, 34], [20.5, 34]]

A: Converting a tuple to a list after extracting the tuple from the strings will consume a lot of memory and is not ideal. If you just want to get the strings of the tuple into floating numbers. You can first do a str.split and eval
[eval(j.split('. ')[1]) for i in alist for j in i]
[(25, 32), (24.2, 31.5), (22, 34), (20.5, 34)]

A: If your input is always in this format, you can do:
your_input = [['1. (25, 32)'], ['2. (24.2, 31.5)'], ['3. (22, 34)'], ['4. (20.5, 34)']]
output = [[float(number) for number in elem[0].split(". ")[1].rstrip(")").lstrip("(").split(", ")] for elem in your_input]

output:
[[25.0, 32.0], [24.2, 31.5], [22.0, 34.0], [20.5, 34.0]]


text:
Q: What is the purpose of multiple-level synchronized statement? I really don't understand what purpose of multiple-level synchronized statement? For instance, in the code:
static void m() throws Exception {
    synchronized (sync) {
        System.err.println("First level synchronized");
        synchronized (sync) {
            System.err.println("Second level synchronized");
            synchronized (sync) {
                System.err.println("Third level synchronized");
            }
        }
    }
}

public static void main(String[] args) throws Exception {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            try {
                m();
            } catch (Exception ex) {
                Logger.getLogger(IO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
    Thread th1 = new Thread(r);
    Thread th2 = new Thread(r);
    th1.run();
    th2.run();
}

It is impossible to execute the most-enclosing synchronized statement for any thread if some thread has already started to execute one. So, I cannot see any usefulness of such construction. Could you provide an example to understand such using?
An other example of nested synchronized statements can be found in the official JLS specs: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.19

A: From the OP's comments this comes from the JLS §14.19
class Test {
    public static void main(String[] args) {
        Test t = new Test();
        synchronized(t) {
            synchronized(t) {
                System.out.println("made it!");
            }
        }
    }
}

The JLS goes on to say:

Note that this program would deadlock if a single thread were not permitted to lock a monitor more than once.

This is example is meant to illustrate that synchronized blocks are reentrant.
This JLS is not a document of useful coding practices.
It is desgined to illustrate how the language is supposed to work. It documents language constructs and defines their behaviour - it is a specification.

A: It's an example of something that is legal, not something that is useful or recommended. It's showing that the lock is recursive ("Note that this program would deadlock if a single thread were not permitted to lock a monitor more than once").


text:
Q: How do I set up a conditional formula with multiple criteria? I recently needed to find matches occurring anywhere within a column.  This article here
How to identify cells in Column A that contain any of the values in Column B
gave me exactly what I needed to execute this task.  Later, I discovered that I needed to do that, plus add additional criteria from a separate column.  I have been to numerous websites and have tried a number of different formulas to make this happen, but, thus far, my formula has failed every time.  To give you a visual of what I want to do, I've included an image below:

It may help to know the following:

*

*Total number of items in Column E are fewer than those in Column T (by a substantial amount).

*Cells in Column E contain a single word and no duplicates exist within that column.

*Cells in Column T contain a single word and no duplicates exist within that column.

*Cells in Column V contain either "Match," "þ" (the checked box), or are blank.

*Contents of cells in Column E may or not exist in Column T.

*"Match" indicates that cells in Column T match words in a column not shown in the image above.  In other words, it is not intended to convey a match with the contents of cells in Column E.

Now, here is what I would like to do with these columns of information:

*

*If the contents of a cell in E do not match any of the cells in T, return "V3 Only" in Column X.

*If the contents of a cell in E are found in Column T AND Column V contains "Match," return "Match" in Column X.

*If the contents of a cell in E are found in Column T AND Column V contains the checked box ("þ"), return "þ" (the checked box) in Column X.

I hope this isn't too difficult to solve.  Despite my difficulty in arriving at a formula that can execute this, I have a feeling someone in this community knows how to set this up.
In case it makes a difference, I need this formula to work for Excel 2007.
Thanks in advance for anyone who knows how to do this and is willing to share it with us.

A:
If the contents of a cell in E are found in Column T AND Column V contains "Match," return "Match" in Column X.
  If the contents of a cell in E are found in Column T AND Column V contains the checked box ("þ"), return "þ" (the checked box) in Column X.

I'd just add "if the contents of a cell in E are found in Column T AND Column V is empty, then return empty string in Column X"
And we can simplify all above to if the contents of a cell in E are found in Column T, then return Column V in Column X
So you don't need to use complex conditions:
=SUBSTITUTE(IF(ISNUMBER(MATCH(T1,$E$1:$E$19,0)),V1,"Only "&ADDRESS(ROW(V1),COLUMN(V1),4)),"0","")
Where

*

*ISNUMBER(MATCH(T1,$E$1:$E$19,0)) - checks whether value from T1 exists in column E

*"Only "&ADDRESS(ROW(V1),COLUMN(V1),4)) - generates address of V1

*IF(ISNUMBER(...),V1,"Only "&...) - If T1 exists in column E, then enters V1, else "Only V1"

*=SUBSTITUTE(IF(...),"0","") - if V1 is blank, than formula would convert it to 0, this converts it to ""

*this is an array formula, so you need to insert it by pressing CTRL+SHIFT+ENTER

A: After additional attempts to solve this the way I had initially envisioned it, I finally decided to yield to a more practical and less complicated way of doing the same thing.  Initially, I attempted to match the words on the shorter list to the words on the longer list (which had the additional columns of information).  As my brainstorming of formulas and functions dwindled, I sat back and wondered if there might be a different approach and got to thinking that this might be much easier if I simply attempted to match the longer list to the shorter list.  I then found the following post
Excel: Check if Cell value exists in Column, and then get the value of the NEXT Cell
in which I came across the following formula:

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", "Match")

I applied it to my problem with this formula [simplified to make it easier to read]:

=IF(ISERROR(MATCH(C2,'[OTHER WORKBOOK.xlsx]SHEET'!$F:$F, 0)), "No Match", "Match")

Note that my original Column E became Column F due to the insertion of a column for other reasons.
In the end, it came out looking like this:

Using the word "vigor" as an example, what this sheet now tells me is that "vigor" matches a word on another list, but not on the list I am currently studying (because Column J contains "No Match") and that it meets two other criteria I have established.  I don't know if this type of solution can work in every instance, but it works for my purposes here, and if you are reading this, perhaps it is a solution that works for you as well.

I'll hold off on giving myself the green checkmark in case someone knows how to solve this the way I had originally envisioned, or has a better solution altogether.  So if you've been working on a solution to this or just now want to take it on, and can come up with something you think would be helpful, don't hesitate to post your answer as well.


text:
Q: How to cluster a finite number of random variables based on their distributions? Suppose that we have $n$ mutually independent (not i.i.d.) random variables $X_1,\dots,X_n$. We assume that these random variables can be divided into $k$ distinct groups ($k<n$), where in each group, all random variables that belong to that group are identically distributed.
Example: There are 10 random variables that can be divided into two groups, where the first group contains four random variables that are i.i.d. with a distribution that has the mean and variance of 4 and 23; and second group contains six i.i.d. random variables that the mean and variance of their distribution is 8 and 66.
Problem: Suppose that the number of groups and the distributions are unknown. Now, let us make $t$ observations for those $n$ random variables, where each observation is a vector $(x_1,\dots,x_n)$. At the end, we will have a $n\times t$ matrix $M$, whose column $i$ corresponds to $t$ different i.i.d. samples for $X_i$. Using matrix $M$, we want to divide the random variables into $k$ groups based on their distributions.
Question: How can we find the number of groups and the variables that belong to each group?
You may assume that the distribution of each r.v. is a Gaussian mixture and that $k$ is less than a known number, e.g., $K$.


text:
Q: VisualEditor in Java - dynamically build sub-panel? I'm using the "Visual Editor" to "paint" my Swing GUI. Can I dynamically build the contents of a sub-panel with VE or do I have to use a predefined sub-class of JPanel (and build that with VE)?

A: You can dynamically build the contents of a sub panel - say based on a file or soemthing - the visual editor is not going to stop you.
Generally, VE is intelligent enough to see that you are dynamically build the panel and show the contents (say contents of a file in a JList)
Sometimes, VE fails to render the items because 'The control is too complex' - but this does not happen frequently.