Q:

Is generating all strings permutation NP Complete?

Calculating all string permutations of a given string can be solved in O(n!) by trying all possibilities.
Now, looking at the Travel Salesman Problem, we can solve it by trying all permutations of cities. Lets say we have cities A, B and C.
Lets say we start at city A. By calculating all permutations of BC string we get ABC ACB, then we just sum (in polynomial time the distance between AB, CB and CA for the first case...)
So isnt this a reduction of the all strings permutation to the travel salesman problem and isnt it a NP Complete problem?

A:

I think you're confusing some concepts:
What you describe is not "reducing the all permutations problem to TSP", but the opposite: reducing TSP to the all permutations problem.
What that proves is that generating all permutations is NP-Hard (at least as hard as the hardest NP problem).
To prove something is NP-Complete, you would also have to prove that it's in NP. But this is not true, right out of the gate: NP is a set of decision problems, and the problem you described isn't a decision problem.
See also: What are the differences between NP, NP-Complete and NP-Hard?


Q:

cypher query: infinite loop with optional match

today I was trying to expand a query that I'm running on a very small test database, but I think that I must be firing some kind of infinite loop, because it keeps executing until it returns an undefined error
so I have no idea what the problem is, and am looking for suggestions...
this query works
MATCH (n:whatnot), (u:user)
OPTIONAL MATCH (u)-[r1:favorites]->(n)

WHERE id(u)=1

RETURN

  id(n) AS id ,
  CASE
    WHEN length((u)-[r1]->(n)) > 0 THEN 1
    ELSE 0
  END AS favorites

ORDER BY id DESC

and this works too
MATCH (n:whatnot), (u:user) , (m)

WHERE id(u)=1 AND id(m) = 73298 AND (n)-->(m)

RETURN id(n) AS id

but even thou they share results, if I try to run them together like so
MATCH (n:whatnot), (u:user) , (m)
OPTIONAL MATCH (u)-[r1:favorites]->(n)

WHERE id(u)=1  AND id(m) = 73298 AND (n)-->(m)

RETURN

  id(n) AS id ,
  CASE
    WHEN length((u)-[r1]->(n)) > 0 THEN 1
    ELSE 0
  END AS favorites

ORDER BY id DESC

it goes into an infinite loop
what am I missing?
many thanks you

A:

You need to do the WHERE for the top MATCH before the OPTIONAL MATCH. Also, it's better to do predicate patterns in the MATCH if you can.
MATCH (n:whatnot)-->(m), (u:user)
WHERE id(u)=1 AND id(m)=73298
OPTIONAL MATCH (u)-[r1:favorites]->(n)
RETURN
  id(n) AS id ,
  CASE
    WHEN length((u)-[r1]->(n)) > 0 THEN 1
    ELSE 0
  END AS favorites
ORDER BY id DESC


Q:

Pair Programming with an uneven number of team members?

Recently, we've come across an issue at work where if one person is working on some code by themselves, it seems to come out with the other team members looking at it and going "Huh? That's ugly, unmanageable, I need to rewrite that"
In fact, recently, I myself have had to re-factor something that was written the week before so that I'd be able to add in my (related) feature.
I know that Pair programming is the way to go for this, but we have an uneven team (3 members). As our team is being pushed pretty hard at the moment, we really don't have time for Peer Reviews (though we can do Pair Programming, as we're allowed to estimate that into our task estimates)
I'm just curious as to how people would suggest we overcome these issues with poor code being generated.

A:

When you work alone, and produce code which your colleagues find ugly and unmanageable and needs to be rewritten, then do you:
(a) agree with them when you look at it a second time,
(b) disagree?
If (a), then the problem is that on your own, you aren't fully clarifying your code when you write it. Since pair programming is the only thing making you write decent code, I suppose I'd recommend that the "odd one out" should work on tasks which do not involve writing long tracts of bad code: bug-hunting; maybe writing test code, since that tends to be a bit less fiendish. Meanwhile, work on improving your skills at writing better code - perhaps do reviews of your own code from a few months ago, and make notes as to what was wrong with it.
If (b), then the problem you have is incompatible ways of expressing your ideas. The code may not be bad by your standards, but it's mutually incomprehensible, which in a corporate setting means it's bad code. Pair programming means what you write is a compromise that 2 out of 3 of you understand, but that's not really a solution.  You need to come to some mutual agreements about what you find most difficult about each other's code, and stop doing that. And you all urgently need to start thinking of "code quality" in terms of "my 2 colleagues will like this code", not "I like this code".
Either way, you all need to work on writing code for the purpose of being read, rather than for the purpose of getting the immediate job done as quickly as you possibly can. Personally I have done this by trying to express things in the way that I think other people might express and understand them, rather than just what makes sense to me at the time. Eventually it becomes habitual. When I write code, I write it for a public audience just like I'm writing this post for a public audience. OK, so on my personal projects it's an audience of people who think just like me, whereas at work it's an audience that thinks like my colleagues. But the principle is to write code as if someone's reading it. You're explaining yourself to them, not the compiler.
Not that my code is the best in the world, but I do think I benefited in that my first job was in a company with 30-odd programmers, so I got to see a wide range of ways of thinking about things. Also a few examples of "what not to do", where one programmer had done something that nobody else could easily understand, and therefore could definitively be said to be bad. With only 3 people, it's not clear whether a 2 v. 1 difference of opinion means that the 1 is a freak or a reasonable minority. When I did something and 4 or 5 people could glance at it and immediately say "eeew, don't do that", then I started to really believe it was just a dumb idea in the first place.
I'd also recommend that if you aren't allowed to budget for code review, lie and cheat. If you're heavily re-writing someone else's code, you're effectively taking the time to review it anyway, you just aren't providing the feedback which is the worthwhile part of code review. So sneak the review in under the radar - write a function or three, then ask a colleague to look at it and give you instant feedback on whether it makes sense to them. It helps to have a conversation as soon as you've done it, with the code on the monitor, but do try not to interrupt people when they have "flow", or to get into lengthy arguments. It's not pair programming, and it's not formal code review, but it might help you figure out what it is you're doing on your own that's so bad.

A:

I'm surprised that you don't have time to do peer reviews but you have time to do paired programming. Is the latter not a much bigger sink of time?
We also have three developers only at our company and, surprise, surprise, we're being pushed hard at the moment. I'm pretty sure my boss would laugh at me if I suggested paired programming because that would be viewed as doubling the number of man hours for a task even though in practice that's not the result it should produce. Our peer reviews are never more than an hour and that is an extreme case. On average I would say they are probably about 10 minutes and, per developer, only happen once or twice in a day.
IMO you should give peer reviews a try. You often find that the offending people (i.e. the people writing the lower quality code) eventually realise that they need to make more of an effort and the quality improves over time.

A:

If you have three developers and each of you think the others code is not good, you urgently need peer reviews.


Q:

Extending Loader

I´m trying to extend the Loader class.
I want to store a variable on it.
Example:
package
{
import flash.display.Loader;

public class MyLoader extends Loader
{
    private var _typeOfGallery:String

    public function MyLoader()
    {
        super()
    }

    public function set typeOfGallery(value:String):void
    {
        _typeOfGallery = value
    }

    public function get typeOfGallery():String
    {
        return _typeOfGallery
    }
}

}

Then I´m using like this:
var loader:MyLoader = new MyLoader()
loader.typeOfGallery = 'games'
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded)

function loaded(e:Event):void{
trace(e.target.typeOfGallery)
}

I´m receiving this error:
ReferenceError: Error #1069: Property typeOfGallery not found in flash.display.LoaderInfo and has no pattern value.
(I have translated from portuguese to english the error message)
How could I extend Loader so I don´t receive this error?
Thanks.

A:

Loader does not dispatch the Event.COMPLETE event. You should listen to
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded)

and then get your MyLoader with
function loaded(e:Event):void{
   trace(((e.currentTarget as LoaderInfo).loader as MyLoader).typeOfGallery);
}

In your code, e.target is a LoaderInfo because the COMPLETE event bubbles to the Loader itself.


Q:

Change Activity theme deppending on fragment in use Android

I have an activity that switches between several fragments. This activity has a default style, but when i change to some particular fragments i want it to change the style. I've done some research and i got this code that i run in the onCreateView() of a fragment:
// create ContextThemeWrapper from the original Activity Context with the custom theme
    Context context = new ContextThemeWrapper(getActivity(), R.style.GreyTheme);
    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(context);
    // inflate using the cloned inflater, not the passed in default

    View rootView = localInflater.inflate(R.layout.my_layout, container, false);

This code only works if the activity is restarted (eg: if i rotate the device it updates to the new style as i want). I think that it is not possible to switch between styles witout recreating an activity or am i wrong?

A:

Technically speaking: no.
You can not change the current theme if the Activity has been created.

This code only works if the activity is restarted (eg: if i rotate the
  device it updates to the new style as i want). I think that it is not
  possible to switch between styles witout recreating an activity or am
  i wrong?

As rotating includes a recreation of the activity, this is the reason on why is "working".
But… there is one application called Pocket (also Press and Firefox if I remember correctly) that does this in a clever way.
How to do it?
Basically the trick lies in this formula:
Base Color1 + Middle Color = Theme Color 1

Base Color2 + Middle Color = Theme Color 2

Keep in mind that Middle Color is the same. For the base color you have to put it to the Window holding your app instance, something like this:
getWindow().setBackgroundDrawable(new ColorDrawable(isLight ? Color.WHITE : Color.BLACK));

Therefore when is combined with an intermediate color, gives you two different themes.
Here you can see how you can do it (it explains the concept very well):
http://sriramramani.wordpress.com/2012/12/06/runtime-theme-change/
EDIT 1:
Added more explanations to the link posts


Q:

Is it possible to access underlying Xamarin UI elements using SkiaSharp?

In a cross platform Xamarin.Forms application, I would like to add a SKCanvas on top of other UI elements to allow the user to draw e.g. on images. I know it is possible to load an image directly into an SKCanvas, but images are not the only application I need.
A perfect solution would be able to load the underlying content of the page, including all of its UI elements into the Canvas/Surface, so that the user can then draw on it and save the drawing + underlying content into an image (probably using the snapshot method?).
Is this possible?

