text:
Q: What "plugins" property in .eslintrc does? module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
  ],
};

Whenever I add or remove this line: plugins: ['@typescript-eslint']
eslint seems to behave the same. What exactly plugins property does and when using it is required?

A: This question is pretty straight forward if you think about what a plugin is.
The docs don't really do a good job of just out-right saying what an ESLint plugin is, though if you read through the docs (https://eslint.org/docs/user-guide/configuring), then it's pretty trivial to figure out:

ESLint supports the use of third-party plugins

When using rules, environments or configs defined by plugins. Before using the plugin, you have to install it using npm.

So a plugin is a 3rd party module that can define rules, environments, or configs.
So to answer your question:

What exactly plugins property does [sic]

the plugins property tells ESLint what plugins you want to use

and when using it is required? [sic]

when you use something from a plugin, you must first tell ESLint about it with the plugins property.

Plugins seem to work anyway when this field is omitted

If you use the extends option with the syntax plugin:<plugin>/<config>, then ESLint will load a specific file from the plugin ahead of time.
Why? Because this allows a plugin to provide a config and reduce the amount of config you need. A plugin's config can provide the plugins option for you, meaning you don't need to do it yourself.

A: I was also curious about what is parser and plugin
From  documentation
"For example, once this parser successfully produces an AST for the TypeScript source code, it might well contain some information which simply does not exist in a standard JavaScript context, such as the data for a TypeScript-specific construct, like an interface.
The core rules built into ESLint, such as indent have no knowledge of such constructs, so it is impossible to expect them to work out of the box with them.
Instead, you also need to make use of one more plugins which will add or extend rules with TypeScript-specific features."
This helped me to understand it better.


text:
Q: FFmpeg: How to add a fading effect to the video slides? I have a text file with the names of the images (paths) which I'm using in the video. The file looks like this
file 'image1.jpg'
file 'image2.jpg'
file 'image3.jpg'
file 'image4.jpg'
file 'image5.jpg'

And the ffmeg command is
ffmpeg -y -r 1/5 -f concat -safe 0 -i imagenames.txt -i some_audio.mp3 -c:v libx264 -vf fps=30 -pix_fmt yuv420p -t 30 output.mp4

And I need to add a fading effect to the video slides ( frames ). And I wonder, is it possible to do it using a text file for the images?

redpajama_set_name: RedPajamaStackExchange


