Q:

What does [i] do after a variable name?

I've been following some Python tutorials and need some help with something.
In htmlfile = urllib.urlopen(urls[i]) in the code below, I couldn't understand why [i] is needed after after the urls.
import urllib

urls = ["http://google.com","http://nytimes.com","http://cnn.com"]
i=0

while i< len(urls):
    htmlfile = urllib.urlopen(urls[i])
    htmltext = htmlfile.read()
    print htmltext
    i+=1

A:

i is indexing the list urls, allowing you to return the items one by one.  See below:
>>> urls = ["http://google.com","http://nytimes.com","http://cnn.com"]
>>> i = 0
>>> while i < len(urls):
...     print i, urls[i]
...     i += 1
...
0 http://google.com
1 http://nytimes.com
2 http://cnn.com
>>>

Also, I would like to mention that your code can be refactored to be more efficient:
import urllib
urls = ["http://google.com","http://nytimes.com","http://cnn.com"]
for url in urls:
    print urllib.urlopen(url).read()

This new code does exactly what the old one does.


Q:

asymptotic of $x^{x^x} = n$

How find the asymptotic behavior for $x(n)$
if $x^{x^x} = n$?
I supposed that $x = O(\log\log{n})$
and took logarithm two times.
So I get
$x = O(\frac{\log\log{n}}{\log\log\log{n}})$
Is it right?
How to improve this estimate?

A:

Let's write
$$
\begin{align}
&\log\log n = L_2(n), \\
&\log\log\log n = L_3(n), \\
&\log\log\log\log n = L_4(n).
\end{align}
$$
Then from $x^{x^x} = n$ we get
$$
x\log x + L_2(x) = L_2(n), \tag{1}
$$
and so, since $x \to \infty$ as $n \to \infty$, we have
$$
x\log x \sim L_2(n) \tag{2}
$$
as $n \to \infty$.  Taking logs of this yields
$$
\log x + L_2(x) \sim L_3(n),
$$
from which it follows that
$$
\log x \sim L_3(n). \tag{3}
$$
By dividing $(2)$ by $(3)$ we then find that
$$
x \sim \frac{L_2(n)}{L_3(n)}, \tag{4}
$$
agreeing with your estimate.  To get the next term we iterate.
Taking logs of $(1)$ and rearranging yields
$$
\log x = L_3(n) - L_2(x) - \log\left(1 + \frac{L_2(x)}{x\log x}\right). \tag{5}
$$
From $(3)$ we know that
$$
L_2(x) = L_4(n) + o(L_4(n)),
$$
so we can rewrite $(5)$ as
$$
\log x = L_3(n) - L_4(n) + o(L_4(n)).
$$
Substituting these into $(1)$ yields
$$
x\Bigl(L_3(n) - L_4(n) + o(L_4(n))\Bigr) = L_2(n) - L_4(n) + o(L_4(n)). \tag{6}
$$
Now
$$
\Bigl(L_3(n) - L_4(n) + o(L_4(n))\Bigr)^{-1} = L_3(n)^{-1} + \frac{L_4(n)}{L_3(n)^2} + o\left(\frac{L_4(n)}{L_3(n)^2}\right),
$$
so we can conclude from $(6)$ that
$$
x = \frac{L_2(n)}{L_3(n)} + \frac{L_2(n) L_4(n)}{L_3(n)^2} + o\left(\frac{L_2(n) L_4(n)}{L_3(n)^2}\right)
$$
as $n \to \infty$.


Q:

How can I fetch data from Firestore only once each even if I modify some fields?

I'm developing a flutter app and I have a problem that I can't solve.
On one of my views, I display all my users from Firestore.
I first Query to Firestore, and I every time save the last user to re-execute the query with startAfterDocument(lastUser).
 fetch10first() async {
 Stream<QuerySnapshot> stream = dbInstance.collection('users').orderBy('prenom', descending: true).limit(10).snapshots();
 stream.listen((snapshot) {
  snapshot.documents.forEach((u) {
    User user = User.fromDocument(u);
    setState(() {
      users.add(user);
      _lastUser = u;
    });
  });
});
}

Every user is stored in a List. To display those users, I'm using a ListView.builder with a scroll controller that checks if I've reached the bottom of my page and fetches 10 new users.
The problem I have is that I'm listening to snapshots. Then if I modify one of my users ( from the app or from Firestore ), it will get another snapshot and I'm going to have the user displayed twice.
How can I solve this?

A:

To fetch data only once, you need to use Future with getDocuments():
fetch10first() async {
 Future<QuerySnapshot> futureCol = dbInstance.collection('users').orderBy('prenom', descending: true).limit(10).getDocuments();
 futureCol.then((snapshot) {
  snapshot.documents.forEach((u) {
    User user = User.fromDocument(u);
    setState(() {
      users.add(user);
      _lastUser = u;
    });
  });
});
}


Q:

Javascript slide form Jquery, Prototype, or pure Javascript

I am a newby and would like some professiona advice about the following:
I want to create a form.
The user fills in one part and clicks 'next'.
The form slides to the left and a new part of the form slides in from the right.
Does anyone have any advice as to the way to go.
Jquery, Prototype, or just plain old javascript.
I am using Ruby on Rails3, Mac OSX10.6, Ruby 1.9.2
Any help would be much appreciated.

A:

There are already jQuery plugins to do this kind of thing. Take a look at http://tympanus.net/codrops/2010/06/07/fancy-sliding-form-with-jquery/ for example.


Q:

Errors when linking 32/64bit assembly in Linux

I am new to assembly language programming. I am trying to follow the steps outlined here to get a better understanding of assembly and optimization. My operating system is Linux Mint, and I am trying to use the NASM assembler, albeit unsuccessfully.
As in the walkthrough, the code is:
BITS 32
GLOBAL main
SECTION .text
main:
    mov eax, 42
    ret