A:

I didn't find a way to do this exactly as planned originally, but ended up doing a workaround that satisfied the requirements at the time.
I added a transparent canvas on top of my content, such that the underlying content would be shown through the canvas, but anything on the canvas would always be drawn on top. The drawings were saved and transmitted separately from the content and re-drawn when needed. On demand, when the user would need to export both together for a snapshot/share/export function, I then loaded the underlying content as image into the canvas and exported it together with the drawings from the canvas into a new image.


Q:

Is there a way to cast shared_ptr to shared_ptr?

I want to keep the smart behavior of std::shared_ptr. So is there a way to cast a shared void pointer to another type while without confusing the reference counting? I can't get the raw pointer and create a new shared pointer from it.

A:

You can use std::static_pointer_cast or std::dynamic_pointer_cast depending on what kind of cast you want.

A:

You can use the pointer casts from rob mayoff's answer; but be careful. It is easy to unintentionally trigger undefined behavior here:
struct MyClass {};

void* rawPtr = new MyClass;
shared_ptr<void> exampleVoid(rawPtr); // Undefined behavior;
                                      // calls delete (void*)ptr;

shared_ptr<void> exampleVoidCons(new MyClass);
    // OK, calls shared_ptr<void>::shared_ptr<MyClass>(MyClass*) which
    // makes a deleter calling delete (MyClass*)ptr;

shared_ptr<MyClass> example(new MyClass); // OK, calls delete (MyClass*)ptr;

shared_ptr<void> castToVoid = static_pointer_cast<void>(example);
    // OK, shared_ptr's deleter is erased so this still calls delete (MyClass*)ptr;

Typically this undefined behavior will result in the type's destructor not being called. For example, see the output on ideone and note that the version put into a void* never prints that it was destroyed.

See C++11 5.3.5 [expr.delete]/3:

In the first alternative (delete object), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

Since the actual object will never have a dynamic type void, and void is never a base class of a dynamic type, deleteing a void* triggers undefined behavior.


Q:

yylloc undefined in this scope