text:
Q: CAML to search for pages returns all files and folders in a site I am trying to write a simple web part for Sharepoint 2013 that searches for all pages of a certain content type and outputs a list of their titles. I am using a CAML query to search for that. But no matter what query, the result I have is just a list of all files and folders in this Sharepoint site.
Finally, I reduced the CAML query to a simple "find everything that starts with the letter T", but still the result is outputting all files and folders in the root level of the site.
What am I doing wrong?
    protected override void CreateChildControls()
    {
        Label label1 = new Label();

        try
        {
            SPQuery query = new SPQuery();
            query.Query = @"<Query>
                            <Where>
                              <BeginsWith>
                                <FieldRef Name='Title'></FieldRef>
                                <Value Type='Text'>T</Value>
                              </BeginsWith>
                            </Where>
                            </Query>";

            using (SPSite site = new SPSite("https://xxxxxx/sites/xxxxx/en/xxxx/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);
                    PublishingPageCollection collection = pubweb.GetPublishingPages(query);

                    //now output the results of the query
                    label1.Text = "Items: " + collection.Count.ToString();
                    for (int i = 0; i < collection.Count; i++)
                    {
                        label1.Text += collection[i].Title + "<br>";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            label1.Text = ex.Message;
        }

        Controls.Add(label1);
    }

A: Weirdly, you need to do two things:
1) Remove the opening and closing  tag;
2) Make sure the query does not start or end with a blank line.
Then the results will change the the correct ones.


text:
Q: How to manage CouchDB code out of it? I am new to CouchDB way of making things. So, I have a lot of questions about it, but let's focus in one of them.
CouchDB has this concept of javascript code (validation + map-reduce + show + ?) being written in the design documents. This is part of the database, like stored procedures or triggers are for more tradittional databases.
Is there anybody maintaining this code inside a project so that we can actually test this code like any other javascript code (through jspec for instance, mocking the dependencies), version in the same repository we version the rest of our code, probably in a separate folder.. is it possible and used? Or isn't it good for some reason I should know?
What I would like to have is some way to do a single rake task and my couchdb design documents get synced with the project, something like that might be useful.
In the case of ruby, it would be helpful also to make some dynamic magic happen (e.g. default views and validations, new views through the use of named scopes).

A: Check out CouchApp: http://github.com/couchapp/couchapp
It's a set of python scripts that take a structured filesystem of js files (amongst others) and converts it into a well-formed Design Doc.
(Pardon me if I misunderstood your question)

A: Yeah, we keep our view code in files and check them in to git and then use a sync script to push them to production once we're confident they work.


text:
Q: using static methods and classes I know that static methods/variables are associated with the class and not the objects of the class and are useful in situations when we need to keep count of, say the number of objects of the class that were created. Non-static members on the other hand may need to work on the specific object (i.e. to use the variables initialized by the constructor)
My question what should we do when we need neither of the functionalities?
Say I just need a utility function that accepts value(s) and returns a value based solely on the values passed. I want to know whether such methods should be static or not. How is programming efficiency affected and which is a better coding practice/convention and why.
PS: I don't want to spark off a debate, I just want a subjective answer and/or references.

A: Methods which are not attached to any specific class like these are called "free functions", and as you have adequately noted, OO does not provide for them, and some languages also do not provide the facilities for them.
In a language like C++ you can just place the function in a namespace. But if you're working in Java or C# you must pointlessly place them in a class and make them a static member for no good reason at all.

A: It's pretty standard in Java to make such methods static and put them in "classes" with other static methods.  You certainly wouldn't want to make the methods non-static--you'd confuse everybody, including the optimizers.  I suppose the designers could have thought of a name besides "class" ("namespace"?) to hold these methods/functions, but most of us have enough to remember as is.  I'll admit, having to add a private constructor to a "static" class seems a bit silly, but it gets the job done without adding new rules.
C# is a bit more explicit, with a static class (no double quotes around static), no need for a private constructor, and enforcing of the static-methods-only rule.
(Java has a "static class", but it's something completely different, primarily intended, no doubt, to confuse discussions like this one.)

A: If those utility functions are relatively small and not similar to others then you can use static functions. Also, the most important thing, they should not be related with the abstraction of the object (the class) and also you should not abuse them; they do not represent a OOPish way of programming.
I mentioned about size, because if they are large then you should use objects in order to obtain a better cohesion (share some data between functions by instance variables). I mentioned about similar functions because you might want to use the power of polymorphism.
Regarding efficiency static methods might be a little faster, but you would not gain any considerable performance gain from this.

A: Continuing with the example of System.Math in C#, some languages such as Nemerle allow you to add a using statement which effectively lets you use a classes behaviour as free functions, as well as direct access to its constants & other static members.
using System.Math // using statement at class level

public class Example
{
    public TestMethod() : void
    {
        def radians = Pi; // direct access to Math.Pi

        def x = Sin(radians); // direct access to Math.Sin & Math.Cos
        def y = Cos(radians);
    }
}

In essence this allows you to treat a class as a namespace, which as DeadMG pointed out is basically what System.Math is...


text:
Q: Как решить проблему с черным экраном vlc player в ubuntu 16.04? Звук проигрывается а вот видео нет.
Не совсем понимаю, как решить эту задачу.

A: Не кодеки, а в настройках вывод установить x11.
Но все равно спасибо, что откликнулись.


text:
Q: SFDX Lightning Page Deployment Issues Property 'itemInstances' not valid in version 47.0 I trying to deploy my package while validating changes salesforce given this error "Lightning Page Property 'itemInstances' not valid in version 47.0" do you guys have any insight for these king of errors.
Please share if you got any solution for these.
Thanks in advance.

A: If you're using the Metadata API to deploy, you need to update your package.xml to indicate version 49.0
<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">

   your types here...

   <version>49.0</version>
</Package>

A: As per documentation itemInstances is available in API 49.0 or later.  Try using 49 version.
 <?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <fullName>New Opportunity Page</fullName>
    <types>
      -------
      -------
    </types>
    <version>49.0</version>
</Package>

Thanks,


text:
Q: What is this in react import { HomePage } from '@/HomePage' I know its importing a file but I don't know what the "@" stands for, I have seen a bunch of code snippets using this same syntax.
I tried implementing the same scenario in any way I thought could be possible but still no success

A: They are webpack alias import, this configuration help to shorten your absolute/relative path.
Read more here: https://webpack.js.org/configuration/resolve/

A: This is used when you want to use Scope Packages.
What are Scope Packages?
Ans - Scopes are a way of grouping related packages together, and also affect a few things about the way npm treats the package.
Please check this docs

A: First you need to add babel-plugin-root-import in your devDependencies in package.json (If using yarn: yarn add babel-plugin-root-import --dev). Then in your .babelrc add the following lines into plugins key:
"plugins": [
[
  "babel-plugin-root-import",
  {
    "rootPathPrefix": "@"
  }
]
]

Now, you can use @. For example:
Instead of:
import xx from '../../utils/somefile'

You Can:
import xx from '@/utils/somefile'


text:
Q: Formatting currency in Android using wrong decimal separator I got a bug report from a Swedish user saying that our Swedish currency was using the wrong decimal separator.
NumberFormat enUS = NumberFormat.getCurrencyInstance(Locale.US);
NumberFormat enGB = NumberFormat.getCurrencyInstance(Locale.UK);
NumberFormat svSE = NumberFormat.getCurrencyInstance(new Locale("sv", "SE"));
double cost = 1020d;
String fmt = "en_US: %s en_GB %s sv_SE %s";
String text = String.format(fmt, enUS.format(cost), enGB.format(cost), svSE.format(cost));
Log.e("Format", text);

> Format﹕ en_US: $1,020.00 en_GB £1,020.00 sv_SE 1 020:00 kr

They say that the format should be "1 020,00 kr". When I inspect the format object, it looks like it has decimalSeparator of "," in the symbols table, but a "monetarySeparator" of ":".
Does anyone know if : is actually correct, whether this is a bug in Android/java, or any sort of workaround?

A: It's like your user says: In Swedish thousand separator is white space " " and decimal separator is comma "," and currency symbol "kr" (Krona). So colon ":" is definitely wrong.
You can check it here too: http://www.localeplanet.com/java/sv-SE/
What Java version are you using? It works well on my desktop 1.6.0_13
-- update --
It seems that on Android there's a bug, but you can go around the bug by using the DecimalFormatSymbols like this:
    DecimalFormat svSE = new DecimalFormat("#,###.00");
    DecimalFormatSymbols symbols = new DecimalFormatSymbols(new Locale("sv", "SE"));
    symbols.setDecimalSeparator(',');
    symbols.setGroupingSeparator(' ');
    svSE.setDecimalFormatSymbols(symbols);

This prints the correct separators in Android as well.


text:
Q: UIActionSheet and UIView I want to create a UIActionSheet but I've also a UIView and this last one must be selectable.
How you can see I can't use the date picker. Ideas?

A: You can't. A UIActionSheet is modal by definition.


text:
Q: Запрос к mysql, где where равно значениям из массива Доброго всем времени суток, господа.
Есть массив с циферками ($array_digit), кол-во циферок не известно. Хочется сделать запрос к БД, что-то в роде
mysql_query("SELECT `field` FROM `table` WHERE `field`='???'",$db);

И тут возникает вопрос. Как? т.е. В моем случае условие для WHERE сейчас пишу ручками. Да и по 20-ть значений разделенными "OR" тоже не оптимально. Как можно решить данную задачу?
p.s. Очень охота сделать массиву implode(',',$array_digit); и как-то с этим уже сделать запрос.
A: mysql_query("SELECT `field` FROM `table` WHERE `field` IN (".implode(',',$array_digit).")",$db);


text:
Q: Extracting formula from a number sequence Let's say I have this sequence:
| Term  | Value |
|-------+-------+
| 1     | 1     |
| 2     | 4     |
| 3     | 9     |
| 4     | 16    |
| 5     | 25    |
| 6     | 36    |
| 7     | 49    |

..and so on

Could anyone possibly find out (in a mathematical way) that the formula behind this sequence is $x_n = n^2$
However, I wish to use more complicated formulas such as in a real enviorment
$$floor\left(\frac{\displaystyle\sum_{x=1}^{n-1}floor\left(x+300*2^\frac{x}{7} \right)}{4}\right)$$

A:
Could anyone possibly find out (in a mathematical way) that the formula behind this sequence is $x_n=n^2$

In general, given $N$ points $(x_i, y_i)$ such that the $x_i$ are all different, there will be a unique polynomial $f$ of degree $N-1$ or less, such that $f(x_i) = y_i$ for all $i$.
Your example has seven points: $(1, 1), (2, 4), (3, 9), \ldots, (7, 49)$.  This means that there is a unique polynomial of degree 6 or less that includes these points.  It turns out in this example that the polynomial turns out to be of degree 2 (namely, $f(x) = x^2$).
To find this polynomial in your example, you'd write:
$$
f(x) = a_0 + a_1 x + a_2 x^2 + \ldots a_6 x^6
$$
Then your seven points yield seven equations:
$$
1 = a_0 + a_1 (1) + a_2 (1)^2 + \ldots a_6 (1)^6
$$
$$
4 = a_0 + a_1 (2) + a_2 (2)^2 + \ldots a_6 (2)^6
$$
$$
\ldots
$$
$$
49 = a_0 + a_1 (7) + a_2 (7)^2 + \ldots a_6 (7)^6
$$
Solving these seven equations for the seven variables $a_0, a_1, \ldots, a_6$ yields the polynomial $f$.  In your example, the solution is $a_0 = a_1 = a_3 = a_4 = a_5 = a_6 = 0$, and $a_2 = 1$, so $f(x) = x^2$.
Now write $a_n = f(n)$ and you're done.
(Note: this process indicates that two points determine a line, as we already know from geometry.  Also, three points determine a parabola, four points determine a cubic, etc.)
Of course, if we now received a new data point, our solution might go out the window and we'd have to start over.  For example, if you expanded your example and told us that $a_8 = -100$, then suddenly our solution $a_n = n^2$ wouldn't seem so good anymore.  However, we could just start all over and find a new polynomial of degree 7, that fit our updated set of 8 data points.
If your $N$ is large, you might not want to use polynomials of degree $N-1$.  In that case, you can always just cap the degree of the polynomials at a convenient size (set the maximum degree $d$ equal to 5 or 14 or whatever you like).  Then this same process gives $N$ linear equations in $d$ variables.  If $N > d$, so that you have more equations than variables, then there probably won't be an exact solution.  However, you can try to find a solution that is "as close as possible" to solving all the equations.  This means finding a curve of dimension $d$ so that the $N$ equations are all as close to being satisfied as possible.  A common approach is the "least-squares approximation."
http://en.wikipedia.org/wiki/Polynomial_regression
http://en.wikipedia.org/wiki/Linear_least_squares_(mathematics)
Your question didn't indicate that you were interested in finding approximate solutions, so I won't go into this further, but there is a lot more (a LOT more) information on the subject of fitting curves to data sets.
Anyway, you hinted that you had some more complicated things in mind, but I'm not sure exactly what you wanted.  However, hopefully this answer will clarify some things for you, and help you find what you're looking for!


text:
Q: Is .onLoad called before rendering is done? I want to call some JS after the page-load, this may involve a delay and as such I want the page loaded first so content is shown... but it seems that the code in onLoad handler is called before the rendering is complete. Is there a better event I can use, which is triggered when the page is 'finished'?
To clarify, I want to run some JS after the page is rendered on-screen, so a 'post-everything event' really.

A: There are several points of interest along the time sequence. This generic sequence is a good overview, even though different browsers and versions implement the details a little differently. (This assumes you're using raw Javascript and need to minimize cross-browser issues; with it's comprehensive internal handling of cross-browser issues JQuery is a little different):
T0] page-begun-- The browser has started working on the page, but otherwise the environment is in flux. Your JS operations may occur in the wrong context, and simply be flushed away when the right context stabilizes. You probably don't want to try to execute any JS at all.
T1] "onLoad" event-- [however you get events: addEventListener("Load"..., window.onload=..., etc.] All parts of the page have been identified and downloaded  from the server and are in the local system's memory. In order for all parts to be identified, some parsing has already occurred. (Note that "load" is a cognate of "download", not "parse" nor "render".)
You now have the right environment and can begin to execute JS code without fear of losing anything. HOWEVER, operations that try to read or manipulate the HTML [getElementById(..., appendChild(..., etc.] may fail in strange ways, or may appear to work but then disappear, or may do something different than you expected.
T2] DOM-almost-ready-- This hack is very simple and fully cross browser. Just put your JS <script>...</script> at the very end of your HTML, just before the </body> tag. Most things will work right, although attempts to append to or modify the DOM at the very end of the <body> may produce surprising results. This isn't fully correct, but it works 99% of the time. Given its simplicity and the very high probability of correct operation, this may be the way to go (at least if you don't use JQuery).
T3] DOM-ready-- [however you get events: addEventListener("DOMContentLoaded"..., window.ondomcontentloaded=..., etc.] At this point the HTML has been completely parsed and JS is 100% available, including all functions that read or manipulate the HTML [getElementById(..., appendChild(..., etc.].
T4] Render-done-- The browser is finished displaying the content on the screen. There is NOT any such event or any reasonable cross-browser version-agnostic way to detect this situation. That's just as well, as you probably don't really want this anyway. If the browser has already displayed the page on the screen and then you manipulate the DOM, you'll get a "flash", where both the before and the after are visible on the screen at least briefly. What you probably really want is the point where you can execute arbitrary JS code; that's the previous (T3] DOM-ready) point in time.

A: Either attach a callback to window.onload
window.onload = function(){
    // your code here
};

this will fire when all resources are loaded (which might be not what you want).
Or put all of your code at the bottom the page (before the closing body tag). The code will be run when the HTML is parsed.

FWIW, here is the jQuery code. You see, the use custom event handlers for IE and the other browsers, but use window.onload as fallback:
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
    // Use the handy event callback
    document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

    // A fallback to window.onload, that will always work
    window.addEventListener( "load", jQuery.ready, false );

    // If IE event model is used
} else if ( document.attachEvent ) {
    // ensure firing before onload,
    // maybe late but safe also for iframes
    document.attachEvent("onreadystatechange", DOMContentLoaded);

    // A fallback to window.onload, that will always work
    window.attachEvent( "onload", jQuery.ready );

    // If IE and not a frame
    // continually check to see if the document is ready
    var toplevel = false;

    try {
        toplevel = window.frameElement == null;
    } catch(e) {}

    if ( document.documentElement.doScroll && toplevel ) {
        doScrollCheck();
    }
}

A: As with a lot of JavaScript this will depend on which browser you are using.
As @Avitus' answer, have you looked at the execution point of JQuery's document ready event? This has been generalised across all browsers.

A: If you plan on using a javascript library (like jQuery) I would rather go with the $(document).ready() statement which is called once the DOM is ready to be manipulated.
The other option I see would be to include your function call at the end of your HTML page so that all the HTML content would be loaded so you can afterward execute your code safely

A: "The onload event waits for all binary content to download before firing. No kitty-tickilng until then."
As this post says, it is called after all binary content is downloaded, you need to listen for a ready event either using jQuery's ready, or your own function. This project looks interesting.
There are many cross browser implementations so use either jQuery or that project I linked to.
I have written my own function for my library, it uses internal methods so will not work on its own but might give you a feel for what you have to do. You can find that function here.


text:
Q: Generalized Eigenvalues of $P_i^TLP_j+zP_i^TP_j$ I have the following generalized eigenvalue problem
$\det[P_i^TLP_j+zP_i^TP_j]=0$
$L$ is a positive-semidefinite matrix with 1 eigenvalue at 0.  More precisely, it is the combinatorial Laplacian matrix for a connected graph.
$P_i$ ($P_j$) is the identity matrix with the $i$-th ($j$-th) column removed.
What, if anything, can be said about the generalized eigenvalues $z$ of this problem?


text:
Q: VS for Database Developers: Lookup Tables How to you handle the contents of lookup tables that should be treated as "code" rather than data?

