Q:

Can't access a stand alone domain object in hql namedQuery

First I need to apologize for the long post, I struggle with being overly verbose and yet not always clear enough. I also have searched extensively for an elegant solution for my issue and if I missed it please direct me to it.
Some Background:
I have a grails app that is using namedQueries for a set of standard result sets. The app finds open advertised Job Orders in our system and sends them to other sites. Recently an additional requirement has become a problem for me if I wish to continue using the namedQueries.
For the sake of simplicity let's just assume a domain model of
    class JobOrder {

  def getOpenAdJobsSql() {
    def qry = "select jo FROM JobOrder jo WHERE isOpen=1 AND publishedTo='All External' AND adCategory.isActive=1 AND jo.adLocation in (select zc.id from Zip zc)"

    JobOrder.executeQuery(qry)

  }

  static namedQueries = {

    openAdJobs {
      eq 'isOpen', true
      eq 'publishedTo', "All External"
      adCategory {
        eq 'isActive', true
      }
    }

  static mapping = {
    table 'dbo.JOBORDER'
    version false
    id generator: 'identity', column: 'JOBORDERID'
    isOpen column: 'ISOPEN'
    publishedTo column: 'customText15'
    adLocation column: 'PUBLISHEDZIP'
    adCategory column: 'customInt3'
  }

  Boolean isOpen
  String publishedTo
  String adLocation
  ClientCorporation client
  AdCategory adCategory

  static constraints = {
    adLocation(size: 0..100)
  }

}

    class AdCategory {
  static mapping = {
    table 'dbo.AdCategory'
    version false
    id generator: 'identity', column: 'adCategory_ID'
    isActive column: 'active'
  }
}

    class Zip {
    static mapping = {
        table 'ZIP'
        version false
        id generator: 'identity', column: 'ZIPCODE'
        city  column: 'city'
        county  column: 'county'
        stateAbbr column: 'statecode'
    }

    String city
    String county
    String stateAbbr
}

I will begin with the current namedQuery in concern:
openAdJobs {
  eq 'isOpen', true
  eq 'publishedTo', "All External"
  adCategory {
    eq 'isActive', true
  }
}

This query exists in my JobOrder domain object which also has a relationship with the AdCategory domain object. The named query is called in multiple places using the following call:
def openJobs = JobOrder.openAdJobs

My New Problem:
Now I have a requirement to make sure I don't publish any jobs that have invalid zip codes. I am integrating with a product which contains no zip validation and I have no control over the product's native domain model. We have added a custom Zip domain object that is stand alone. I have struggled figuring out a way to include code that will work with the named query in my JobOrder object to accomplish what the following query would return: (i run this query against the sql db in dbvisualizer)
  select * from dbo.JobOrder jo
  inner join dbo.AdCategory ac on jo.adCategory=ac.adCategory_ID
  where
  jo.isOpen=1
  and
  jo.publishedTo='All External'
  and
  ac.isActive=1
  and
  jo.publishedZip in (
        select zc.zipcode from dbo.Zip zc
  )

A not-so-pretty solution:
The only way I and a couple of peers have gotten the desired result set is by creating a method like the following in my JobOrder object:
def getOpenAdJobsSql() {
    def qry = "select jo FROM JobOrder jo WHERE isOpen=1 AND publishedTo='All External' AND adCategory.isActive=1 AND jo.adLocation in (select zc.id from Zip zc)"

    JobOrder.executeQuery(qry)
}

The method, of course, is not available unless I instantiate a JobOrder. Since I am actually attempting to build my list of JobOrders at this point there is a very unappetizing hack to get my result set. I would need to fetch a known good JobOrder (or create one) so the getOpenAdJobsSql() method is available to call.
something like:
def jo = JobOrder.get(2)
def rset = jo.openAdJobsSql

would need to be added everywhere I currently call the openAdJobs named query (currently 9 or more usages). To even consider this approach is sending mental warning flares up for me, but I see no other way to add the additional feature.
Again, ultimately it is my desire to call a named query, but the additional zip code sql appears to be something GORM + hibernate is not going to be able to handle.
It is my hope that someone will know of a more elegant solution. And please ask for clarity anywhere it is missing in this post.

A:

Okay, so if I understand your problem:

JobOrder, more specifically the underlying JOBORDER table and the mechanism to populate that table, is a 3rd party product.  You cannot change either.
Rows in JOBORDER may contain PUBLISHEDZIP values which do not exist in your ZIP table.
Your current GORM model does not contain a relationship between JOBORDER and ZIP so you therefore cannot use a Criteria/HQL to select a subset of the data that contains only valid ZIP codes.

Options that might work:

make the method you described static so you don't need to instantiate an object of the underlying class.
use the inList restriction on your named query (I haven't tested this, but seems like it should work).

.
openAdJobs {
    eq 'isOpen', true
    eq 'publishedTo', "All External"
    inList 'adLocation', Zip.list()
    adCategory {
      eq 'isActive', true
   }
 }

I think there is probably a better performing alternative that you could use involving a Subquery expression that replaces the inList with an Exists clause, but off the top of my head I'm not sure if CriteriaBuilder/GORM Criteria supports that or not.  You might have to get down into the Hibernate to do that and I'm not sure how well that approach plays with named queries.


Q:

Efficiently build a python set from a list of unique elements

I have a list of elements which should be unique by construction. I mean, no element will be present more than once in the list.
I want to efficiently test if an item is present in that list, and this for many items.
The test is more efficient if I convert the list into a set.
Now my questions are about how to efficiently build the set.
I guess that when I do my_set = set(my_list), python somehow has to test membership of items in the list as it progressively constructs the set.

Is this sub-optimal given the knowledge that I know that the list does not contain duplicates?
Is it possible to do better?
Does the answer to the question above change if instead of a list, I have an iterator (about which I still know that the items it will yield will be unique)?

A:

Python doesn't do explicit membership tests when constructing a set. It doesn't need to; sets are unique by their nature, which is that the members are indexed by their hash values. So in constructing a set, all Python does is hash each element in turn and then insert it in the appropriate place.
The Python docs on time complexity don't explicitly list set construction, but they do say that most operations are the same as for a dict, and insertion into a dict is O(1), by which we can assume that set construction is O(n).

A:

Since set() uses a hashtable (see How is set() implemented?), more time would be spent hashing than comparing, and this is unavoidable.
I assume your dataset is very large if you're this concerned about performance. The only way you're going to get better performance is by creating the set() in the first place and avoiding the intermediate memory usage of the list().
$ python3 -m timeit 'set(list(range(100000)))'
100 loops, best of 3: 8.69 msec per loop

$ python3 -m timeit 'set(range(100000))'
100 loops, best of 3: 7.67 msec per loop

$ python3 -m timeit 'frozenset(range(100000))'
100 loops, best of 3: 7.68 msec per loop


Q:

Why is associativity required for groups?

Why is associativity required for groups?
I'm doing a linear algebra paper and we're focusing on groups at the moment, specifically proving whether something is or is not a group. There are four axioms:

The set is closed under the operation.
The operation is associative.
The exists and identity in the group.
Each element in the group has an inverse which is also in the group.

Why does the operation need to be associative?
Thanks

A:

It is not that associativity is required for groups... That is quite backwards: the truth is actually that groups are associative.
Your question seems to come from the idea that people decided how to define groups and then began to study them and find them interesting. In reality, it happened the other way around: people had studied groups way before actually someone gave a definition. When a definition was agreed upon, people looked at the groups they had at hand and saw that they happened to be associative (and that that was a useful piece of information about them when working with them) so that got included in the definition.
If I may say so, it is this which is important to understand. The way we teach abstract algebra nowdays somewhat obscures this fact, but this is how essentially everything comes to be.

A:

Groups are an abstraction. What do they abstract? The idea of symmetry. Symmetries are functions from a set to itself that preserve some structure of that set; for example, the symmetries of a square are rotations and reflections, and they preserve "squareness" (to put it vaguely).
The multiplication in a group abstracts composition of symmetries (for example "rotate $90^{\circ}$, then reflect about the line $x = y$"), and composition of functions is always associative.

A:

The formalist's answer is: it is just a definition. You could just as well consider studying algebraic structures that satisfy all the axioms for a group except for associativity, and you would be then studying loops.
Now the question might be: why is the study of groups more ubiquitous than the study of loops? There are historical reasons (surely others with greater knowledge can expand upon this), and the fact that most loops that arise naturally when doing math are in fact groups is probably a reason too.


Q:

Windows Powershell: Executing commands via the context menu?

I'm using kramdown to convert my markdown-formatted source files into html. The command I've been using is:
kramdown %filename | Out-Clipboard

(Out-Clipboard is from the fantastic PSCX. This means my formatted html is immediately ready to paste into another program or editor)
I'd love to streamline this process and be able to use a context menu item to do the same thing, instead of opening a shell and typing out the command each time. What's the best way to pass these instructions to powershell, and add it as menu option?

A:

You can run PowerShell commands from the command-line (batch files, etc.) by using this format:
C:\> PowerShell <PowerShell command you want to run>
ie:
C:\> PowerShell "kramdown MyFileName.txt | Out-Clipboard"
So we can use that in a context menu entry.
For simplicity here's how you can add a new Context Menu command to run it against whichever file you have selected/right-clicked (this is probably not the ONLY way to do this):

Head to HKEY_CLASSES_ROOT\*\shell in the registry.
Create a new Key named what you want (like say "Kramdown").
Set the "Default" REG_SZ value of that new key to the text you want to appear on the context menu (like say "Kram This Down").
Create another new Key inside the key you just made, and name it "command".
Set the value of the "Default" REG_SZ in that new 'command' key to run the command you want.

The command you'll want to enter is like above, only we need to tell it to do it in the command prompt, and use the %1 variable so it knows the file you clicked on:
cmd /C PowerShell "kramdown %1 | Out-Clipboard"

The /C causes the CMD window to close after it's done.
As soon as you make these registry changes they will affect the context menu, so you don't need to logout or reboot to enable or test your changes.
Since I don't have your source files, Kramdown, or Out-Clipboard I can't test this 100%; but this should be enough info to get you going, if it doesn't 'just work' as-is. :)


Q:

how to hide previous one when showing next one with jquery?

I ain't find the vertical news scroller for joomla 2.5 So I wanted to make my own.
Firstly I have hidden first two lists and then I wanted to show next list when clicked but I'm doing wrong
$('ul li').slice(2).hide();
$('#up').on('click',function(){
    $('ul li').slice(3).hide();
});

here is the demo
I also wanted to show the next list and hide the previous first list. How can I do?

Edit
Okay now I have made working like using this demo
var countnews = 3;
$('ul li').slice(countnews).hide();
$('#up').on('click',function(){
    $('ul li').show();
    $('ul li').slice(countnews++).hide();
});

Now, how can I hide the previous one when showing next one?

A:

Try this,
var start = 0;
var end = 3;
var len=$('li').length;
$('ul li').hide().slice(start, end).show();
$('#up').on('click',function(){
    if(end<len)
    {
       start++;end++;
       $('ul li').hide().slice(start, end).show();
    }
});

Fiddle
For down
$('#down').on('click',function(){
    if(start>0)
    {
       start--;end--;
       $('ul li').hide().slice(start, end).show();
    }
});

Updated Fiddle
Updated code with animation
$('#up').on('click',function(){
    if(end<len)
    {
        $('ul li').slice(start, end).slideUp(500);
        start++;end++;
        setTimeout(function(){
           $('ul li').hide().slice(start, end).slideDown(500);
        },500);

    }
});
$('#down').on('click',function(){
    if(start>0)
    {
         $('ul li').slice(start, end).slideUp(500);
         start--;end--;
         setTimeout(function(){
            $('ul li').hide().slice(start, end).slideDown(500);
         },500);
    }
});

Animated Fiddle


Q:

Scoring strategy of sklearn.model_selection.GridSearchCV for LatentDirichletAllocation

I am trying to apply GridSearchCV on the LatentDirichletAllocation using the sklearn library.
Current pipeline looks like so:
vectorizer = CountVectorizer(analyzer='word',
                         min_df=10,
                         stop_words='english',
                         lowercase=True,
                         token_pattern='[a-zA-Z0-9]{3,}'
                        )

data_vectorized = vectorizer.fit_transform(doc_clean) #where doc_clean is processed text.

lda_model = LatentDirichletAllocation(n_components =number_of_topics,
                                    max_iter=10,
                                    learning_method='online',
                                    random_state=100,
                                    batch_size=128,
                                    evaluate_every = -1,
                                    n_jobs = -1,
                                    )

search_params = {'n_components': [10, 15, 20, 25, 30], 'learning_decay': [.5, .7, .9]}
model = GridSearchCV(lda_model, param_grid=search_params)
model.fit(data_vectorized)

Current the GridSearchCV uses the approximate log-likelihood as score to determine which is the best model. What I would like to do is to change my scoring method to be based on the approximate perplexity of the model instead.
According to sklearn's documentation of GridSearchCV, there is a scoring argument that I can use. However, I do not know how to apply perplexity as a scoring method, and I cannot find any examples online of people applying it. Is this possible?

A:

GridSearchCV on its default will use the score() function of final estimator in the pipeline.
make_scorer can be used here, but for calculating perplexity you will need other data from the fitted model as well, which could be a little complex to provide through make_scorer.
You can make a wrapper over your LDA here and in which you can re-implement the score() function to return perplexity. Something along the lines:
class MyLDAWithPerplexityScorer(LatentDirichletAllocation):

    def score(self, X, y=None):

        # You can change the options passed to perplexity here
        score = super(MyLDAWithPerplexityScorer, self).perplexity(X, sub_sampling=False)

        # Since perplexity is lower for better, so we do negative
        return -1*score

And then can use this in place of LatentDirichletAllocation in your code like:
...
...
...
lda_model = MyLDAWithPerplexityScorer(n_components =number_of_topics,
                                ....
                                ....
                                n_jobs = -1,
                                )
...
...


Q:

Questions about schemas.microsoft.com.2003.10.Serialization.xsd generated by svcutil.exe

I want to distribute the WSDL file of my WCF service to all the stakeholders. Some will be generating actual web service out of it and a few will be writing client part of it.
When i generated wsdl, i found that schemas.microsoft.com.2003.10.Serialization.xsd is also generated. My questions are:

Is this file/schema necessary in distribution package? (I think, yes.)
Is it compliant with the standards?
Will there be any interoperability issue? Some stakeholders are on Java and Delphi platforms.
Why the similar schema definition is not generated for the ASMX services?

A:

My questions are:
1) Is this file/schema necessary in distribution package? (I think, yes.)
  2) Is it compliant with the standards?
  3) Will there be any interoperability issue? Some stakeholders are on Java and Delphi platforms.
  4) Why the similar schema definition is not generated for the ASMX services?