I have the following problem while compiling the files. I have overwritten the definition of YYLTYPE as follows(though it is the same as default but I will extend it
typedef struct YYLTYPE
{
  int first_line;
  int first_column;
  int last_line;
  int last_column;
} YYLTYPE;

and when I add the following in the lex file I get the "yylloc undefined in this scope" error.
#define YY_USER_INIT yylloc.first_line = yylloc.first_column = 1;

Pastebin:

flex file
bison file
makefile

A:

You need to put the definition of YYLTYPE and YYLTYPE_IS_DECLARED into a header file that you #include in both your .y and .l files, and you need to #include the .tab.h file in your .l file AFTER the #include of the file that defines YYLTYPE.
The reason for the above is that bison DOES NOT export your definition of YYLTYPE from the top of your .y file, so if you want it somewhere else, you need to arrange that it be available.  Worse, the .tab.h file will always have the default YYLTYPE (guarded by #ifndef YYLTYPE_IS_DECLARED) so you need to ensure that your definition is seen before it.


Q:

PopupWindow at a specific coordinate with no anchor view

I have a custom ImageView and in the OnDraw I have added some bitmap overlays. I can capture the click event for any overlay using action up type event in the OnTouchEvent callback. The thing is for me to display a popup window I must supply a view anchor for the popup window to show but I am using the bitmaps as anchors not a particular view, so I am stuck. I cannot find any sollution on the web regarding this issue. Passing the parent ImageView and adding the overlay x-y offsets (with Gravity.NO_GRAVITY) are not producing the desired result(Also the window arrow will not point correctly).

A:

Use PopupWindow.showAtLocation
The problem is that x/y params into that function is offset relative to Window, to which anchor view belongs. You can see it clearly from function's source, where nothing from 'parent' is used except of its window token.
public void showAtLocation(View parent, int gravity, int x, int y) {
    showAtLocation(parent.getWindowToken(), gravity, x, y);
}

So to make your offsets good, you have to determine anchor's position relative to its window.
For this, use
Rect rc = new Rect();
View.getWindowVisibleDisplayFrame(rc);
int[] xy = new int[2];
View.getLocationInWindow(xy);
rc.offset(xy[0], xy[1]);

now you have
inx x = rc.left, y = rc.top;

This is point of your ImageView's left-top corner relative to its window.
Finally show your PopupWindow at location relative to this point, and it should display correctly on top of your ImageView.


Q:

Como fazer com que carregue a url completa do welcome-file

No web.xml esta mapeado assim:
<welcome-file-list>
    <welcome-file>agendamento/index.xhtml</welcome-file>
</welcome-file-list>

Ao abrir a aplicação no browser esta abrindo certo, mas preciso que essa url esteja presente por causa de um redirect nesse index.

A:

A configuração welcome-file não serve para fazer redirecionamentos.
A ideia é: quando um usuário acessa um diretório não mapeado da sua aplicação, o web container irá procurar naquele diretório por arquivos com os respectivos nomes.
Para redirecionar o usuário a partir da raiz da aplicação, crie um filtro ou servlet mapeando mapeado na raiz (/) que faça esse redirecionamento via código.
Ou, mova o arquivo index.html para a raiz da sua aplicação e mude a configuração para:
<welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
</welcome-file-list>

Finalmente, faça o redirecionamento a partir daí.
Por outro lado, se você quer redirecionar o usuário que acessar /agendamento/, simplesmente deixe o arquivo index.html na pasta agendamento e use a configuração acima, sem especificar o diretório.


Q:

Adding data to list - JDBC

I want to put all the data that I have in my database in an ArrayList.
        ResultSet rs = callableStatement.executeQuery();
        ArrayList<Object> list = new ArrayList<Object>();
        List<ArrayList> table = null;

        while (rs.next()) {

                for (int i = 1; i < rs.getMetaData().getColumnCount() + 1; i++) {
                System.out.print(" " + rs.getMetaData().getColumnName(i) + "=" + rs.getObject(i));

                    String data = rs.getString(i);
                    list.add(data);

                }
                table.add(list);
                System.err.println(table);
            }

I am printing all the data in my database correctly. My problem is that I'm getting
  java.lang.NullPointerException

A:

I am printing all the data in my database correctly. My problem is that I'm getting
java.lang.NullPointerException

List<ArrayList> table = null;

followed by a
table.add(list);

without init table like
table = new ArrayList<ArrayList>(); //Consider some rework here ;)

will ofc cause a npe


Q:

Select max 5 integers from set of 20

I'm trying to select the 5 most viewed articles out of a list of the 20 most recent entries in a table.  My table structure is essentially this:
id | date | title | content | views

My first thought was just to use an inner select to get the 20 most recent articles, then select from that, but I have yet to have any luck.
//doesn't work (my version of mysql doesn't support LIMIT in sub queries)
$recent = "(SELECT id FROM news ORDER BY date DESC LIMIT 20)";
$result = $db->query("SELECT id, title, date, content FROM news WHERE id IN $recent ORDER BY views DESC LIMIT ".self::RECENT_MAX);

//neither does this (syntax error @ 'OFFSET 20')
$recent = "(SELECT MAX(date) FROM news ORDER BY date DESC OFFSET 20)";
$result = $db->query("SELECT id, title, date, content FROM news WHERE date > $recent ORDER BY views DESC LIMIT ".self::RECENT_MAX);

Anyone got any suggestions on how you would structure this query?

A:

I just tested this and it works
SELECT *
FROM (
    SELECT *
    FROM news
    ORDER BY id DESC
    LIMIT 0, 20
) lasttwenty
ORDER BY views DESC
LIMIT 0, 5

Server version: 5.0.51a-3ubuntu5.4


Q:

Can we control a robot using an Android phone?

After stepping into the world of Android, I wondered if an Android phone can be used as a remote to control a basic pick and place robot . If just an SMS could be send to control the action of a robot like say "pick object 1 at distance x" would result in the bot performing the specified action.
Yes, It will involve Artificial Intelligence coupled with the basics of developing a robot but then I wanted to know whether it's possible to develop a machine like this ? If yes , how should one kickstart things ? Would Android ADK be helpful ?
Thanks

A:

Cellbots Has what you are looking for. They have several different platforms set up using various control methods(lego NXT, arduino, etc.) Many of them are able to be controlled either remotely, or even with an onboard Android device.


Q:

How do I force Process.Start() to complete before proceeding?

I'm creating a console app to process a file and then move it to a 'processed' folder. The main console app calls another app using Process.Start(). This secondary app actually does the work of bulk inserting data into a database. Once the bulk insert is complete, the main app will move the file to another folder and then move on to additional tasks.
In the main app, how do I prevent the code from continuing until the secondary app finishes? I really need to have the first process finish before moving on to the next step.
Thanks!

A:

Use this method:
process.WaitForExit();

A:

You can use the WaitForExit() Methode

A:

You might try:
Process.Start(...).WaitForExit();

Presuming you are using ProcessStartInfo, you might write it more like this:
var psi = new ProcessStartInfo();
psi.FileName = "SecondProcess.exe";
psi.Arguments = "arg1 arg2";
var process = Process.Start(psi);
if(process != null) process.WaitForExit();


Q:

gnuplot epslatex terminal problematic dvi or ps output

I am using the epslatex terminal to generate eps figures with gnuplot 4.6.4.
However, I am having problem with this script
# reset
reset
#
sz = 1.4
rx = 10.0/7.0
#
set style line 1 lt 1 pointsize 1
# blue line
set style line 2 lt 12 pointsize 1
#
set terminal epslatex size rx*sz,2*sz color standalone
set output 'output.tex'

set multiplot layout 2,2

# Figure 1,1
set tmargin 0
set bmargin 0
set lmargin at screen 0.05
set rmargin at screen 0.475
set format x ""
set xrange [30:130]
set ylabel offset 2,0 "Y label [sec]"
unset xlabel
set grid
set yrange [0:9]
set ytics ("" 0, "1" 1, "2" 2, "3" 3, "4" 4, \
"5" 5, "6" 6, "7" 7, "8" 8, "" 9)
unset key
plot "./inp" u 1:2 t "tsL" w lp ls 1, \
"" u 1:3 t "vL" w lp ls 2
#

# Figure 1,2
set bmargin 0
set tmargin 0
set lmargin at screen 0.525
set rmargin at screen 0.95
set format x ""
set format y ""
set xrange [30:130]
set yrange [0:9]
#set mytics 2
unset ylabel
unset xlabel
set grid
plot "./inp" u 1:2 t "tsL" w lp ls 1, \
"" u 1:3 t "vL" w lp ls 2

# Figure 2,1
set tmargin 0
set bmargin 0
set lmargin at screen 0.05
set rmargin at screen 0.475
set format x "%g"
set format y "%g"
set xrange [30:130]
set ylabel offset 2,0 "Ylabel"
set xlabel offset 0,0.6 "neig"
set grid
set yrange [0:9]
set ytics ("" 0, "1" 1, "2" 2, "3" 3, "4" 4, \
"5" 5, "6" 6, "7" 7, "8" 8, "" 9)
unset key
set xtics ("40" 40, "" 60 , "80" 80,\
"" 100, "120" 120)
set mxtics 2
plot "./inp" u 1:2 t "tsL" w lp ls 1, \
"" u 1:3 t "vL" w lp ls 2
#

# Figure 2,2
set bmargin 0
set tmargin 0
set lmargin at screen 0.525
set rmargin at screen 0.95
set format y ""
set format x "%g"
set xrange [30:130]
set yrange [0:9]
#set ylabel "Ylabel"
unset ylabel
set xlabel offset 0,0.6 "neig"
set grid
set xtics ("40" 40, "" 60 , "80" 80,\
"" 100, "120" 120)
set mxtics 2
plot "./inp" u 1:2 t "tsL" w lp ls 1, \
"" u 1:3 t "vL" w lp ls 2
#
unset multiplot
#
set output

with the input file inp which includes
40 1 3
60 2 4
80 3 5
100 4 6
120 5 7

If I compile the document, everything goes fine. However, there is a line missing in dvi file and the labels seem to be at wrong location. After that, if I execute "dvips output.dvi", I get a completely wrong ps output without any labels and ytics at the wrong location. What is my mistake with this implementation?

A:

The dvi output is usually wrong, especially the labels, because these are typeset with Postscript operations, which aren't interpreted correctly by many dvi viewers.
Concerning the labels, your left margins are too small, so that the labels are outside of the image. For you example I had to use
set lmargin at screen 0.2
set ylabel offset 0.5,0 "Y label [sec]"

for Figure 1,1 in order to have reasonable margins and see all labels (ytic labels and ylabel). The ytics are ok.
In the same manner you have to fix the other settings of lmargin and rmargin of the other subfigures, and also the bmargin of the bottom row in order to see the xlabel and the xtic labels.
And you don't need to set the ytics manually. Use
set ytics 1,1,8 # tics from 1 to 8 in steps of 1
set xtics 40    # distance of 40 between tics.

Margins and plot area
Some remarks about the margins, plot area and canvas size.

The image size (i.e. the canvas size) is given by the size terminal option (e.g. set terminal pngcairo size 800,400).
Usually, the size and position of the plotting area inside the canvas is determined automatically based on several points:

Font size
Presence and position of xlabel, ylabel etc, title, key being outside, colorbox, length of tic labels and so on.
The plotting area can be changed relative to the automatically determined one by set size and set origin (and for splot it can be scaled with set view).

The plotting area can also be set fixed by specifying explicit margins. In this case the user has to care about providing large enough margins to fit in all the elements. The margins can be specified independently with set lmargin, set rmargin, set bmargin and set tmargin. Their values can be specified in two ways:

set tmargin 1 leaves a top margin equivalent to one character height.
set tmargin at screen 0.95 leaves a top margin of 5% of the total canvas size.


Q:

React-native watchman doesn't work anymore

Few days ago I noticed watchman stopped working.
Using a real android device with shake gesture I cannot Reload the app (a reload doesn't take the changes to the code). Live reload and hot reloading don't work either.
The only way I have to get the app take the changes is to kill the packager and relaunch it (often neither this method makes the app takes changes!).
There is a way I can solve? This issue It's pretty frustrating.

A:

I'll answer to myself. After further research, this issue looks to be caused by this option in app.json
"packagerOpts": {
  "nonPersistent": "--nonPersistent"
}

which I've added to be able to produce a release build using Expo (otherwise I get error "socket hang up").
It would be nice if some Expo developer would post some infos about this issue and what that option in app.json really does (the docs says nothing).


Q:

Get Sequelize.js ENUM Values from Already Defined Model

How do we get the ENUM values of a model after defining it in Sequelize.js?
For example, we define our model as:
sequelize.define('model', {
  states: {
    type:   Sequelize.ENUM,
    values: ['active', 'pending', 'deleted']
  }
})

How do we get the pre-defined ['active', 'pending' ,'deleted'] values from this model?

A:

The ENUM values in a schema can be found in the rawAttributes property of the model.
var Model = sequelize.define('model', {
  states: {
    type:   Sequelize.ENUM,
    values: ['active', 'pending', 'deleted']
  }
});

console.log(Model.rawAttributes.states.values);
// logs ['active', 'pending', 'deleted'] in console


Q:

How to put the footer div below the content?

I have this code here: http://jsfiddle.net/52yekaL9/

html, body {
  height: 100%;
}

.content {
  height: 100%;
}

.part {
  height: 100%;
  width: 100%;
}

.a { background-color: red; }
.b { background-color: green; }
.c { background-color: blue; }
.d { background-color: orange; }

1

2

3

  this footer

The problem is in my div.footer d. I see that it is in this form: div.part b. I was testing and I see if I change the height of .content, the footer moves as well.
But I don´t think the correct way to change is: 200% + 150px
Is there another way to put the footer div after the content div?

A:

Instead of percentage heights (which are overly complicated and tricky), use viewport percentage units, which are simple, stable and reliable:

.content {
  min-height: 100vh;
}

.part {
  height: 100vh;
}

.a { background-color: red; }
.b { background-color: green; }
.c { background-color: blue; }
.d { background-color: orange; }

1

2

3

this footer

jsFiddle


Q:

How to copy an xml file and rename it and save in the same root directory using c#?

Do I need to use linq to xml recursively and copy every node and element from one xml to another or is there a better way to directly copy and save it in the same root directory by renaming it? Can anyone give an example

A:

File.Copy("root.xml", "copy.xml");

That copies your xml file and renames it.


Q:

Android: how do I check if activity is running?

Is there any simple way of determining whether or not a certain activity is active?
I want to do certain things depending on which activity is active.
eg:
if(activityrunning == activity1)
//do this
else if (activityrunning == activity2)
//do something else

A:

You can use a static variable within the activity.
class MyActivity extends Activity {
     static boolean active = false;

      @Override
      public void onStart() {
         super.onStart();
         active = true;
      }

      @Override
      public void onStop() {
         super.onStop();
         active = false;
      }
}

The only gotcha is that if you use it in two activities that link to each other then onStop on the first is sometimes called after onStart in second. So both might be true briefly.
Depending on what you are trying to do (update the current activity from a service?). You could just register a static listener in the service in your activity onStart method then the correct listener will be available when your service wants to update the UI.

A:

I realize this issue is quite old, but I think it's still worth sharing my solution as it might be useful to others.
This solution wasn't available before Android Architecture Components were released.
Activity is at least partially visible
getLifecycle().getCurrentState().isAtLeast(STARTED)

Activity is in the foreground
getLifecycle().getCurrentState().isAtLeast(RESUMED)

A:

I think more clear like that:
  public boolean isRunning(Context ctx) {
        ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

        for (RunningTaskInfo task : tasks) {
            if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName()))
                return true;
        }

        return false;
    }


Q:

How to exit the elm repl?

I am learning Elm, and need to be able to exit the elm repl. I tried exit() like python, \q like postgres, typing just exit like MySQL, even :q like Haskell. The only thing I can do is close the terminal to exit, there has to be a better way.

A:

To exit the elm repl you need to type :exit. You can also use Ctrl + d, but I prefer typed commands instead of multi-key holds. I found this answer here as part of the (unofficial) getting started with elm programming guide.


Q:

How to run greeter/login script with lightdm

Is there a workaround to run a lightdm script?  The one in the docs doesn't work.  Anything placed there will prevent X from working.
The script I would like to use is my KVM utility synergy.  I thought for a while it was synergy that was causing the problems.  However, I found that anytime there is a lightdm.conf file with anything on that line X will fail to load.
Example:
greeter-setup-script=/etc/lightdm/test.sh

The text.sh file is simply a shell command to indicate it ran:
test.sh:
#!/bin/bash
date >> /tmp/test.log

Thanks in advance for anyone who has any input, or as I mentioned a workaround so that I could have a resource that will run upon X startup before the user actually logs in.

A:

During the past week I saw this problem many times doing my research and effort to fix it.  It turns out that any entries placed in a "lightdm.conf" file for Ubuntu 13.10 will break lightdm.
There is an entry in the lightdm.conf.d provided for this.  I added my KVM script to:
/etc/lightdm/lightdm.conf.d/50-unity-greeter.conf

This works!


Q:

How can I rotate the content of a cell without changing the layout of the table

I'm currently working on a UI that requires that I have a table with cells whose text is read vertically instead of horizontally.  To do this, I am using CSS rotate transforms.
The problem I am running into is that the content is being measured before the render transform is taking place.  This is causing my table to render incorrectly, giving wide columns instead of narrow ones.
Is there any way to fix this behavior with either css or javascript?
JSFiddle

A:

Not the best solution, but here's what I came up with: http://jsfiddle.net/gJCtN/2/
Also, vertical-align is not supported by elements without display:table-cell or something like it. More info.


Q:

1.9.0.1 shopping cart rules using stop further rule processing

Would someone please share his knowledge in setting up discount:
Tried like 1000x combinations, but I cant get it to work as expected, so pls tell me if it is possible or not:
   I have coupon-codes 50%,30%,20%,10% - Priority high (works standalone)
   I have a 10% discount on a specific category if product form other    category is in cart. - Priority mid (works standalone)
   I have mass discount 3 5% and 10 10% (works standalone)

Now when all comes together I need the following:
   1. Discount of discount code on all items
   2. Discount of 10% specific discount on specific items
   3. STOP mass discount from being discounted

Any suggestions? :)
Thx in forward