A: There is currently no good support in VS for Database Developers for managing reference data.
There is a good post at MSDN that proposes a work around for this missing feature that uses a temp table and a post deployment script to merge changes to the reference data at deployment time.
Essentially your reference data exists as a static set of insert statements into your temp table and then the merge keeps the live tables up to date.
I've been using the approach on a large fully CI project for the last five months or so and found it works well.
I've also got my fingers crossed that they will add better support for this in VSDB vNext.


text:
Q: Which algorithm do I need for this directed graph operation? I may be overthinking this and be missing something obvious, but I was wondering which NetworkX algorithm I could use to achieve the following:
Given a DiGraph such as:

And a list of nodes such as: Q1, Q2
Find all nodes which are connected to (or in other words children of) Q1 and Q2, the results would be as following:

Which algorithm would accomplish this?

A: Looks like you just need to make a recursion over networkx.Digraph.predecessors

A: A first way is to use a list, visit the predecessor of each node starting from your node and put it in the list, building in this way a tree with the nodes you find.
Another way is to use a  visit (DFS or BFS) on the graph reversing the edges.
Consider the following example where I build a bfs tree starting at Node "Q1".
import networkx as nx

g = nx.DiGraph()

g.add_edges_from([("M1","Q1"),("I1","M1"),("I2","M1"),("I3","M1"),("I3","M2"),("M2","Q2")])

#creating a graph with the edges reversed
g2 = nx.DiGraph()
g2.add_edges_from([(v,u) for (u,v) in g.edges()])

t = nx.bfs_tree(g2, "Q1")

for (u,v) in t.edges():
    t.remove_edge(u,v)
    t.add_edge(v,u)

print(t.nodes(),t.edges())
# ['Q1', 'M1', 'I1', 'I2', 'I3'] [('M1', 'Q1'), ('I1', 'M1'), ('I2', 'M1'), ('I3', 'M1')]


text:
Q: QtChartView missing namespace in the generated UI file I am working on visual c++ with the Qt Framework.
I am trying to add a QChartView in a project. I added the included paths and the files to link.
When I try to make compilation, I have a lot of syntaxe error in my code. These come from the fact that in the generated UI_XXX.h file (I use QtDesigner), the namespache QtCharts is not used. The problem is that I can not add the line manually in this generated file : it will be deleted at every change of the form.
I would like the make the compiler use the QtCharts namespace inside the class Ui_XXX.h generated but without editing this Ui_XXX.h
How can I do?

To illustrate, here is the a part of my code:
#include<qchartview.h>

class test : public QMainWindow
{
    Q_OBJECT

public:
    test(QWidget *parent = 0);
    ~test();

private:
    Ui_testClass ui; //---> here is the generated class by QtDesign. I want to use qtCharts namespace here

};

Here is a part of the UI_XXX.h generated class
#include <QtWidgets/QWidget>
#include "qchartview.h"

QT_BEGIN_NAMESPACE

//using namespace QtCharts-----> if I put this line it will works. But these line will be deleted when recompiling the UI file

class Ui_testClass
{
public:
    QWidget *centralWidget;
    QChartView *widget;
    QMenuBar *menuBar;
    QToolBar *mainToolBar;
    QStatusBar *statusBar;
    QToolBar *toolBar;


text:
Q: How To Retrieve And Save a Date Via Shared Preferences Original Post:
In the following example:
How to save and retrieve Date in SharedPreferences
What should I be looking to replace the ... with?
Save:
SharedPreferences prefs = ...;
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", date.getTime());
editor.commit()

I'm attempting to use something such as:
SharedPreferences.Editor editor = getSharedPreferences(DATE_PREF, MODE_PRIVATE);

but I'm getting an error stating DATE_PREF cannot be resolved to a variable.
MY SOURCE:

        //get the current date
        Date date = new Date(System.currentTimeMillis());

        // convert the date to milliseconds
        long millis = date.getTime();

        // save the date to shared preferences

        SharedPreferences prefs = millis ;
        SharedPreferences.Editor editor = getSharedPreferences(DATE_PREF, MODE_PRIVATE);
        editor.putLong("time", date.getTime());
        editor.commit();

Update After First Response:  (Help Still Needed)
After removing the lines:
// SharedPreferences prefs = millis;
    // SharedPreferences.Editor editor = PreferenceManager
    // .getDefaultSharedPreferences(getApplicationContext())

I'm getting two errors stating "editor cannot be resolved" at:
editor.putLong("time", date.getTime());
        editor.commit();

due to the fact I removed the lines which referenced the editor - my question is: will my preferences still be saved as shown below? (I need this value to persist after reboot.)
I've tried using:
SharedPreferences.putLong("time", date.getTime());
        SharedPreferences.commit();
as well as:
putLong("time", date.getTime());
        commit();
However both methods are causing errors and I just want to make sure the values will be stored after reboot.
public class WifiMonitor extends Activity {

    Button sendButton;

    EditText msgTextField;

    private PendingIntent pendingIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView infoView = (TextView) findViewById(R.id.traffic_info);

        // get traffic info
        double totalBytes = (double) TrafficStats.getTotalRxBytes()
                + TrafficStats.getTotalTxBytes();
        double mobileBytes = TrafficStats.getMobileRxBytes()
                + TrafficStats.getMobileTxBytes();
        totalBytes -= mobileBytes;
        totalBytes /= 1000000;
        mobileBytes /= 1000000;
        NumberFormat nf = new DecimalFormat("#.##");
        String totalStr = nf.format(totalBytes);
        String mobileStr = nf.format(mobileBytes);
        String info = String.format(
                "Wifi Data Usage: %s MB\tMobile Data Usage: %s MB", totalStr,
                mobileStr);
        infoView.setText(info);

        // send traffic info via sms
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("7862611848", null, info, null, null);
        String alarm = Context.ALARM_SERVICE;

        // get the current date
        Date date = new Date(System.currentTimeMillis());

        // convert the date to milliseconds
        long millis = date.getTime();

        // save the date to shared preferences
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(getApplicationContext());
        // SharedPreferences prefs = millis;
        // SharedPreferences.Editor editor = PreferenceManager
        // .getDefaultSharedPreferences(getApplicationContext());

        editor.putLong("time", date.getTime());
        editor.commit();

        // get the saved date

        Date myDate = new Date(prefs.getLong("time", 0));
    }

    // set the alarm to expire 30 days from the date stored in sharePreferences
    public void invokeAlarm(long invokeTime, long rowId) {
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent i = new Intent(this, Alarm.class);
        i.putExtra("rowId", String.valueOf(rowId));
        am.set(AlarmManager.RTC_WAKEUP, invokeTime, PendingIntent.getService(
                this, (int) System.currentTimeMillis(), i, 0));
    }

}

A: PreferenceManager.getDefaultSharedPreferences(context);

Context can be getApplicationContext().


text:
Q: Cuda Native Provider - Missing MathNet.Numerics.CUDA.dll Math.Net 3.7.0 Release Notes on nuget mention a CUDA native provider.
Control.UseNativeCUDA();

throws a DllNotFoundException for MathNet.Numerics.CUDA.dll. For the MKL-provider i need to install an extra NuGet-Package. Is there no package for the CUDA.dll yet? Or what do i have to install?
I'm using MathNet on linux with mono.

A: You are right. Currently there is no NuGet package available.
Also note that the CUDA support is not stable (alpha) yet.


text:
Q: Looking for an implementation of an abstract method I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
    gp1.agregar(v1);
    //gp1.mostrar(v1);
    gp1.agregar(v2);
    System.out.println(gp1.check());

    GrandPrix gp2 = new GrandPrix();
    gp2.agregar(vt1);
    gp2.agregar(vt2);
    gp2.agregar(m2);
    System.out.println(gp2.check());

    GrandPrix gp3 = new GrandPrix();
    gp3.agregar(vt1);
    gp3.agregar(vt2);
    gp3.agregar(m1);
    System.out.println(gp3.check());

    GrandPrix gp4 = new GrandPrix();
    gp4.agregar(m1);
    gp4.agregar(m2);
    System.out.println(gp4.check());

This is the class that is using
import java.util.ArrayList;

    public class GrandPrix extends Rally{

        ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();

        public void agregar(Vehiculo v) {
            ve.add(v);
        }

        public void agregar(Carro c) {
            ve.add(c);
        }

        public void agregar(Moto m) {
            ve.add(m);
        }

        @Override
        boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
            return false;
        }

    }

This is the class where everything goes on
public class Vehiculo {

    private String Nombre;
    private double velocidad_max;
    private int peso;
    private int comb;

    public Vehiculo() {
        setNombre("Anónimo");
        setVel(130);
        setPeso(1000);
        setComb(0);
    }

    public Vehiculo(String string, double d, int i, int j) {
        setNombre(string);
        setVel(d);
        setPeso(i);
        setComb(j);
    }

    double rendimiento() {
        return velocidad_max/peso;
    }

    public boolean mejor(Vehiculo otroVehiculo) {
        return rendimiento()>otroVehiculo.rendimiento();
    }

    public String toString() {
        return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
    }

    /**************************************
    ---------SET And GET Nombre------------
    ***************************************/

    public String getNombre() {
        return Nombre;
    }
    public void setNombre(String nuevoNombre) {
        this.Nombre=nuevoNombre;
    }

    /**************************************
    ---------SET And GET velocidad_max------------
    ***************************************/

    public double getVel() {
        return velocidad_max;
    }
    public void setVel(double nuevaVel) {
        this.velocidad_max=nuevaVel;
    }

    /**************************************
    ---------SET And GET peso------------
    ***************************************/

    public double getPeso() {
        return peso;
    }
    public void setPeso(int nuevoPeso) {
        this.peso=nuevoPeso;
    }

    /**************************************
    ---------SET And GET comb------------
    ***************************************/

    public int getComb() {
        return comb;
    }

    public void setComb(int comb) {
        this.comb = comb;
    }

    boolean esDe2Ruedas() {
        return false;
    }

}