My answers are:
1) Yes, it's necessary - typically, WCF doesn't generate stuff that's not necessary....
2) Yes, it's 100% compliant with all WS-* and XML Schema standards.
3) Only if the other side of the equation doesn't conform to the documented standards....
4) That's something only the designers at Microsoft can answer ..... I don't know - and frankly I don't care since ASMX is legacy technology


Q:

Can I check in code to another project in TFS 2013?

I'm writing code in a TFS 2013 Project. I'd like to check it into a different Project on the same server. Can I do this? Thanks

A:

You can not directly check in the code to another project, you need to add the code file to another project first for source control, then check in the code  changes.
In visual studio Team Explorer:

Connect To TFS project 1, configure the workspace and map source
code to local folder1. Open the folder1 in windows explorer.
Connect To project 2, configure the workspace and map source code to
local folder2. Open the folder2 in windows explorer.
Copy the code file which you want to check into another project (eg,
project 2 here ) from folder1 to folder2, then the system
will detected the new added files under Pending Changes >
Excluded changes.
Click the Detected link to Promote the new added files.
Check in the files to Project 2

Refer to these articles for more information : Add files to the server
and Check in your work to the team's codebase

UPDATE:
You can link to the WI in the same collection, but cannot link to the WI which in another collection.
That means, if the team projects are in the same collection, then you can link the WI (associate with the changeset) which belongs to another project directly.


Q:

What's the best way to compare 2 vectors or strings element by element?

What's the best way to compare 2 vectors or strings element by element in Rust, while being able to do processing on each pair of elements? For example if you wanted to keep count of the number of differing elements. This is what I'm using:
let mut diff_count: i32 = 0i32;
for (x, y) in a.chars().zip(b.chars()) {
    if x != y {
        diff_count += 1i32;
    }
}

Is that the correct way or is there something more canonical?

A:

To get the count of matching elements, I'd probably use filter and count.
fn main() {
    let a = "Hello";
    let b = "World";

    let matching = a.chars().zip(b.chars()).filter(|&(a, b)| a == b).count();
    println!("{}", matching);

    let a = [1, 2, 3, 4, 5];
    let b = [1, 1, 3, 3, 5];

    let matching = a.iter().zip(&b).filter(|&(a, b)| a == b).count();
    println!("{}", matching);
}


Q:

I got this JSON (this is a small snippet) from the alphavantage API and I need to extract only the close data but can't figure out how

I'm fairly new to python (and coding in general) and trying to write a  program got to analyse stock market data. I got this JSON (this is a small snippet) from the alphavantage API and I need to extract only the close data but can't figure out how. How would I go about only taking the close data and retaining the date stamp?
    '2020-07-30': {   '1. open': '201.0000',
                      '2. high': '204.4600',
                      '3. low': '199.5700',
                      '4. close': '203.9000',
                      '5. volume': '25079596'},
    '2020-07-31': {   '1. open': '204.4000',
                      '2. high': '205.1000',
                      '3. low': '199.0100',
                      '4. close': '205.0100',
                      '5. volume': '51247969'},
    '2020-08-03': {   '1. open': '211.5200',
                      '2. high': '217.6400',
                      '3. low': '210.4400',
                      '4. close': '216.5400',
                      '5. volume': '78983009'},
    '2020-08-04': {   '1. open': '214.1700',
                      '2. high': '214.7700',
                      '3. low': '210.3100',
                      '4. close': '213.2900',
                      '5. volume': '49280056'},
    '2020-08-05': {   '1. open': '214.9000',
                      '2. high': '215.0000',
                      '3. low': '211.5700',
                      '4. close': '212.9400',
                      '5. volume': '28858621'}}

A:

Here is a example, you should look up:

How to send requests.
How to work with Python dictionaries.

import requests

# Sample data URL
url = "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo"
# Get the data
response = requests.get(url)
# Convert the data to a python Dictionary
data = response.json()
# Get the 5 minute quotes from the data
five_min_data = data["Time Series (5min)"]
# Loop through each 5 minute quote and print the date and close price
for date in five_min_data:
    print("The date is ", date)
    print("The close price is ", five_min_data[date]["4. close"])


Q:

R: Make plot axis as in histogram

I want the y axis in regular plot() function to start at the bottom of the plot area similar to hist() function. In other words I would like to have zeros of both axis at the same level. Here is my working example
set.seed(1)
data <- data.frame(
  type = as.factor(sample(c('A', 'B', 'C'), size = 100, replace = T)),
  value = rexp(100, 1/3)
)
plot(data$type)
par(new=TRUE)
plot(tapply(data$value, data$type, mean),
     xaxt="n", yaxt="n", xlab="", ylab="",
     xlim=c(0.55,3.45), ylim=c(0, 5), bty='n', pch=24, bg='black')
axis(4)

I tried to use parameter yaxs = 'i' in the plot() function, but it moved the axis too low. Is there any solution to this?

A:

Find one variant
set ylim in first plot
try
plot(data$type, yaxs = 'i',ylim=c(0,max(apply(data, 2, table)[[1]])))
par(new=TRUE)
plot(tapply(data$value, data$type, mean),
     xaxt="n", yaxt="n", xlab="", ylab="",
     xlim=c(0.55,3.45), ylim=c(0, 5), bty='n', pch=24, bg='black',yaxs = 'i')
axis(4)
axis(1,at=c(0,5)) #only for show that one lvl


Q:

iOS: Container view - animate push transition when changing child view controllers

Apple discusses how to have a container view controller transition between two child view controllers in this document. I would like to animate a simple push vertical slide up identical to UIModalTransitionStyleCoverVertical in UIModalTransitionStyle. However,  transitionFromViewController only allows use of UIViewAnimationOptions, not transition styles. So how would one animate sliding a view up?
It's odd that to transition between child view controllers you can't call a simple push method similar in UINavigationController to animate the transition.

A:

Load child view, set frame with origin.y under bottom screen. After change it to 0 in animation block. Example:
enum Animation {
    case LeftToRight
    case RightToLeft
}

func animationForLoad(fromvc: UIViewController, tovc: UIViewController, with animation: Animation) {

        self.addChildViewController(tovc)
        self.container.addSubview(tovc.view)
        self.currentVC = tovc

        var endOriginx: CGFloat = 0

        if animation == Animation.LeftToRight {
            tovc.view.frame.origin.x = -self.view.bounds.width
            endOriginx += fromvc.view.frame.width
        } else {
            tovc.view.frame.origin.x = self.view.bounds.width
            endOriginx -= fromvc.view.frame.width
        }

        self.transition(from: fromvc, to: tovc, duration: 0.35, options: UIViewAnimationOptions.beginFromCurrentState, animations: {
            tovc.view.frame = fromvc.view.frame
            fromvc.view.frame.origin.x = endOriginx
            }, completion: { (finish) in
                tovc.didMove(toParentViewController: self)
                fromvc.view.removeFromSuperview()
                fromvc.removeFromParentViewController()
        })
    }

Above code is transition between 2 child view with push and pop horizontal animation.


Q:

Why does ("a" in ["a","b"]) yield false, and (1 in [1,2]) yield true?

Possible Duplicate:
javascript in operator

Why does ("a" in ["a","b"]) yield false, and (1 in [1,2]) yield true ?
Is there a reason why "a" does not match the first element of that array and 1 does ?
Why won't it work with strings ?

A:

The in operator checks for the existence of properties by key, not by value. And your array of length 2 has an index "1" - arr["1"] is the value 2. For example, also 0 in ["a", "b"] is true. The behaviour does not depend on a string or a number being used.
You usually would use it on plain objects, not on arrays. Like "a" in {a:1} === true, or "b" in {a:1} === false.


Q:

Is continuity of first partials required for analyticity?