A:

Turns out ... somehow... the cart rule logic in 1.9.0.1 is wrong.
You can get a fix here. Worked 100% perfect from start then.
https://github.com/husseycoding/cartrulefix
So for everyone struggling problems with cart rules in 1.9.0.1 while using "stop further rule processing" -> use this fix!


Q:

Getting 'Cannot read property "length" from undefined' exception while rendering chart at JasperReports Server

While generating report with high chart stacked lines getting
net.sf.jasperreports.engine.JRRuntimeException: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "length" from undefined (com/jaspersoft/jasperreports/highcharts/charts/render/scripts/jquery-1.10.2.min.js#4)

Full trace
    2016-08-04 01:32:43,508 ERROR AsyncThumbnailCreatorImpl,pool-29-thread-2:59 - net.sf.jasperreports.engine.JRRuntimeException: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "length" from undefined (com/jaspersoft/jasperreports/highcharts/charts/render/scripts/jquery-1.10.2.min.js#4)
net.sf.jasperreports.engine.JRRuntimeException: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "length" from undefined (com/jaspersoft/jasperreports/highcharts/charts/render/scripts/jquery-1.10.2.min.js#4)
        at com.jaspersoft.jasperreports.highcharts.charts.ChartGraphics2DHandler.exportElement(ChartGraphics2DHandler.java:52)
        at net.sf.jasperreports.engine.export.draw.FrameDrawer.draw(FrameDrawer.java:246)
        at net.sf.jasperreports.engine.export.draw.FrameDrawer.draw(FrameDrawer.java:198)
        at net.sf.jasperreports.engine.export.JRGraphics2DExporter.exportPage(JRGraphics2DExporter.java:342)
        at net.sf.jasperreports.engine.export.JRGraphics2DExporter.exportReportToGraphics2D(JRGraphics2DExporter.java:311)
        at net.sf.jasperreports.engine.export.JRGraphics2DExporter.exportReport(JRGraphics2DExporter.java:236)
        at net.sf.jasperreports.engine.print.JRPrinterAWT.printPageToImage(JRPrinterAWT.java:290)
        at net.sf.jasperreports.engine.JasperPrintManager.printToImage(JasperPrintManager.java:290)
        at com.jaspersoft.jasperserver.api.metadata.common.service.impl.ThumbnailGenerationServiceImpl.obtainImage(ThumbnailGenerationServiceImpl.java:71)
        at com.jaspersoft.jasperserver.api.metadata.common.service.impl.ThumbnailGenerationServiceImpl.createThumbnail(ThumbnailGenerationServiceImpl.java:50)
        at com.jaspersoft.jasperserver.api.metadata.common.service.impl.ThumbnailGenerationServiceImpl.createThumbnail(ThumbnailGenerationServiceImpl.java:24)
        at com.jaspersoft.jasperserver.api.metadata.common.service.impl.AsyncThumbnailCreatorImpl$ThumbnailRunnable.run(AsyncThumbnailCreatorImpl.java:55)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "length" from undefined (com/jaspersoft/jasperreports/highcharts/charts/render/scripts/jquery-1.10.2.min.js#4)
        at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3785)
        at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3763)
        at org.mozilla.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3791)
        at org.mozilla.javascript.ScriptRuntime.typeError2(ScriptRuntime.java:3810)
        at org.mozilla.javascript.ScriptRuntime.undefReadError(ScriptRuntime.java:3823)
        at org.mozilla.javascript.ScriptRuntime.getObjectProp(ScriptRuntime.java:1508)
        at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1398)
        at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:854)
        at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:164)
        at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:76)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2._c_anonymous_7(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js:46)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2.call(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js)
        at org.mozilla.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2521)
        at org.mozilla.javascript.BaseFunction.execIdCall(BaseFunction.java:300)
        at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:129)
        at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:76)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_99(com.jaspersoft.jasperreports.highcharts.render.r.js:1889)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callN(OptRuntime.java:86)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_55(com.jaspersoft.jasperreports.highcharts.render.r.js:1105)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:119)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_67(com.jaspersoft.jasperreports.highcharts.render.r.js:1382)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:119)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_49(com.jaspersoft.jasperreports.highcharts.render.r.js:1013)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callN(OptRuntime.java:86)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_89(com.jaspersoft.jasperreports.highcharts.render.r.js:1655)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:57)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_104(com.jaspersoft.jasperreports.highcharts.render.r.js:1996)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:66)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_localRequire_88(com.jaspersoft.jasperreports.highcharts.render.r.js:1644)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callN(OptRuntime.java:86)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_102(com.jaspersoft.jasperreports.highcharts.render.r.js:1976)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:97)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2._c_anonymous_6(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js:45)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2.call(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js)
        at org.mozilla.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2521)
        at org.mozilla.javascript.BaseFunction.execIdCall(BaseFunction.java:300)
        at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:129)
        at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1701)
        at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:854)
        at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:164)
        at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:76)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2._c_anonymous_5(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js:41)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2.call(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js)
        at org.mozilla.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2521)
        at org.mozilla.javascript.BaseFunction.execIdCall(BaseFunction.java:300)
        at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:129)
        at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:76)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_99(com.jaspersoft.jasperreports.highcharts.render.r.js:1889)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callN(OptRuntime.java:86)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_55(com.jaspersoft.jasperreports.highcharts.render.r.js:1105)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:119)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_67(com.jaspersoft.jasperreports.highcharts.render.r.js:1382)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callProp0(OptRuntime.java:119)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_49(com.jaspersoft.jasperreports.highcharts.render.r.js:1013)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callN(OptRuntime.java:86)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_89(com.jaspersoft.jasperreports.highcharts.render.r.js:1655)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:57)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_104(com.jaspersoft.jasperreports.highcharts.render.r.js:1996)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:66)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_localRequire_88(com.jaspersoft.jasperreports.highcharts.render.r.js:1644)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callN(OptRuntime.java:86)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1._c_anonymous_102(com.jaspersoft.jasperreports.highcharts.render.r.js:1976)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_r_js_1.call(com.jaspersoft.jasperreports.highcharts.render.r.js)
        at org.mozilla.javascript.optimizer.OptRuntime.callName(OptRuntime.java:97)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2._c_renderSVGFromJson_4(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js:31)
        at org.mozilla.javascript.gen.com_jaspersoft_jasperreports_highcharts_render_svg_renderer_highcharts_js_2.call(com.jaspersoft.jasperreports.highcharts.render.svg-renderer-highcharts.js)
        at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:1701)
        at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:854)
        at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:164)
        at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:426)
        at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3178)
        at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:175)
        at org.mozilla.javascript.Context.evaluateString(Context.java:1111)
        at com.jaspersoft.jasperreports.highcharts.charts.render.RhinoChartSvgProducer.getChartSvg(RhinoChartSvgProducer.java:104)
        at com.jaspersoft.jasperreports.highcharts.charts.render.DefaultChartSvgProducer.getChartSvg(DefaultChartSvgProducer.java:39)
        at com.jaspersoft.jasperreports.highcharts.charts.render.ChartSvgImageProducer.createRenderable(ChartSvgImageProducer.java:81)
        at com.jaspersoft.jasperreports.highcharts.charts.render.ChartSvgImageProducer.getChartImage(ChartSvgImageProducer.java:45)
        at com.jaspersoft.jasperreports.highcharts.charts.ChartGraphics2DHandler.exportElement(ChartGraphics2DHandler.java:47)
        ... 16 more