This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{

    private boolean sidecar;
    public Moto(String string, double d, int i, int j) {
        setNombre(string);
        setVel(d);
        setPeso(i);
        setComb(j);
        setSidecar(false);

    }
    public Moto(String string, double d, int i, int j, boolean b) {
        setNombre(string);
        setVel(d);
        setPeso(i);
        setComb(j);
        setSidecar(b);
        esDe2Ruedas(false);
    }

    public String toString() {
        String str = null;
        if(isSidecar())
            str =super.toString()+", Moto, con sidecar";
        else
            str =super.toString()+", Moto";
        return str;
    }
    public boolean isSidecar() {
        return sidecar;
    }
    public void setSidecar(boolean sidecar) {
        this.sidecar = sidecar;
    }

A: I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.


text:
Q: Retrieve response informaton in view I'm using ASP.NET Controller accessing account data to another database. I'm doing a login where it gets an ID and checks if it's a Mentor or Student.
With this information we want it to be used in a .js file we have thats makes a get request to our server. We want to send an ID here and later other informations.
We have this controller:
public IActionResult Calendar(LoginViewModel loginViewModel)
    {

        Student student = null;
        Mentor mentor = null;

        if (loginViewModel.UserType == 0)
        {
            student = db.GetStudentObject(loginViewModel.Id);
        }
        else if (loginViewModel.UserType == 1)
        {
            mentor = db.GetMentorObject(loginViewModel.Id);
        }

        if (student != null)
        {
            return View(student.Id);
        }if(mentor != null)
        {
            return View(mentor.Id);
        }

        return View("Index");

    }

When our view is initialized we want to send an ajax request where we use the Id we sent to the view
eventSources: [
        {
            url: '/api/Bookings?id=' + id, //we need to access the Id here
            color: 'blue',
            textColor: 'white'
        }
    ],

How can we retrieve the Id from the controller we are sending to the view? I know this can be solved by making a static class however is there a better options?

A:

//Accessing the Id on JS file:

'/api/Bookings?id=' + $('#Id').val();
@*
if the view is binding to a complex model, you must return View(model), instead of View(model.Id) on controller.
assuming that is a complex model, you have in your view (cshtml):
*@

@model Xpto.Models.MyViewModel

@Html.HiddenFor(i => i.ID) //to access the property on JS file.


text:
Q: Bootstrap PCA with varimax rotation I have microfossil data from across the Cretaceous-Tertiary boundary, 20 species (=variables) and 27 samples (=observations). I have run a PCA with varimax rotation on these data using the rgr package. I now want to determine the significance of the PC loadings using bootstrap BCa confidence intervals from package boot, but I can't get it to work. I have found using Krzanowski cross-validation that 5 PCs appear to be significant (NRETAIN in the script below is thus equal to 5). The script I have been attempting looks like this (the data matrix is called "x"):
BS.vmax <- function(d, f)
{    n <- nrow(d)
     unrot <-gx.mva(d)
     unrot$eigenvectors
         vmax <- gx.rotate(unrot, nrot=NRETAIN)
         vload <- vmax$rload[,1:NRETAIN]
}

BS.vmax.boot <- boot(x, BS.vmax, R = 99)
boot.ci(BS.vmax.boot, type = "bca")

This script returns a BS.vmax.boot value that looks like this:
ORDINARY NONPARAMETRIC BOOTSTRAP
Call:
boot(data = x, statistic = BS.vmax, R = 99)
Bootstrap Statistics :
          original  bias    std. error
t1*   -0.745596283       0           0
t2*   -0.902044503       0           0
...
lines removed here
...
t99*  -0.144587913       0           0
t100*  0.076592734       0           0

which doesn't make any sense (because all biases and SEs are zero)! I will later on increase the number of bootstrap replicates to 2000; this is just for testing.

A: I don't think the increase in the number of bootstrap replications will help much.  The problem is probably due to the small sample size of 27.  Even second order accurate bootstrap confidence intervals such as BCa are approximate and the coverage can be way off in small samples.  Schenker illustrated this problem with the BC confidence intervals for variance parameters when the population distribution is a highly skewed chi square distribution. Chernick and LaBudde also showed that this would occur for BCa with highly skewed distributions such as lognormal.  I have mentioned this previously on this site.  Links to the papers are as follows:
Schenker (1) http://www.tandfonline.com/doi/abs/10.1080/01621459.1985.10478123#preview
My Bootstrap Methods StatProb article with several references including the Chernick-LaBudde article and our book on the bootstrap (2) http://statprob.com/encyclopedia/ResamplingMethods.html


text:
Q: Android - start new activity that does not extend Activity? I am trying to run a Processing class from my MainActivity. I believe that I am running my intent properly but I get the error:
12-17 22:53:44.221: E/AndroidRuntime(1904): FATAL EXCEPTION: main
12-17 22:53:44.221: E/AndroidRuntime(1904): Process: bard.edu.focus2, PID: 1904
12-17 22:53:44.221: E/AndroidRuntime(1904): android.content.ActivityNotFoundException: Unable to find explicit activity class {bard.edu.focus2/bard.edu.focus2.ProcessingInterface}; have you declared this activity in your AndroidManifest.xml?
12-17 22:53:44.221: E/AndroidRuntime(1904):     at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1628)
12-17 22:53:44.221: E/AndroidRuntime(1904):     at android.app.Instrumentation.execStartActivity(Instrumentation.java:1424)
12-17 22:53:44.221: E/AndroidRuntime(1904):     at android.app.Activity.startActivityForResult(Activity.java:3424)

And the class is declared in my manifest:
<activity
        android:name="edu.bard.focus2.ProcessingInterface"
        android:parentActivityName="edu.bard.focus2.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.DEFAULT" />
        </intent-filter>
</activity>

Here is my intent:
runFocus = (Button)findViewById(R.id.buttonProcessing);
    runFocus.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
                Intent intent = new Intent(MainActivity.this,ProcessingInterface.class);
                startActivityForResult(intent,START_PROCESSING);
        }
     }

The thing is my processing class (which functions properly on its own) extends PApplet and not Activity which could be at the origin of the error.
If I'm right, what can I do to fix it?
If not, any suggestion?
Thanks !

A: You've got to extend Activity, so far as I know, otherwise it's not going to work -- no Context, no . . . . well, many, many things. Try the approach in this tutorial instead. It walks you through using a special Android-enabled Processing build.

A: you havn't add you newly created Activity in your Manifest file.
Add following code in your manifest file before  tag
 <activity android:name=".newclassname" >
        </activity>

or
  <activity android:name="packagename.newclassname" >
            </activity>

A: I guess you have given the wrong package name according to your log.
Change:
<activity
        android:name="edu.bard.focus2.ProcessingInterface"
        android:parentActivityName="edu.bard.focus2.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.DEFAULT" />
        </intent-filter>
    </activity>

to
<activity
        android:name="bard.edu.focus2.ProcessingInterface"
        android:parentActivityName="bard.edu.focus2.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.DEFAULT" />
        </intent-filter>
    </activity>

or,if your main packcage name is bard.edu.focus2 then you can simply write:
 <activity
            android:name=".ProcessingInterface"
            >
        </activity>


text:
Q: Testing series $ \sum\limits_{n= 1}^{\infty} \sin{\frac{n + \sin(n)}{3n + 1}} $ I have a problem which is related to testing the divergence or convergence of a series. For more detail:
$$
\sum\limits_{n= 1}^{\infty} \sin{\frac{n + \sin(n)}{3n + 1}}
$$
I find it hard here because inside $\sin(n)$ does not go to $0$ but $\frac{1}{3} $ when $n \rightarrow \infty$, therefore, I don't know if I can conclude it is convergent here or not

A: Using the n-th term test:
$$\lim_{n \to \infty} a_n=\sin{\frac{1}{3}} \neq 0$$
Therefore, $\sum_{n=1}^{\infty} a_n$ diverges.


text:
Q: how can my app modify the shop's template files I need to inject liquid markup to the store's theme templates when my app is installed. I know there are ScriptTags, but they load scripts. And I know that the scripts can change the page's DOM. but I need to install my liquid to the product details pages. is it possible?

A: I would add your Liquid as a new snippet asset. The merchant can then be instructed to paste a  Liquid include statement you provide them in their product Liquid scripts.
That is fairly clean. Otherwise, your App could download their product Liquid script, edit it, and then add it to the shop as an alternative template. You could then instruct the merchant to render their products with the alternative template.
I am sure there are other possibilities too.


text:
Q: R spaghetti plot - changing line colour with connected points Spaghetti plot with geom_line and geom_smooth.
I have to plot "f0" according to "time_steps" with the lines changing their colour according to the factor "part" without disconnecting between its two levels "os" and "fv". Also the smooth disappear when "part" changes.
The structure of my dataset:
structure(list(time_steps = 1:20, f0.2 = c(203.61, 204.62, 204.23,
207.71, 198.5, 184.43, 185.15, 182.13, 183.2, 189.47, 188.88,
188.43, 188.53, 189.41, 191.15, 193.76, 196.6, 199.44, 201.45,
202.53), part = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("os",
"fv"), class = "factor")), row.names = c(NA, -20L), class = "data.frame")

The code I wrote:
ggplot (df, aes(time_steps, f0, colour = (part))) +
  geom_line(alpha = 0.1) + geom_smooth(size = 2)

The plot I got with a disconnected line:

Does someone have suggestions to solve this problem?

A: Breaking the line plot by color will always leave a gap unless there is a point in common between the two values of part. That gap signifies that there is no value of time_steps  > 10 for part == "os" and no values of time_steps < 12 for part == "fv".
Using some simulated data that looks like yours, here is a work around. It involves using geom_line twice, once without a color aesthetic mapped so you can connect the points. Then I used stat_smooth() twice (once for the line and once for the ribbon) because it gives more control over the appearance of the plot.
df <- data.frame(time_steps = 1:20,
                 f0 = round(runif(20, 190, 210)),
                 part = c(rep("os", 10), rep("fv", 10)))

ggplot(df) +
   geom_line(aes(x = time_steps, y = f0), color = "black", size = 1.5, alpha = 0.5) +
   geom_line(aes(x = time_steps, y = f0, color = part), size = 1.5, alpha = 1) +
   stat_smooth(geom ='line', aes(x = time_steps, y = f0), color = "black", size = 1.5, linetype = 2, alpha=0.5) +
   stat_smooth(geom = 'ribbon', aes(x = time_steps, y = f0), color = "NA", fill = "black", alpha = 0.1)


text:
Q: docker container using the same volume even after running new container image I have f.e. two containers in docker
compose.yml
version: '2'
services:
  nginx:
    image: local-nginx:0.3
    ports:
      - "81:81"
    volumes_from:
      - webapp
  webapp:
    image: local-webapp:0.65