It compiles successfully with nasm using the command: nasm -f elf tiny.asm
But if I try to use gcc to link with the command: gcc -Wall -s tiny.o
I get the following error:
/usr/bin/ld: i386 architecture of input file `tiny.o' is incompatible with i386:x86-64 output
A quick search told me that I should link using this ld command: ld -m elf_i386 -s -o tiny tiny.o
However, doing this gives me the following warning:
ld: warning: cannot find entry symbol _start; defaulting to 0000000008048060
And if I ./tiny I get a Segmentation Fault. And ./tiny ; echo $? also returns the number '139' which is... unexpected.
Browsing around, I see that the problem is solved for some by passing 1 to the eax register and 0 to ebx, and using an int command I'm unfamiliar with to end the program... But considering my objective is to make the program as small as possible, I would rather not add additional lines of code.
I should add that compiling and linking this similar code (GAS):
.global main
.text
main:
    mov $32, %eax

Using the gcc compiler seems to run flawlessly. I'm at a loss here. Any point in the right direction would be greatly appreciated.

A:

This applies to Linux Mint, Ubuntu, Xubuntu and other modern Ubuntu based distributions. For other Debian systems the information is the same, but you can remove the sudo command from the installation command and run the command as the root user.

By default files needed for GCC to create 32-bit program are not installed on 64-bit Linux Mint. This command will install the required files:
sudo apt-get install gcc-multilib g++-multilib

To assemble asa 32-bit object, and then link to a 32-bit executable you can do this:
nasm -f elf32 tiny.asm -o tiny.o
gcc -m32 -Wall -s tiny.o -o tiny

Since you had BITS 32 at the top of the assembler file you want to compile that to a 32-bit ELF object which is what the -f elf32 option on the NASM command line does.
GCC is used to link objects to a final executable. The addition of -m32 tells GCC to link the objects to a 32-bit executable. The -m32 option overrides the normal default behavior of generating 64-bit executables on a 64-bit Linux distribution.

By using GCC to link the executable, the generated program actually supplies a _start that does C runtime initialization and then calls the label called main as if it was a C function.
When you do the ret in your main function it returns back to the C runtime code and exits the program cleanly for you.
Using GCC is the easier and safer method for new assembly language developers. It also allows you to add code that calls the C runtime functions like printf, scanf, atoi and most of the other standard C library functions.


Q:

I add a line of text to my CSS file, garbage comes through the browser

I'm using Vagrant to manage a VirtualBox instance of Debian Wheezy with PHP 5.5 and nginx 1.4.4. My local environment is Mac OS X 10.9 with PHP 5.5 and Apache 2.2.24. I have a synced directory that points to my document root for this particular project.
My local machine has a VirtualHost setup that also points to the document root for this project. Therefore, I actually have two different URLs that I can point my browser to, and the same code will be executed. One URL hits the virtual machine, while the other URL hits my local Apache installation.
I've been able to edit several PHP files with no problems. I make the changes locally and they immediately show up on both the virtual machine and my local web server. However, whenever I try to edit CSS, things get bizarre. I'm trying to add a single line of CSS to a static CSS file. Something along the lines of:
.body {margin-top:50px}

When I make this change, the virtual machine goes nuts. I'm not sure if it's sending a corrupted file, or if it's just appending a bunch of weird characters at the end of the CSS file, but I can't even paste them here. I did a Charles dump of the request for the CSS file and the response looks like this:

I've looked at the file in vim through the virtual machine. I've looked at the file using multiple text editors. For the life of me I can't find anything wrong with it. When I load the exact same file through my local Apache installation, it works just fine:

Notice that the body declaration appears between button and footer, and there are no weird characters at the end of the document.
The other thing that I noticed is that my the whitespace is being manipulated at some point as well. The CSS file in question uses four spaces for indentation, but in the response from the virtual machine, the lines only have two spaces of indentation. You can't see it from the pictures because they're formatted by Charles, but I looked at the raw data. It's truly bizarre.
Do you have any idea what is causing the manipulation of my CSS file when it is being served via the Vagrant/nginx combo vs my local/Apache combo?
EDIT
I pasted some of the characters into a hexadecimal converter and it converted all the characters to question marks. I tried a binary to decimal conversion and they all turned into �, which from what I can find is "used to replace a character whose value is unknown or unrepresentable in unicode". I ran file --mime on the file and it returned rental-application.js: text/plain; charset=us-ascii. So...nginx settings maybe?
I'm having the exact same issue with JavaScript files. If I vagrant destroy and vagrant up is the only way I've found to resolve the issue so far. It doesn't make for quick troubleshooting when I have to reboot my VM between file saves.
Every method that I use to look at the file works. The only issue is when it is served through nginx, which makes me think I have some type of encoding setting wrong. It's a mostly stock setup.
More bizarre
If I mv rental-application.js rental-application.html and load the page in my browser, it comes across perfectly. The same applies if I change the name to rental-application.php. However, as soon as I change the name to rental-application.js or rental-application.css, my changes disappear and the � characters re-appear at the end of the document.
Even MORE bizarre
I can create a js file on the VM and it will load fine via the VM nginx server. If I subsequently modify the file I just created and reload it, the changes don't appear, just the garbage characters.
If I mv that file to a different name that ends in .js, the garbage character problem still persists. However, if I then cat the contents of the renamed file to a new file with the original name, all is well in the universe.

A:

Just so if people end up here for the same issue, they have the solution on how to resolve this: you need to turn off sendfile() in your web server' settings.
For Apache: EnableSendfile off
For Nginx: sendfile off
Quick explanation: https://coderwall.com/p/ztskha
You can find more online if you need more details.
Now you can get a beer and enjoy your static file being transferred properly, not more corrupted files :)


Q:

PHP kill exec() background process after php-fpm restarted

I use nginx and php7.1-fpm. I want to run a background process using PHP and exec().
My short code:
<?php
exec('/usr/local/bin/program > /dev/null 2>&1');

Unfortunately after the systemd restart php7.1-fpm the program is killed.
I have tried to run with a different user than the one running the pool:
<?php
exec('sudo -u another_user /usr/local/bin/program > /dev/null 2>&1');

However, this does not solve the problem - still kills.
I can not use ssh2_connect(). How can I solve this problem?

A:

It seems this is due to the php-fpm service being managed by the systemd.
All processes launched from php-fpm belong to its control-group and when you restart the service systemd sends the SIGTERM to all the processes in the control-group even if they are daemonized, detached and/or belong to another session.
You can check your control-groups with this command:
systemd-cgls

What I've done is to change the KillMode of the php-fpm service to process.
Just edit it's .service file:
vi /etc/systemd/system/multi-user.target.wants/php7.0-fpm.service

and change or add the line to the [Service] block:
KillMode=process

Then reload the configuration by executing:
systemctl daemon-reload

That worked for me.
References:
Can't detach child process when main process is started from systemd
http://man7.org/linux/man-pages/man5/systemd.kill.5.html
What would be wonderful would be a command (similar to setsid) that allowed to launch a process and detach from control-group but I haven't been able to find it.


Q:

Finding intersecting points of a circle inside a triangle

If I have a triangle, and I wanted to place a circle with a given diameter that fits snuggly inside any one of the three angles, how can I find the x, y points of where the triangle and circle meet?

A:

As a hint:  if the diameter is $d$ and the angle at a specific vertex is $\alpha$ then the distances from that vertex along each side is $$ \frac{d}{2} \times \frac{1}{\tan\left(\frac{\alpha}{2}\right)}.$$


Q:

How to setText of elements in JLabel array?

I want to change the text displayed on JLabels within an array after instantiation.
I currently get a java.lang.NullPointerException.
import javax.swing.JFrame;
import javax.swing.JLabel;

public class App
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("Swing Frame");

        JLabel[] labelArray = new JLabel[2];

        labelArray[0].setText("a");
        labelArray[1].setText("b");

        frame.add(labelArray[0]);
        frame.add(labelArray[1]);

        frame.setSize(350, 200); // width=350, height=200
        frame.setVisible(true); // Display the frame
    }
}

A:

You are instantiating the array but their are no values in it. So if you access labelArray[0] it would return null.
You should set the values of the array:
JLabel[] labelArray = new JLabel[2];
labelArray[0] = new JLabel("someText");
labelArray[1] = new JLabel("someText");

Now you can access the labels without the NullPointer Exceptions.


Q:

How was the universe created?

I do not know much beyond high school Physics. Thus, I am asking this question from almost layman's perspective:

What, as per the best of our existing knowledge and widely accepted among the scientific community, are the models of creation of the universe, and what is their core argument?

A:

If you mean by world the earth, you can find a fairly good discussion at
http://en.wikipedia.org/wiki/Formation_and_evolution_of_the_Solar_System
If you mean by world the universe:
The big bang is a singularity, and we can study scientifically only what came out of it. See, e.g.,
http://en.wikipedia.org/wiki/Big_Bang
Thus there is no model of creation of the universe widely accepted among the scientific community.
However, there are various scientific speculations based on physical reasoning, e.g.,
Eternal inflation, http://arxiv.org/abs/hep-th/0702178
Extra dimensions, http://www.superstringtheory.com/cosmo/cosmo4.html
Big crunch, http://arxiv.org/pdf/hep-th/0108187
Cyclic universe, http://arxiv.org/abs/hep-th/0111098
Big bang particle lattice, http://www.awesomeanimator.com/bigbangstatevector.pdf
Now or in former times widely accepted models for the creation of the universe can be found not in science but in theology, e.g.,
http://www.catholic.com/tracts/creation-and-genesis
http://www.talkorigins.org
http://www.aljazeerah.info/Islamic%20Editorials/2007/October/Creation%20and%20Evolution%20in%20the%20Holy%20Qur%27an%20By%20Hassan%20El-Najjar.htm
http://www.answering-islam.org/Shamoun/creationdays.htm
or mythology, e.g.,
http://dept.cs.williams.edu/~lindsey/myths/myths.html
http://www.desy.de/gna/interpedia/greek_myth/creation.html
http://www.egyptartsite.com/crea.html


Q:

How to Change Title of field in popup kendo grid as same as kendo grid by html helper

I use kendo ui grid in project,I have a problem in popup kendo grid.
I have a kendo grid. and i customize title of column in grid by html helper.but in edit popup window title not set as same as kendo grid.
    <div class="k-rtl">

    @(Html.Kendo().Grid<KendoSample.Models.Person>()
   .Name("grid")
   .Columns(columns =>
    {
        columns.Bound(p => p.PersonId).Title("کد").Width(100).Sortable(true);
        columns.Bound(p => p.Name).Title("نام").Width(200).Sortable(true);
        columns.Bound(p => p.Family).Title("نام خانوادگی").Sortable(false);
        columns.Command(c => { c.Edit().Text("ویرایش").CancelText("انصراف").UpdateText("ذخیره"); c.Destroy().Text("حذف"); });
    })
.Pageable()

.ToolBar(s => { s.Create().Text("ایجاد"); })
.Editable(c => { c.TemplateName("Default").Mode(GridEditMode.PopUp); c.Window(x => x.Title("ویرایش")); })

.Scrollable()
.Sortable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
    .Ajax()
                            .Model(c => c.Id(p => p.PersonId))
                            .Create(c => c.Action("Read", "Home"))

    .Read(read => read.Action("EditingPopup_Read", "Grid"))
    .Update(update => update.Action("EditingPopup_Update", "Grid"))
    .Destroy(update => update.Action("EditingPopup_Destroy", "Grid"))

                            .ServerOperation(true)
    .PageSize(8)
    .Read(read => read.Action("EditingPopup_read", "Home"))
 )
 .Sortable()
 .Filterable()
 )

</div>

please help me.

A:

i fix this issue by use EditorTemplates in view.


Q:

How does electron "orbit" nucleon unless 3 coloured charges act like positive charge?

Do quark(s) emit(s) electromagnetic wave otherwise how do(es) electron(s) form an orbital? Can colour charges somehow mimic electric charge? Btw I know quarks interact via strong nuclear force.

A:

Quarks have both color charge and electric charge. Their electric charge is the reason they interact with electrons.
In units where a single electron has electric charge $-1$, the up quark has electric charge $+2/3$ and the down quark has electric charge $-1/3$. A proton (two ups and one down) has total electric charge $2/3 + 2/3 - 1/3 = 1$, same magnitude but opposite sign as the electron.
The color and electric charges are independent of each other in the sense that they are controlled by independent coefficients in the equations that describe the behavior of subatomic particles. Quarks have both kinds of charge, and electrons have only one of them (electric but not color).


Q:

What are the differences among ‘Hurricane,’ ‘Super storm,’ and ‘Typhoon’?

In this morning’s (November 2nd) live-video report of New York Times, the caster asked a guest commentator if the tropical storm Sandy can be classified as a hurricane because there are many others who say it’s not hurricane, but a strong storm. The commentator answered "It’s definitely Hurricane, not a storm."
Actually the same NY-Times carries an article captioned “Toll rises amid Storm recovery” next to the video report, while showing pictures under the caption, “Hurricane Sandy Aftermath” in other corner, and, its co-ed columnist Paul Krugman wrote “Polls show overwhelming approval for Mr. Obama’s handling of the storm, and a significant rise in his overall favorability ratings,” in his article, “Sandy Versus Katrina” appearing in NY-Times on November 4th.
AP News on Nov. 5 says “There are a plenty of demands and some desperation for gasoline in New York and New Jersey and surrounding areas where people try to recover from the recent storm,” and the same day’s NY-Times also carries the headline, “A scramble to help those displaced by storm cast ballots.”
What is the difference between Hurricane and Strong or Super storm, and additionally Typhoon, so that I can explain to my granddaughter in a single, or few words, without going into lengthy meteorologist’s wordings? We have Storm and Typhoon, but not hurricane in our country. Do they differ by strength, affected regions, or other plain criteria?
Which was the one that buoyed the votes for re-election of President Obama at the last minutes of the race, “Hurricane” or “Super storm” Sandy?

A:

Which term is appropriate for a weather pattern at sea depends on location (generally Atlantic, Pacific, Australian) and on sustained wind speeds, as explained below.  Briefly, hurricanes and typhoons have windspeeds of at least 74 mph (ca. 119 km/h).   The storms are of the same character under either name; such storms in the Atlantic or the Northeast Pacific are called hurricanes, and if elsewhere in the Pacific are typhoons except where they are severe tropical cyclone or storms.  Terminology details are given below.
The following information is quoted from topic A5, “What is a tropical disturbance, a tropical depression, or a tropical storm?”  and topic A1,  “What is a hurricane, typhoon, or tropical cyclone?” in the NOAA FAQ.

The terms "hurricane" and "typhoon" are regionally specific names for a strong "tropical cyclone". ... Tropical cyclones with maximum sustained surface winds of less than 17 m/s (34 kt, 39 mph) are usually called "tropical depressions"... Once the tropical cyclone reaches winds of at least 17 m/s (34 kt, 39 mph) they are typically called a "tropical storm" or in Australia a Category 1 cyclone and are assigned a name. If winds reach 33 m/s (64 kt, 74 mph), then they are called:
  • "hurricane" (the North Atlantic Ocean, the Northeast Pacific Ocean east of the dateline, or the South Pacific Ocean east of 160E)
  •     "typhoon" (the Northwest Pacific Ocean west of the dateline)
  •     "severe tropical cyclone" or "Category 3 cyclone" and above (the Southwest Pacific Ocean west of 160°E or Southeast Indian Ocean east of 90°E)
  •     "very severe cyclonic storm" (the North Indian Ocean)
  •     "tropical cyclone" (the Southwest Indian Ocean)

The term Superstorm has been attached to Sandy, partly because of the amount of damage it caused and partly because of the several factors that combined to make it so damaging.
As KitFox notes in a comment, a storm need not be rotationally organized, while the terms hurricane, typhoon, and cyclone specifically refer to strongly-rotating weather patterns.

A:

Here’s my try, according to:

. . .that I can explain to my granddaughter in a single, or few words, without going into lengthy meteorologist’s wordings?

Typhoon and hurricane are the same thing in English. In other languages — take Spanish, for example — they have only one word, which is normally huracán (hurricane) but sometimes  ciclón tropical (tropical cyclone) in science writing.
The difference between this and storm (note that big storm keeps being a storm, but bigger) is quite clear, as a hurricane or typhoon is like an arrangement of thunderstorms that produces stronger effects than a simple storm.
So this would be the answer: a hurricane is the same as a typhoon, and both are technically called a tropical cyclone, which is a spiral arrangement of storms.
Note that a big storm could also be referring to a hurricane in some contexts.

A:

If you look at the dictionary entries for hurricane, you will see that the definitions do not wholly agree.
The most rigorous definition requires (constant) wind speeds of over 74 mph, restricted regions for origin, and restricted directions of travel.
The loosest (literal - there are metaphorical usages) definition (given as the most fundamental sense in Collins) requires only that a 'severe storm' be involved.
Taking the strict, meteorological sense, qualifying storms are further graded into five classes using the Saffir-Simpson Hurricane Wind Scale (Category 5 being the fiercest). Storms below hurricane strength but still severe are known as 'tropical storms'.


Q:

JQuery Accordion Menu in Conflict with mmenu - JQuery 1.4 vs 1.7

I'm using the following code for a simple JQuery accordion menu which uses JQuery 1.4
The issue is that I'm also using mmenu which requires JQuery 1.7 or higher in order to function and so the two are now conflicting.
Can I therefore update the following code to make it JQuery 1.7 friendly?  Are there any other recommendations?
Thanks all for your help - much appreciated...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript" src="js/jquery.cookie.js"></script>

<script>
$(document).ready(function () {
  var checkCookie = $.cookie("nav123-item");
  if (checkCookie != "") {
    $('#nav123 > li > a:eq('+checkCookie+')').addClass('active').next().show();
  }
  $('#nav123 > li > a').click(function(){
      var nav123Index = $('#nav123 > li > a').index(this);
      $.cookie("nav123-item", nav123Index);
      $('#nav123 li ul').slideUp();
       if ($(this).next().is(":visible")){
           $(this).next().slideUp();
       } else {
       $(this).next().slideToggle();
       }
       $('#nav123 li a').removeClass('active');
       $(this).addClass('active');
  });
});
</script>

A:

You can run multiple jQuery versions in noconflict mode, just wrap your code like this:
(function($) {
    /*your code here*/
}(jquery_x_x_x)); // jquery_1_4_1 for example

HERE is more info.


Q:

Take each first element from sub-groups ordered by a second column

I have data that has been ordered by two columns looks like:
X | Y
--+---
A | 4
A | 2
A | 0
B | 3
B | 2
B | 1

And I want to structure my SQL query so that it would output:
X | Y
--+---
A | 4
B | 3

Any tips?
SELECT
    table1.X,
    max(table2.Y)
FROM
    table1
INNER JOIN
    table2
ON table1.X = table2.X
ORDER BY
    table1.X,
    table2.Y DESC;

A:

SQL tables represent unordered sets, so there is no concept of "first" row in a group, unless a column specifies the ordering.
From you sample data, though, a simple max() would suffice to get the desired results:
select x, max(y)
from table t
group by x;

A:

You can also use ROW_NUMBER like this:
SELECT
    x, y
FROM (
    SELECT
        t1.x, t2.y,
        ROW_NUMBER() OVER (PARTITION BY t1.x ORDER BY t1.x, t2.y DESC) as seq
    FROM
        table1 t1
        JOIN
        table2 t2 ON t1.x = t2.x) t
WHERE
    (seq = 1)

The seq is sorted over t1.x and t2.y DESC and resets  by changing t1.x.


Q:

Remove duplicate values from an array of objects in javascript

i have an array of objects like this:
arr = [
    {label: Alex, value: Ninja},
    {label: Bill, value: Op},
    {label: Cill, value: iopop}
]

This array is composed when my react component is rendered. The i user Array.prototype.unshift for adding a desired element in the top of my array.
So i write arr.unshift({label: All, value: All}). When my component first rendered my array is successfully created as i desire. But when i rerender it it shows me the array with the value {label: All, value: All} as duplicate. To be more specific it is shown something like this:
arr = [
    {label: All, value: All},
    {label: All, value: All},
    {label: Alex, value: Ninja},
    {label: Bill, value: Op},
    {label: Cill, value: iopop}
]

How can i fix this? I tried the methods described in a specific topic here but it didn't work

A:

You can use array#reduce and array#some.

const arr = [
    {label: 'All', value: 'All'},
    {label: 'All', value: 'All'},
    {label: 'Alex', value: 'Ninja'},
    {label: 'Bill', value: 'Op'},
    {label: 'Cill', value: 'iopop'}
]

var result = arr.reduce((unique, o) => {
    if(!unique.some(obj => obj.label === o.label && obj.value === o.value)) {
      unique.push(o);
    }
    return unique;
},[]);
console.log(result);

A:

One liner solutions for ES6+
Unique by label and value
arr.filter((v,i,a)=>a.findIndex(t=>(t.label === v.label && t.value===v.value))===i)

Unique by all properties of the object:
arr.filter((v,i,a)=>a.findIndex(t=>(JSON.stringify(t) === JSON.stringify(v)))===i)


Q:

How to show that the intersection of 2 distinct p-Sylows (p prime) is the identity?

Let us suppose that $G$ is a simple group of order 90. Show that 2 distinct 3-Sylows cannot contain the same element $g \neq e_G$ where $e_G$ is the identity.
First we can compute the number of 3-Sylows: there are 10 3-Sylows.
Let T, S be 2 distinct 3-Sylows. We want to prove that $T \cap S = e_G$
How to do so? Is there a general methodology?
My idea is to consider $g \neq e_G \in T \cap S$ and to show that it is no possible.
We consider the centralizer $Z(g) = \{h \in G, hg=gh\}$ of $g \in G$.
$Z(g)$ is a subgroup of $G$ and contains T,S. $Z(g)$ is of order 18, 45 or 90.
Then we would need to show that $Z(G)$ cannot be of order 18, 45 or 90 for various reasons that make $G$ not simple anymore, but I don't know how to do so.

If $|Z(g)|=90$ then $Z(g)=G$ and ?
If $|Z(g)|= 45$ then $Z(g)$ is of index 2 in $G$ and?
If $|Z(g)|= 18$ then ?

A:

If $|Z(g)|=90$, $Z(g)=G$, so $g$ is central, hence generates a (proper) normal subgroup.
If $|Z(g)|=45$, $Z(g)$ has index $2$, as you noted, and it's well known that subgroups of index $2$ are always normal.
If $|Z(g)|=18$, the group action of $G$ on $G/Z(g)$ by multiplication on cosets gives a homomorphism $G\to\operatorname{Sym}(G/Z(g))\simeq S_5$, since $Z(g)$ has index five. This morphism is not trivial since not every element of $G$ induces the identity permutation. So if $G$ is simple, the map must have trivial kernel, implying $G$ embeds in $S_5$, but $90\nmid 120$.
Added: In more detail, each $x\in G$ defines a permutation $\rho_x$ on the set of $5$ cosets of $Z(g)$ in $G$ by the rule $\rho_x(hZ(g))=xhZ(g)$. The map $\rho\colon G\to\operatorname{Sym}(G/Z(g)):x\mapsto \rho_x$ is a group homomorphism, and $\operatorname{Sym}(G/Z(g))\simeq S_5$ since it is the group of permutations of a set of $5$ elements (the $5$ cosets of $Z(g)$). Since $\rho$ is a group homomorphism, $\ker\rho\unlhd G$. Since $G$ is simple, either $\ker\rho=G$ or $\ker\rho=\{e\}$. The former case means every $\rho_x$ the identity permutation, but this is not true since any element $y$ outside of $Z(g)$ does not induce the identity since $\rho_y(Z(g))=yZ(g)\neq Z(g)$. So $\ker\rho=\{e\}$, meaning $\rho$ is injective, so the image $\rho(G)$ is an isomorphic copy of $G$ in $S_5$, so by LaGrange $|G|$ divides $|S_5|$, contradiction.


Q:

How to start a terminal from a recovery USB flash drive

On Mavericks I want to start the terminal when using my Live-USB.

A:

A bash shell is available in Maverick's Recovery Mode from the menubar under Utilities:

If you suspect that the internal recovery disk is compromised and cannot boot into it with Command+r, you could try booting into the "internet recovery mode" with Command+Option+r. It might take a minute or two to load the Terminal option.


Q:

On Foundation 5, what CSS is generated by setting $include-html-classes to false?

Specifying $include-html-classes to false and then importing Foundation 5 to your Sass file still generates a bunch of CSS.  Looks like some of it is meta stuff for versioning  information I suppose, but some of it looks like HTML classes.  I thought the whole point of using this variable was to remove HTML classes?
Here's my SCSS file:
@import "../foundation/settings";
$include-html-classes: false;
@import "foundation";

This wasn't a problem in Foundation 4.  What are these styles and how can I get rid of 'em?

A:

This looks like it is a bug where new presentational classes have been added above the conditionals. Since you question is how to fix it, here is the process if you don't want to wait until it is fixed officially.
Move your Scss into a different directory or fork the foundation bower repo.
Update your config.rb (line 2) to point to the new files, this is relative to your project directory
# Require any additional compass plugins here.
add_import_path "some_other_directory/foundation/scss"

Then you will need to modify each file that generates presentational classes. Luckily Compass/Sass gives us the exact place to look.
/* line 259, ../bower_components/foundation/scss/foundation/components/_global.scss */
meta.foundation-version {
  font-family: "/5.1.0/";
}

On line 296 you will see the conditional line:
@if $include-html-global-classes {

and all of the classes that have been added above it.
You will need to move this line to 260 and it should look like the following.
@include exports("global") {

  @if $include-html-global-classes {

    meta.foundation-version {
      font-family: "/5.1.0/";
    }

Since this is Scss you could either leave or correct the indentation to match.
You would need to repeat this for each file that generates CSS with Compass. If you are running compass watch, you can just check or reload your stylesheets/app.css after each correction.


Q:

Using CASE inside conditional IN clause

I have the failing statement:
select
    value_1, value_2
from
    zt_Report
where
    Division_CD in CASE WHEN @Division ='(ALL EPCD)' THEN ('Epoxy', 'MDP', 'OTG', 'PSR') ELSE @Division END
    and [Business_CD] like CASE WHEN @Business='(All)' THEN '%' ELSE @Business END
    and [Plant_TX] like CASE WHEN @Plant='(All)' THEN '%' ELSE @Plant+'%' END

Getting an error on the line:
Where Division_CD in CASE WHEN @Division ='(ALL EPCD)' THEN ('Epoxy', 'MDP', 'OTG', 'PSR') ELSE @Division END

What essentially needs to happen is when the division parameter is passed (ALL EPCD), then the WHERE clause will only allow the divisions 'Epoxy', 'MDP', 'OTG', 'PSR', otherwise it should filter exactly on that divison, ie. passing Epoxy into Division will set the WHERE to locate only Epoxy division

A:

That is not how case works.  It returns a scalar value, not a list.  So, you want to do something like this:
Where (@Division = '(ALL EPCD)' and Division_CD IN ('Epoxy', 'MDP', 'OTG', 'PSR') or
       Division_CD = @Division
      ) and
      (@Business = '(All)' or Business_CD = @Business) and
      (@Plant = '(All)' or Plant_TX like @Plant + '%')

Your logic is mixing equality, like, and case in very strange (and incompatible) ways.


Q:

How to do R multiplication with Nx1 1xM for Matrix NxM?

I want to do a simple column (Nx1) times row (1xM) multiplication, resulting in (NxM) matrix.
Code where I create a row by sequence, and column by transposing a similar sequence
row1 <- seq(1:6)
col1 <- t(seq(1:6))
col1 * row1

Output which indicates that R thinks matrices more like columns
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    4    9   16   25   36

Expected output: NxM matrix.
OS: Debian 8.5
Linux kernel: 4.6 backports
Hardware: Asus Zenbook UX303UA

A:

In this case using outer would be a more natural choice
outer(1:6, 1:6)

In general for two numerical vectors x and y, the matrix rank-1 operation can be computed as
outer(x, y)

If you want to resort to real matrix multiplication routines, use tcrossprod:
tcrossprod(x, y)

If either of your x and y is a matrix with dimension, use as.numeric to cast it as a vector first.
It is not recommended to use general matrix multiplication operation "%*%" for this. But if you want, make sure you get comformable dimension: x is a one-column matrix and y is a one-row matrix, so x %*% y.

Can you say anything about efficiency?

Matrix rank-1 operation is known to be memory-bound. So make sure we use gc() for garbage collection to tell R to release memory from heap after every replicate (otherwise your system will stall):
x <- runif(500)
y <- runif(500)
xx <- matrix(x, ncol = 1)
yy <- matrix(y, nrow = 1)

system.time(replicate(200, {outer(x,y); gc();}))
#   user  system elapsed
#  4.484   0.324   4.837

system.time(replicate(200, {tcrossprod(x,y); gc();}))
#   user  system elapsed
#  4.320   0.324   4.653

system.time(replicate(200, {xx %*% yy; gc();}))
#   user  system elapsed
#  4.372   0.324   4.708

In terms of performance, they are all very alike.

Follow-up
When I came back I saw another answer with a different benchmark. Well, the thing is, it depends on the problem size. If you just try a small example you can not eliminate function interpretation / calling overhead for all three functions. If you do
x <- y <- runif(500)
microbenchmark(tcrossprod(x,y), x %*% t(y), outer(x,y), times = 200)

you will see roughly identical performance again.
#Unit: milliseconds
#             expr     min      lq     mean  median      uq      max neval cld
# tcrossprod(x, y) 2.09644 2.42466 3.402483 2.60424 3.94238 35.52176   200   a
#       x %*% t(y) 2.22520 2.55678 3.707261 2.66722 4.05046 37.11660   200   a
#      outer(x, y) 2.08496 2.55424 3.695660 2.69512 4.08938 35.41044   200   a


Q:

How to extract Route Params via Props

I am learning VueJs and trying to understand how to extract route params via props.
I was looking at the following documentation, where it seems to have three options to have this done, but I cannot understand it quite well so far - https://github.com/vuejs/vue-router/tree/dev/examples/route-props.
I have tried adding props: true to my router object array (routes.js file posted below) with no success as well.
As this is vue-cli study project I will post the separate pertinent blocks of code in order to try to illustrate this properly.
Main - App.vue below:
 <template>

Routing

                <app-header></app-header>
                <router-view></router-view>

</template>

Component - Header.vue below:
<template>

        <router-link to="/" tag="li" active-class="active" exact>Home</router-link>
        <router-link to="/user/10" tag="li" active-class="active">User 1</router-link>
        <router-link to="/user/5" tag="li" active-class="active">User 2</router-link>

</template>

Component - User.vue below:
<template>

The User Page

Route ID: {{id}}

        <button class="btn btn-primary" @click="goHome">Go to Home</button>

</template>

main.js below:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import {routes} from "./routes";

Vue.use(VueRouter)

export const router = new VueRouter({
  routes,
  mode: 'history'
})

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

routes.js below (located at SRC folder):
import User from './components/user/User.vue'
import Home from './components/Home.vue'

export const routes = [
    {path: '', component: Home},
    {path: '/user/:id', component: User}
]

Do I need to also set Props at User.vue component as well in order to make it work and quit using watch?
In other words, I would like to see my user route being listened at
Route ID: {{id}}
 from this hardcoded 10 to 5 using this new method which I cannot understand, mentioned at the top of this post.
Could anyone please walk me through this issue in this specific situation?
Thanks in advance to all.

A:

According to the docs on passing Props to Route components, you can decouple it, with the props option on the router config.
import User from './components/user/User.vue'
import Home from './components/Home.vue'

export const routes = [
    {path: '', component: Home},
    {path: '/user/:id', component: User, props: true}
]

<template>

The User Page

Route ID: {{id}}

    <button class="btn btn-primary" @click="goHome">Go to Home</button>

</template>


Q:

Perl installation on Debian vs CentOS with Makefile.PL error

I am trying to figure out how to install the proper Debian packages for Perl. I am getting a make error of:
Failed to read the configuration: Bad file descriptor at Makefile.PL line 8.

My Makefile.PL file contain the following line up to line 9:
use 5.008000;
use ExtUtils::MakeMaker;

# Read the parameters from Triceps Makefiles
delete $ENV{MAKEFLAGS}; # these cause spurious messages from make
delete $ENV{MAKELEVEL};
my $TRICEPS_CONF = `make --quiet -f ../../cpp/Makefile.inc getconf`;
die "Failed to read the configuration: $!" if ($! != 0);

As described here at http://www.directadmin.com/forum/showthread.php?t=43558&page=1 I am trying to find the equivalent apt-get install commands for the current version of Debian for:
yum install cpan
yum install perl-ExtUtils-CBuilder perl-ExtUtils-MakeMaker
cpan install ExtUtils::Install

I am trying to find the equivelant Debian solution but unsure which packages to download or install. What would be the exact apt-get install commands needed to properly make this within Debain?
These Perl packages don't appear in Debian as you would expect Thanks

A:

You're using $! before checking if it contains something useful. Here's what the code should be:
die("Failed to read the configuration: " . (
   $? < 0    ? "Unable to launch: $!" :
   $? & 0x7F ? "Signal ".($? & 0x7F) :
   $? >> 8   ? "Exit ".($? >> 8) :
   "Unknown error"
)) if $?;


Q:

What should we consider when Anumana contradicts Shabda?

According to Vedantic pramana system
Anumana is Inferential knowledge and
Shabda is Scriptural/Testimonial knowledge.
So when these two contradict each other which one should we consider as true?
If you can site sources it will be very helpful

A:

Śabda needs to be rejected when it doesn't sit well with Anumāna.
From Yoga-Vāsiṣṭha:

api pauruṣamādeyaṃ śāstraṃ cedyuktibodhakam |
anyattvārṣamapi tyājyaṃ bhāvyaṃ nyāyyaikasevinā || 2.18.2 ||
Even human compositions are acceptable when they are instructive of good sense; otherwise the Vedas also are to be renounced (as unreliable); because men are required always to abide by reason.

yuktiyuktamupādeyaṃ vacanaṃ bālakādapi |
anyattṛṇamiva tyājyamapyuktaṃ padmajanmanā || 2.18.3 ||
Words conformable with reason are to be received even if spoken by boys; otherwise they are to be rejected as straws though pronounced by the lotus-born (Brahma himself).

yo'smattātasya kūpo'yamiti kaupaṃ pibatyapaḥ |
tyaktvā gāṅgaṃ purasthaṃ taṃ ko nāśāstyatirāgiṇam || 2.18.4 ||
Whoever drinks from a well by reason of its being dug by his ancestors, and rejects the holy water of the Ganges even when placed before him, is an incorrigible simpleton.

A:

From a Dvaita perspective:
Pratyaksha as verified by "sakshi", the indwelling self, is not an erroneous experience. This is not to negate the erroneous experiences at all.
As far as Anumana is concerned, as its name implies, it is anu-mana, secondary to and based on pratyaksha.
As far as the Paramatma or Brahman is concerned, only source of knowledge is Sabda. Neither pratyaksha, nor anumana can help here. (Pratyaksha negatees and Anumaana can go both ways.)
And,this Sabda should be a non-dushta source and it should be so always- not only here in this so called phenomenal world but even in Mukthi, because if it can be negated, or if it is also in the realm of mithya, what it says may carry no value, and as a source, it is useless.
The dvaita system of Shri Madhvacharya accepts the Vedas as Nitya  precisely for this reason.
An additional concept accepted by others too is the Veda-apaureshayatva. If the Vedas are the source of Brahmajnana and if the Source of the vedas is the Brahman, it becomes anyonyaashraya.
Another axiomatic concept is the svatahpraamaanya of the Vedas.
Now coming to your question:
When inference contradicts Sabda-
a. Suppose Sabda tells 'fire is cold', Sabda cannot be valid. So, is Sabda wrong? Sabda needs to be reinterpreted according to rules of grammar and rules of interpretation without contradicting pratyaksha or anumaana -a process called samanvaya. Thus, for a dvaitin, the whole vedas are pramana, even the so called karma kaanda portions (which classification it does not accept as there is no internal evidence for the same)
b. when the Sabda-contradicting inference is wrt Brahman, Shruti and those sadaagamas aligned with it alone are valid proof.

सदागमैकविज्ञेयं समतीतक्षराक्षरं  नारायणं सदा वन्दे निर्दोषाशेषसद्गुणम्
  ||(Shriman Madhvacharya in Vishnutattvanirnaya).

The supreme is knowable only through sadaagamas.
So as far as the existence of the Brahman, Mukti etc are concerned, only Scripture is valid.


Q:

PHP Show links a user haven't clicked

Hey guys I am trying to code this link exchange site where users click other users links to get clicks of their own. What I am trying to accomplish is display a list of links that the user have not clicked and I am stuck!
I managed to display the links but I don't know how to show only the ones they have not clicked.
Every time they click a link their username, the link id and the link name goes into the database.
Help me!

A:

Assuming you are using MYSQL you need to select all links regardless if they have been clicked or not
   SELECT links.id, links.link FROM links WHERE links.id NOT IN (SELECT id FROM clickedLinks);


Q:

How to get current system date and time without am/pm Designators using c#

I set my system region settings to "spanish", So I'm getting the time format like: 20/02/2016 02:39:40 a.m.  ;I have stored this value in datetime variable and passed to sql database table. I set my database default language also to "spanish", at the time of inserting datetime varaible..getting exception

conversion failed when converting date and/or time from character
  string

due to having "." (preiod) in a.m./p.m. I am getting this exception. I searched a lot on this issue, every where converting the datetime varaible to string format.But I should pass this as a datetime variable only.
So please let me know how to get current system datetime without am/pm or without having "." in am/pm
 //Here is my code:

    DomainSchema.DOMAINRow drDomain = domain_dataset.DOMAIN.NewDOMAINRow();
    //Assigning the values to the DataRow of the table Domain
       drDomain.CREATED_DATE = DateTime.Now;
       drDomain.LAST_UPDT_DATE = DateTime.Now;
       domain_dataset.DOMAIN.AddDOMAINRow(drDomain);
     CultureInfo i;

  i = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
                if (i.Name == "es-PE")
                {
                   CultureInfo c = CultureInfo.CreateSpecificCulture("es-ES");
         String s = DateTime.Now.ToString(c); //getting s="20/02/2016 08:07:54"
   DateTime d = DateTime.Parse(s, c, System.Globalization.DateTimeStyles.AssumeLocal); //geting d="20/02/2016 08:07:54 a.m."
}

    //method that uses this dataset

    public override string Create(DataSet ds, string tableName, IDbTransaction transaction, IPrincipal user)
            {
                DataRow dRow = null;
                CommandStatement cmdStatemnt;
                string strResult = string.Empty;
                try
                {
                  dRow = ds.Tables[tableName].Rows[0];
            cmdStatemnt = Execute(dRow, tableName, transaction, true, null, user);
                   //Here I'm getting exception,conversion failed when converting date and/or time from character string,due to having "." in "a.m."
                }

        }

thanks in advance.

A:

When passing date/time to databases I always use this
Datetime d = DateTime.Today;

String s = d.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// output   "02/20/2016 12:00:00 AM"

String s = d.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
// output   "02/20/2016 00:00:00"

Using capitals HH gives 24-hour format

Here you can find a lot more regarding date time formatting

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

Update based on comments
In the situation described, you should be able to do something like this.
CultureInfo c = CultureInfo.CreateSpecificCulture("es-ES");
String s = DateTime.Now.ToString(c);
DateTime d = DateTime.Parse(s, c, System.Globalization.DateTimeStyles.AssumeLocal);

2nd update based on comments
2 more ways could be:

Toggle the culture when running the database transaction
// Switch Current Culture
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

// run database code

// Switch Back To Origin Current Culture
Thread.CurrentThread.CurrentCulture = new CultureInfo("es-ES");

Change your dataset object and have the CREATED_DATE typed as string instead of datetime
After all, when you execute a SQL query, datetime's are treated as string (quoted) in the query, even if the field they are stored in is of datetime type.


Q:

What's the best practice to update a specific db-table-row-column simultaneously?

A row column in db(If the row does not exists, it should be created first.) can be updated by multiple users simultaneously, what's the best practise to update the row efficiently and correctly?
The Model
@Entity(table = "counters")
public class Counter {

    @Id
    public Long id;

    /**
     * <b>count</b> and can be updated by users simultaneously and frequently. count is
     * very important, every updates should be success without lost updates.
     */
    public int  count;
}

possible solutions:
1) Use synchronized keywords
public static synchronized void createOrUpdateCount(int counterId, int increments) {
    Counter counter = Counter.findById(counterId);
    if(counter == null) {
        counter = new Counter();
        counter.count = increments;
    } else {
        counter.count += increments;
    }
    counter.saveToDb();
}

2) Use optimistic locking and retry updating if there is a optimistic exception
public static createOrUpdateCount(int counterId, int increments) {
    try {
        doCreateOrUpdateCount(counterId, increments);
    } catch (OptimisticLockException e) {
        // retry updating on optimistic exception, maybe several times will be
        // tried until updating succeed.
        doCreateOrUpdateCount(counterId, increments);
    }
}

private static void doCreateOrUpdateCount(int counterId, int increments) {
    Counter counter = Counter.findById(counterId);
    if(counter == null) {
        counter = new Counter();
        counter.count = increments;
    } else {
        counter.count += increments;
    }
    counter.saveToDb();
}

3) Set Transation isolation level to Serializable.
@Transactional(isolation = TxIsolation.SERIALIZABLE)
public static void createOrUpdateCount(int counterId, int increments) {
    Counter counter = Counter.findById(counterId);
    if(counter == null) {
        counter = new Counter();
        counter.count = increments;
    } else {
        counter.count += increments;
    }
    counter.saveToDb();
}

What's your best practise? Any suggestion will be appreciated.

A:

In my opinion you need to look at the specific database you are using. Most have some type of 'upsert' statement which can perform an insert or update as a single sql statement. You need to then check the database specific documentation regarding that and specifically you are checking to see if you can improve on that by writing a stored procedure to do it (and explicitly choosing to do the most common thing first such as update then insert versus insert then update).
It is very likely that doing this at the ORM level will be no where near as good when compared to using a stored procedure or db specific 'upsert' or 'merge' statement.


Q:

Representing and rounding currency in python pandas

Working with currency data in Python Pandas/Numpy, I am experiencing "unexpected" rounding behavior due to the float representation of decimals. For example
import numpy as np
np.round(19.95 * 0.9, 2)
17.949999999999999

Calculating in decimals as I learned in school, the result is 17.955 so I would expect rounding to 17.96.
How can I represent numbers in Python Pandas to achieve "decimal style" rounding? I have seen the Decimal module and the currency package, but I'm not sure how to efficiently use them with Pandas data frames.
SOLUTION:
In case anybody else is interested, this is how I solved the problem:
from decimal import Decimal
import pandas as pd

def float2dec(value):
    "Convert `value` to Decimal cents."
    return Decimal(value).quantize(Decimal('0.01'))

df = pd.DataFrame({'price': [1.90, 1.95, 19.95]})

df['price_reduced'] = (df['price'].map(float2dec) * float2dec(0.9)).map(float2dec)

#    price      price_reduced
#0  1.90        1.71
#1  1.95        1.76
#2  19.95       17.96

Also, I ended up using the cdecimal implementation, which uses the same syntax but is some 10x faster.

A:

You can use the Decimal type in pandas dataframes. Everything should work as expected since the Decimal type implements it's own versions of addition and multiplication, which pandas will happily use behind the scenes for sum, cumsum, etc.
It won't be as fast as floating points, but using precise decimal representations is never as fast as using floating points.
I wouldn't worry about efficiency unless you actually run into performance problems in your program.
http://rhodesmill.org/brandon/2014/pandas-payroll/


Q:

OR clasue in a query using bookshelf

I want the users with stateOne or stateTwo, how can I do this using bookshelf?
This is what I got
User.where({id: req.user, state: 'stateOne'}).fetchAll().then((result) => {
        return res.json(result);
    }).catch(err => {
        console.log(err);
    });

A:

I am unsure if the below will work but it uses the orWhere operation.
User.query({
    where: {id: req.user, state: 'stateOne'},
    orWhere: {id: req.user, state: 'stateTwo'}
})
    .fetchAll()
    .then((result) => {
        return res.json(result);
    }).catch(err => {
        console.log(err);
    });

Here is a link to the documentation for reference


Q:

Notice: Object of class mysqli_result could not be converted to int and Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean

the code is for inserting user data in database
getting error on
$run = mysqli_query($con,$check_email);

Notice: Object of class mysqli_result could not be converted to int

and

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean

    <?php
    $con = mysqli_connect("localhost","root","","users_db");
    if (mysqli_connect_errno())
    {
    echo 'connection was not established'. mysqli_connect_error();
    }

        if(isset($_POST['submit'])){
             $user_name = $_POST['name'];
             $user_pass = $_POST['pass'];
             $user_email = $_POST['email'];

             if($user_name==''){
                 echo "<script>alert('please Enter your Nmae!')</script>";
                 exit();
             }
             if($user_pass==''){
                 echo "<script>alert('please Enter your password!')</script>";
                 exit();
             }
             if($user_email==''){
                 echo "<script>alert('please Enter your Email!')</script>";
                 exit();
             }

                 $check_email = "select * from users where user_email='$user_email'";

                $run = mysqli_query($con,$check_email);
                if(mysqli_num_rows($run>0)){
                    echo "<script>alert('Email $user_email is already exist in database please try another one')</script>";
                    exit();
                }
                $query = "insert into users(user_name,user_pass,user_email) values ('$user_name','$user_pass','$user_email')";
                if(mysqli_query($con,$query)){

                    echo "<script>alert('Registration completed')</script>";
                }
                else{
                    echo"<script>alert('Data not inserted')</script>";
                }

             }
    ?>

A:

Syntax is wrong
if(mysqli_num_rows($run>0)){

this should be
if(mysqli_num_rows($run) > 0){
                          ^ should be moved

This should fix both the errors.


Q:

What is AVHWAccel, and how can I use it?

I want to make use of hardware acceleration for decoding an h264 encoded MP4 file.
My computing environment:
Hardware: MacPro (2015 model)
Software: FFmpeg (installed by brew)

Here is the output of FFmpeg command:
$ffmpeg -hwaccels
Hardware acceleration methods:
vda
videotoolbox

According to this document, there are two options for my environment, that is, VDA and VideoToolBox. I tried VDA in C++:
Codec = avcodec_find_decoder_by_name("h264_vda");

It kind of worked, but the output of the pixel format is UYVY422 which I have trouble to deal with (any suggestion on how to render UYVY422 in C++? The ideal format is yuv420p)
So I want to try VideotoolBox, but there is no such simple thing like (it may work in the case of encoding though)
Codec = avcodec_find_decoder_by_name("h264_videotoolbox");

It seems I should use AVHWAccel, but what is AVHWAccel and how to use it?
Part of My C++ code:
for( unsigned int i = 0; i < pFormatCtx->nb_streams; i++ ){
        if(pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){
            pCodecCtx = pFormatCtx->streams[i]->codec;
            video_stream = pFormatCtx->streams[i];
            if( pCodecCtx->codec_id == AV_CODEC_ID_H264 ){
                //pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
                pCodec = avcodec_find_decoder_by_name("h264_vda");
                break;
            }
        }
    }
    // open codec
    if( pCodec ){
        if((ret=avcodec_open2(pCodecCtx, pCodec, NULL)) < 0) {
        ....

A:

It's nothing to do with the decoder for which pix format to choose.
Your video pix format is UYVY422, so you got this format after you decode the frame.
Like the answer @halfelf mentioned, you can perform a swscale after you decode a frame, to convert the pix format to your ideal format yuv420p, then render it.
Meanwhile, if you are sure it's the format UYVY422, SDL2 can handle the render directly for you.
In the example below, my format is yuv420p, and I use swscale to convert to UYVY422 to render to SDL2
// prepare swscale context, AV_PIX_FMT_UYVY422 is my destination pix format
SwsContext *swsCtx = sws_getContext(codecCtx->width, codecCtx->height, codecCtx->pix_fmt,
                                    codecCtx->width, codecCtx->height, AV_PIX_FMT_UYVY422,
                                    SWS_FAST_BILINEAR, NULL, NULL, NULL);

SDL_Init(SDL_INIT_EVERYTHING);

SDL_Window *window;
SDL_Renderer *render;
SDL_Texture *texture;

SDL_CreateWindowAndRenderer(codecCtx->width,
                            codecCtx->height, SDL_WINDOW_OPENGL, &window, &render);

texture = SDL_CreateTexture(render, SDL_PIXELFORMAT_UYVY, SDL_TEXTUREACCESS_STREAMING,
                            codecCtx->width, codecCtx->height);

// ......
// decode the frame
// ......
AVFrame *frameUYVY = av_frame_alloc();
av_image_alloc(frameUYVY->data, frameUYVY->linesize, codecCtx->width, codecCtx->height, AV_PIX_FMT_UYVY422, 32);

SDL_LockTexture(texture, NULL, (void **)frameUYVY->data, frameUYVY->linesize);

// convert the decoded frame to destination frameUYVY (yuv420p -> uyvy422)
sws_scale(swsCtx, frame->data, frame->linesize, 0, frame->height,
                      frameUYVY->data, frameUYVY->linesize);

SDL_UnlockTexture(texture);

// performa render
SDL_RenderClear(render);
SDL_RenderCopy(render, texture, NULL, NULL);
SDL_RenderPresent(render);

In your example, if your pix format is uyvy422, you can skip the swscale part, and perform the render directly after decode from ffmpeg.


Q:

How to fix java warning for "The value of the local variable is not used "

How to avoid java warning which says

The value of the  local variable is not used

for the variable which is declared as private?

A:

You have multiple choices:

Remove the field.
It is unused, so it shouldn't be there.
Comment out the field, e.g. using // TODO
Good for temporary hiding of warning until you write code using field.
Suppress the warning using @SuppressWarnings("unused").
Disable the warning in IDE settings. For Eclipse, that would be in

Window > Preferences
Java > Compiler > Error/Warnings
Unnecessary code > Unused private member
Select option Ignore

For #3 and #4, though, although you can, why would you want to?


Q:

php операторы, проблемка

Привет, столкнулся с проблемой, у меня сделано чтоб нельзя было отправлять форму где money < 1 и >1, надо сделать так что бы можно было отправлять форму только с целыми числами, т.е 0.1 и 0.1.0 и т.д нельзя было, прилагаю код моего запрета на <1 и >1, заранее спасибо!     if($number > 3 || $money < 1 || $money > 1) return response()->json(['msg' => 'Nice try bro :(', 'status' => 'error']);

A:

Запись
$money < 1 || $money > 1

эквивалента
$money != 1


Q:

VBA Type mismatch in Find method

I'm trying to create a function that will input "Yes" in the 11th column in every row if there's a word "Market" in a row. But i get the error mismatch.
Option Explicit

Sub findMarketing()
    Dim r As Range

    For Each rw In Worksheets("Sheet1").Rows
    Set r = rw.Range("A:G")

        If r.Find(What:="market") Then
            rw.Columns(11).Value = "Yes"
        Else
              rw.Columns(11).Value = "No"
        End If
    Next rw
End Sub

A:

You have an answer from the comments (thanks Ron Rosenfeld) but you also do not want to go through 1,048,576 rows. Use the Intersect function to operate on columns A:G on any particular row and limit the rows to the worksheet's .UsedRange so you are only examining the rows that actually have data in them.
I've changed your method of locating 'Market' in columns A:G because you are not specifying enough parameters. The .Find function relies a lot on what was used last. If the user used Find or Replace on the worksheet and changed the Match Case, Match entire contents, etc then that is what you are going to be operating under. I'll assume that you want a non-case-sensitive, full cell value match. [edit] Apparently a wildcard partial match is required.
Option Explicit

Sub findMarketing()
    Dim r As Range, rw As Range

    With Worksheets("Sheet1")
        For Each rw In .UsedRange.Rows
            Set r = Intersect(rw, .Range("A:G"))

            If IsError(Application.Match("*market*", r.Cells, 0)) Then
                .Cells(rw.Row, "K") = "No"
            Else
                .Cells(rw.Row, "K") = "Yes"
            End If
        Next rw
    End With
End Sub


Q:

How do I clear text from the  element?

I have put text on an image in a <canvas> tag (the text was taken from an input box).
Now if I put a new text on the <canvas>, it is imposed on the previous text. How do I clear the existing text on the canvas before putting in the new text?
I have tried resetting the canvas by assigning canvas.width but the text stays on. Any help people?

A:

If you know you're going to be adding and removing text a lot, it might make sense to keep track of the old text. Then you could just use this:
context.fillStyle = '#ffffff'; // or whatever color the background is.
context.fillText(oldText, xCoordinate, yCoordinate);
context.fillStyle = '#000000'; // or whatever color the text should be.
context.fillText(newText, xCoordinate, yCoordinate);

This way you don't have to redraw the whole canvas every time.

A:

You use context.clearRect(), but first you have to figure out the rectangle to clear. This is based off a number of factors, such as the size of the text and the textAlign property of the canvas context when the text was originally drawn. The code below would be for the draw method of a object that draws text into a canvas context, as such it has properties for x, y, text size, horizontal alignment etc. Note that we always store the last piece of text drawn so we can clear an appropriately sized rectangle when the value is next changed.
this.draw = function() {
  var metrics = this.ctx.measureText(this.lastValue),
      rect = {
        x: 0,
        y: this.y - this.textSize / 2,
        width: metrics.width,
        height: this.textSize,
      };

  switch(this.hAlign) {
    case 'center':
      rect.x = this.x - metrics.width / 2;
      break;
    case 'left':
      rect.x = this.x;
      break;
    case 'right':
      rect.x = this.x - metrics.width;
      break;
  }

  this.ctx.clearRect(rect.x, rect.y, rect.width, rect.height);

  this.ctx.font = this.weight + ' ' + this.textSize + ' ' + this.font;
  this.ctx.textAlign = this.hAlign;
  this.ctx.fillText(this.value, this.x, this.y);
  this.lastValue = this.value;
}

A:

You need to use clearRect(x, y, w, h); More details at MDC


Q:

Making .NET configuration environment-neutral

I want to get some thoughts on best practices around making .NET app configuration environment-neutral.
Background. Some background first. I come from the Java world, not the .NET world, and in Java there are certain things that we can do to build packages that are environment-neutral. They are generally based on abstracting the configuration in some fashion. Here are a few examples:

JNDI allows apps to reference enterprise resources (e.g., databases, JavaMail sessions, JCR repositories, etc.) by name, and then the name is mapped to a specific configuration according to the environment (dev, test, prod).
Another example would be properties files. You might have a bunch of properties (e.g., "encryption_key", "smtp.server.url", "admin.email", etc.) that the app grabs from a properties file in a known location when the app starts up. The property keys are mapped to different values depending again on the environment.
Some app development frameworks (like Spring) know how to pull properties files in so the properties can be integrated with the framework configuration.

Another approach I've seen in Java is a build-time approach, where you use Ant (token substitution) or Maven (build profiles) to build environment-specific packages. I don't like this approach quite as much just because I strongly prefer to deploy exactly the same package to test and prod. But it's an approach I've seen.
Desired solution. I'm assuming that in .NET there are some comparable strategies for decoupling a configuration (and by extension the containing package) from its environment.
Ideally I'd like a solution that allows me to keep non-environmental configuration closely associated with the app, externalizing only the environmental stuff. To go back to the Java examples, a lot of times the "configuration" is really something that the developers control, such as including a Sitemesh servlet filter for page decorations, dependency injection or app wiring, mapping such-and-such MVC controller method to a request URI, etc. That stuff I don't want to be externalized. But encryption keys, DB connection strings, log levels and so forth, yes.

A:

.NET executables and web applications by default implement .config files which do exactly what you describe.  There's an entire namespace, System.Configuration, that deals with .config files.
Go look for reference material on App.config and Web.config.  App.config is a generic term for an executable's default config file, which is named foo.exe.config, where foo.exe is the name of the executable.  Web.config applies to web applications.
This seems to be a decent primer on App.config.


Q:

How to set iPhone tab bar icon in code?

I am using the same ViewController for several different views.
When instantiating the ViewController for a specific view, is there an easy way to specify the tab bar icon via code?

A:

yourViewController.tabBarItem = [[UITabBarItem alloc]
initWithTitle:NSLocalizedString(@"Name", @"Name")
image:[UIImage imageNamed:@"tab_ yourViewController.png"]
tag:3];

The viewControllers are added to the tab bar, so the image and names should be set before the tab bar becomes visible (appDelegate if they are there on app start for instance). After that, you could use the above code to change the icon and text from the loadView or viewDidAppear within that viewController.


Q:

What is a complete list of Exceptions that can be thrown by shutil.rmtree

I am using the rmtree method from shutil in Python (2.7).
What are all possible exceptions that can occur while calling this method?

A:

According to the implementation, you'll have to check OSError.
But you can use the argument ignore_errors=True on call to...ignore errors ;) or give a callback onerror that will check the exceptions during the execution of file removal. (cf shutil.rmtree documentation)

A:

Unless you do something very funky, os.error and OSError


Q:

Any way to change names for auto-created views by kotlin-extensions?

I'm new in Kotlin. I've red https://kotlinlang.org/docs/tutorials/android-plugin.html and noticed that views can be auto-binded to activity via importing
kotlinx.android.synthetic.main.activity_main.*.
If I declaring view with id = "btn_login" in Activity I can access to it via
activity.btn_login.setText("Login")

But. Is there any way to change alias to view, such as ButterKnife does :
@BindView(<id of view>)
<name of view>

A:

It's a synthetic import, so technically you can use an import alias to call it by another name:
import kotlinx.android.synthetic.main.activity_main.view.btn_login as btnLogin

But considering there is no tool that does this automatically, you might want to just embrace a different ID naming scheme.
Here's a reasonable one:

What-Where-Description-Modifier:
recyclerSearchSuggestions - RecyclerView showing search suggestions
fabSearchGo - FloatingActionButton that executes a search
textSearchFilterChip - TextView that represents search filters, styled as a material chip
buttonSearchClearFilter - Button that clears selected filter chips
editSearchFilter - EditText used to narrow down search suggestions


Q:

C++ explicit char/short?

I'd like to pass a char to my function (fn). I DO NOT want ints and shorts to be typecast into it. So i figure i should have the value be implicitly cast into MyInt (which will only support char) then pass into fn. This should work bc IIRC only one typcast is allowed when passing onto function (so char->MyInt is ok while int->char->MyInt shouldn't).
However it appears both int and char work so i figure another layer of indirection (MyInt2) would fix it. Now they both can not be passed into fn... Is there a way where i can have chars passed in but not int?
#include <cstdio>
struct MyInt2{
    int v;
    MyInt2(char vv){v=vv;}
    MyInt2(){}
};
struct MyInt{
    MyInt2 v;
    MyInt(MyInt2 vv){v=vv;}
};
void fn(MyInt a){
    printf("%d", a.v);
}
int main() {
    fn(1);       //should cause error
    fn((char)2); //should NOT cause error
}

A:

Function templates to the rescue:
template<typename T> void fn(T t);

void fn (char a){
    printf("%c", a);
}

If someone attempts to call fn with anything other than a char argument the function template will be chosen as a match and the linker will complain that it cannot find the appropriate specialization.

A:

You can use polymorphism and define several versions one accepting int and one short and throw exceptions or cause assertion failures, or hide the constructor:
struct MyInt2{
    int v;
    MyInt2(char vv){v=vv;}
    MyInt2(short s) { throw "short"; } /* exception, runtime error */
    MyInt2(){}
    private:
    MyInt2(int v) { } /* hidden, compile time error */
};

A:

You want char to implicitly convert into MyInt2 which then to MyInt. But two level of conversion is not allowed by the language specification.
If you want to do it for one-level of implicit conversion, then C++11 can help you.
In C++11, you can delete constructor taking int, allow the one which takes char as:
struct MyInt{
    int v;

    MyInt(char vv) : v(vv) {} //use mem-initialization list

    MyInt(int) = delete;  //VALID only in C++11
};

Notice the deleted constructor which takes int, it means this:
MyInt m1(10); //error - can't accept int!

MyInt m2((char)10); //okay - can accept char!

See Online Demo
In fact, you can delete ALL constructors except one which takes char as:
struct MyInt{
    //..
    MyInt(char vv); //ALLOW

    template<typename T>
    MyInt(T) = delete;  //DELETED the rest!
};

Demo
Learn more about :

Explicitly deleted special member functions

Hope that helps.


Q:

The rails params are not symbolized

def log_experiments
     => 23:   binding.pry
        24:   logger.debug "Experiment: 'navigation_location': '#{navigation_location_experiment}'"
        25: end

[1] pry(#<MainController>)> params
=> {"sub_category1"=>"shoes", "controller"=>"main", "action"=>"index"}
[2] pry(#<MainController>)>

How and where can I check what is wrong here? by default the param keys should be symbolized...

A:

Params use a special type of hash - hash with indifferent access. Elements of such hashes can be accessed both by symbols and string. For printing hash the default form is string.
Look at rails reference -  http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html This is doc for rails 4.0, but the previous versions have the same


Q:

Groovy:XML structure translation

Input XML
<ClientInformation>
<FirstName>Ram</FirstName>
<LastName>Shah</LastName>
<MiddleName></MiddleName>
<DateOfBirth>01/01/1972</DateOfBirth>
<TaxIdentification>12346</TaxIdentification>
<RelationshipToInsuredCT>Spouse</RelationshipToInsuredCT>
<RelationshipToEmployeeCT>Spouse</RelationshipToEmployeeCT>
<RoleTypeCT>Insured</RoleTypeCT>
</ClientInformation>

Output XML
<ContractClientVO>
 <ConstantElement1></ConstantElement1>
 <ConstantElement2></ConstantElement2>
 <RelationshipToInsuredCT>Spouse</RelationshipToInsuredCT>
 <RelationshipToEmployeeCT>Spouse</RelationshipToEmployeeCT>
 <ClientRoleVO>
  <ClientRoleConstantElement1></ClientRoleConstantElement1>
  <RoleTypeCT>Insured</RoleTypeCT>
  <ClientDetailVO>
   <FirstName>Ram</FirstName>
    <LastName>Shah</LastName>
    <MiddleName></MiddleName>
    <DateOfBirth>01/01/1972</DateOfBirth>
    <TaxIdentification>12346</TaxIdentification>
  </ClientDetailVO>
 <ClientRoleVO>
</ContractClientVO>

XML for Mapping Reference
<ClientInformation>
    <ContractClientVO>
     <AssignmentReasonCT></AssignmentReasonCT>
     <Associated></Associated>
     <AuthorizedSignatureCT></AuthorizedSignatureCT>
     <ClassCT></ClassCT>
     <RelationshipToInsuredCT></RelationshipToInsuredCT>
     <RelationshipToEmployeeCT></RelationshipToEmployeeCT>
     <ClientRoleVO>
      <AgentFK></AgentFK>
      <Associated></Associated>
      <RoleTypeCT></RoleTypeCT>
      <ClientDetailVO>
        <address></address>
        <city></city>
        <state></state>
        <Amount></Amount>
        <CountryTypeCT></CountryTypeCT>
        <AmountOfInsurance></AmountOfInsurance>
        <FirstName></FirstName>
        <LastName></LastName>
        <TaxIdentification></TaxIdentification>
     </ClientDetailVO>
   </ClientRoleVO>
  </ContractClientVO>
 </ClientInformation>

So third xml is for reference. It helps to define the structure of output xml.
Is there a out of the box solution from Groovy for this kind of problem? Or I have go by each input xml element and validate it with reference xml.

A:

So, given this xml:
<Clients>
    <ClientInformation>
        <FirstName>Ram</FirstName>
        <LastName>Shah</LastName>
        <MiddleName></MiddleName>
        <DateOfBirth>01/01/1972</DateOfBirth>
        <TaxIdentification>12346</TaxIdentification>
        <RelationshipToInsuredCT>Spouse</RelationshipToInsuredCT>
        <RelationshipToEmployeeCT>Spouse</RelationshipToEmployeeCT>
        <RoleTypeCT>Insured</RoleTypeCT>
    </ClientInformation>
</Clients>

You can use this XSL:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <Output>
            <xsl:for-each select="Clients/ClientInformation">
                <ContractClientVO>
                    <ConstantElement1></ConstantElement1>
                    <ConstantElement2></ConstantElement2>
                    <RelationshipToInsuredCT><xsl:value-of select="RelationshipToInsuredCT"/></RelationshipToInsuredCT>
                    <RelationshipToEmployeeCT><xsl:value-of select="RelationshipToEmployeeCT"/></RelationshipToEmployeeCT>
                    <ClientRoleVO>
                        <ClientRoleConstantElement1></ClientRoleConstantElement1>
                        <RoleTypeCT><xsl:value-of select="RoleTypeCT"/></RoleTypeCT>
                        <ClientDetailVO>
                            <FirstName><xsl:value-of select="FirstName"/></FirstName>
                            <LastName><xsl:value-of select="LastName"/></LastName>
                            <MiddleName><xsl:value-of select="MiddleName"/></MiddleName>
                            <DateOfBirth><xsl:value-of select="DateOfBirth"/></DateOfBirth>
                            <TaxIdentification><xsl:value-of select="TaxIdentification"/></TaxIdentification>
                        </ClientDetailVO>
                    </ClientRoleVO>
                </ContractClientVO>
            </xsl:for-each>
        </Output>
    </xsl:template>
</xsl:stylesheet>

To generate:
<Output>
   <ContractClientVO>
      <ConstantElement1 />
      <ConstantElement2 />
      <RelationshipToInsuredCT>Spouse</RelationshipToInsuredCT>
      <RelationshipToEmployeeCT>Spouse</RelationshipToEmployeeCT>
      <ClientRoleVO>
         <ClientRoleConstantElement1 />
         <RoleTypeCT>Insured</RoleTypeCT>
         <ClientDetailVO>
            <FirstName>Ram</FirstName>
            <LastName>Shah</LastName>
            <MiddleName />
            <DateOfBirth>01/01/1972</DateOfBirth>
            <TaxIdentification>12346</TaxIdentification>
         </ClientDetailVO>
      </ClientRoleVO>
   </ContractClientVO>
</Output>

The groovy to transform the xml would be (assuming the xml is in a String called xml and the xsl is in a String called xsl):
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.stream.StreamSource

def w = new StringWriter()
TransformerFactory.newInstance()
                  .newTransformer( new StreamSource( new StringReader( xsl ) ) )
                  .transform( new StreamSource( new StringReader( xml ) ),
                  new StreamResult( w ) )
println groovy.xml.XmlUtil.serialize( w.toString() )


Q:

Nodejs- capturing business events - http,http outbound

I am trying to capture business events - APIs (http-GET and http outbound- POST,PUT) and I am using appmetrics package but it capures events of http request of page
But it is not capturing all API calls made and posting data
const appmetrics = require('appmetrics');
const monitoring = appmetrics.monitor();
const request    = require('request');
const http = require("http");
const metrics = require('./index.js');

module.exports = http.createServer(function (request, response) {

   response.writeHead(200, {'Content-Type': 'text/plain'});

   response.end('Hello World\n');
}).listen(8083);

request
  .get('https://jsonplaceholder.typicode.com/users')
  .on('response', function(response) {
    console.log(response.statusCode) // 200
    console.log(response.headers['content-type']);
  })

console.log('Server running at http://127.0.0.1:3000/');

appmetrics.enable('http');
appmetrics.enable('request');
monitoring.on('request', function (request) {
        console.log('request', request);
});
monitoring.on('http', function (http) {
        console.log('http', http);
});

Above appmetrics captures only page requests but not all api GET calls from this script

A:

'request' in appmetrics is not actually related to the request module, it means something else.  Add monitoring.on('http-outbound', ...)
to record outgoing http calls and make sure you put it before your call to request.get, e.g.
const appmetrics = require('appmetrics');
const monitoring = appmetrics.monitor();
const request    = require('request');
const http = require("http");
const metrics = require('./index.js');

monitoring.on('http', function (http) {
    console.log('http', http);
});

monitoring.on('http-outbound', function (http) {
    console.log('http-outbound', http);
});

module.exports = http.createServer(function (request, response) {

   response.writeHead(200, {'Content-Type': 'text/plain'});

   response.end('Hello World\n');
}).listen(8083);

request
  .get('https://jsonplaceholder.typicode.com/users')
  .on('response', function(response) {
    console.log(response.statusCode) // 200
    console.log(response.headers['content-type']);
  })

console.log('Server running at http://127.0.0.1:3000/');


Q:

When I need to constructively criticize someone's code, what can I do to "soften the blow" and increase the impact at the same time?

A junior developer was having some issues on a project. As the deadline got closer without any resolution in sight, my manager asked me to help out. I'm a mid-level developer on the team.
After getting the rundown, I saw that there were three main issues:

Major issues in the logic
Lack of knowledge for how to trace back an issue to the root cause
Very obscure naming conventions (this was very problematic due to the nature of the project).

I helped him solve the issues, but b/c of the deadline I had to be very "to the point" and didn't have enough time to discuss the "whys" for everything I was recommending & helping him with. We hit the deadline in time, and now I'd like to go back & do a 1:1 post-mortem "code review", giving him a crash course tutorial on the 3 issues I mentioned above.
I have a good rapport with him, but this code review will literally shred apart the solution he built. I'm worried about this for a few reasons:

He's very soft spoken & seems to take things to heart sometimes.
He has only been with the company for 6 months and it's his first job out of college. I've gotten the impression that he's under a lot of scrutiny from our boss about his performance. Having a harsh code review at this time might be too hard on him (although it should certainly help him improve performance!).
He doesn't seem to take good notes during reviews/trainings, and he also isn't very proactive about asking questions when he gets stuck on tasks. As such, I'm not so sure how much this code review will really "stick" in his brain.

So the bottom line questions are:

I'll obviously make sure to emphasize anything he did right & will speak as kindly as possibly, but what else can I do to soften the blow when I go through the laundry list of the things he did wrong in the code?
Given his personality & lack of note-taking, what are some methods to increase the impact of this training/review? I truly want him to succeed at the company, but having seen his work I don't think he will succeed unless he really makes an effort to learn the best practices & methods that everyone else on the team uses. One code review meeting probably won't do the trick.

One side note - Due to the nature of our work (I'm leaving out details for privacy), there is no option for automated code reviews before pushing the code to "production". This makes it harder to catch the types of issues I described above.
Also, I did read this & this question but the focus of my question is pretty different than either of those.

A:

There's a couple of things that I've found help a lot with the reception of code reviews:
Don't say "you", or variations on it ("your code", etc).
You're not ripping apart "his" code or "his" solution. It's our code, or this solution, and we need to do things to it.
As soon as someone starts talking about "your" code, a lot of people's natural reaction is to become defensive, or even combative - especially if they don't feel very confident to start with. If you avoid implying ownership of the code to the junior developer then they will feel less like they're being attacked. The company owns the code, after all.
Instead use language that makes it clear that the team is working together to improve both the quality of the product, and the skills of the team members.
Use positive language, and avoid being negative as much as possible.
For example, instead of talking about why the naming convention chosen by the junior is bad, talk about the benefits of the convention that you're recommending.
Similarly with logic problems, rather than spending ages talking about how bad the first solution is, quickly touch on the major problems but spend the majority of the time explaining a better way to do it, and the benefits that come with the second way.

A:

I have been in such a situation a lot of times. And the first thing I usually say is: sorry....
Yes, right... because if he did not get easiest things right, like naming conventions, that means that you (or whoever was responsible for him) did not make a good job in introducing them to him...
So apologize for not having given him enough information to do a good job. Even if this is only partly true, this will make him feel understood and he will see, that you don‘t want to blame him for something he did wrong, but to improve together as a team as a learning process for both of you.
When you then go through the code, the most important thing is to make him understand his logical flaws instead of telling him what's wrong.
I personally use something quite like „rubber duck debugging“ in that case: make him explain what his code is meant to do.
Now there are two possibilities:
First: If his understanding of the task is right, but the code is wrong, then go deeper into the code review.
Try to make him realize - by asking him questions about „what will the code do, if....“- what is wrong with the code and make him try to fix it himself. The same with the variables: ask him which names he would give them now, after you taught him the right naming conventions.
Second: If his understanding of what was recommended is already false, then explain him what the task really was about and let him explain how he would implement that.
That way you don’t destroy his solution, but make him improve it himself. And even if after that time the new code is 100% different from what he had first, this new code is still „his“ code.
TL;DR: take the responsibility for the quality of the code by apologizing for not having told him enough what to do / what to expect, and then let him correct his code himself.
In other words (very famous quote):

Tell me and I forget,
  teach me and I remember,
  involve me and I learn

A:

First of all, don't insist on a particular way of taking feedback and learning from it.
In particular, not taking notes on paper is not necessarily a sign that the junior does not get anything/enough out of the code review. For most "programming style" code reviews I've never taken paper notes, because I rather focus on talking about the code and thinking about the "rules" and their benefits during that time where I have someone to discuss this right next to me than being busy writing stuff down. And I have the "notes" anyway - in the code repository! (At least I should have!).
Focussing on the actual issue helps me a lot more than writing stuff down and then tossing the piece of paper on a heap of other notes never to look at again. If being forced to appear taking notes, all I'd take from the meeting is that I'd not like to work with that senior because he's all about having everything his way.
So: yes, please suggest options, e.g. by asking whether the junior needs his notebook, but don't impose your way to learn on them. Rather, as far as possible, make sure the junior has the relevant information available afterwards anyway - e.g. by having the naming conventions written down somewhere in a wiki for everyone to look up and by committing necessary changes identified in the review - or at least some examples - into a review branch.
If you provide code reviews only orally at the moment, explaining the Junior what he did wrong in a conversation, I'd strongly suggest to either directly make sure to commit changes you suggest in the respective code or make the junior do the changes and then re-check the code. In the latter case, keep the amount of rework small per session and rather do multiple sessions. If you already did the changes point them out in the code repository, such that the Junior can remember the places rather than random examples not connected to your daily work.
Show him he's not alone, go public
As for how to make the code review open and not intimidating, I agree with Player One's answer and would add one more suggestion: Don't just have code reviews with him. Make code reviews an official regular part of your process and do them with everyone.
Furthermore, if you feel he is defensive, make (some of) the code reviews with the whole group, but start with some of your more senior colleagues and treat them the exact same way you would treat him: Talk about their code, not them. There is nearly always something worth discussing about even in code from seniors. And if it only is a case of "yeah it's done that way because of a),b) and c), but one could have made it more generic/following principle X by doing Z, but that would have drawback Y". Make sure you use the same tone and neutrality for everyone. This shows the junior that you are not trying to bully him with your stupid rules but that everyone is under the same scrutiny and that it aren't "your" stupid rules, but the team's common rules - preferably based on benefits the team as a whole likes to have. In addition, the junior can also learn from the mistakes (or great design choices) of others. That makes it even less personal for him and gives him opportunity to get in touch with other business logic areas and software principles before having to work on them - thus he may have the necessary time to "digest" them before having to apply / work on them.


Q:

JavaScript move array element to end of array

EDIT - 2 elegant solutions
Two elegant solutions, from Pranav and Bekim. Thanks, both tested and worked perfectly.
One
     for(var x in data)data[x].name == "other" ? data.push( data.splice(x,1)[0] ) : 0;

Two
   var res = data.slice(),
   len = res.length;

    for (var i = 0; i < len; i++) {
        if (res[i].name == 'other') {
            res.push(res.splice(i, 1)[0]);
            i--;
            len--;
        }
    }

JS TOOLS IM USING
Angular 1.5.6, lodash 4.1x
Here is the scenario I have an array of objects sorted alphabetically e.g. sortedData below etc.. However, within that array is also the catch all Other which is obviously sorted alphabetically as well. I want to remove other from the array and then move to the end of array without messing with the current sorted array.
NOTE
My current approach below works but is ugly. Does JS, angular or lodash have something more elegant?
var data = [
    {id:1,name:'apple'},
    {id:2,name:'banana'},
    {id:3,name:'other'},
    {id:4,name:'tomato'},
    {id:5,name:'strawberry'}
];

function move(array, fromIndex, toIndex) {
    array.splice(toIndex, 1, array.splice(fromIndex, 1)[0]);
    return array;
}

var moved = move(
    data,
    _.findIndex(data, ['name', 'other']),
    Object.keys(data).length
);

Ideal Outcome
 var data = [
        {id:1,name:'one'},
        {id:2,name:'two'},
        {id:4,name:'four'},
        {id:5,name:'five'}
        {id:3,name:'other'},
    ]

A:

You do Array.findIndex in pure Javascript (ES6), without using any libs:
data.push(data.splice(data.findIndex(v => v.name == 'other'), 1)[0])

Array.findIndex is new, but most browsers people actually use these days have it. So you can probably use it. (Edge supports it, but not IE).
If you find the [0] ugly, you can use spread to unpack the array (that way it'll also work for more than one item with some changes):
data.push(...data.splice(data.findIndex(v => v.name == 'other'), 1))

A:

A plain (Vanilla) JavaScript will do just fine:
 for(var x in data)data[x].name == "other" ? data.push( data.splice(x,1)[0] ) : 0;

var data = [
    {id:1,name:'apple'},
    {id:2,name:'banana'},
    {id:3,name:'other'},
    {id:4,name:'tomato'},
    {id:5,name:'strawberry'}
];

for(var x in data)data[x].name == "other" ? data.push( data.splice(x,1)[0] ) : 0;

console.log( JSON.stringify(data))


Q:

Getting the selector of $this

I basically am trying to copy my selector and create a new one.. this is what im trying to achieve...
I have many inputs in divone and dont want to list out each one in my jquery, so i would like to dynamically find the object and link to the corresponding divtwo object

<input type="textbox" id="tb1" value="TEXTHERE">
<input type="textbox" id="tb2" value="TEXTHERE">

<input type="textbox" id="tb3" value="TEXTHERE">
<input type="textbox" id="tb4" value="TEXTHERE">

$("#divOne:input").bind("keyup change", function(e) {
            var selector = ($(this).selector()); //hoping this would return input object from DivOne
            var value = ($(this).val());
            var newselector = //modify divOne object to have divTwo selector
            $(newselector).val() = value;

        });

Then I'd like to to save divOne text into the divTwo textbox.
I want it to look like this, only using this.  So lets say i change textbox value of tb1 to "textthere":
$("#divOne:input").bind("keyup change", function(e) {
                    var selector = $(#divOne.attr("id", tb1"));  //this should be covered dynamically using $this or another jquery method
                    var newselector = $(#divTwo.attr("id", tb3)); //this however should be generated dynamically by selector var
                    $(newselector).val() = selector.val();

                });

Thanks

A:

If you want to match corresponding elements you can use index() and eq()
var $d1Inputs = $("#divOne input").on("keyup",function(e) {
     var index = $d1Inputs.index(this);
     $('#divTwo input').eq(index).val($(this).val());
});


Q:

Lenovo IdeaPad Z570 touchpad stopped working after upgrade to 15.04

Having just upgraded to Ubuntu 15.04 (from 14.04 via 14.10) my touchpad does not appear to be working. It is still however possible to make use of a USB connected mouse.
Following the instructions here I have tried to diagnose the problem with the following results:

Check whether the kernel has detected the Touchpad

$ cat /proc/bus/input/devices | grep TouchPad
N: Name="SynPS/2 Synaptics TouchPad"

Check whether xserver has detected the Touchpad

$ xinput --list | grep TouchPad
⎜   ↳ SynPS/2 Synaptics TouchPad                id=13   [slave  pointer  (2)]

Check whether the synaptics module is correctly loaded in xserver

$ cat /var/log/Xorg.0.log | grep -i synaptics
[    33.606] (II) config/udev: Adding input device SynPS/2 Synaptics TouchPad (/dev/input/event5)
[    33.606] (**) SynPS/2 Synaptics TouchPad: Applying InputClass "evdev touchpad catchall"
[    33.606] (II) Using input driver 'evdev' for 'SynPS/2 Synaptics TouchPad'
[    33.606] (**) SynPS/2 Synaptics TouchPad: always reports core events
[    33.606] (**) evdev: SynPS/2 Synaptics TouchPad: Device: "/dev/input/event5"
[    33.606] (--) evdev: SynPS/2 Synaptics TouchPad: Vendor 0x2 Product 0x7
[    33.606] (--) evdev: SynPS/2 Synaptics TouchPad: Found 3 mouse buttons
[    33.606] (--) evdev: SynPS/2 Synaptics TouchPad: Found absolute axes
[    33.606] (--) evdev: SynPS/2 Synaptics TouchPad: Found absolute multitouch axes
[    33.606] (--) evdev: SynPS/2 Synaptics TouchPad: Found x and y absolute axes
[    33.606] (--) evdev: SynPS/2 Synaptics TouchPad: Found absolute touchpad.
[    33.606] (II) evdev: SynPS/2 Synaptics TouchPad: Configuring as touchpad
[    33.606] (**) evdev: SynPS/2 Synaptics TouchPad: YAxisMapping: buttons 4 and 5
[    33.606] (**) evdev: SynPS/2 Synaptics TouchPad: EmulateWheelButton: 4, EmulateWheelInertia: 10, EmulateWheelTimeout: 200
[    33.606] (II) XINPUT: Adding extended input device "SynPS/2 Synaptics TouchPad" (type: TOUCHPAD, id 13)
[    33.606] (II) evdev: SynPS/2 Synaptics TouchPad: initialized for absolute axes.
[    33.606] (**) SynPS/2 Synaptics TouchPad: (accel) keeping acceleration scheme 1
[    33.606] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration profile 0
[    33.606] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration factor: 2.000
[    33.606] (**) SynPS/2 Synaptics TouchPad: (accel) acceleration threshold: 4
[    33.606] (II) config/udev: Adding input device SynPS/2 Synaptics TouchPad (/dev/input/mouse1)

For problems such as scrolling area, touch area, button wrong mapping, and multitouch

$ xinput --list-props 13
Device 'SynPS/2 Synaptics TouchPad':
Device Enabled (116):   1
Coordinate Transformation Matrix (118): 1.000000, 0.000000, 0.000000, 0.000000, 1.000000, 0.000000, 0.000000, 0.000000, 1.000000
Device Accel Profile (243): 0
Device Accel Constant Deceleration (244):   1.000000
Device Accel Adaptive Deceleration (245):   1.000000
Device Accel Velocity Scaling (246):    10.000000
Device Product ID (236):    2, 7
Device Node (237):  "/dev/input/event5"
Evdev Axis Inversion (247): 0, 0
Evdev Axis Calibration (248):
Evdev Axes Swap (249):  0
Axis Labels (250):  "Abs MT Position X" (269), "Abs MT Position Y" (270), "Abs Pressure" (267), "Abs Tool Width" (268), "None" (0), "None" (0)
Button Labels (251):    "Button Left" (119), "Button Unknown" (239), "Button Right" (121), "Button Wheel Up" (122), "Button Wheel Down" (123)
Evdev Scrolling Distance (252): 0, 0, 0
Evdev Middle Button Emulation (253):    0
Evdev Middle Button Timeout (254):  50
Evdev Third Button Emulation (255): 0
Evdev Third Button Emulation Timeout (256): 1000
Evdev Third Button Emulation Button (257):  3
Evdev Third Button Emulation Threshold (258):   20
Evdev Wheel Emulation (259):    0
Evdev Wheel Emulation Axes (260):   0, 0, 4, 5
Evdev Wheel Emulation Inertia (261):    10
Evdev Wheel Emulation Timeout (262):    200
Evdev Wheel Emulation Button (263): 4
Evdev Drag Lock Buttons (264):  0

I cannot see anything in the results to suggest I have a problem and have yet to find any solutions to similar problems that have worked for me.
I would appreciate any assistance in this matter.
My system information is:

$ uname -a
Linux Ideapad-Z570 3.19.0-26-generic #28-Ubuntu SMP Tue Aug 11 14:16:45 UTC 2015 i686 i686 i686 GNU/Linux

Thanks.

A:

It's probably because there's something wrong with the synclient installation. Reinstall that and reboot.