Let's cast the complex function $f(z) = u(z) + iv(z), z = x+iy$, as the multivariable function $F(x,y) = U(x,y) + iV(x,y) ; x,y \in R$.
Thus, $$dF = F_x\,dx + F_y\,dy = U_x\,dx + iV_x\,dx + U_y dy + iV_y\,dy$$
Making use of $$dz = dx + i\,dy,$$ $$dz∗ =dx−i\,dy,$$
We plug in $$dx = \frac 1 2 (dz + dz∗),$$ $$dy= \frac 1 {2i}(dz−dz∗)$$
into the equation of $dF$, thus we get:
$$dF = \frac 1 2 (U_x + V_y + i(V_x - U_y))\, dz + \frac 1 2 (U_x - V_y + i(V_x + U_y))\, dz*$$
Now it can be seen that if the function $f(z)$ (and thus $F(x,y)$) satisfies the Cauchy Riemann Equations, then the factor in front of $dz*$ will be zero, and we will have the expression for the derivative of the function $F(x,y)$ (and hence $f(z)$).
Now there are two assumptions for the derivative of a complex function to exist, namely that (1) it satisfies CR equations, and (2) it has continuous first partial derivatives.
But we just found the derivative of $f(z)$, without assuming the condition of continuous first partials!! How is this?

A:

The exterior derivative $dF$ isn't really well-defined if we just assume existence of partial derivatives. Of course, we could formally write:
$$
dF = F'_x\,dx + F'_y\,dy
$$
but if we don't know that $F$ is differentiable, $dF$ doesn't have very nice properties. (For example, invariance under coordinate transformations is no longer guaranteed.) In particular, just because you can read off that
$\frac{\partial F}{\partial \bar z} = 0$, it doesn't imply that $f'$ exists.
As a concrete counterexample, let
$$
F(z) = \begin{cases} \exp(-1/z^4), & z \neq 0 \\ 0, & z = 0 \end{cases}
$$
You can check that $F$ has partial derivatives everywhere and that they satisfy Cauchy-Riemann's equations, but of course $F$ is not even continuous at $z=0$.
On a related, but different note. If $F$ is continuous and has partial derivatives which satisfy Cauchy-Riemman's equations, then $F$ is in fact holormorphic. This result is known as Looman-Menchoff's theorem and is pretty difficult.


Q:

Bash Regex comparison not working

keyFileName=$1;
for fileExt in "${validTypes[@]}"
 do
   echo $fileExt;
   if [[ $keyFileName == *.$fileExt ]]; then
       keyStatus="true";
   fi
done;

I am trying to check the file extension of a file passed in against an array of multiple file extensions. However it doesn't seem to be working properly. Any help?

A:

validTypes=(".txt" ".mp3")
keyFileName="$1"
for fileExt in "${validTypes[@]}"
 do
   echo $fileExt;
   if [[ $keyFileName =~ ^.*$fileExt$ ]]; then
       keyStatus="true";
       echo "Yes"
   fi
done;

Effectively, you could change your if statement to either:
if [[ $keyFileName == ?*$fileExt ]]   # Glob pattern case, ? denotes single char

or:
if [[ $keyFileName =~ .*$fileExt ]]   # Regex case, . denotes single char


Q:

C# searching through lists

In the following code I'm using 3 foreach statements.  I'm just looking to populate a list when a list of items matches another but the ones that don't match also have to be added.  So I was wondering if there is an easier way to do the following.
        List<T> ds = new List<T>();  //is populated
        foreach (var b in template.Bs)
        {
            List<BD> tempList = new List<BD>();
            foreach (BD bd in b.BDs)
            {
                Boolean found = false;
                foreach (DV dv in items)
                {
                    if (bd.C == dv.C)
                    {
                        found = true;
                        tempList.Add(new BD ()
                        {
                            //populating
                        });
                    }
                }
                if (!found)
                    tempList.Add(new BD()
                    {
                        //populating
                    });
            }

        }

A:

The relationship between ds and tempList is not clear, but it looks to me like your inner loops are really a left outer join:
List<T> ds = new List<T>();  //is populated
foreach (var b in template.Bs)
{
    var newBDs = from bd in b.BDs
                 join dv in items on bd.C equals dv.C into j
                 from dv in j.DefaultIfEmpty()
                 select dv == null ? NoMatch(bd) : Match(bd, dv);

    List<BD> tempList = newBDs.ToList();

    // Do something with tempList
}

For each b in template.Bs, we're matching bd's from b.BDs with dv's in items. We then use DefaultIfEmpty() to put null in dv if there was no match, which we then use to determine which projection method to call: NoMatch() would create a new BD based on the unmatched bd, and Match() would create a new BD based on the matched bd and dv.
That whole query is represented by newBDs, which will be IEnumerable<BD>. We can then buffer that sequence into tempList or do something else useful with it.


Q:

Flex 3 - List - checkbox itemrenderer enabled property

I have a list that uses a checkbox itemrenderer.  The dataprovider is a collection of people.  When I load the data from a file, each list item shows the person's name (last, first -- labelFunction), and the checkbox's selected property shows the person's included property.  I.e.,
Smith, Doug - [x]
Williams, Bob - [ ]
Morris, Anne - [x]
However, each person also has an active property.  I want to disable the checkbox for people who are inactive (meaning, "you can't include inactive people").  I have tried several methods to get this to work, including what's suggested here http://forums.adobe.com/thread/416786 to do the same thing in a datagrid.  However, none of them work and all the checkboxes are enabled regardless of the person's active status.  Here is my basic code:
<mx:List id="peopleIncludedList"
     dataProvider="{someProvider}"
     labelFunction="peopleLabelFunction">
     <mx:itemRenderer>
          <mx:Component>
               <mx:CheckBox change="onChange(event)"
                    selected="{outerDocument.isIncluded(data)}">
                    <mx:Script>
                         <![CDATA[

                              private function onChange(e:Event):void
                              {
                                   ...
                              }
                         ]]>
                    </mx:Script>
               </mx:CheckBox>
          </mx:Component>
     </mx:itemRenderer>
</mx:List>

Any help on this would be greatly appreciated.  Thank you.
-- Ian

A:

Since stackoverflow only notifies me daily of new answers, I wasn't actively looking at this thread, and was more involved on the Adobe boards.  Anyway, found a solution.  Reference it here http://forums.adobe.com/message/3267367.  Thanks everyone for your suggestions and helpfulness!


Q:

How to display the default user picture programatically?

I'd like to print a user's image in a View's template file. If the user hasn't set an image yet, the default user picture (set to public://pictures/default.jpg at Configuration > People > Account settings) should be rendered.
I used the following code:
<?php $account = user_load($user->uid); ?>
<?php if (isset($account->picture->uri)) {
          $path = $account->picture->uri; }
      else {$path = "public://pictures/default.jpg"; } ?>
<?php $array = array('style_name' => 'picture',
                     'path' => $path,
                     'alt' => 'Picture'); ?>

<?php print theme('image_style', $array); ?>

That works perfectly, but I don't really like the isset approach, because it makes me think that it was redundant to specify the default image path in the configurations. Is there another method that uses the default path automatically?

A:

It's a bit of a strangled route - Drupal itself uses some conditionals in template_preprocess_user_picture() to make that decision:
if (!empty($account->picture)) {
  // @TODO: Ideally this function would only be passed file objects, but
  // since there's a lot of legacy code that JOINs the {users} table to
  // {node} or {comments} and passes the results into this function if we
  // a numeric value in the picture field we'll assume it's a file id
  // and load it for them. Once we've got user_load_multiple() and
  // comment_load_multiple() functions the user module will be able to load
  // the picture files in mass during the object's load process.
  if (is_numeric($account->picture)) {
    $account->picture = file_load($account->picture);
  }
  if (!empty($account->picture->uri)) {
    $filepath = $account->picture->uri;
  }
}
elseif (variable_get('user_picture_default', '')) {
  $filepath = variable_get('user_picture_default', '');
}

If it suits your use case, you can just set the user_picture_style variable to your style name, and use theme_user_picture():
$build = array(
  '#theme' => 'user_picture',
  '#account' => $user,
);
$picture = drupal_render($build);

The caveat is that user_picture_style is a global var, so if you want to use something different for the style used elsewhere in the site, you're stuck with reproducing the same logic as the preprocess function above.


Q:

MySQLdb - Check if row exists Python

I am trying to check if a row exist with the same Name my database with python and can't quite get it here is what I am trying: (I know the connection is wokring)
try:
    cursor.execute("SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name"), (item_name)
catch:
     print "it does not exist"

Can someone help me out here
Thanks

A:

First of all you have a wrong syntax in your code. Python doesn't have a try...catch block. It has try...except block which is used like this:
try:
    #something here
except:
    #something here

MySQL does not return an error when you use SELECT command. However there are two different ways you can find out if it returned something or not.

PYTHON 2.7
    cursor.execute(
        "SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
        (item_name,)
    )
    # gets the number of rows affected by the command executed
    row_count = cursor.rowcount
    print "number of affected rows: {}".format(row_count)
    if row_count == 0:
        print "It Does Not Exist"

PYTHON 3+
  cursor.execute(
        "SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
        (item_name,)
    )
    # gets the number of rows affected by the command executed
    row_count = cursor.rowcount
    print ("number of affected rows: {}".format(row_count))
    if row_count == 0:
        print ("It Does Not Exist")

Another way to do this would be to fetch the statement and check if it is empty:
#execute statement same as above
msg = cursor.fetchone()
# check if it is empty and print error
if not msg:
    print 'It does not exist'

This is my first answer, so I don't know how to style the code in the answer properly, it also seems messy because of that. Sorry for that.
Also i use Python 3 and pymysql, so there may be some syntax error but I have tried to write the code according to python 2.7 from what I could remember about it.
EDIT (5/1/2020)
Thanks to @Arishta for pointing out that the first method will require you to fetch all rows before using row_count. i.e adding cursor.fetchall() before the row_count = cursor.rowcount
cursor.execute(
    "SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
    (item_name,)
)
# Add THIS LINE
results = cursor.fetchall()
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print ("number of affected rows: {}".format(row_count))
if row_count == 0:
    print ("It Does Not Exist")

Use the cursor.fetchone() if you only care if the record exists or not.


Q:

Twitter share page does not open in an iframe

I'm trying to open the Twitter share URL http://twitter.com/share?url=http://google.com&text=Google using Highslide iframe http://highslide.com/ref/hs.objectType
But the Highslide popup has no content!
Anybody knows what seems to be the problem?

A:

The page has code specifically to prevent you from displaying it in a frame. The page is only made visible if it detects that it's not inside a frame.
So, you shouldn't put it in an iframe.


Q:

Dúvida sobre getSource() instanceof

Instanceof é um operador binário que testa se um objeto é o subtipo de um determinado tipo.
Ex:
Object fonte = e.getSource();
if (fonte instanceof JButton){
...
}

Se getSource() retornou informações de um JButton o resultado da expressão será true.
O que não entendo é o por que do retorno da expressão ser verdadeiro, já que o retorno do getSource() é do tipo objeto, então todo objeto é subtipo de JButton? Caso eu tenha:
Object fonte = e.getSource();
if (fonte instanceof JLabel){
...
}

Supondo que o getSource() agora retorne informações sobre um JLabel, como acontece a diferenciação já que fonte é sempre do tipo Object? Instanceof vai testar o contéudo de fonte?

A:

Isso se chama polimorfismo. E todo objeto implicitamente herda de Object. Entendendo polimorfismo, respondera sua dúvida.
Não entrando em detalhes sobre polimorfismo,
como ja sabemos que todo objeto herda de Object,
então por polimorfismo um objeto do tipo Object pode receber(guardar referencia) de qualquer outro objeto, e é isso que está acontecendo.
E quando você faz a verificação com instanceof a jvm em tempo de execução verifica a classe do objeto que está sendo verificada.(ou seja, verifica qual classe foi instanciado esse objeto, se foi instanciada como JButton, JList, etc.)


Q:

Bird effect using Javascript and HTML5

Please can someone suggest me a way to use the birds effect in the below website in some other website?? I am only concerned about the birds and nothing related to maps and other features in this website
www.thewildernessdowntown.com

A:

I believe those are Boids, a method for simulating group animal motion developed by Craig Reynolds (start reading here for background).
You can then look at the work of Daniel Shiffman, who has done a lot of fun things with Boids, including this tutorial on making a simple 2D Boid system in javascript.
Once you understand these basics you can Google around to see how other people have used tools like Three.js (which that example you linked to uses) and the Boid concept. For example this guy made an aquarium using Boids and Three.js and helpfully guides you to his source code on Github.
As for the actual birds, I imagine they are made up of a Three.js container Object3D which holds a body and two wings (which look like they are made of either planes-with-bitmaps or just raw triangles). The wings constantly rotate up and down, and the container object just rotates to point in whichever direction the Boid logic is taking it.
That is my educated guess anyway, and would be how I would recreate it.


Q:

If current page URL equals X OR X?

I found this code on the internetz, it checks the current page url;
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}