webapp Dockerfile
FROM node:4.3.0
...
VOLUME /www
CMD npm run some_script

So, what's happening, webapp container shares folder /www to nginx, and static files are serving from nginx container.
I'm starting my app with command
docker-compose -f compose.yml up

everything working fine, good. But when I want for example run application with another version of webapp local-webapp:0.66
I change version to 0.66 in compose.yml, stop current containers and run again
docker-compose -f compose.yml up

But, I still see the same version of webapp. when i go inside nginx container I still see the same files from previous 0.65.  To see correct files, I must remove all containers, and then again docker-compose -f compose.yml up.
So, the question. How is this possible to configure my compose.yml file to update volume without removing all containers?

A: This is because Compose preserves volumes.
If you want new data, you have two options:

*

*don't use a volume

*remove the containers first


text:
Q: event.preventDefault() not waiting till promise is resolved I'm using event.preventDefault() technique to conditionally redirect user to an appropriate state based on a flag value which I'm fetching from backend. Eveything seems to be working fine except that sometimes the actual page is rendered and then redirection happens and that too in very few cases. This render of actual page is also for a very short duration. Following is the code snippet which I'm using:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){

  if (fromState.name === '' && toState.name === "myState"){

    Auth.isLoggedInAsync(function(loggedIn) {
      if (!loggedIn) {
        event.preventDefault();
        $state.go('state1');
      } else {
          event.preventDefault();
          Auth.getNextStateForUser()
          .then(function(data) {
            console.log(data.nextState);
            $state.go(data.nextState);
          })
          .catch(function(err){
              console.log(err);
              $state.go(toState.name);
          });
      }
    });

The logic which I'm following is, check if a user is logged in, then redirect to state1, else redirect to next appropriate state based on nextstateValue fetched from backend. If some error occurs, open the actual page without any redirection.
I hope I make my myself clear with what I'm doing. Just want to know if the issue which I'm facing is a genuine issue or there is something wrong which I'm doing from my side.
I have posted it on github page as well but it seems that I'm the only one who is facing this issue.
Do check this for more info:
https://github.com/angular-ui/ui-router/issues/2088
Thanks
Edit: Based on the answers I have updated my code for using ui-router resolve and converted my isLoggedInAsyc to return promise.
resolve: {

  promiseState: function(Auth, $state, $q, $stateParams) {

    var deferred = $q.defer();

    Auth.isLoggedInSync()
    .then(function(isLoggedIn){
        console.log(isLoggedIn);
        if(isLoggedIn) {
          Auth.getNextStateForUser()
              .then(function(data) {
                console.log(data.nextState);
                $state.go(data.nextState);
                deferred.resolve(data);
               })
              .catch(function(error) {
                console.log(error);
                deferred.reject(error);
          });
        }

        deferred.resolve(isLoggedIn);
    })
    .catch(function(err){
        console.log(err);
        deferred.reject(err);
    });

    return deferred.promise;
  }
}

And my isLoggedIn() returning promise.
  isLoggedInSync: function(callback) {
    var cb = callback || angular.noop;
    var deferred = $q.defer();
    if(currentUser.hasOwnProperty('$promise')) {
      currentUser.$promise.then(function() {
        deferred.resolve(true);
        return cb(true);
      }).catch(function() {
        deferred.resolve(false);
        return cb(false);
      });
    } else if(currentUser.hasOwnProperty('role')) {
      deferred.resolve(true);
    } else {
      deferred.resolve(false);
    }
    return deferred.promise;
  }

A: As mentioned by @milaenlempera, all Angular events are synchronous and there is no real way for you to nicely handle asynchrony in this instance. We had this issue in our production code and our solution was to use the resolve functionality in ui-router. This is how we solved it (plugged into your code obviously)
.state({
  name: 'myState',
  resolve: {
    principal: ['Auth', '$state', '$q', function(Auth, $state, $q) {
      var deferred = $q.defer();
      Auth.isLoggedInAsync(function(loggedIn) {
        if(!isLoggedIn) {
          deferred.resolve($state.go('state1'));
          return;
        }
        return Auth.getNextStateForUser()
          .then(function(data) {
            $state.go(data.nextState);
           })
          .catch(function(error) {
            deferred.reject(error);
          });
      });
      return deferred.promise;
    }]
  }
});

I'd recommend turning Auth.isLoggedInAsync to return a promise.
Also, your original code will cause an infinite loop if Auth.getNextStateForUser() is rejected. It will attempt to go to the state with the name toState.name, which is the state that just caused the error, which will cause another error and cause it to go to toState.name....
Because resolve cascades, you can implement child states if you want to share rules for permissions. It does really suck that there is no way to just put a property on the state and handle asynchronous permission checking elsewhere, but that's the hand we have been dealt at the moment.
As per comments, here's an example of promise chaining with your amended code.
  promiseState: ['Auth', '$state', function(Auth, $state) {
    return Auth.isLoggedInSync()
      .then(function(isLoggedIn) {
        if(isLoggedIn) {
          return Auth.getNextStateForUser().then(function(data) {
            return data.nextState;
          });
        }
        // If the user isn't logged in, return the state that you should go to instead
        return 'state1';
      })
      .then(function(nextState) {
        return $state.go(nextState);
      });
  }]

A: Angular events are synchoronously.
If you need stop it, you must do it synchronously in event handler function.
In you example is asynchronously checked login, meanwhile routing continue. This is why you see page and to redirect happens afterwards.
$rootScope.$on('$stateChangeStart',
    function(event, toState, toParams, fromState, fromParams){

      // here check if route can be display (synchronously)
      // or event.preventDefault()

      Auth.isLoggedInAsync(function(loggedIn) {
      if (loggedIn) {
        // continue to original route or go to state by server data
      } else {
        // redirect to login page
      }
});

you can be inspired in my solution here


text:
Q: As I can export the GridControl2 GridControl1 and united? I have GridControl1 and GridControl2, and I can export each Grid to. XLS (Excel) separately.
can I export the GridControl2 GridControl1 united??
This is what I have done so far but I can not export them unless I do it separately:
grid1.ExportToXls (argumentss);
grid2.ExportToXls (argumentss);

A: There is something called CompositeLink.
Have a look at this Devex article. It has an example.
http://www.devexpress.com/Support/Center/KB/p/A2730.aspx


text:
Q: find out if vertices are connected to each other I can't solve this problem, any help will be good.
teacher Açaizeiro Bórus Djorus is responsible for the new big project in his city: an aqueduct to supply açaí in almost every home. As the piping is expensive, he asked for your help to minimize costs and guarantee the energy of the people! His task is to find the lowest possible expense on the piping to connect all the homes as a supplier. Each meter of pipe costs R$ 3.14.
Input:
The first input line indicates how many there are n households in the region (1 ≤ n ≤ 100). The next n lines each represent information from a vertex in the format: id,d1,v1,d2,v2,⋯,dA,vA, where id is an integer identifying the residence, A is the number of neighbors of id, and each vi ≠ id is an integer identifying a neighboring house, which is located at a distance of di meters from id.
Exit:
Present the total value of the piping needed to connect all the homes.
Comments:
Each network user is confirmed by a unique id, the todograph is undirected, connected and loopless. In the first example, all vertices are connected to each other, and the minimum pipe required is 13 meters (R$ 40.82) connecting the houses in the following sequence: (3.1) and (1,2) In the second example, the minimum pipe required is 190 meters (R$ 596.60) connecting the residences in the following sequence: (3.1), (1,5),(5,4),(4,2) and (2, 6).

this is my code so far:
vertex, edges = [], []
for _ in range(int(input())):
  v, A, *neighbors = input().split()
  vertex.append(int(v))
  for i in range(0, len(neighbors), 2):
    edges.append((int(neighbors[i]), vertex[-1], int(neighbors[i + 1])))

total = 0
edges.sort(reverse=True)
agm = {v: set() for v in vertex}


text:
Q: generate barcode and show on ImageView in android I am new in android development,and I'm working on android with eclipse now.
I want to generate barcode and show it in ImageView by clicking Button.

A: Use zxing generate barcodes
Follow these steps and you are good to go.
first, locate core.jar under libs folder.
libs/core.jar
You can download ZXing-2.1.zip from here.
http://code.google.com/p/zxing/downloads/
After unzipping the file, find the jar file.
\ZXing-2.1\zxing-2.1\core\core.jar
And then write your own code like below.
import java.util.EnumMap;
import java.util.Map;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public class BarcodeExampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout l = new LinearLayout(this);
    l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    l.setOrientation(LinearLayout.VERTICAL);

    setContentView(l);

    // barcode data
    String barcode_data = "123456";

    // barcode image
    Bitmap bitmap = null;
    ImageView iv = new ImageView(this);

    try {

        bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
        iv.setImageBitmap(bitmap);

    } catch (WriterException e) {
        e.printStackTrace();
    }

    l.addView(iv);

    //barcode text
    TextView tv = new TextView(this);
    tv.setGravity(Gravity.CENTER_HORIZONTAL);
    tv.setText(barcode_data);

    l.addView(tv);

    }

    /**************************************************************
     * getting from com.google.zxing.client.android.encode.QRCodeEncoder
     *
     * See the sites below
     * http://code.google.com/p/zxing/
     * http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/EncodeActivity.java
     * http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java
     */

    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;

    Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
    String contentsToEncode = contents;
    if (contentsToEncode == null) {
        return null;
    }
    Map<EncodeHintType, Object> hints = null;
    String encoding = guessAppropriateEncoding(contentsToEncode);
    if (encoding != null) {
        hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
        hints.put(EncodeHintType.CHARACTER_SET, encoding);
    }
    MultiFormatWriter writer = new MultiFormatWriter();
    BitMatrix result;
    try {
        result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
    } catch (IllegalArgumentException iae) {
        // Unsupported format
        return null;
    }
    int width = result.getWidth();
    int height = result.getHeight();
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
        pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
        }
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height,
        Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
    }

    private static String guessAppropriateEncoding(CharSequence contents) {
    // Very crude at the moment
    for (int i = 0; i < contents.length(); i++) {
        if (contents.charAt(i) > 0xFF) {
        return "UTF-8";
        }
    }
    return null;
    }

}


text:
Q: Opacity Not Applying JavaScript Canvas I am calling my method drawInventory() when my mouse moves and when I press i.
I set the opacity at the start of the drawInventory Method:
 function drawInventory() {
inventoryCtx.fillStyle = "rgba(0, 0, 0, 0.7)";
inventoryCtx.fillRect(10, 10, invWidth-20, invHeight-20);
 }