Jrxml file is below
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="AbandonedWorkflowPercentage" pageWidth="842" pageHeight="595" orientation="Landscape" whenNoDataType="AllSectionsNoDetail" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="fc97a963-c0b6-4c19-a348-7e2773e092a3">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="DM"/>
    <queryString language="SQL">
        <![CDATA[SELECT ...]]>
    </queryString>
    <field name="INTERVALS" class="java.util.Date"/>
    <field name="PERCENTAGE_TO_GOAL" class="java.math.BigDecimal"/>
    <field name="TOTAL" class="java.math.BigDecimal"/>
    <field name="SERIES" class="java.lang.String"/>
    <summary>
        <band height="550" splitType="Stretch">
            <property name="local_mesure_unitheight" value="pixel"/>
            <property name="com.jaspersoft.studio.unit.height" value="px"/>
            <componentElement>
                <reportElement x="0" y="50" width="700" height="500" uuid="edf50a68-78c7-45b6-8246-57d927666a3d">
                </reportElement>
                <hc:chart xmlns:hc="http://jaspersoft.com/highcharts" xsi:schemaLocation="http://jaspersoft.com/highcharts http://jaspersoft.com/schema/highcharts.xsd" type="StackedLine">
                    <hc:chartSetting name="default">
                        <hc:chartProperty name="chart.zoomType">
                            <hc:propertyExpression><![CDATA["xy"]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.enabled">
                            <hc:propertyExpression><![CDATA[false]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.href">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="credits.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="title.text">
                            <hc:propertyExpression><![CDATA[""]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="xAxis.labels.rotation">
                            <hc:propertyExpression><![CDATA[new Integer(-45)]]></hc:propertyExpression>
                        </hc:chartProperty>
                        <hc:chartProperty name="yAxis.title.text">
                            <hc:propertyExpression><![CDATA["Percent To Goal"]]></hc:propertyExpression>
                        </hc:chartProperty>
                    </hc:chartSetting>
                    <multiAxisData>
                        <multiAxisDataset/>
                        <dataAxis axis="Rows">
                            <axisLevel name="Interval">
                                <labelExpression><![CDATA["Level Label expression"]]></labelExpression>
                                <axisLevelBucket class="java.lang.String">
                                    <bucketExpression><![CDATA[$F{INTERVALS}]]></bucketExpression>
                                </axisLevelBucket>
                            </axisLevel>
                        </dataAxis>
                        <dataAxis axis="Columns">
                            <axisLevel name="series">
                                <labelExpression><![CDATA[]]></labelExpression>
                                <axisLevelBucket order="None" class="java.lang.String">
                                    <bucketExpression><![CDATA[$F{SERIES}]]></bucketExpression>
                                </axisLevelBucket>
                            </axisLevel>
                        </dataAxis>
                        <multiAxisMeasure name="PercentToGoal" class="java.math.BigDecimal" calculation="Nothing">
                            <labelExpression><![CDATA[""]]></labelExpression>
                            <valueExpression><![CDATA[$F{PERCENTAGE_TO_GOAL}]]></valueExpression>
                        </multiAxisMeasure>
                    </multiAxisData>
                    <hc:series name="PercentToGoal"/>
                </hc:chart>
            </componentElement>
        </band>
    </summary>
</jasperReport>

There are not compile error and SQL is returning empty data. So report prints "Empty report" but after that there are above exceptions in the logs

A:

Issue is solved.
When the data set is empty high chart still try to render the chart and it will fail. To prevent it added print when condition for chart element in report jrxml.
<printWhenExpression><![CDATA[$V{REPORT_COUNT} > 0]]></printWhenExpression>


Q:

Find the ratio of the two triangles?

PQRS is a trapezium , in which PQ is parallel to RS , and
PQ = 3(RS).
The diagonal  of the trapezium intersect each other at X,
Then the ratio of the  area of the Triangle PXQ and RXS.
I tried but could not get it.
Does the area will be in the ratio of the base i.e. 1:3
Thanks in advance.

A:

Since triangles are similar , as Andre correctly observed , and similar ratio is : $1 : 3$ we can write :
$|PQ| = 3k ~\text { and }~ h_1=3k$
$|RS| = k ~\text { and }~ h_2=k$
where $h_1 ~\text { and } ~h_2$ are corresponding heights of triangles .
Now , since :
$A_1=\frac{|PQ| \cdot h_1}{2} ~\text { and } A_2=\frac{|RS| \cdot h_2}{2}~$ it follows that :
$A_1 : A_2 = 9 : 1$


Q:

ioct multiple arguments passing

I try to pass two arguments from user space program to change a buffer size and number of buffer on char device. I tried multiple cast I get always cast errors
 error: cannot convert to a pointer type copy_from_user((char *)msg, arg, sizeof(msg));

or
cannot convert to a pointer typecopy_from_user((char *)msg, (char *)arg, sizeof(msg));

header.h
struct ioctl_arguments {
         int block_number;
         int block_size;
 };

the kernel module and the c program include both the header.h
c program
#define DEVICE_PATH "/dev/driver"
#define MAGIC_NO 'k'
struct ioctl_arguments args;
#define IOCTL_CMD _IOWR(MAGIC_NO, 0, args)
int main()
{
    int fd;
    args.block_number = 10;
    args.block_size = 10;
    fd = open(DEVICE_PATH, O_RDWR);
    ioctl(fd, IOCTL_CMD,&args);
    close(fd);
    return 0;
}

device driver
static int BlockNumber = 20;
static int BlockSize = 5;
struct ioctl_arguments msg;

static int sample_ioctl (struct file *filp, unsigned int cmd, unsigned long arg);

static int sample_ioctl (struct file *filp, unsigned int cmd, unsigned long arg)
{

  // copy two parameters from outside, we use struct
  copy_from_user((char *)msg, (char *)arg, sizeof(msg));

A:

In your device-driver function arg is in reality a pointer so that cast is valid, but msg is not a pointer so the cast to pointer is not valid. You should use &msg (just like you use &args in the user-space code).


Q:

parsing pandas data frame base on conditions and save it to a csv

so i have a data frame from (csv very long) i would like to parse it based on a condition(every time column D come back to zero creat a new data frame name data#) on one of the column and save them to a new csv file as i go. i know that in python i can do mp.mlab.find(mp.logical_and(D== 0.0)) it will give me the indexes where D=0 but i don't know how to then identify the beginning of that sequence and its end and parse it to a new data frame keeping all of the columns.
data
     A          B         C     D  E  F  H
0    0  12.000000 -8.000000   0.0  1  1  2
1    1  12.000000 -8.000000   0.0  1  1  1
2    2  12.100000 -8.100000   0.0  1  1  0
3    3  12.020000 -8.000000   0.0  1  1  1
4    4  12.010000 -8.000000   1.2  1  1  0
5    5  12.000000 -8.000000   1.3  1  1  2
6    6   1.500000 -8.200000   1.9  1  1  1
7    7  12.600000 -8.000100   2.0  1  1  1
8    8  12.400000 -8.000000   3.5  1  1  2
9    9  12.200000 -8.050036   6.0  1  1 -1
10  10  12.020000 -8.053374   7.8  1  1  2
11  11  12.000000 -8.056713   9.0  1  1  1
12  12  12.000000 -8.060051  12.5  1  1  1
13  13   1.500000 -8.063389  18.0  1  1  1
14  14  12.600000 -8.066728  19.0  1  1 -1
15  15  12.000000 -8.070066  15.0  1  1  2
16  16  12.400000 -8.073404  16.0  1  1  1
17  17  12.300000 -8.076743  10.0  1  1  0
18  18  12.000000 -8.080081   5.0  1  1  2
19  19  12.300000 -8.083419   4.5  1  1  0
20  20  12.600000 -8.086758   1.2  1  1  1
21  21  12.000000 -8.090096   0.0  1  1  1
22  22  12.000000 -8.093434   0.0  1  1  0
23  23  12.000000 -8.096773   0.0  1  1  1
24  24  12.200000 -8.100111   1.5  1  1  2
25  25  12.200000 -8.103449   3.0  1  1  2
26  26  12.300000 -8.106788   7.0  1  1  0
27  27  12.500000 -8.110126   5.0  1  1  2
28  28  12.000000 -8.113464   2.0  1  1 -1
29  29  12.300000 -8.116803   0.0  1  1  1
30  30  12.400000 -8.120141   0.0  1  1  1
31  31  12.600000 -8.123479   0.0  1  1 -1
32  32  12.500000 -8.126818   0.0  1  1 -1
33  33  12.000000 -8.130156   0.8  1  1  1
34  34  12.360000 -8.133494   1.6  1  1 -1
35  35  12.370909 -8.136833   2.0  1  1  2
36  36  12.381818 -8.140171   5.0  1  1  1
37  37  12.392727 -8.143509   4.0  1  1  0
38  38  12.403636 -8.146848   3.0  1  1  0
39  39  12.414545 -8.150186   2.6  1  1  1
40  40  12.425455 -8.153524   1.2  1  1  2
41  41  12.436364 -8.156863   0.0  1  1  1
42  42  12.447273 -8.160201   0.0  1  1  1
43  43  12.458182 -8.163539   0.0  1  1 -1
44  44  12.469091 -8.166878   0.0  1  1  0
45  45  12.480000 -8.170216   0.0  1  1  1
46  46  12.490909 -8.173554   2.5  1  1  2
47  47  12.501818 -8.176893   3.0  1  1 -1
48  48  12.512727 -8.180231   7.0  1  1 -1
49  49  12.523636 -8.183569   9.0  1  1 -1
50  50  12.534545 -8.186908  15.0  1  1  0
51  51  12.545455 -8.190246  26.0  1  1 -1
52  52  12.556364 -8.193584   9.0  1  1  0
53  53  12.567273 -8.196923   7.0  1  1 -1
54  54  12.578182 -8.200261   6.0  1  1  0
55  55  12.589091 -8.203599   4.3  1  1  1
56  56  12.600000 -8.206938   3.3  1  1  2
57  57  12.610909 -8.210276   2.3  1  1  0
58  58  12.621818 -8.213614   2.1  1  1 -1
59  59  12.632727 -8.216953   0.9  1  1 -1
i would like to get some thing like
data1
     A          B         C     D  E  F  H
0    0  12.000000 -8.000000   0.0  1  1  2
1    1  12.000000 -8.000000   0.0  1  1  1
2    2  12.100000 -8.100000   0.0  1  1  0
3    3  12.020000 -8.000000   0.0  1  1  1
4    4  12.010000 -8.000000   1.2  1  1  0
5    5  12.000000 -8.000000   1.3  1  1  2
6    6   1.500000 -8.200000   1.9  1  1  1
7    7  12.600000 -8.000100   2.0  1  1  1
8    8  12.400000 -8.000000   3.5  1  1  2
9    9  12.200000 -8.050036   6.0  1  1 -1
10  10  12.020000 -8.053374   7.8  1  1  2
11  11  12.000000 -8.056713   9.0  1  1  1
12  12  12.000000 -8.060051  12.5  1  1  1
13  13   1.500000 -8.063389  18.0  1  1  1
14  14  12.600000 -8.066728  19.0  1  1 -1
15  15  12.000000 -8.070066  15.0  1  1  2
16  16  12.400000 -8.073404  16.0  1  1  1
17  17  12.300000 -8.076743  10.0  1  1  0
18  18  12.000000 -8.080081   5.0  1  1  2
19  19  12.300000 -8.083419   4.5  1  1  0
20  20  12.600000 -8.086758   1.2  1  1  1
21  21  12.000000 -8.090096   0.0  1  1  1
data2
22  22  12.000000 -8.093434   0.0  1  1  0
23  23  12.000000 -8.096773   0.0  1  1  1
24  24  12.200000 -8.100111   1.5  1  1  2
25  25  12.200000 -8.103449   3.0  1  1  2
26  26  12.300000 -8.106788   7.0  1  1  0
27  27  12.500000 -8.110126   5.0  1  1  2
28  28  12.000000 -8.113464   2.0  1  1 -1
29  29  12.300000 -8.116803   0.0  1  1  1
30  30  12.400000 -8.120141   0.0  1  1  1
31  31  12.600000 -8.123479   0.0  1  1 -1
32  32  12.500000 -8.126818   0.0  1  1 -1
33  33  12.000000 -8.130156   0.8  1  1  1
34  34  12.360000 -8.133494   1.6  1  1 -1
35  35  12.370909 -8.136833   2.0  1  1  2
36  36  12.381818 -8.140171   5.0  1  1  1
37  37  12.392727 -8.143509   4.0  1  1  0
38  38  12.403636 -8.146848   3.0  1  1  0
39  39  12.414545 -8.150186   2.6  1  1  1
40  40  12.425455 -8.153524   1.2  1  1  2
41  41  12.436364 -8.156863   0.0  1  1  1
data3
...
...
...

Any help will greatly be appreciated.
thank you!

A:

Finding the rows where D has gone back to 0 can be done like this:
df['back_to_0'] = (df['D'] == 0) & (df['D'].diff() < 0)

i.e. the value is 0 and the value has gone down since the last row.
Then we create a grouping variable:
df['time_group'] = df['back_to_0'].cumsum() + 1

And we can split by time_group to get individual data frames:
grouped = df.groupby('time_group')

for group_number, group_data in grouped:
    print(group_data.head())
    # Could also do group_data.to_csv() here if you want
    # to save the individual pieces as separate files


Q:

Multiple youtube players?

I want to have two youtube players:
1. will be vissible and play from start till end in loop.
2. will be hidden and will play from lets say 10 seconds to 20 seconds in loop.
I have this two scriptsm that actually works separatedly, but will not work together, I am not sure how to combine them in one function.
Can anyone help?
First player: https://pastebin.com/vhX2qJ5R
Second player: https://pastebin.com/Pge6mM7q

This is hidden player that loops: http://jsbin.com/zuxoxoqeko/edit?html,js,output
This is normal player: http://jsbin.com/bibafewave/edit?html,js,output
Javascript
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      // 3. This function creates an  (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '315',
          width: '560',
          videoId: 'Kf4GkHsRB2w',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
           event.target.setVolume(0);
       event.target.playVideo();
      }
      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
    //      setTimeout(stopVideo, 6000);
                  done = true;
        }
           event.target.setVolume(0);
      }

      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var section = {
  start: 30,
  end: 58
};

// 3. This function creates an  (and YouTube player)
//    after the API code downloads.
var player1;
function onYouTubeIframeAPIReady() {
  player1 = new YT.Player(
    'player1',
    {
      height: '0',
      width: '0',
      videoId: 'S5xDk7dnmbw',
      events: {
        'onReady': onPlayerReady1,
        'onStateChange': onPlayerStateChange1
      }
    }
  );
}

function onPlayerReady1(event) {
  player1.seekTo(section.start);
  player1.playVideo();
}

function onPlayerStateChange1(event) {
  if (event.data == YT.PlayerState.PLAYING) {
    var duration = section.end - section.start;
    setTimeout(restartVideoSection1, duration * 1000);
  }
}

function restartVideoSection1() {
  player1.seekTo(section.start);
}

HTML

A:

I don't really know why people easily give thumbs down, soon I won't be able to ask anything from account.
Solution is:
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      // 3. This function creates an  (and YouTube player)
      //    after the API code downloads.
      var player,player1;
      var section1 = {
      start: 30,
      end: 58
      };
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '315',
          width: '560',
          videoId: 'Kf4GkHsRB2w',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
           event.target.setVolume(0);
       event.target.playVideo();
      }
      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
    //      setTimeout(stopVideo, 6000);
                  done = true;
        }
           event.target.setVolume(0);
      }

  player1 = new YT.Player(
    'player1',
    {
      height: '50',
      width: '50',
      videoId: 'S5xDk7dnmbw',
      events: {
        'onReady': onPlayerReady1,
        'onStateChange': onPlayerStateChange1
      }
    }
  );
}