So now I can do something like this;
elseif (curPageURL() == "http://www.example.com/pageexample") {
<meta tags here>
}

Great. But I would also like to use this for pagination pages. Those URLs look like this:
http://www.example.com/pageexample?start=30&groep=0
http://www.example.com/pageexample?start=60&groep=0
http://www.example.com/pageexample?start=90&groep=0
[....]
http://www.example.com/pageexample?start=270&groep=0

I could use a if statement for every of those links.. but I would much rather like to use one. Is it possible to add a wildcard or something? Like this I guess (notice the *)
elseif (curPageURL() == "http://www.example.com/pageexample" OR curPageURL() == "http://www.example.com/pageexample?start=*&groep=0") {

edit: I would like to do this for all those URLs because I want to give them the same meta description, <title> and <link rel="canonical". I could do this manually by doing an if-statement for every page (10+ atm) but I figured there was a better way.

A:

Why not just use the parse_url() function?  From the manual page:
<?php

$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));

?>

// The above would print
Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

For your particular case, you could then just check against the host and path variables.

A:

Sounds a lot like regex problem:
if (preg_match("#^http://www.example.com/pageexample(\?start=[^&]*&groep=0)?#", curPageURL())) {
    // it matches
}

The expression [^&]* acts like your *.; to match non-empty items, use[^&]+`. It matches these:
http://www.example.com/pageexample
http://www.example.com/pageexample?start=30&groep=0

Update
It's not entirely clear why you need to compare against the full canonical URL, unless you have multiple domains point to the same code base.


Q:

Boost C++ and Android 3

I tried to google and SO search. So far I was able to find only conflicting information. If it is too hard to marry Boost and Android, maybe there are replacements? I am especially interested in smart_ptr, threads, function, lexical_cast, string_algo and containers. Any input is appreciated. Thank you.

A:

Have a look at this project: https://github.com/MysticTreeGames/Boost-for-Android

Boost for android is a set of tools to compile the main part of the
  Boost C++ Libraries for the Android platform.
To compile Boost for Android you may use the customized NDK r4b
  provided by Dmitry Moskalchuk aka CrystaX. Or you may download
  official NDK r5c.

Since it was written NDK r6 have been released by Google (and customized by CrystaX). Thus I suggest you to build "Boost for Android" against the latest NDK r6 from CrystaX, as described on its site:

./build-android.sh crystax/ndk/root
This command will download and build boost against the Crystax NDK and output the final header and libs and in the build folder.
Now that you got boost compiled you must add it to your Android.mk file. First copy the the include and lib folder over to your jni folder. I copied it just into: /jni/boost/.
Add the following to your Android.mk:
LOCAL_CFLAGS += -I$(LOCAL_PATH)/boost/include/
LOCAL_LDLIBS += -L$(LOCAL_PATH)/external/boost/lib/ -lboost_system -lboost_...

LOCAL_CPPFLAGS += -fexceptions
LOCAL_CPPFLAGS += -frtti


Q:

Put all occurences in the String in quotes using regex in python

I hava a long string were I can find something like this data() { <some data which is always different here> } I want to put all occurences in quotes. This is what I'm doing but it has no effect:
string = re.sub(r'data \(\) {(.*)}', r'"/1"', string)

I suppose there should be something different between curly brackets but I have no idea what...
@EDIT
I realized my String look like this:
data() {
  <some white spaces> here is text
<some white spaces> }

A:

Whitespace matters, the direction of slashes matters (thanks Wiktor, I overlooked that before) and that quantifier should probably be lazy. Also, if there are newlines within your text, you need to allow for that
string = re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string)

Testing it on your sample text:
In [4]: string = """data() {
   ...:   <some white spaces> here is text
   ...: <some white spaces> }"""

In [5]: print(re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string))
"
  <some white spaces> here is text
<some white spaces> "


Q:

CSS Selector - how to select the first and last div

I am having trouble selecting the first and last div for the following html markup:

                  yoyoyoyoyoyoy

                  yoyoyoyoyoyoy

                  yoyoyoyoyoyoy

                  yoyoyoyoyoyoy

                  yoyoyoyoyoyoy

                  yoyoyoyoyoyoy

I am trying to select and style only the id1 div header without explicitly selecting it using the div id. I tried using the div:first-child selector, but all of the divs are being selected! This is what I tried, along with using nth-child(1)
.layout__side .portlet-dropzone div:first-child header{
    padding: 10px;
    border: 1px solid red;
}

A:

The problem is that you're selecting all div descendant elements that are a first child.
In other words, the descendant div elements .portlet-borderless-container, .portlet-body, and .inner are selected (since they are descendants of .portlet-dropzone and they are the first child relative to their parent element). Since all the div elements are selected, each header element is thereby selected and styled.
You need to select the direct child div element instead (by using the direct child combinator, >). In doing so, only the div element that is a direct child of .portlet-dropzone will be selected if it is the first child.
Example Here
.layout__side .portlet-dropzone > div:first-child header {
    padding: 10px;
    border: 1px solid red;
}

As your title suggests, if you also want to select the last one:
Updated Example
.layout__side .portlet-dropzone > div:first-child header,
.layout__side .portlet-dropzone > div:last-child header  {
    padding: 10px;
    border: 1px solid red;
}

It's also worth pointing out that there are :first-of-type and :last-of-type pseudo classes which will select the first/last element by type (unlike :first-child/:last-child which will select based on the index only rather than the type).
Updated Example
.layout__side .portlet-dropzone > div:first-of-type header,
.layout__side .portlet-dropzone > div:last-of-type header  {
    padding: 10px;
    border: 1px solid red;
}

This may be useful if there are elements of varying types and you only want to target the div elements. For instance, if there was a random h1 element before the first div, like in the example above, the first div would still be selected.


Q:

HTML Body CSS Transform Scaling Up causing content to be removed

I am working on a project where I am using CSS transform to scale up the whole body of a page. After scaling up a bit, content from corners start becoming un-viewable because they are outside visible ranges. Is there a way for the content to still be viewable by scrolling vertically or horizontally using transform scaling?
I am currently using Javascript to scale up the body like so
document.body.style.transform = 'scale(1.5)';

However, this cuts off some content from pages. I need it to work as I continue scaling up from 1.0.

A:

Try adjusting the transform-origin:
document.body.style.transformOrigin = 'top left';
document.body.style.transform = 'scale(' + scaleFactor + ')';

You may also need to adjust the width and height of the body to match the scaling.
var scaleFactor = 1.5;
document.body.style.transformOrigin = 'top left';
document.body.style.transform = 'scale(' + scaleFactor + ')';
document.body.style.width = 100 * scaleFactor + "%";
document.body.style.height = 100 * scaleFactor + "%";

A note concerning transforms. Transforms are imaginary and don't alter physical dimensions including x, y, width and height. So you'll have to manage these physical dimensions manually to match your "transform'd" dimensions in order to keep the scroll bars happy.


Q:

How to compare extracted digits in C++

I'm trying to implement the Bulls & Cows game and I have a logic problem. I am explicitly checking if each digit is either equal to a digit in the corresponding index (bulls) or at other indexes (cows).  The value that I check with (4321) should yield "0 bulls and 4 cows" but it instead gives me "0 bulls and 3 cows.
Here is my code (and I apologize for the code repetition. I am also wondering if anyone has recommendations to make this code smaller):
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int guessValue = 1234;
    int guess;

    int bulls = 0;
    int cows = 0;

    cout << "Enter a 4 digit guess: ";
    cin >> guess;

    int firstValue = (guess % 10000) / 1000;
    int secondValue = (guess % 1000) / 100;
    int thirdValue = (guess % 100) / 10;
    int fourthValue = guess % 10;

    if (firstValue == ((guessValue % 10000) / 1000)) {bulls += 1;}
    else if(firstValue == ((guessValue % 1000) / 100) ||
            firstValue == ((guessValue % 100) / 10) ||
            firstValue == (guess % 10))
            {cows += 1;}

    if (secondValue == ((guessValue % 1000) / 100)) {bulls += 1;}
    else if (secondValue == ((guessValue % 10000) / 1000) ||
             secondValue == ((guessValue % 100) / 10) ||
             secondValue == (guess % 10))
             {cows += 1;}

    if (thirdValue == ((guessValue % 100) / 10)) {bulls += 1;}
    else if (thirdValue == ((guessValue % 10000) / 1000) ||
             thirdValue == ((guessValue % 1000) / 100) ||
             thirdValue == (guess % 10))
             {cows += 1;}

    if (fourthValue == (guessValue % 10)) {bulls += 1;}
    else if (fourthValue == ((guessValue % 10000) / 1000) ||
             fourthValue == ((guessValue % 1000) / 100) ||
             fourthValue == (guessValue % 100) / 10)
             {cows += 1;}

    cout << bulls << " bulls and " << cows << " cows" << endl;
}

A:

2 concepts that absolutely you need to master: loops and functions. First create some helpful functions.
These are the functions you could built your program upon:
int get_digit(int number, int order)

with example test cases:
get_digit(7895, 0) == 5
get_digit(7895, 1) == 9
get_digit(7895, 2) == 8
get_digit(7895, 3) == 7

then:
bool has_digit(int number, int digit)

with example test cases:
has_digit(7895, 1) == false
has_digit(7895, 8) == true
has_digit(7895, 5) == true
has_digit(7895, 0) == false
has_digit(7000, 0) == true

then:
bool matches_digit(int a, int b, int order)

with test cases:
matches_digit(1239, 4269, 0) == true
matches_digit(1239, 4269, 1) == false
matches_digit(1239, 4269, 2) == true
matches_digit(1239, 4269, 2) == false

and finally:
int get_cow(int a, int b)
int get_bull(int a, int b)
int main()

This is a top-down design, bottom-up implementation approach. First you think of the big picture and figure out what small pieces you need (functions) and then start implementing from the smallest most independent functions and step by step combine then into higher functions until you reach main.


Q:

$f$ is an unbounded monotonic increasing function: $\lim \limits_{x \to \infty} \frac{1}{x}\int_{0}^{x}f(t)dt=\infty$

This is not homework.
I'd love your help proving that if  $f$ is an unbounded monotonic increasing function, then $$\lim_{x \to \infty} \frac{1}{x}\int_{0}^{x} \ f(t)\, dt=\infty.$$ I want to use it in a couple of proofs, but I can't prove it by myself.
Thanks a lot.

A:

You need to assume that the integral $\int_0^x f(t) dt$ is always finite ; it can be possible that it is $-\infty$, because $f$ might go to $-\infty$ when $x \to 0^+$ and this might cause problems. Assume that the integral from $0$ to some point $a$ is finite, so that we don't have any problems. Thus without loss of generality we can assume that $f$ is positive, because at some point $c$, $f(x)$ must be positive for all $x > c$ and we can separate the integral in two parts : the one before $c$ and the one after. Since the integral from $0$ to $c$ will be finite, we have that
Then
$$
\frac 1x \int_c^x f(t) dt \ge \frac 1x \int_{x/2}^x f(t) \, dt \ge \frac {(x/2) f(x/2)}{x} = \frac {f(x/2)}2 \to \infty.
$$
Hope that helps,

A:

I think the l'Hôpital's rule may be helpful here if your $f$ satisfies the requirements of the rule. And say the antiderviative of $f$ is $F(x)$, then
$$ \lim_{x\to\infty}\frac{1}{x}\int_{0}^{x}f(t)dt = \lim_{x\to\infty}\frac{F(x) - F(0)}{x} = \lim_{x\to\infty}f(x) .$$
Since your tag is calculus, not something like real analysis, I assume your function is a relatively normal function involving Riemann integral.


Q:

How to populate a dropdown menu using JavaScript on multiple rows

Am trying out an invoice generation system from, https://www.phpzag.com/build-invoice-system-with-php-mysql/. Demo on https://phpzag.com/demo/build-invoice-system-with-php-mysql-demo/create_invoice.php. Everything works just fine but the fields given as examples are just input fields. However, I need to use select options from my mysql database. The fields given in the “htmlRows” are supposed to be added as much as when the user wants using the add buttons in the html form. I have created a separate function for pulling the products from the database and now I don’t know why they are not being populated in the option values on the “htmlRows”.

load.php
            case 'products':
            try
            {
                require_once("connect.php");

                $sql="CALL sp_getProducts()";
                $pdo = new PDOConfig();
                $resultset = $pdo->query($sql);
                foreach($resultset as $row)
                        {
                          $data[] = array(
                                  'id' => $row['ProductID'],
                                  'display' => $row['ProductDetails']
                                  );
                        }
                echo json_encode($data);

            }
                catch(PDOException $e) {
                        die("Could not connect to the database\n");

            }

            break;

A:

Replace your javascript code with following:


Q:

Recursively differentiating basic expression

If I have an expression, such as x * x * x, stored in a data structure like: mult(var x, mult(var x, var x))
And I want to implement a function to recursively differentiate the equation (so to 3 * x * x or x*x + (x + x)*x etc, no simplification required), any suggestions how to being this?

A:

You would find a matching differentiation rule and apply it. For example in this case we have the rule (where A and B stand for whole subexpressions)
diff(mult(A, B)) -> add(mult(diff(A),B), mult(A, diff(B)))

The left hand side of this rule matches the formula when we set
A = var x
B = mult(var x, var x)

So we can apply this rule to the formula and get
diff(mult(var x, mult(var x, var x))) ->
  add(mult(diff(var x),mult(var x, var x)), mult(var x, diff(mult(var x, var x))))

Now do the same recursively for the remaining diff operations.
The other other rule you will need here is:
diff(var x) -> 1


Q:

How to programmatically set up fallback font in Java?

I wanted to localize my app to my Tamil language. I was disappointed that Java supports only Hindi out of all Indian Languages "out of the box."
I searched the internet for some workaround. I learnt from John O'Conner's blog post and Naotoj Sato's blog post that I've to use a technique called "Font Fallback."
I manually copied the "LATHA.TTF" Tamil font available for Windows to /jre/lib/fonts/fallback directory.
It worked! But how can I copy the font programmatically to my users' /jre/lib/fonts/fallback directory?
I thought to add a code that will copy the included font to that fallback directory during the first launch and if it is not already there. Will it cause any permission problems like "Write access denied" to that folder or something?
Or is there a way to make the app search for the fallback font to application directory instead of /jre/lib/fonts/fallback?
Note that the app will have to use this LATHA font only when Tamil language is selected and default font for all other languages.
Please give your opinions.

A:

There seems to be no way to programmatically copy the fallback font to jre if it is in system location without admin rights. It works only if the jre is in some other location. So I have finally decided to put a readme file asking users to copy the font manually if they want it. Expecting Java to support Tamil by default soon.
Hope this will be useful for anyone searching for something like this.


Q:

Android SD card storing checking using Emulator

I am storing the information in a file in SD card in Android applicaiton. Can i check in emulator whether the information is correctly storing in sd card?

A:

Try this way:

First u need to Run your App.
Then Goto Window->ShowView->File Explorer
open File Explorer tab on right hand side.
expand tree structure. mnt/sdcard/
Select your File and on TopMost bar of File Explorer, u will find two buttons for 'Pull/Push a File from Device'. Select that.

And it will be on your computer. Hope it is what you want.


Q:

GULP Failed with error on VSTS?

While performing build on VSTS Gulp operation fails with an error:
"Gulp failed with error: C:\NPM\Modules\gulp.cmd failed with return code: 1"
I have configured my project on VSTS as you can see in the screenshot attached below along with the log file.
The following is the error log:
 2017-11-22T09:30:58.3245047Z ##[debug]Evaluating condition for step: 'gulp '
    2017-11-22T09:30:58.3245047Z ##[debug]Evaluating: succeeded()
    2017-11-22T09:30:58.3245047Z ##[debug]Evaluating succeeded:
    2017-11-22T09:30:58.3245047Z ##[debug]=> (Boolean) True
    2017-11-22T09:30:58.3245047Z ##[debug]Expanded: True
    2017-11-22T09:30:58.3245047Z ##[debug]Result: True
    2017-11-22T09:30:58.3245047Z ##[section]Starting: gulp
    2017-11-22T09:30:58.3255058Z ==============================================================================
    2017-11-22T09:30:58.3255058Z Task         : Gulp
    2017-11-22T09:30:58.3255058Z Description  : Node.js streaming task based build system
    2017-11-22T09:30:58.3255058Z Version      : 0.5.31
    2017-11-22T09:30:58.3255058Z Author       : Microsoft Corporation
    2017-11-22T09:30:58.3255058Z Help         : [More Information](https://go.microsoft.com/fwlink/?LinkID=613721)
    2017-11-22T09:30:58.3255058Z ==============================================================================
    2017-11-22T09:30:58.3265054Z ##[debug]tf vc resolvePath "$\VisitReport_Br\Client Components\Main\Source\vr20-11.1\vr20-11.1\gulpfile.js" /loginType:OAuth /login:.,******** /noprompt
    2017-11-22T09:30:58.8355028Z ##[debug]d:\a\3\s\gulpfile.js
    2017-11-22T09:30:58.8535002Z ##[debug]tf vc resolvePath "$\VisitReport_Br\Client Components\Main\Source\vr20-11.1\vr20-11.1" /loginType:OAuth /login:.,******** /noprompt
    2017-11-22T09:30:59.3974984Z ##[debug]d:\a\3\s
    2017-11-22T09:31:00.2756125Z ##[debug]agent.workFolder=d:\a
    2017-11-22T09:31:00.2796114Z ##[debug]loading inputs and endpoints
    2017-11-22T09:31:00.2806186Z ##[debug]loading ENDPOINT_AUTH_PARAMETER_SYSTEMVSSCONNECTION_ACCESSTOKEN
    2017-11-22T09:31:00.2826125Z ##[debug]loading ENDPOINT_AUTH_SCHEME_SYSTEMVSSCONNECTION
    2017-11-22T09:31:00.2826125Z ##[debug]loading ENDPOINT_AUTH_SYSTEMVSSCONNECTION
    2017-11-22T09:31:00.2836118Z ##[debug]loading INPUT_CWD
    2017-11-22T09:31:00.2836118Z ##[debug]loading INPUT_ENABLECODECOVERAGE
    2017-11-22T09:31:00.2836118Z ##[debug]loading INPUT_GULPFILE
    2017-11-22T09:31:00.2846108Z ##[debug]loading INPUT_GULPJS
    2017-11-22T09:31:00.2846108Z ##[debug]loading INPUT_PUBLISHJUNITRESULTS
    2017-11-22T09:31:00.2846108Z ##[debug]loading INPUT_TESTFILES
    2017-11-22T09:31:00.2846108Z ##[debug]loading INPUT_TESTFRAMEWORK
    2017-11-22T09:31:00.2856108Z ##[debug]loading INPUT_TESTRESULTSFILES
    2017-11-22T09:31:00.2856108Z ##[debug]loaded 11
    2017-11-22T09:31:00.2856108Z ##[debug]check path : d:\a\_tasks\Gulp_b82cfbe4-34f9-40f5-889e-c8842ca9dd9d\0.5.31\task.json
    2017-11-22T09:31:00.2866123Z ##[debug]set resource file to: d:\a\_tasks\Gulp_b82cfbe4-34f9-40f5-889e-c8842ca9dd9d\0.5.31\task.json
    2017-11-22T09:31:00.2866123Z ##[debug]system.culture=en-US
    2017-11-22T09:31:00.2916104Z ##[debug]gulpFile=d:\a\3\s\gulpfile.js
    2017-11-22T09:31:00.2926117Z ##[debug]check path : d:\a\3\s\gulpfile.js
    2017-11-22T09:31:00.2976112Z ##[debug]gulp=C:\NPM\Modules\gulp.cmd
    2017-11-22T09:31:00.2986113Z ##[debug]enableCodeCoverage=false
    2017-11-22T09:31:00.2986113Z ##[debug]publishJUnitResults=false
    2017-11-22T09:31:00.2986113Z ##[debug]testResultsFiles=d:\a\3\s\**\TEST-*.xml
    2017-11-22T09:31:00.2996115Z ##[debug]cwd=d:\a\3\s
    2017-11-22T09:31:00.3006117Z ##[debug]path exists: d:\a\3\s
    2017-11-22T09:31:00.3006117Z ##[debug]check path : C:\NPM\Modules\gulp.cmd
    2017-11-22T09:31:00.3026103Z ##[debug]targets=null
    2017-11-22T09:31:00.3026103Z ##[debug]C:\NPM\Modules\gulp.cmd arg: []
    2017-11-22T09:31:00.3026103Z ##[debug]C:\NPM\Modules\gulp.cmd arg: --gulpfile
    2017-11-22T09:31:00.3036112Z ##[debug]C:\NPM\Modules\gulp.cmd pathArg: d:\a\3\s\gulpfile.js
    2017-11-22T09:31:00.3036112Z ##[debug]C:\NPM\Modules\gulp.cmd arg: d:\a\3\s\gulpfile.js
    2017-11-22T09:31:00.3036112Z ##[debug]arguments=null
    2017-11-22T09:31:00.3046108Z ##[debug]exec tool: C:\NPM\Modules\gulp.cmd
    2017-11-22T09:31:00.3046108Z ##[debug]Arguments:
    2017-11-22T09:31:00.3046108Z ##[debug]   --gulpfile
    2017-11-22T09:31:00.3046108Z ##[debug]   d:\a\3\s\gulpfile.js
    2017-11-22T09:31:00.3046108Z [command]C:\NPM\Modules\gulp.cmd --gulpfile d:\a\3\s\gulpfile.js
    2017-11-22T09:31:02.0185156Z [09:31:02] Local gulp not found in d:\a\3\s
    2017-11-22T09:31:02.0185156Z [09:31:02] Try running: npm install gulp
    2017-11-22T09:31:02.0305468Z ##[debug]rc:1
    2017-11-22T09:31:02.0305468Z ##[debug]success:false
    2017-11-22T09:31:02.0365138Z ##[debug]taskRunner fail
    2017-11-22T09:31:02.0375154Z ##[debug]task result: Failed
    2017-11-22T09:31:02.0475149Z ##[error]Gulp failed with error: C:\NPM\Modules\gulp.cmd failed with return code: 1
    2017-11-22T09:31:02.0475149Z ##[debug]Processed: ##vso[task.issue type=error;]Gulp failed with error: C:\NPM\Modules\gulp.cmd failed with return code: 1
    2017-11-22T09:31:02.0545148Z ##[debug]Processed: ##vso[task.complete result=Failed;]Gulp failed with error: C:\NPM\Modules\gulp.cmd failed with return code: 1
    2017-11-22T09:31:02.0555145Z ##[section]Finishing: gulp

The screenshot of the error is:

The contents of my package.json files are as follows:
"devDependencies": {
      "karma": "^0.13.0",
      "karma-jasmine": "^0.3.6",
      "karma-chrome-launcher": "^0.2.0",
      "gulp": "^3.9.0",
      "jasmine-core": "^2.8.0",
      "karma-edge-launcher": "^0.4.2"
    }

A:

The reason is that you don’t install Gulp in the same folder of gulpfile.js. I think package.json file is not in the same folder of gulpfile.js file.
Since the gulpfile.js file is in the source directory, you can add npm task (working folder: $(build.sourcesdirectory); npm command: install; arguments: gulp)


Q:

I am using this code on popup window.in this code data insert into database

I am using this code on popup window.in this code data insert into database,validation is work and success message is also display but i want display error message on pop up and reset the form Pls help me how to fix this...
     <script type="text/javascript">
     $(document).ready(function(){
    $("#insert").click(function(){

    var OPRID=$("#OPRID").val();
    var OPRNAME=$("#OPRNAME").val();
    var OPERPSWD=$("#OPERPSWD").val();
    var OPRTYPE=$("#OPRTYPE").val();
    var PHONENO=$("#PHONENO").val();
    var ACCTLOCK=$("#ACCTLOCK").val();
    var ENCRYPTED=$("#ENCRYPTED").val();

   if (OPRID==null || OPRID=="")
   {
    alert("Operator Id must be filled out");
    return false;
    }
    if (OPRNAME==null || OPRNAME=="")
   {
    alert("Operator Name must be filled out");
    return false;
    }
    if (OPERPSWD==null || OPERPSWD=="")
     {
   alert("Password must be filled out");
   return false;
     }
   if (OPRTYPE==null || OPRTYPE=="")
   {
   alert("Operator Type must be filled out");
   return false;
    }
  if (PHONENO==null || PHONENO=="")
   {
   alert("Phone Number must be filled out");
    return false;
     }
  else{

  $.post('insert_opr.php',
    {OPRID: OPRID,OPRNAME: OPRNAME,OPERPSWD: OPERPSWD, OPRTYPE:
    OPRTYPE,PHONENO:PHONENO,ACCTLOCK:ACCTLOCK,ENCRYPTED:ENCRYPTED},

   function(data){
   $("#message").html(data);
   $("#message").hide();
    $("#message").show().fadeOut(5000);
    $('#myForm')[0].reset();

    });
   }
  return false;
  });
  });

A:

You can use associative array and convert the same to json object and return json object from function. Also in ajax post method you have to add one more argument as below
$.post('insert_opr.php',
{OPRID: OPRID,OPRNAME: OPRNAME,OPERPSWD: OPERPSWD, OPRTYPE:
OPRTYPE,PHONENO:PHONENO,ACCTLOCK:ACCTLOCK,ENCRYPTED:ENCRYPTED},

function(data){
if(data.status == "error")
{
$("#message").html(data.message);
$("#message").hide();
$("#message").show().fadeOut(5000);
$('#myForm')[0].reset();
}
if(data.status == "success")
{
 //your success code goes here
}
}, 'json');

You can return the json object as follows :
$data = array( 'status' => 'error' , 'message'  => 'error message' );
echo json_encode($data);

Likewise you can return success message with status as success.


Q:

Simplify quotient rings

I still struggle with elementary knowledge about quotient rings.
For example, why can I just write down the second following isomorphism:
$$\frac{\mathbb{C}[x, y, z]}{(x^2 + y^2 - 1, y \pm iz)} \simeq \frac{\frac{\mathbb{C}[x, y, z]}{(y \pm iz)}}{\frac{(x^2 + y^2 - 1,y \pm iz)}{(y \pm iz)}} \simeq \frac{\mathbb{C}[x, y]}{(x^2 + y^2 - 1)} $$
I know the first isomorphism is right by the third isomorphism theorem. But why can I write down the second one?

A:

It follows from the first isomorphism theorem for rings, like this:

Suppose $\phi: R\to S$ is any injective ring homomorphism. Then $R/I\cong \phi(R)/\phi(I)$ as rings.
Proof:
  Let $\psi: R\to \phi(R)/\phi(I)$ be given by $\psi(r)=\phi(r) + \phi(I)$. It can be checked that this is a ring homomorphism.
Moreover, its kernel is precisely $I$. Just chase it down: $\psi(r)=0+\phi(I)$ iff $r-i\in \ker \phi$, and $\phi$ was injective so...

Now, it's fairly obvious that there is an isomorphism between the rings in the "numerators" of the latter half, and the denominator of the second quotient is the image of the denominator in the first quotient, so you can apply this lemma above.


Q:

Convert list of id to Object using AutoMapper

I have objects :
class Group {
    public string GroupName ;
    public List<Access> Details ;
}

Class Access {
     public int Id;
     public string Name;
}

Now I have a Dto like:
Class GroupDto
{
    string GroupName;
    List<int> Details ;
}

User can create/send GroupDto and converted to Group before saving.
how to define the MappingProfile for this ?

A:

In your mapping profile just use MapFrom method and let AutoMapper know how to get the data like below:
CreateMap<Group, GroupDto>()
    .ForMember(
        destination => destination.Details,
        options => options.MapFrom(
            source => source.Details.Select(detail => detail.Id).ToList()
        )
    );

Side Note: please expose a property instead of field like you did in your sample. Also make sure that properties on GroupDto class are public too.


Q:

How do ISO standards work (particularly ISO 9126)

I'm taking a course in software project management and right now I'm writting a "quality plan"... We've discussed ISOs in class, and I would particularly like my fake company to say the project complies with ISO norm 9126.
The thing is I don't really know what that means. Is it just something you say to your client, does your company need to be affiliated under some international organization for standard compliance, do you have to have your project audited? How does it work?
By the way, if you have any tips on what I can say I'll do to guarantee project quality, just tell me.
Edit I know what ISO 9126 is, what I don't know is who's is responsibly to certify you, how do auditory works, or if auditory is at all necessary (if the project is small does it suffices to show the client you met the goals you talked about when applying ISO 9126?)

A:

ISO qualification is all about making sure your company does everything in it's power to ensure a quality product.   Quality is a broad term, but in actuality, what an auditor usually looks for to see if your company is ready to be ISO certified, is that mechanisms are in place to guarantee that a product does does what you designed it to do, and that you have verified that before your product leaves the door.
These mechanisms can be all sorts of things... but really start with a design plan (a list of WHAT your product will do), and a test procedure/list (to see if your final product/output does what the design plan says the product will do when it is complete).   A lot of companies have things in place between these two steps, but the input/output steps are most critical.
Does your shipped product do what you designed it to do?
An auditor has to come in to certify you. There are various companies that do this. You can not simply say you are "ISO 9xxx certified". The auditor will give you a certificate. There are different types of ISO certification. And even after the certification, you get re-audited to keep your certification. The goal being that your product and the processes that guarantee its quality improve over time.


Q:

running of out of memory android?

I made custom gallery app with gallery view and image view.its working nice in 4.2 devices,but its getting force closes in 2.3.3
    myHorizontalListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View arg1,
                int position, long id) {
            // if (lastview != null)
            // lastview.setBackgroundColor(0xFFFFFFFF);
            // lastview = arg1;
            // arg1.setBackgroundColor(0xFFFF0000);
            ImageView imageView = (ImageView) findViewById(R.id.image);
            p=position;

            imageView.setBackgroundResource(itemsArray[position]);}}

i think this code caused running out of memory,because every time i am setting new picture under old picture
                 imageView.setBackgroundResource(itemsArray[position])

A:

Reload ur image in imageview in smaller size
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html


Q:

Find the order of an element of finite group

Let $G$ be a finite group and $g,h\in G-\{1\}$ such that $g^{-1}hg=h^2$.
In addition $o(g)=5$ and $o(h)$ is an odd integer. Find $o(h)$.
I know from a previous exercise that if there exists a natural number $i$ such that $g^{-1}hg=h^i$ then for all $n\in \mathbb{N}$, $g^{-n}hg^n=h^{i^n}$.
I thought I could use this fact somehow, but so far no luck.
Please give me a hint.

A:

Square both sides
$$
g^{-1}h^2 g = h^4
$$
Now replace $h^2$
$$
g^{-1}(g^{-1} h g) g  = g^{-2} h g^2 = h^4
$$
Again square and expand
$$
g^{-3}hg^3 = g^{-2}h^2g^2 = h^8.
$$
By repeating this process we find
$$
g^{-k} h g^k = h^{2^k}
$$
for $k>0$
so in particular
$$
h = g^{-5}hg^5 = h^{32}.
$$
Hence $h^{31} = 1$. Thus $O(h)$ divides $31$. But $31$ is prime, so $O(h) = 1$ or $O(h) = 31$. Since we assumed $h \neq 1$, we find $O(h) = 31$.
Note here that the given information $O(h)$ is an odd integer was an unnecessary assumption. We could immediately see this by noting that the order of $h$ and any conjugate, e.g. $g^{-1}h g = h^2$, are the same. Thus $h,h^2$ have the same order, so $2$ is not a divisor of $O(h)$.

A:

try finishing off this line of argument...
$$
\begin{align}
h &= ehe \\&= g^{-5}hg^5 \\&= g^{-4} (g^{-1}h g) g^4 \\&= g^{-4}h^2 g^4
\\&=g^{-3}(g^{-1}h^2g)g^3 \\&=g^{-3}h^4g^3 \\&= \dots \\&=h^?
\end{align}
$$
so $h^{?-1}=e$


Q:

What is the symbolism of Atticus killing the mad dog?

So in To Kill A Mockingbird, Atticus kills a mad dog. He does it with one shot.
Is there some more symbolism to this or is it just an event?

A:

This scene is meant to reveal more about Atticus to Scout.  When he kills the mad dog--and does so expertly, with one shot--it shows Scout that there is more to him than a lawyer and a father.  He knows how to shoot and he's good at it.

“Take him, Mr. Finch.” Mr. Tate handed the rifle to Atticus; Jem and I nearly
  fainted.

This illustrates my point well; Jem and Scout have no idea about him, really.  This also develops Atticus's character for the reader.  He can shoot and he's good at it, but he hates to and he hasn't in thirty years.  It can also be seen as a symbol for the entire Tom Robinson trial.

A:

It foreshadows the death of Ewell in a way:

When the dog, who has been around for a long time, becomes a real threat to the children, the shooting skills of Atticus, which haven't been seen for many years, reveals itself to deal with the threat.
When Bob Ewell, who also has been around for a long time, becomes a real threat to the children, Boo Radley, who hasn't been seen for many years, reveals himself to deal with the threat.


Q:

With Google Kubernetes Engine is it possible to have a multi zone master cluster with a single zone node pool?

I want to have masters in multiple zones and then attach node pools confined to a single zone, so I can take advantage of the different gpu accelerator types in the different zones. Whenever I try to create a cluster in multiple zones it replicates my nodes in each zone. This is really wasteful for me, because I only need one gpu at a time.

A:

No, this isn't possible since regional clusters are expected to work like that. If you deploy a regional cluster all zones should be the same. So to achieve your workload, you could deploy one node-pool with a GPU attached and make a regional node-pool without any GPU attached.


Q:

Writing a continuous function of bounded variation as the sum of a singular function and an absolutely continuous function.

A function $\varphi[a,b] \to \mathbb{R}$ is said to be singular if

$\varphi \in C[a,b]$ (i.e., $\varphi$ is continuous on $[a,b]$),
$\varphi'(x)$ exists a.e. in $[a,b]$,
$\varphi'(x)=0$ a.e. in $[a,b]$.

Let $f$ be continuous on $[a,b]$ and of bounded variation on $[a,b]$.
Prove that there is an absolutely continuous function
$F: [a,b] \to \mathbb{R}$ and a singular function
$\varphi: [a,b] \to \mathbb{R}$ such that $f = F + \varphi$.

A:

Any function of bounded variation is  a difference of two monotone increasing functions. Just note that linear combinations of absolutely continuous functions are absolutely continuous  and linear combinations of singular continuous functions are singular.


Q:

Returning a Pointer to a Multidimensional Array

I'd like to use the following function to return a transposed pointer to a multidimensional array.
Code
float** Matrix3f::Transpose( void )
{

    float matrix[MATRIX3_DIMS][MATRIX3_DIMS] =
    {
        { mMatrix[ 0 ][ 0 ], mMatrix[ 1 ][ 0 ], mMatrix[ 2 ][ 0 ] },
        { mMatrix[ 0 ][ 1 ], mMatrix[ 1 ][ 1 ], mMatrix[ 2 ][ 1 ] },
        { mMatrix[ 0 ][ 2 ], mMatrix[ 1 ][ 2 ], mMatrix[ 2 ][ 2 ] }
    };

    float** ret = new float*[ MATRIX3_DIMS ];

    for ( int i = 0; i < MATRIX3_DIMS; i++ )
    {
        for ( int j = 0; j < MATRIX3_DIMS; j++ )
        {
            ( *ret )[ i ][ j ] = matrix[ i ][ j ];
        }
    }

    return ret;

}

Description
As shown, I declare a multidimensional array using initialization syntax(using the class-member matrix - mMatrix - to create a transposed version of the matrix itself. I then assign a multidimensional pointer to an array (ret) and loop through, assigning each member of the local array - matrix - to the ret pointer array.
The error I receive is the following:
error: invalid types ‘float[int]’ for array subscript

Question
What exactly am I doing wrong, and how can I accomplish this task?

A:

ret is a pointer to pointer to float.  When you dereference it, like this: (*ret), you get a pointer to float.  When you take an index on that, like this: ( *ret )[ i ], that gives you a float.  When you take an index on that, like this: ( *ret )[ i ][ j ], well, you're trying to index off of a float.  That's not legal.
Putting my disgust for this style of coding aside, the first thing you're doing wrong is you are not allocating the sub-arrays.  The compiler error though, refers to the error I illustrated in the first paragraph.  Just remove the dereferencing of ret to fix that.  You end up with this:
for ( int i = 0; i < MATRIX3_DIMS; i++ )
{
    ret[i] = new float[MATRIX3_DIMS];
    for ( int j = 0; j < MATRIX3_DIMS; j++ )
    {
        ret[ i ][ j ] = matrix[ i ][ j ];
    }
}

This is totally not exception safe though, and you should be using a class that properly manages memory in an exception safe way, like std::vector.


Q:

Looking ahead to Wolfram Language

Wolfram has been making some big announcements lately regarding Wolfram Language which seems--for the most part--to be Mathematica-"language" accessible from other interfaces. Browsing through the documentation, I see some new functions and ideas (ex: Association) that we currently don't have. What are the plans for Mathematica SE if we start seeing the traditional Mathematica language in other areas?

A:

There are three separate but interrelated questions here, touched on by the other answers and the many comments.

Should we treat questions about the Wolfram Language as on-topic even when it is not specifically about Mathematica, the product? (And if so, does this change our decision to make Wolfram Alpha questions off-topic?)
Are these new Wolfram Language products, such as the recently announced implementation on Raspberry Pi, an opportunity to promote Mathematica.SE?
What should be the role of the Mathematica.SE community in building a broader following for both Mathematica the product and the Wolfram Language more broadly?

My own answers to the above three questions are “yes”, “yes”, and “possibly a bit more than we are currently doing”.
My rationale for answering “yes” to question 1 is that the Wolfram Language implementation is essentially equivalent to the kernel in the Mathematica application, or maybe a future version of it. There are also questions about the Mathematica front end that are explicitly on-topic (and were a lot of the reason why the Mathematica community could never have stayed on StackOverflow). There is a question about whether other “front ends” are on-topic; I don’t have a strong view on this.
On question 2, I think we are already getting an uptick in interest in the site because of the Raspberry Pi publicity. We could find a way to capitalise on this.
I sympathise with the frustration about the way Wolfram Inc markets its products. You only get to cry “New Kind of Breakthrough” so many times before people stop listening. In many ways, this site could serve as a source of less-hyperbolic advocacy, making the practical case for Mathematica the product and the related Wolfram technologies. How exactly we go about that, if indeed that is what people want, is a matter for a separate meta thread and/or chat event, I think.

A:

I agree that it's a "New kind of Marketing" for Mathematica, but in my opinion its a important steep towards make Mathematica more known in the traditional programming community. Today, I believe that 99,9% of programmers think in Mathematica (when they know it exists!) as an tool for Physicist and Matematicians, and Wolfram wants to break this concept, making it an really language. I like to call it W, just as we have R. :)
When I see Tiobe list today, I get worried about the future of Mathematica, and I fell Mathematica really needs a new strategy to reverse that. I agree that language rename is a nice try.
I have send an mail to Tiobe, here is my question:

Hi
I would like to know if Wolfram Mathematica could not participate.
  I think that with wolfram alpha it gets a little bit more popular no?
  It has a very active google groups forum and exists since 1988.
Tks in advance
   Murta

and the answer:

Hi Rodrigo,
Thanks for your feedback to our TIOBE index. Mathematica has been
  tracked for almost 10 years now. Currently Mathematica is at position
  128 down from position 118 last year. In the past it was quite popular
  but as you can tell from the attached trend graph its popularity is
  declining. I hope that this answers your question.
Regards, Paul

...with Mathematica chart attached.

Let's see what the future bring to us.

A:

The more I think about this, the more I agree with the "New Kind of Marketing" assertion. I also agree with other assertions that Wolfram Language really isn't a good name for what amounts to the Mathematica kernel + a few new features that we'll no doubt see in v10.
As an engineer in an industry basically run off of Excel, Mathematica really gives an upper hand in manipulating large amounts of data, and using the extensive, high-level language to present that data in forms that provide a greater level of understanding or provoke "New Ways of Thinking" (trademarked, probably). It would behoove a lot of people to at least augment their Excel usage with a little dose of Map, Apply, and f[x]:=f[x]=expr.
But in reality, I'm the only one that religiously uses Mathematica in the entire company. Not because of lack of licenses or accessibility, but because--I think--of the steep learning curve and the relative obscurity ("I didn't know we have MATLAB license here???..."). Despite the acknowledgment of Mathematica's power, there still seems to be hesitation at taking the plunge to become somewhat fluent in the language.
So, if we take Mr. Wolfram at his word, and despite the rather verbose new marketing nomenclature, if Wolfram Language increases the use of what we think of the traditional Mathematica language, then I'm all for it. Even if that means expanding the scope of questions fielded here at M.SE.


Q:

How can i store the value of a React input element and use it in some other elements

I am facing a problem with React input element, in which i want to take the input value (which is a number) and multiply it with another number and show the value on a span element.
I am open for any solution or changes in my code
I have tried to use normal javaScript but it is not working at all with React. such as getElementByClass("className").value
Here is my code
class Counter extends Component {
    constructor() {
        super();
        this.state = {
            totalPrice: "Total Price:"
        };
    }

    render() {
        return (

                <input type="number" />
                 {this.state.totalPrice}

        );
    }
}

A:

You can achieve it by this:-
import React from 'react'

export default class YourComponent extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            totalPrice: 0
        }
    }
    handleChange(ev){
        let totalPrice = ev.target.value * 10 // your number here i have taken 10 for example
        this.setState({totalPrice:totalPrice})
    }
    render() {
        return (

                <input type="number" onChange={this.handleChange.bind(this)}/>
                Total Price: {this.state.totalPrice}

        )
    }
}


Q:

converting multiple lines of text into a data frame

I'm trying to find a way to convert multiple lines of text into a
data frame.  I'm not sure if there's a way where you can use read.delim()
to read in multiple lines of text and create the following data frame
with something akin to rehape()?.
The data is structured as follows:
A: 1
B: 2
C: 10
A: 34
B: 20
C: 6.7
A: 2
B: 78
C: 35

I'd like to convert this data to something that looks like the following data frame:
A             B             C
1             2             10
34            20            6.7
2             78            35

Apologies if there is an obvious way to do this!

A:

How about :
s<-"A: 1
B: 2
C: 10
A: 34
B: 20
C: 6.7
A: 2
B: 78
C: 35
"
d<-read.delim(textConnection(s),header=FALSE,sep=":",strip.white=TRUE)
cols<-levels(d[,'V1'])
d<-data.frame(sapply(cols,function(x) {d['V2'][d['V1']==x]}, USE.NAMES=TRUE))

which yields:
   A  B    C
1  1  2 10.0
2 34 20  6.7
3  2 78 35.0

A:

Here is how to do it with the plyr package:
require("plyr")
my.data <- "A: 1
            B: 2
            C: 10
            A: 34
            B: 20
            C: 6.7
            A: 2
            B: 78
            C: 35"
df <- read.delim(textConnection(my.data),header=FALSE,sep=":",strip.white=TRUE)

as.data.frame(dlply(df,.(V1),function(x) x[[2]]))

You get
   A  B    C
1  1  2 10.0
2 34 20  6.7
3  2 78 35.0

You can see what magic plyr is doing just by playing with dlply(df,.(V1)) or dlply(df,.(V1),function(x) x)


Q:

Javascript - variable for method name?

How can you reference a javascript object indirectly?
Suppose:

FooBar

How can I access this.dataset.{someVariable}? In this case, this.dataset.tempVariable
Is it only possible using eval or window?

A:

Use square bracket notation:
this.dataset[tempVariable];

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors


Q:

jQuery search page for documents

I have a page that looks like this:
HTML

                    <input type="text" id="SearchText" class="form-control link-search" placeholder="Document Name..." style="width:20%;margin-left: 43%;" />

                    <input type="submit" value="Search" id="ButtonSearch" class="btn btn-default SearchButtons" style="float: right; margin-right: -2%;" />

                    <input type="reset" value="Clear Search" id="ButtonClearSearch" class="btn btn-default SearchButtons" style="margin-left: -69%;" />

                        Panel One

Test Document 1

Test Document 2

Test Document 3

                        Panel Two

Test Document 4

Test Document 5

Test Document 6

Test Document 7

jQuery
$(function() {
    $("#SearchText").keyup(function(event) {
        if (event.keyCode == 13)
            search($(this).val());
    });

    $('#ButtonSearch').click(function() {
        search($("#SearchText").val());
    });

    function search(keyword) {
        var textboxValue = keyword.toLowerCase();
        $('.panel-body').each(function() {
            var exist = false;
            $(this).find('.my-ul li').each(function () {
                if ($(this).find('a').text().toLowerCase().indexOf(textboxValue) !== -1) {
                    exist = true;
                }
            });
            if (exist === false) {
                $(this).parent().removeClass('in');
            } else {
                $(this).parent().addClass('in');
            }
        });
    }

    // When user wants to clear search

    $("#ButtonClearSearch").click(function() {
        $("#SearchText").val("");
        $('.panel-body').each(function() {
            $(this).parent().removeClass('in');
        });
        $('#SearchText').blur(function () {
            if ($.trim(this.value) == null) {
                $(this).val($(this).attr('placeholder','Document Search'));

            }
        });
    });
});

My Goal
I would like to display an alert if the user types in a word that doesn't match any document names, saying "No documents found that match what the user typed in".  Also, currently when a user doesn't type in anything and clicks search, every panel opens.  If the textbox is empty and the user tries to search.. I would like an alert to pop-up saying "No value to search".  I am lost on where to put this code because the jQuery is using .each and I don't need an alert for every item that it is searching.
Example in Action
Bootply

A:

You could add a class to your documents, like documents and then loop through each of these documents, filter by one that the html contains the search terms and check for the length of the remaining array. Something like

$('input').on('change', function(value) {
  var val = $('input').val();
 var array = $('.documents').filter(function(index, item) {
    return item.innerHTML.indexOf(val) !== -1;
  })
  if(array.length == 0) {
  alert("No documents found that match " + val);
  }
})

doc 1

doc 2

doc 3

doc 4

<input type="text">


Q:

Can't figure out this Trig. proof: cos(x+y)cos(x-y)=cos^2(x)-sin^2(x)

$$\cos(x+y)\cos(x-y)=\cos^2(x)-\sin^2(x)$$
I use the sum and difference formula to reduce the right hand side of the equation to $$[\cos(x)\cos(y)-\sin(x)\sin(y)][\cos(x)\cos(y)+\sin(x)\sin(y)]$$  then foil to end up with $$\cos^2(x)\cos^2(y)-\sin^2(x)\sin^2(y)$$ and I can't see what to do from here any help? I know it's really simple but I can't figure out how to get it.

A:

HINT:
Notice,
$$LHS=\cos(x+y)\cos(x-y)=(\cos x\cos y-\sin x\sin y)(\cos x\cos y+\sin x\sin y)$$
$$=(\cos x\cos y)^2-(\sin x\sin y)^2$$
$$=\cos^2 x\cos^2 y-\sin^2 x\sin^2 y$$
$$=\cos^2 x(1-\sin^2 y)-(1-\cos^2 x)\sin^2 y$$
$$=\cos^2 x-\cos^2 x\sin^2 y-\sin^2 y+\cos^2 x\sin^2 y$$
$$=\cos^2 x-\sin^2 y$$


Q:

Creating Frames in tkinter

In the following code I am creating a window and a frame inside it.
Code 1:
import tkinter as tk

class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent)
        self.parent = parent

        button = tk.Button(parent, text="a button")
        button.pack()

root = tk.Tk()
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()

Code 2:
import tkinter as tk

class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent)
        self.parent = parent

        button = tk.Button(self, text="a button")
        button.pack()

root = tk.Tk()
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()

Then I create a button in two ways (Button(self) and Button(parent)). The question is: Do the buttons, in both cases, get placed in the frame that I created (like that: tk.Frame.__init__(self, parent)), both next to it, or one next to it and one inside it?
If both get created inside it, what's the point in doing tk.Frame.__init__(self, parent) if nothing goes inside it?

A:

A widget is packed (of course) within its parent, otherwise it would not make much sense to specify the parent of a widget (unless there are other special reasons). Therefore, in your first case, the button is packed within the root (the parent of the frame), and, in the second case, the button is packed within the frame itself.
To see better what's going on, the best solution is to set background colors of both the frame and the root. See the following example:
Code 1:
import tkinter as tk

class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent, bg="blue")
        self.parent = parent

        button = tk.Button(parent, text="a button")
        button.pack()

root = tk.Tk()
root.geometry("200x200+300+300")
root.config(background="yellow")
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()

Result 1

Code 2:
import tkinter as tk

class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent, bg="blue")
        self.parent = parent

        button = tk.Button(self, text="a button")
        button.pack()

root = tk.Tk()
root.geometry("200x200+300+300")
root.config(background="yellow")
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()

Result 2

Note also that frames have no size until you fill them with some widgets. Note also that you are expanding the frame (or MainApp) and making it fill in bother vertical and horizontal directions, thus the blue takes all the window in this last case.

A:

In the following code I am creating a window and a frame inside it.

That is an incorrect statement. You are creating a single window which inherits from tk.Frame. Within the class, self represents that frame. Outside the class, that frame is app.

Then I create a button in two ways (Button(self) and Button(parent)). The question is: Do the buttons, in both cases, get placed in the frame that I created (like that: tk.Frame.init(self, parent)), both next to it, or one next to it and one inside it?

When you do Button(self), the button is a child of the frame and thus will appear inside the frame.
When you do Button(parent) the button is a child of the parent (in this case, the root window), and thus will appear outside of the frame.
You can easily see this by giving the frame a distinctive color.
import tkinter as tk

class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self, parent, background="pink")
        self.parent = parent

        button = tk.Button(parent, text="a button")
        button.pack()

root = tk.Tk()
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()


Q:

Don't look back, crazy clown

Start with these two words
INSANE                RETROSPECT

and see if you can get them to exchange places by transferring one letter at a time.  With each transfer, you may also rearrange (anagram) each word in any way you choose.  However, each side must always remain a valid English word.

You are finished when you have reached
RETROSPECT            INSANE

All the intermediate words should be fairly common, so you shouldn't have to reach for your dictionary.  There is one word along the way which might seem a little unfamiliar to some, so I will give it to everyone as a guidepost:  INTERCASTE.

Here is an unrelated example just to illustrate the movement:
MAGISTRATE          DENSER
    |     .           |
    |       .         |
    |         I       |
    |           .     |
    v             .   v
STRATAGEM           DENIERS
    |     .           |
    |       .         |
    |         T       |
    |           .     |
    v             .   v
MEGASTAR            RESIDENT
    |             .   |
    |           .     |
    |         N       |
    |       .         |
    v     .           v
MAGNETARS           DIETERS
    |     .           |
    |       .         |
    |         A       |
    |           .     |
    v             .   v
GARMENTS            STEADIER
    |     .           |
    |       .         |
    |         M       |
    |           .     |
    v             .   v
STRANGE             DIAMETERS
    |             .   |
    |           .     |
    |         D       |
    |       .         |
    v     .           v
GRANDEST            STEAMIER
    |             .   |
    |           .     |
    |         I       |
    |       .         |
    v     .           v
GRADIENTS           STEAMER
    |             .   |
    |           .     |
    |         E       |
    |       .         |
    v     .           v
DENIGRATES          MASTER

Notice that at each step, you may transfer in either direction.  You are not obligated to alternate between right to left and left to right.

Afterword:
Here is another solution using more familiar words:

 INSANE        RETROSPECT
CANINES        PROTESTER
CRANNIES        TREETOPS
CANNERIES        PROTEST
NECTARINES        POSTER
ENTRANCES        RIPOSTE
REENACTS        PROTEINS
EASTERN        INSPECTOR
ASTERN        RECEPTIONS
SENATOR        PRESCIENT
REASON        INTERCEPTS
PERSONA        INTERSECT
PERSON        INTERCASTE
OPENERS        INTERACTS
PIONEERS        TRANSECT
INTERPOSE        TRANCES
PROTEINS        REENACTS
RIPOSTE        ENTRANCES
POSTER        NECTARINES
PROTEST        CANNERIES
TREETOPS        CRANNIES
PROTESTER        CANINES
RETROSPECT        INSANE

A:

Amazing puzzle! Found a solution after a couple of hours of hunting (I hope that all the words I used are allowed in this puzzle)

     INSANE             RETROSPECT
        |             .   |
        |           .     |
        |         T       |
        |       .         |
        v     .           v
     INANEST            RECEPTORS
        |             .   |
        |           .     |
        |         C       |
        |       .         |
        v     .           v
     INSTANCE           REPOSTER
        |             .   |
        |           .     |
        |         E       |
        |       .         |
        v     .           v
    TENANCIES           REPORTS
        |             .   |
        |           .     |
        |         T       |
        |       .         |
        v     .           v
    ANCIENTEST          PROSER
        |             .   |
        |           .     |
        |         R       |
        |       .         |
        v     .           v
    INTERSECANT         PROSE
        |     .           |
        |       .         |
        |         N       |
        |           .     |
        v             .   v
    INTERCASTE          PERSON
        |     .           |
        |       .         |
        |         A       |
        |           .     |
        v             .   v
    INTERSECT           PERSONA
        |     .           |
        |       .         |
        |         T       |
        |           .     |
        v             .   v
    ENTICERS            OPERANTS
        |             .   |
        |           .     |
        |         O       |
        |       .         |
        v     .           v
    RESECTION           PARENTS
        |     .           |
        |       .         |
        |         I       |
        |           .     |
        v             .   v
    TENSCORE            PAINTERS
        |             .   |
        |           .     |
        |         P       |
        |       .         |
        v     .           v
    COPRESENT           RETAINS
        |             .   |
        |           .     |
        |         R       |
        |       .         |
        v     .           v
    PRECENTORS          TINEAS
        |     .           |
        |       .         |
        |         N       |
        |           .     |
        v             .   v
    RECEPTORS           INANEST
        |             .   |
        |           .     |
        |         T       |
        |       .         |
        v     .           v
    RETROSPECT          INSANE