When I move the mouse, the opacity stays at .7 correctly, however after pressing i, the opacity decreases.
Here is the method I call upon the i keypress:
    function toggleInventory() {
    if(!showInventory) {
        showInventory = true;
        $("#inventoryCanvas").removeClass("hideClass");
        drawInventory();
        $("#inventoryCanvas").fadeIn(1);
    }
    else {
        $("#inventoryCanvas").fadeOut(100);
        showInventory = false;
    }
};

The strange part is, the first time after refreshing the page and pressing i the opacity is there. If I press i twice, it comes back with even higher opacity (darker) then the next time it is completely dark. I do not know why it is losing opacity each time when I am calling the same method.
Note: I've tried inventoryCtx.globalAlpha, it does not change the issue.
Any help is appreciated.

A: A canvas object is an image and is initially completely transparent.
When you draw on it using the context however the pixels are changed to reflect your drawing.
If you draw a second time on it you will start from what is currently on the canvas and that's why it seems to you that the opacity is not applied; the reason is that it's applied but on pixels that are already not completely transparent.
Note that hiding and showing the element doesn't wipes off its content. Each canvas instance will remember the value of its pixels even if you move it around the DOM tree.
To keep repeatable results when drawing you need to clear the canvas on starting of the paint procedure using
canvas.clearRect(0, 0, canvas.width, canvas.height);

or by setting the canvas object size with
canvas.width = canvas.width;

as resizing a canvas has the documented side effect of clearing its content even if the size remains exactly the same.


text:
Q: SugarCrm: How to find caller of a logic hook Suppose we have a before save logic hook on leads, now How we can detect if this called logic hook is:

*

*a crm user who is saving a lead form

*is a lead captured from on of entry points

*is a save triggered by soap calls

*is a workflow which is modifying lead fields

*is called because of csv import

*...

I have checked some of the behaviors, it seems logic hooks are not called on workflows (at least in my test)
Also I hope to figure out this issue in global variables, but there are a lot of global variables.
So How I can detect caller of a logic hook ?

A: The best way that I found to figure this out is to add a:
$GLOBALS['log']->fatal(print_r($_REQUEST,true));

To your logic hook. Then test each scenario that you need to account for and see how the request differs. Also check $_SESSION. You'll be able to find a few things that you can depend upon for your logic.

A: That's what I did eventually. I share some of my observations so it may help the others (these are statements, based on the case some of them may applies)

*

*in third party entry point calls $_SESSION is empty, in direct entry    point calls is not so. Also in rest calls session is not empty.

*rest calls have $_REQUEST[rest_data] and others don't.

*entry point calls have $_REQUEST[entryPoint] available in the array

*global $current_user is available, but the id var ($current_user->id)    is a string only in the case a user is submitting a form in crm.

*in inline editing $_REQUEST[action] is equal to saveHTMLField

*in user calls $_SERVER[HTTP_USER_AGENT] is available and in other    calls it is not.

In a simple case this code shows how to detect user calls:
$trigger = false;
global $current_user;
if (!isset($current_user->id) || !strlen($current_user->id) > 2)
    $trigger = true;
if ($trigger) {
    //#My Custome Code
}


text:
Q: prettypopin Modal with ASP.NET buttons I'm using prettypopin Modal(Stéphane Caron) to Edit my FormView. Looks like it's only working with regular submit button.
<input type="submit" value="Submit" id="buttSubmit" />

But it's not working with any .net buttons(asp:button, asp:LinkButton). Does anyone has any suggestions?
Or can you recomend any other jQuery Modals, for editing that works with asp.net controls?
Thanx.

A: This is because the modal is being removed from the DOM and replaced at the end of the document just before the  tag.  you will need to modify the jQuery to place items before the </form> tag for this to work.
edit:
in the source for prettypopin in the buildpopin function, there is a line that looks like:
$('body').append('
...

you will want to change this to:
$('body form:first').append('
...

this is because jquery is removing the form within the modal dialog and replacing it AFTER the form tag, which is why it is not posting back.  you will see this in action if you use firefox's "View Generated Source"


text:
Q: How to make Material-UI GridListTitleBar and Image a Link in ReactJS I am using Material UI GridList to display a list of Events in React. Everything is working fine except that I am not able to make Title or Image a Link. Does anyone know how to make Title and Image a Link?
Here is my Component.

  <GridListTile key="Subheader" style={{ height: "auto" }}>
    <ListSubheader component="div">This is List of Events</ListSubheader>
  </GridListTile>
  <GridList
    cellHeight={330}
    cols={matches ? 1 : 3}
    className={classes.gridList}
    spacing={12}
  >
    {tileData.length > 0 &&
      tileData.map((tile, index) => {
        return (
          <GridListTile
            key={Math.floor(Math.random() * new Date().getTime())}
          >

            <GridListTileBar
              title={tile.title}
              subtitle={by: {tile.description}}
              actionIcon={<IconButton title={tile.title} />}
            />
          </GridListTile>
        );
      })}
  </GridList>

);

Update
This is an update to the answer that was given below. The first image is now smaller than the rest of the images after update the code with the solution given below.

Here is the new code that I am trying:

  <GridListTile key="Subheader" style={{ height: "auto" }}>
    <ListSubheader component="div">This is List of Events</ListSubheader>
  </GridListTile>
  <GridList
    cellHeight={330}
    cols={matches ? 1 : 3}
    className={classes.gridList}
    spacing={12}
  >
    {tileData.length > 0 &&
      tileData.map((tile, index) => {
        return (
          <GridListTile
            key={Math.floor(Math.random() * new Date().getTime())}
          >

              <GridListTileBar title={tile.title} />

          </GridListTile>
        );
      })}
  </GridList>

A: Try wrapping the image with an anchor tag like this:
// ...
<GridListTile key={Math.floor(Math.random() * new Date().getTime())}>

  <GridListTileBar
    title={tile.title}
    subtitle={by: {tile.description}}
    actionIcon={<IconButton title={tile.title} />}
  />
</GridListTile>
// ...

It is important, after wrapping the image inside an anchor tag to add the class MuiGridListTile-imgFullHeight to the image to keep the same styling of the grid. Normally this class is added automatically, but if you wrap it inside an anchor tag it isn't. So you need to add it manually.
Update
The image shows expected behavior, because your first image is not wide enough to cover the whole tile and you only added the class to scale the img to full height. There is also a class to scale to full width: MuiGridListTile-imgFullWidth, but you can't use both of these classes together for your use case as the styles conflict (see the style definition here: https://github.com/mui-org/material-ui/blob/master/packages/material-ui/src/GridListTile/GridListTile.js).
You can try to set the width to 100% in the image style prop:

A: I eventually managed to get it to work without breaking or stretching my images, and here is what I did.

  <GridListTile key="Subheader" style={{ height: "auto" }}>
    <ListSubheader component="div">This is List of Events</ListSubheader>
  </GridListTile>
  <GridList
    cellHeight={330}
    cols={matches ? 1 : 3}
    className={classes.gridList}
    spacing={12}
  >
    {tileData.length > 0 &&
      tileData.map((tile, index) => {
        return (
          <GridListTile
            component={Link}
            to={"/events/" + tile._id + "/eventcomments"}
            key={Math.floor(Math.random() * new Date().getTime())}
          >

            <GridListTileBar title={tile.title} />
          </GridListTile>
        );
      })}
  </GridList>

A: const Gallery = () => {
  const classes = useStyles();
  return (
    <Fragment>

    <Toolbar/>
    <Grid container spacing={0}>
    <Grid item xs={12}>
    <Paper className={classes.paper}>GALERIA</Paper>

    <GridList cellHeight={280} className={classes.gridList} cols={1}>
        {tileData.map((tile) => (
          <GridListTile style={{ width: "100%" }}  key={tile.img} cols={tile.cols || 1}>

          </GridListTile>
        ))}
    </GridList>

    </Grid>
    </Grid>

    </Fragment>
  )
}
export default Gallery;

A: You can change the type of underlying component rendered by the GridListTime Material-UI component. Just add the component="a" to have it render as an anchor tag. Then you may specify an href prop to pass in your route. See below:
<GridList cellHeight={160} className={classes.gridList} cols={3}>
  {tileData.map((tile) => (
    <GridListTile key={tile.img} cols={tile.cols || 1} component="a" href="/">

    </GridListTile>
  ))}
</GridList>


text:
Q: Is it possible to create a meeting request for outlook with nodeJS? I am developing a very basic calendar with Angular and Node and I haven't found any code on this.
Workflow is the following : create an event, input the recipient's e-mail address, validate the event.
This triggers an e-mail sent to the recipient. The mail should be in the outlook meeting request format (not an attached object).
This means that when received in outlook the meeting is automatically added in the calendar.
Is this possible? If yes is it possible with only javascript on Node side?

A: If you do not want to use smtp server approach in earlier accepted solution, you have Exchange focused solution available. Whats wrong in current accepted answer? it does not create a meeting in sender's Calendar, you do not have ownership of the meeting item for further modification by the sender Outlook/OWA.
here is code snippet in javascript using npm package ews-javascript-api
var ews = require("ews-javascript-api");
var credentials = require("../credentials");
ews.EwsLogging.DebugLogEnabled = false;

var exch = new ews.ExchangeService(ews.ExchangeVersion.Exchange2013);

exch.Credentials = new ews.ExchangeCredentials(credentials.userName, credentials.password);

exch.Url = new ews.Uri("https://outlook.office365.com/Ews/Exchange.asmx");

var appointment = new ews.Appointment(exch);

appointment.Subject = "Dentist Appointment";
appointment.Body = new ews.TextBody("The appointment is with Dr. Smith.");
appointment.Start = new ews.DateTime("20170502T130000");
appointment.End = appointment.Start.Add(1, "h");
appointment.Location = "Conf Room";
appointment.RequiredAttendees.Add("user1@constoso.com");
appointment.RequiredAttendees.Add("user2@constoso.com");
appointment.OptionalAttendees.Add("user3@constoso.com");

appointment.Save(ews.SendInvitationsMode.SendToAllAndSaveCopy).then(function () {
    console.log("done - check email");
}, function (error) {
    console.log(error);
});

A: Instead of using 'ical-generator', I used 'ical-toolkit' to build a calender invite event.
Using this, the invite directly gets appended in the email instead of the attached .ics file object.
Here is a sample code:
const icalToolkit = require("ical-toolkit");

//Create a builder
var builder = icalToolkit.createIcsFileBuilder();
builder.method = "REQUEST"; // The method of the request that you want, could be REQUEST, PUBLISH, etc

//Add events
builder.events.push({
  start: new Date(2020, 09, 28, 10, 30),
  end: new Date(2020, 09, 28, 12, 30),
  timestamp: new Date(),
  summary: "My Event",
  uid: uuidv4(), // a random UUID
  categories: [{ name: "MEETING" }],
  attendees: [
    {
      rsvp: true,
      name: "Akarsh ****",
      email: "Akarsh **** <akarsh.***@abc.com>"
    },
    {
      rsvp: true,
      name: "**** RANA",
      email: "**** RANA <****.rana1@abc.com>"
    }
  ],
  organizer: {
    name: "A****a N****i",
    email: "A****a N****i <a****a.r.n****i@abc.com>"
  }
});

//Try to build
var icsFileContent = builder.toString();

//Check if there was an error (Only required if yu configured to return error, else error will be thrown.)
if (icsFileContent instanceof Error) {
  console.log("Returned Error, you can also configure to throw errors!");
  //handle error
}

var mailOptions = { // Set the values you want. In the alternative section, set the calender file
            from: obj.from,
            to: obj.to,
            cc: obj.cc,
            subject: result.email.subject,
            html: result.email.html,
            text: result.email.text,
            alternatives: [
              {
                contentType: 'text/calendar; charset="utf-8"; method=REQUEST',
                content: icsFileContent.toString()
              }
            ]
          }

        //send mail with defined transport object
        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                console.log(error);
            }
            else{
                console.log('Message sent: ' + info.response);
            }
        });