function onPlayerReady1(event1) {
  player1.seekTo(section1.start);
  player1.playVideo();
}

function onPlayerStateChange1(event1) {
  if (event1.data == YT.PlayerState.PLAYING) {
    var duration = section1.end - section1.start;
    setTimeout(restartVideoSection1, duration * 1000);
  }
}

function restartVideoSection1() {
  player1.seekTo(section1.start);
}


Q:

problem hosting a Static page with loopback

I want to host a static page in loopback. I have added HTML in client dir and removed the default path in server/boot/root.js
But, I have to follow some rules about routes so that I replaced '/api/' to '/' in config.json's restApiRoot. Now I want to host this static HTML page on '/' route. But It gives this error
{"success":false,"message":"There is no method to handle GET /"}

Also, I tried to set a different path for static page in middleware.json like this,
"files": {
    "loopback#static": {
      "paths": [
        "/admin/"
      ],
      "params": "$!../client"
    }
  },

Still, this is also not working.
PS: I have added a boot script for following our code of conduct for the response, that's why it's giving this type of response.

A:

By default, LoopBack's REST API handler takes ownership of the entire path namespace it's mounted on. If you mount your REST API at /api, then our handler will return 404 whenever a path is not mapped to any remote methods. When you mount your REST API at /, the handler will take over the entire HTTP server.
Fortunately, it's possible to disable this behavior via configuration. See rest. handleUnknownPaths option in config.json >> Remoting properties.
Here is an example showing how to disable this flag in your server/config.json file (please note I omitted any other configuration you may already have in that file):
{
  "remoting": {
    "rest": {
      "handleUnknownPaths": false
    }
  }
}

I have added a boot script for following our code of conduct for the response, that's why it's giving this type of response.

You may want to set both errorHandler and rest.handleErrors to false, so that LoopBack does not convert errors to HTTP responses.
Example server/config.json:
{
  "remoting": {
    "errorHandler": false,
    "rest": {
      "handleErrors": false,
      "handleUnknownPaths": false
    }
  }
}