A: For those still looking for an answer, here's how I managed to get the perfect solution for me.
I used iCalToolkit to create a calendar object.
It's important to make sure all the relevant fields are set up (organizer and attendees with RSVP).
Initially I was using the Postmark API service to send my emails but this solution was only working by sending an ics.file attachment.
I switched to the Postmark SMTP service where you can embed the iCal data inside the message and for that I used nodemailer.
This is what it looks like :
        var icalToolkit = require('ical-toolkit');
        var postmark = require('postmark');
        var client = new postmark.Client('xxxxxxxKeyxxxxxxxxxxxx');
        var nodemailer = require('nodemailer');
        var smtpTransport = require('nodemailer-smtp-transport');

        //Create a iCal object
        var builder = icalToolkit.createIcsFileBuilder();
        builder.method = meeting.method;
        //Add the event data

        var icsFileContent = builder.toString();
        var smtpOptions = {
            host:'smtp.postmarkapp.com',
            port: 2525,
            secureConnection: true,
            auth:{
               user:'xxxxxxxKeyxxxxxxxxxxxx',
               pass:'xxxxxxxPassxxxxxxxxxxx'
            }
        };

        var transporter = nodemailer.createTransport(smtpTransport(smtpOptions));

        var mailOptions = {
            from: 'message@domain.com',
            to: meeting.events[0].attendees[i].email,
            subject: 'Meeting to attend',
            html: "Anything here",
            text: "Anything here",
            alternatives: [{
              contentType: 'text/calendar; charset="utf-8"; method=REQUEST',
              content: icsFileContent.toString()
            }]
        };

        //send mail with defined transport object
        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                console.log(error);
            }
            else{
                console.log('Message sent: ' + info.response);
            }
        });

This sends a real meeting request with the Accept, decline and Reject button.
It's really unbelievable the amount of work you need to go through for such a trivial functionality and how all of this not well documented.
Hope this helps.

A: It should be possible as long as you can use SOAP in Node and also if you can use NTLM authentication for Exchange with Node. I believe there are modules for each.
I found this blog very helpful when designing a similar system using PHP

A: Please check the following sample:
const options = {
    authProvider,
};

const client = Client.init(options);

const onlineMeeting = {
  startDateTime: '2019-07-12T14:30:34.2444915-07:00',
  endDateTime: '2019-07-12T15:00:34.2464912-07:00',
  subject: 'User Token Meeting'
};

await client.api('/me/onlineMeetings')
    .post(onlineMeeting);

More Information: https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-1.0&tabs=http


text:
Q: How can I visualize triples in the form of a knowledge graph in a web application? I have a text file with all the triples (from OpenIE). I want to visualize the triples in the form of a knowledge graph in my web application. I am already aware of Neo4j, but they have a seperate UI of their own to visualize the knowledge graph.
How can I use the same or are there other good JavaScript libraries to do the same?


text:
Q: Issue with hoverIntent and slideUp slideDown So I have a group of <li>s that are headings in a slider. Each heading has sub-headings contained in .sub-menu with the current menu that is already selected being .current-menu-item. I would like the current item to be present upon load. I am currently calling this with:
var myPath = window.location.pathname;

console.log(myPath);

if(myPath == '/thing/'){
   $('#menu-item-1 .sub-menu').slideToggle("1000");
};
if(myPath == '/other-thing1/'){
   $('#menu-item-2 .sub-menu').slideToggle("1000");
};
if(myPath == '/other-thing2/'){
   $('#menu-item-3 .sub-menu').slideToggle("1000");
};

This causes the current page's .sub-menu to display whenever I'm on that page.
The goal is to get the nav so that when I initially load the page, the sub-menu for the page displays. Then, when I mouse over the other menus, the sub menu for the current menu slides up. Then, when I mouse out of any heading, the sub-menus of the .current-menu-item slides down again. Below is what I have so far, which gets me pretty close, but the .current-menu-item isn't sliding up again.
$(".aside-section-content ul li").each(function(){
if($(this).children('.sub-menu').length){
    $(this).hoverIntent({
        interval: 50,
        over: function navHoverInDrop () {
            $(this).children('.sub-menu').slideDown(300).prev('a').css({'background-image':'none'});
        },
        timeout: 250,
        out: function navHoverOutDrop () {
            $(this).not('.current-menu-item').children('.sub-menu').slideUp(300).prev('a').css({'background':"url('uploads/plus.png') no-repeat center right 13px"});
        }
    });
}
});

I've been able to get some variations that have gotten close, but haven't yet gotten it bug free. Anyone have any ideas?


text:
Q: Hello, working on Practice It-Javascript So here is the initial Question
"The following program attempts to print a full name given a first name and last name as parameters. The last name should be printed in full, starting with a capital letter and followed by all lowercase letters. A comma and the capitalized first name initial should then follow. For example, the call printName("Abby", "Stepp") should output "Stepp, A." to the console. The initial code contains several kinds of errors. Fix the code below so that it compiles and runs properly."
Here's the answer you start off with
// Prints a full name where last is followed by a ", " and the capital letter
// of first, which is followed by a "."
    function printName(first, last) {
        string fullname = last + ", " + substring(first(0, 1)) + ".";
        return fullname;
    }

Here's my answer
// Prints a full name where last is followed by a ", " and the capital letter
// of first, which is followed by a "."

function printName(first, last) {
    var fullName = last + "," + first + ".";
    return fullName;
};

I want to understand why my code is not passing, in my answer I am passing in a concatenated value into var fullName I have a previous question through the same platform that did not have to concatenate in which that was passed and is similar to my answer here so I am thinking that it has something to do with the value that is being passed into var fullName
Here's a sample of that problem, I would like to know the difference between the two problems. Both these questions are asking me to fix these Errors
Question
public static int add(x, y) {
    int sum = x + y;
    return sum;
}

Answer
function add(x, y) {
    var sum = x + y;
    return sum;
};

A: For the first code snippet:
this expression: substring(first(0, 1)) gets the first letter of first. In your code you just concatenate last and first, whereas the original answer concatenates last and the first letter of first. For example:
The first answer would give you:
Smith, J.
Your answer would give you:
Smith, John.
I'm not entirely sure what the second part of your question is asking, if you clarify in a comment I will update my answer.

A: You have to get the first letter of the first name, and make sure that it is capital; first.toUpperCase().split()[0] outputs the first letter and ensures that it is capital.
function printName(first, last) {
    var fullName = last + "," + first.toUpperCase().split()[0] + ".";
    // "," should be ", " ; with a space
    return fullName;
}


text:
Q: second dojo FilteringSelect control onChange event doesn't get fired I'm working with arcgis Javascript Api 3.7 (wich includes dojo 1.9.1), and I have been developing a custom templated dijit that has two filteringSelect controls, the first one gets pupulated correctly, and i have a second one that gets populated when the user selects one item from the first one setting its data store at that particular moment. this second filteringSelect gets correctly populated everytime, but something happens with the onchange event, because the function handler never gets fired, I need to do some other staff on the onchange event of the second FilterinSelect.
It seems something gets messed up with the second filteringSelect (guessing something with the handler context) but I can't figure it out yet.
My two filtering controls template declaration (part of my dijit html template:

                    Capa:

                    <input data-dojo-type="dijit.form.ComboBox" name="layerDijit" id="layerDijit"
                           data-dojo-props="autoComplete:true, required:true, searchAttr:'name', style:'width:100%;'"
                           data-dojo-attach-point="layerDijit" data-dojo-attach-event="change:_handleLayerSelected"/>

                    Campo:

                    <input data-dojo-type="dijit.form.FilteringSelect" name="fieldDijit" id="fieldDijit"
                           data-dojo-props="autoComplete:true, required:true, searchAttr:'name', style:'width:100%;'"
                           data-dojo-attach-point="fieldDijit" data-dojo-attach-event="change:_handleFieldSelected"/>

Dijit JS Script:
The code that populates the first Filtering Select
postCreate: function() {
        this.inherited(arguments);

        ....

        this.rootMapLayer = this.map.getLayer("ELAPAS");
        if (this.rootMapLayer.loaded){
            this.listLayers(this.rootMapLayer);
        }
        else{
            this.rootMapLayer.on("load", lang.hitch(this, this.listLayers));
        }

        //enlace de eventos (tested this, and it doesn't work for the second filtering select either)
        //this.fieldDijit.on('change', lang.hitch(this, this._handleFieldSelected));
        //this.layerDijit.on('change', lang.hitch(this, this._handleLayerSelected));
    },

listLayers: function() {

        var layerInfos = [];

        layerInfos = array.filter(this.rootMapLayer.layerInfos,function(info,index){
            return info.subLayerIds === null;
        });

        if(layerInfos.length === 0) {
            console.error("No se encontro ninguna capa para el servicio de mapa seleccionado");
            return;
        }

        var layersStore = new Memory({
            data: layerInfos
        });

        this.layerDijit.set('store', layersStore);
    },

The code that handles the selection change in the first filteringSelect called layerDijit and loads the data for the second one (FieldDijit):
_handleLayerSelected: function () {
        var selectedLayer = this.layerDijit.item;

        if(this.getSelectedLayerUrl() === null) {
            return;
        }

        //Se limpia el campo actual
        this.fieldDijit.set("value", "");

        //Se arma la url del layer específico para traer la información de la capa (sus campos)
        var layerUrl = this.rootMapLayer.url + "/" + selectedLayer.id;

        esri.request({
            url: layerUrl,
            content: {
                f: "json"
            },
            handleAs: "json",
            callbackParamName: 'callback',
            load: lang.hitch(this, '_handleLayerInfo'),
            error: lang.hitch(this, '_handleLayerInfoError')
        });
    },
_handleLayerInfo: function(data) {
        var layerInfo = data;
        if (!layerInfo.fields) {
            console.error("No se pudo obtener la información de los campos de la capa");
            return;
        }

        var fieldsStore = new Memory({
            data: layerInfo.fields
        });

        this.fieldDijit.set('store', fieldsStore);
    },

    getSelectedLayerUrl: function(){
        var selectedLayer = this.layerDijit.item;
        if(!selectedLayer) {
            return null;
        }
        //Se arma la url del layer específico para traer la información de la capa (sus campos)
        return this.rootMapLayer.url + "/" + selectedLayer.id;
    },

    _handleLayerInfoError: function(err){
        console.error(err);
    },

The function that doesn't get fired, the one that is supossed to handle se change event of the second filtering select:
_handleFieldSelected: function () {
        alert("doesn't get fired");
        /*var selectedField = this.fieldDijit.item;

        if(!selectedField) {
            return;
        } */
    },

Could you give me some advice about this problem?, What am I doing wrong?.
Thanks in advance

A: bishop, thanks for your answer, I think I wasn't clear with my question, I do understand that the "onChange" event is supposed to get fired when the user (or something in the background) changes the selected item in the FilteringSelect, so my problem was that when the user selects an item from the second FilteringSelect control its onchange event didn't get fired.
As you suggested I tryed a simpler example (with a hard coded Memory objects) and it did work, so I started to dig a little bit more and realized that the problem was with my memory object,
Aparently when you declare a Memory object you have to make sure that there is an ID filed in the array collection objects, like in the next example:
var stateStore = new Memory({
            data: [
                {name:"Alabama" id:"AL"},
                {name:"Alaska", id:"AK"},
                {name:"American Samoa", id:"AS"},
                {name:"Arizona", id:"AZ"},
                {name:"Arkansas", id:"AR"},
                {name:"Armed Forces Europe", id:"AE"},
                {name:"Armed Forces Pacific", id:"AP"},
                {name:"Armed Forces the Americas", id:"AA"},
                {name:"California", id:"CA"},
                {name:"Colorado", id:"CO"},
                {name:"Connecticut", id:"CT"},
                {name:"Delaware", id:"DE"}
            ]
        });
        this.fieldDijit.set('store', stateStore);

When you don't explicitly tell it in the memory object declaration, it is asummed that there is a field  called "id". In my case, the array that I assing to the memory object in the second filteringSelect didn't have a field called "id"
so I changed:
var fieldsStore = new Memory({
            data: layerInfo.fields
        });

for:
var fieldsStore = new Memory({
            idProperty: "name", //added this
            data: layerInfo.fields
        });

and now the event gets fired when the selected item in the second filterin select changes.

A: Based on what I'm reading, I think you're expecting this code:
this.fieldDijit.set('store', fieldsStore);

to cause the second select in your co-dependent select arrangement to fire its change event -- after all, the select has "changed" in the sense that it has a different store.
But that's not what the change event means.  The change event means the user has changed the selected value.  So after setting a new store, if you select a value in the second drop down, your change handler should fire.
Here's an example that I think reduces yours to its simplest elements.  Notice how when you select the first box's value, the second's store changes but its onchange event does not fire (as expected).  But when you select the second box's value, its onchange does fire (as expected):
<!DOCTYPE html>

        <link href='//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dijit/themes/claro/claro.css' rel='stylesheet' type='text/css' />

        <select data-dojo-id='first' data-dojo-type='dijit/form/ComboBox' data-dojo-props='store:s1'>

        </select>

        <select data-dojo-id='second' data-dojo-type='dijit/form/ComboBox'>

        </select>

If I'm not understanding the error you're describing, can you send a simpler test case?


text:
Q: Matrix report with columns grouped with Date field has strange column added Hi so my question is what is this strange column i can see after i group my columns with Date?

I do not know what it shows and why it is there. How to remove it?


text:
Q: How to remove plurals in Lucene.NET? I'm trying to extract some keywords from a text. It works quite fine but I need to remove plurals.
As I'm already using Lucene for searching purpose, I'm trying to use it to extract keyword from indexed terms.
1st, I index the document in a RAMDirectory index,
RAMDirectory idx = new RAMDirectory();
using (IndexWriter writer =
    new IndexWriter(
        idx,
        new CustomStandardAnalyzer(StopWords.Get(this.Language),
        Lucene.Net.Util.Version.LUCENE_30, this.Language),
        IndexWriter.MaxFieldLength.LIMITED))
{
    writer.AddDocument(createDocument(this._text));
    writer.Optimize();
}

Then, I extract the keywords:
var list = new List<KeyValuePair<int, string>>();
using (var reader = IndexReader.Open(directory, true))
{
    var tv = reader.GetTermFreqVector(0, "text");
    if (tv != null)
    {
        string[] terms = tv.GetTerms();
        int[] freq = tv.GetTermFrequencies();

        for (int i = 0; i < terms.Length; i++)
            list.Add(new KeyValuePair<int, string>(freq[i], terms[i]));
    }
}

in the list of terms I can have terms like "president" and "presidents"
How could I remove it?
My CustomStandardAnalyzer use this:
public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
{
    //create the tokenizer
    TokenStream result = new StandardTokenizer(this.version, reader);

    //add in filters
    result = new Lucene.Net.Analysis.Snowball.SnowballFilter(result, this.getStemmer());
    result = new LowerCaseFilter(result);
    result = new ASCIIFoldingFilter(result);
    result = new StopFilter(true, result, this.stopWords ?? StopWords.English);

    return result;
}

So I already use the SnowballFilter (with the correct language specific stemmer).
How could I remove plurals?

A: My output from the following program is:
text:and
text:presid
text:some
text:text
text:with

class Program
{
    private class CustomStandardAnalyzer : Analyzer
    {
        public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader)
        {
            //create the tokenizer
            TokenStream result = new StandardTokenizer(Lucene.Net.Util.Version.LUCENE_30, reader);
            //add in filters
            result = new Lucene.Net.Analysis.Snowball.SnowballFilter(result, new EnglishStemmer());
            result = new LowerCaseFilter(result);
            result = new ASCIIFoldingFilter(result);
            result = new StopFilter(true, result, new HashSet<string>());
            return result;
        }
    }

    private static Document createDocument(string text)
    {
        Document d = new Document();
        Field f = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
        f.SetValue(text);
        d.Add(f);
        return d;
    }

    static void Main(string[] args)
    {

        RAMDirectory idx = new RAMDirectory();
        using (IndexWriter writer =
            new IndexWriter(
                idx,
                new CustomStandardAnalyzer(),
                IndexWriter.MaxFieldLength.LIMITED))
        {
            writer.AddDocument(createDocument("some text with president and presidents"));
            writer.Commit();
        }

        using (var reader = IndexReader.Open(idx, true))
        {
            var terms = reader.Terms(new Term("text", ""));
            if (terms.Term != null)
                do
                    Console.WriteLine(terms.Term);
                while (terms.Next());
        }
        Console.ReadLine();

    }
}


text:
Q: What is the appropriate way to get notified on DFS junction mount in smb server on Mac OS? When smb volume is mounted, we are getting notification in didMount event callback of NSWorkspace. Same is not consistent for DFS volume mount on browse. Is there a way to detect DFS junction mount on browse of smb shares?
We are watching for DFS target mounted on smb volume using NSWorkSpace's NSWorkspaceDidMountNotification notification in our code. But didMount notification is inconsistent and not reliable. Only for the first time, didMount notification is notified. Later on we are not getting notified with didMount notification, though notification is successful.
Is there any other better approach to be notified on DFS junction mount?
Code snippet:
let workspace = NSWorkspace.shared
        workspace.notificationCenter.addObserver(self, selector: #selector(didMount(_:)) , name: NSWorkspace.didMountNotification, object: nil)

@objc func didMount(_ notification: NSNotification)  {
        NSLog("didMount, mounted userinfo - '%@'.", notification.userInfo!)
}

Expecting some way to get notified on DFS junction mount


text:
Q: Prolog rule assertion with variable name I try to assert some rules automatically in SWI-Prolog:
generate_rule_len(FG,SG):-
    length(FG,L),length(SG,L0),
    Head = input_len(FG,SG,FS,SS,X),
    Body = (length(FG,L1),L1 is L, length(SG,L2), L2 is L0, X = SS),
    % Rule = (Head :- Body), \+Rule,
    assertz(Head :- Body),
    append('rulesDB.pl'),
    writeq(Head :- Body),write('.'),nl,
    told.

This works pretty fine, but the asserted result in the rulesDB.pl do not use the names of the variables FG,SG,FS,SS,Xthey are replaced with their memory position (?), this looks like:
input_len(_3078,_3080,_3082,_3084,_3086):-
   length(_3078,_3098),_3098 is 2,length(_3080,_3122),_3122 is 2,_3086=_3084.

Is it possible to use the names of the variables instead?
Futhermore I want to prevent the duplication of generated rules. Therefore I tried Rule = (Head :- Body), \+Rule, but this give me an Undefined procedure: (:-)/2.
Can anybody tell me what´s wrong with my code?
Thanks in advance!