With this setup in place, you can edit server/middleware.json and replace the default strong-error-handler middleware with your own error-handling implementation (see Defining middleware >> Path to middleware function.


Q:

How to determine if a UITableViewCell is being dragged?

I would like to know if a cell is being dragged (via the grip on the right side when a UITableView is in editing mode). I would like to change the background while it is in that state.

A:

There is no callback unfortunately, but since the default behaviour is to adjust the 'alpha' value of the UITableViewCell you can check for that in '- (void)layoutSubview' of your UITableViewCell subclass.
- (void)layoutSubviews
{
    [super layoutSubviews];
    if (self.alpha < 0.99) {
        // we are most likely being dragged
    } else {
        // restore for not being dragged
    }
}

Note that this is a bit of a hack. I noticed that this doesn't work when the table view's separatorStyle is set to 'UITableViewCellSeparatorStyleNone'.


Q:

does jest have a --require command like mocha

Does Jest have a similar option like mocha's --require? I would prefer to have an option like --require in the command line rather than putting a require(x) in the title of every file.

A:

Jest configuration provides setupFiles and setupTestFrameworkScriptFile which can be used to run setup code before tests run.
The require(x) statement would need to perform all of the needed side-effects, there isn't a way to access the module exports of x from a require statement in the setup file, but it looks like that is exactly how the --require option works in Mocha.
Just create a setup file that calls require(x) and either add it to the Jest config using one of the two options listed above or pass it on the command line using the --setupTestFrameworkScriptFile option


Q:

glClear() Takes Too Long - Android OpenGL ES 2

I'm developing an Android app using OpenGL ES 2. The problem I am encountering is that the glClear() function is taking so long to process that the game appears jittery as frames are delayed.
The output of a run of the program with timing probes shows that while setting up all vertices and images from the atlas only takes less than 1 millisecond, glClear() takes between 10 and 20 milliseconds. In fact, the clearing often takes up to 95% of the total rendering time.
My code is based upon common tutorials, and the Render function is this:
private void Render(float[] m, short[] indices) {
    Log.d("time", "--START RENDER--");

    // get handle to vertex shader's vPosition member
    int mPositionHandle = GLES20.glGetAttribLocation(riGraphicTools.sp_Image, "vPosition");

    // Enable generic vertex attribute array
    GLES20.glEnableVertexAttribArray(mPositionHandle);

    // Prepare the triangle coordinate data
    GLES20.glVertexAttribPointer(mPositionHandle, 3,
    GLES20.GL_FLOAT, true,
    0, vertexBuffer);

    // Get handle to texture coordinates location
    int mTexCoordLoc = GLES20.glGetAttribLocation(riGraphicTools.sp_Image, "a_texCoord" );

    // Enable generic vertex attribute array
    GLES20.glEnableVertexAttribArray ( mTexCoordLoc );

    // Prepare the texturecoordinates
    GLES20.glVertexAttribPointer ( mTexCoordLoc, 2, GLES20.GL_FLOAT,
    false,
    0, uvBuffer);

    // Get handle to shape's transformation matrix
    int mtrxhandle = GLES20.glGetUniformLocation(riGraphicTools.sp_Image, "uMVPMatrix");

    // Apply the projection and view transformation
    GLES20.glUniformMatrix4fv(mtrxhandle, 1, false, m, 0);

    // Get handle to textures locations
    int mSamplerLoc = GLES20.glGetUniformLocation (riGraphicTools.sp_Image, "s_texture" );

    // Set the sampler texture unit to 0, where we have saved the texture.
    GLES20.glUniform1i ( mSamplerLoc, 0);

    long clearTime = System.nanoTime();
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
    Log.d("time", "Clear time is " + (System.nanoTime() - clearTime));

    // Draw the triangles
    GLES20.glDrawElements(GLES20.GL_TRIANGLES, indices.length,
    GLES20.GL_UNSIGNED_SHORT, drawListBuffer);

    // Disable vertex array
    GLES20.glDisableVertexAttribArray(mPositionHandle);
    GLES20.glDisableVertexAttribArray(mTexCoordLoc);

    Log.d("time", "--END RENDER--");
}

I have tried moving the png atlas to /drawable-nodpi but it had no effect.
I have tried using the glFlush() and glFinish() functions as well.
Interestingly, if I do not call glClear() then it must automatically be called. This is because the total rendering time is still as high as when it was called, and there is no remnants of the previous frame onscreen. Only the first call to glClear() is time-consuming. If it is called again, the subsequent calls are only 1 or 2 milliseconds.
I have also tried different combinations of parameters (such as GLES20.GL_DEPTH_BUFFER_BIT), and using glClearColor(). The clear time is still high.
Thank you in advance.

A:

You're not measuring what you think you are. Measuring the elapsed time of an OpenGL API call is mostly meaningless.
Asynchronicity
The key aspect to understand is that OpenGL is an API to pass work to a GPU. The easiest mental model (which largely corresponds to reality) is that when you make OpenGL API calls, you queue up work that will later be submitted to the GPU. For example, if you make a glDraw*() call, picture the call building a work item that gets queued up, and at some point later will be submitted to the GPU for execution.
In other words, the API is highly asynchronous. The work you request by making API calls is not completed by the time the call returns. In most cases, it's not even submitted to the GPU for execution yet. It is only queued up, and will be submitted at some point later, mostly outside your control.
A consequence of this general approach is that the time you measure to make a glClear() call has pretty much nothing to do with how long it takes to clear the framebuffer.
Synchronization
Now that we established how the OpenGL API is asynchronous, the next concept to understand is that a certain level of synchronization is necessary.
Let's look at a workload where the overall throughput is limited by the GPU (either by GPU performance, or because the frame rate is capped by the display refresh). If we kept the whole system entirely asynchronous, and the CPU can produce GPU commands faster than the GPU can process them, we would be queuing up a gradually increasing amount of work. This is undesirable for a couple of reasons:

In the extreme case, the amount of queued up work would grow towards infinity, and we would run out of memory just from storing the queued up GPU commands.
In apps that need to respond to user input, like games, we would get increasing latency between user input and rendering.

To avoid this, drivers use throttling mechanisms to prevent the CPU from getting too far ahead. The details of how exactly this is handled can be fairly complex. But as a simple model, it might be something like blocking the CPU when it gets more than 1-2 frames ahead of what the GPU has finished rendering. Ideally, you always want some work queued up so that the GPU never goes idle for graphics limited apps, but you want to keep the amount of queued up work as small as possible to minimize memory usage and latency.
Meaning of Your Measurement
With all this background information explained, your measurements should be much less surprising. By far the most likely scenario is that your glClear() call triggers a synchronization, and the time you measure is the time it takes the GPU to catch up sufficiently, until it makes sense to submit more work.
Note that this does not mean that all the previously submitted work needs to complete. Let's look at a sequence that is somewhat hypothetical, but realistic enough to illustrate what can happen:

Let's say you make the glClear() call that forms the start of rendering frame n.
At this time, frame n - 3 is on the display, and the GPU is busy processing rendering commands for frame n - 2.
The driver decides that you really should not be getting more than 2 frames ahead. Therefore, it blocks in your glClear() call until the GPU finished the rendering commands for frame n - 2.
It might also decide that it needs to wait until frame n - 2 is shown on the display, which means waiting for the next beam sync.
Now that frame n - 2 is on the display, the buffer that previously contained frame n - 3 is not used anymore. It is now ready to be used for frame n, which means that the glClear() command for frame n can now be submitted.

Note that while your glClear() call did all kinds of waiting in this scenario, which you measure as part of the elapsed time spent in the API call, none of this time was used for actually clearing the framebuffer for your frame. You were probably just sitting on some kind of semaphore (or similar synchronization mechanism), waiting for the GPU to complete previously submitted work.
Conclusion
Considering that your measurement is not directly helpful after all, what can you learn from it? Unfortunately not a whole lot.
If you do observe that your frame rate does not meet your target, e.g. because you observe stuttering, or even better because you measure the framerate over a certain time period, the only thing you know for sure is that your rendering is too slow. Going into the details of performance analysis is a topic that is much too big for this format. Just to give you a rough overview of steps you could take:

Measure/profile your CPU usage to verify that you are really GPU limited.
Use GPU profiling tools that are often available from GPU vendors.
Simplify your rendering, or skip parts of it, and see how the performance changes. For example, does it get faster if you simplify the geometry? You might be limited by vertex processing. Does it get faster if you reduce the framebuffer size? Or if you simplify your fragment shaders? You're probably limited by fragment processing.


Q:

Grouping Log Entries By Month And IP Using Hadoop MapReduce

I'm really new to Apache Hadoop. But I want to learn how to use it to summarize my machine logs. Actually it's not big enough (GBs) and I could just parse it and wait for, like, hours. But I think learning Hadoop might be useful.
So, I have a log entries with format like below.
Location, Date, IP Address

e.g.
New York, 2011-11-31 10:50:59, 1.1.1.1
New York, 2011-11-31 10:51:01, 1.1.1.2
Chicago, 2011-11-31 10:52:02, 1.1.1.1
Los Angeles, 2011-11-31 10:53:04, 1.1.1.4

And I want to aggregate it by Location, grouped by months, and then by the IP address. Below is something in my mind of what it would look like.
  Location, Month, IP,   Count
+ New York
|   +-- November 2011
|   |     +---- 1.1.1.1    5
|   |     +---- 1.1.1.2    2
|   |     +---- 1.1.1.3    7
|   +-- December 2011
|   |     +---- 1.1.1.1    6
|   |     +---- 1.1.1.4    6
|   +-- January 2012
|         +---- 1.1.1.1   10
+ Chicago
|   +-- November 2011
|   |     +---- 1.1.1.1   20
|   |     +---- 1.1.1.2    1
|   |     +---- 1.1.1.3   10
(so on)

My questions are :

Can I do this using Hadoop or is there a better way to do it?
What is the common way to do this using Hadoop?

Thank you for giving a pointer to a link or article or a sample code.

A:

can I do this using Hadoop or is there a better way to do it?

You definitely can use Hadoop for this, if you only got a few Gbs it's probably not that necessary, but what you gain with doing this with Hadoop is that you will be able to scale easily, let's say tomorrow you have to do the same on 500Gb, you would potentially have nothing to change in your code, just the hardware and configuration.
what is the common way to do this using Hadoop?

I don't think there's a "common way" so to speak, Hadoop is a framework encapsulating multiple projects, you could do this in Map/Reduce, Hive, Pig, ...
I think your use case lends itself pretty well to doing this using Hive since you want to do aggregations and have a structure that can easily it into tables, and if you are new to Hadoop you can have the familiarity with SQL, so here are some hints.

Upload these logs into HDFS. This is the number one step required regardless of how you want to do the processing, HDFS is a distributed file system so your logs will be split in blocks across your cluster and replicated.
hadoop fs -put /path/to/your/log/directory /user/hive/warehouse/logs

Create a table in Hive. You have to set it external to the location where you put your logs in HDFS (and specify the delimiter you have in your files):
hive -e "create external table logs(location string, day string, ip string) row format delimited fields terminated by ',' location /user/hive/warehouse/logs"

Now you can do some queries on your data ! In your example you should do the following:
hive -e "select location, month(day), ip, count(*) from logs group by location, month(day), ip order by location, month, ip"

Note that I'm calling MONTH() on the day to extra the month part of the day for the aggregation, this is what Hive calls UDFs.

Even if you are writing SQL queries, this will generate under the hood Map/Reduce jobs that will run on your cluster and so your job will scale based on the size of your cluster.
I hope that makes sense, if you want more details on Hive I'd like to redirect you to the Hive DDL description as well as the official project page.


Q:

Rust, FFI, and lifetime for string transmutation

I'm working in an FFI library and have encountered this pattern quite a few times that I don't know how to handle idiomatically.
impl CanVoidStar for str {
    fn as_cvoid_ptr(&self) -> *const c_void {
        let string = CString::new(self).unwrap();
        unsafe {
            return mem::transmute(string.as_ptr());
        }
    }
}

My intent was to create a const *void pointer to a piece of memory that I can hand off to a C function. The problem that here is that string goes out of scope and thus I get undefined behavior in the unsafe block.
Is there a way I can keep string allocated on the heap until whatever it is that is using the return value done with it? Further, is there a idiomatic way to handle this or do I need to redesign my algorithms?

A:

It looks like you're using the wrong method on CString, and CString::into_raw() is what you want.  Even better, it needs no unsafe code until you want to free the memory again.
While CString::as_ptr() returns a pointer into the string, CString::into_raw() passes the ownership of the memory into the raw pointer; this is intended for exactly your use case:
trait CanVoidStar {
    fn as_cvoid_ptr(&self) -> *const c_void;
}

impl CanVoidStar for str {
   fn as_cvoid_ptr(&self) -> *const c_void {
        let string = CString::new(self).unwrap();
        string.into_raw() as *const c_void
    }
}

As the documentation says, if you ever want to free it, you'll need to reconstruct the CString using CString::from_raw() and then have it dropped as usual.


Q:

How to solve this ODE using integrating factors and differential form

I'm currently trying to solve this particular ODE:
$$(x^3 + xy^2)y' = y^3$$
but am having trouble finding the way to do so. I'm currently going through the textbook Advanced Engineering Mathematics 10e (Kreyszig) and the methods that I've studied are separating variables, using integrating factors, and using the Bernoulli equation. I've tried all three with this particular ODE and have been unsuccessful.
My initial thought was to change it into its differential form:
$$-y^3dx + (x^3 + xy^2)dy = 0$$
so that we can find the integrating factor to solve it. However, I've observed that finding the integrating factor isn't quite working out the way that the textbook describes (i.e. integrating factor $F$ should be of one variable rather than two) and am puzzled as to how to proceed from here.
Any tips or advice on how to solve this would be greatly appreciated. Thank you.

A:

The terms that can combine to the derivative of a monomial are $-y^3\,dx+xy^2\,dy=x^2y^2\,d(y/x)$. This suggests to insert $y=xu$ into the ODE to get
$$
x^3(1+u^2)(xu'+u)=x^3u^3\implies x(1+u^2)u'+u=0
$$
which is now separable. You can then, if you want, reconstruct the integrating factor that produces the integrable form in one step. This is more confirmation than solution method.

Trying to match the list of "classical methods", a change of dependency, $x(y)$ instead of $y(x)$, and $x'(y)=1/y'(x)$, gives the equation
$$
y^3x'=y^2x+x^3,
$$
which is now a Bernoulli equation. Set $u=x^{-2}$ to get the linear DE
$$
y^3u'(y)=-2y^2u-2\\~\\
(y^2u(y))'=-\frac{2}y\implies \frac{y^2}{x^2}=-2\ln|y|+c
$$


Q:

How do I fix this JSON object to html table code?

I've been modifying a little bit a piece of code I found, but I can't make it work as I want. This is the current Javascript:
function JsonUtil() {
    /**
     * Given a provided object,
     * return a string representation of the object type.
     */
    this.isType = function (obj_) {
        if (obj_ === null) {
            return "null";
        }
        if (obj_ === NaN) {
            return "Nan";
        }
        var _type = typeof obj_;
        switch (_type) {
        case "undefined":
            return "undefined";
        case "number":
            return "number";
        case "boolean":
            return "boolean";
        case "string":
            return "string";
        case "function":
            return "function";
        case "object":
            if (this.isArray(obj_)) {
                return "array";
            }
            return "associative";
        }
    },
    /**
     * Recursively search and display array as an HTML table.
     */
    this.tableifyArray = function (array_) {
        if (array_.length === 0) {
            return "[ empty ]";
        }

        var _out = "
";

        for(var i = 0; i < array_.length; i++) {
            _out += "
"
                 + this.tableifyObject(array_[i]) + "
";
        }
        _out += "
";
        return _out;
    },
    /**
     * Recursively search and display common javascript types as an HTML table.
     */
    this.tableifyObject = function (obj_) {
        /*
   if (obj_ === '') {
        return "[ empty ]";
     }
     */
        switch (this.isType(obj_)) {
        case "null":
            return "¡The data object is null!";
        case "undefined":
            return "undefined";
        case "number":
            return obj_;
        case "boolean":
            return obj_;
        case "string":
            return obj_;
        case "array":
            return this.tableifyArray(obj_);
        case "associative":
            return this.tableifyAssociative(obj_);
        }
        return "!error converting object!";
    },
    /**
     * Recursively search and display associative array as an HTML table.
     */
    this.tableifyAssociative = function (array_) {
        if (this.isEmpty(array_)) {
            return "{ empty }";
        }

        var _out = "
";

        for (var _index in array_) {
            _out += "
"
                + this.tableifyObject(_index) + "	"
                + this.tableifyObject(array_[_index]) + "
";
        }
        _out += "
";
        return _out;
    },
    /**
     * identify if an associative array is empty
     */
    this.isEmpty = function (map_) {
        for (var _key in map_) {
            if (map_.hasOwnProperty(_key)) {
                return false;
            }
        }
        return true;
    },
    /**
     * Identify is an array is a 'normal' (not associative) array
     */
    this.isArray = function (v_) {
        return Object.prototype.toString.call(v_) == "[object Array]";
    },
    /**
     * given the desire to populate a map of maps, adds a master key,
     * and child key and value to a provided object.
     */
    this.addToMapOfMaps = function (map_, mkey_, key_, value_) {
        if (map_ === undefined) {
            map_ = {};
        }
        if (map_[mkey_] === undefined) {
            map_[mkey_] = {}
        }
        if (map_[mkey_][key_] === undefined) {
            map_[mkey_][key_] = null;
        }
        map_[mkey_][key_] = value_;
        return map_;
    }
}

This is it's CSS:
 .arrayTable { border: 1px solid #c2c2c2; background-color: #c2c2c2; padding: 5px;}
 .arrayTr { border: 1px solid #c2c2c2; background-color: #c2c2c2; padding: 5px;}
 .arrayTd { border: 1px solid #c2c2c2; background-color: #c2c2c2; padding: 5px; vertical-align: top;}
 .associativeTable { border: 1px solid #c2c2c2; background-color: #fff; padding: 5px;}
 .associativeTr { border: 1px solid #c2c2c2; background-color: #fff; padding: 5px;}
 .associativeTd { border: 1px solid #c2c2c2; background-color: #eee; padding: 5px; vertical-align: top;}

And to call you just simply do:
var json = new JsonUtil();
json.tableifyObject(jsonObject);

Works really great but is not what I want, currently the array table is being shown like the following:
NAME 123123
ID 1
CATEGORY 12412

NAME AAAA
ID 2
CATEGORY 2123

I want to modify how the array tables are shown, need them vertically and all the data in one single table structure and not a lot of tables from each register. Like this:
NAME ID CATEGORY
123123 1 12412
AAAA 2 2123

How would I need to change the recursive Javascript in order to create such result?

A:

Made it guys! added the code to generate another type of table if the _obj is an array.
Just in case someone needs the same thing, this works EXCELLENT!
function createTableBasedOnJsonArray(array_) {

    var _out = "";
    for(var index in array_) {
        if(index == 0) {
            _out += "

";
            //create thead
            for(var key in array_[0]) {
                _out += "" + key + "	";
            }
            _out += "
";
        }
        var values = array_[index];
        //create tbody
        _out += "

";
        for(var key in values) {
            _out += "" + values[key] + "	";
        }
        _out += "
";
    }
    _out += "

"
    return _out;
}

So the entire json library for JSON Object to HTML is the following now:
function JsonUtil() {
    /**
     * Given a provided object,
     * return a string representation of the object type.
     */
    this.isType = function (obj_) {
        if (obj_ === null) {
            return "null";
        }
        var _type = typeof obj_;
        switch (_type) {
        case "undefined":
            return "undefined";
        case "number":
            return "number";
        case "boolean":
            return "boolean";
        case "string":
            return "string";
        case "function":
            return "function";
        case "object":
            if (this.isArray(obj_)) {
                return "array";
            }
            return "associative";
        }
    },
    /**
     * Recursively search and display array as an HTML table.
     */
    this.tableifyArray = function (array_) {
        if (array_.length === 0) {
            return "[ empty ]";
        }

        var _out = createTableBasedOnJsonArray(array_);

        return _out;
    },
    /**
     * Recursively search and display common javascript types as an HTML table.
     */
    this.tableifyObject = function (obj_) {
        switch (this.isType(obj_)) {
        case "null":
            return "¡The data object is null!";
        case "undefined":
            return "undefined";
        case "number":
            return obj_;
        case "boolean":
            return obj_;
        case "string":
            return obj_;
        case "array":
            return this.tableifyArray(obj_);
        case "associative":
            return this.tableifyAssociative(obj_);
        }
        return "!error converting object!";
    },
    /**
     * Recursively search and display associative array as an HTML table.
     */
    this.tableifyAssociative = function (array_) {
        if (this.isEmpty(array_)) {
            return "{ empty }";
        }

        var _out = "
";

        for (var _index in array_) {
            _out += "
"
                + this.tableifyObject(_index) + "	"
                + this.tableifyObject(array_[_index]) + "
";
        }
        _out += "
";
        return _out;
    },
    /**
     * identify if an associative array is empty
     */
    this.isEmpty = function (map_) {
        for (var _key in map_) {
            if (map_.hasOwnProperty(_key)) {
                return false;
            }
        }
        return true;
    },
    /**
     * Identify is an array is a 'normal' (not associative) array
     */
    this.isArray = function (v_) {
        return Object.prototype.toString.call(v_) == "[object Array]";
    },
    /**
     * given the desire to populate a map of maps, adds a master key,
     * and child key and value to a provided object.
     */
    this.addToMapOfMaps = function (map_, mkey_, key_, value_) {
        if (map_ === undefined) {
            map_ = {};
        }
        if (map_[mkey_] === undefined) {
            map_[mkey_] = {}
        }
        if (map_[mkey_][key_] === undefined) {
            map_[mkey_][key_] = null;
        }
        map_[mkey_][key_] = value_;
        return map_;
    }
}

function createTableBasedOnJsonArray(array_) {

    var _out = "";
    for(var index in array_) {
        if(index == 0) {
            _out += "

";
            //create thead
            for(var key in array_[0]) {
                _out += "" + spaceRawKeyName(key).toUpperCase() + "	";
            }
            _out += "
";
        }
        var values = array_[index];
        //create tbody
        _out += "

";
        for(var key in values) {
            _out += "" + values[key] + "	";
        }
        _out += "
";
    }
    _out += "

"
    return _out;
}

If someone is interested in the "spaceRawKeyName" function, which is used to separate a string like this accountId to account_Id by capslock recognition.
function spaceRawKeyName(string) {
    var newone = [];
    for(i=0; i<string.length;i++) {
        character = string.charAt(i);
        if(character == character.toUpperCase()) {
            newone.push("_");
        }
        newone.push(character);
    }
    var text = "";
    for(i=0;i < newone.length;i++){
        text += newone[i];
    }
    return text;
}

Of course you can make a .toUpperCase() later to make it look a little bit more fancy ACCOUNT_ID, btw... if you don't want to add a "_" you can simply replace it for a space.


Q:

RSpec: Stub controller method in request spec

I'm writing an RSpec request spec, which looks roughly like (somewhat shortened for brevity):
describe 'Items', type: :request do
  describe 'GET /items' do
    before do
      allow_any_instance_of(ItemsController).to receive(:current_user).and_return(user)
      get '/items'
      @parsed_body = JSON.parse(response.body)
    end

    it 'includes all of the items' do
      expect(@parsed_body).to include(item_1)
      expect(@parsed_body).to include(item_2)
    end
  end
end

The controller looks like:
class ItemsController < ApplicationController
  before_action :doorkeeper_authorize!
  def index
    render(json: current_user.items)
  end
end

As you can see, I'm trying to stub doorkeeper's current_user method.
The tests currently pass and the controller works as expected. My question is about the line:
allow_any_instance_of(ItemsController).to receive(:current_user).and_return(user)

I wrote this line based on the answers in How to stub ApplicationController method in request spec, and it works. However, the RSpec docs call it a "code smell" and rubocop-rspec complains, "RSpec/AnyInstance: Avoid stubbing using allow_any_instance_of".
One alternative would be to get a reference to the controller and use instance_double(), but I'm not sure how to get a reference to the controller from a request spec.
How should I write this test avoid code smells / legacy testing approaches?

A:

You're supposed to be on vacation.
I think the right way is to avoid stubbing as much as you can in a request spec, doorkeeper needs a token to authorize so I'd do something like:
describe 'Items', type: :request do
  describe 'GET /items' do
    let(:application) { FactoryBot.create :oauth_application }
    let(:user)        { FactoryBot.create :user }
    let(:token)       { FactoryBot.create :access_token, application: application, resource_owner_id: user.id }
    before do
      get '/items', access_token: token.token
      @parsed_body = JSON.parse(response.body)
    end

    it 'includes all of the items' do
      expect(@parsed_body).to include(item_1)
      expect(@parsed_body).to include(item_2)
    end
  end
end

Here are some examples of what those factories might look like.
Lastly, nice SO points!