Checked items in C# Listview

Question: I have a Listview control in C# application filled with some names and checkboxes to select one or more value. Apart from clicking on checkboxes, user can also click on the name and it will become blue. I want to keep this functionality as clicking on the name shows some more data and clicking on checkbox marks it for further processing
I believed that clicking on checkbox changes Item.Checked property and clicking on name Changes Item.Selected but it seems to be no so simple.
I have a code that counts checked items:
private void Listview1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    foreach(ListViewItem Item in ListView1.Items)
    {
        if (Item != null)
        {
            if (Item.Checked == true) N++;
        }
    }
    Textbox1.Text = N.ToString();
}

When user clicks checkboxes there is proper number displayes but when he clicks name, the checked number changes to 1 even if there are still more checkboxes checked, which is obviously wrong. Also when the form and the control load, I get my N=1 even if there are no checkboxes checked.
What am I doing wrong?
Edit:
Thanks for quick response and useful hints!
And I've just discovered that my problem was my negligence  as I forgot to remove my old code! :)
At first I used multiple selection to pick up items, then I  switched to checkboxes but still was calling SelectionChanged event and modifying textbox content
Comment: Where is N initialized? In the event code, N is not set back to 0 to restart counting.
Comment: @Yogendra: Please use proper spelling. We are not in a script kiddie chat here.
Comment: I hope N is not 1 b4 u r getting into the loop :)
Comment: Oops, noted, newbie here.
Comment: possible duplicate of [C# ListView - control checkBox event](http://stackoverflow.com/questions/976569/c-sharp-listview-control-checkbox-event)
Answer: To get the number of checked items in a ListView control, use the ListView.CheckedItems.Count property.
Example:
int numCheckedItems = myListView.CheckedItems.Count;

or
TextBox1.Text = myListView.CheckedItems.Count.ToString();

Answer: You should not iterate trough all items as ItemCheckedEventArgs provides all info you need:
private void Listview1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
    ListViewItem item = e.Item as ListViewItem;
    if (item != null)
    {
       if (item.Checked)
       {
           N++;
       }
       else
       {
           N--;
       }
    }
    Textbox1.Text = N.ToString();
}

Comment: `ListView` with event `ItemChecked` is `Winforms` so no `ViewState` involved :)
Answer: private void saveButton_Click(object sender, EventArgs e)
{

    SelectEmployeeBLL selectEmployeeBLL = new SelectEmployeeBLL();

    int employeeId = Convert.ToInt32(employeeNameInsertComboBox.SelectedValue);

    int departmentId= Convert.ToInt32(departmentNameInsertComboBox.SelectedValue);

    bool departmentNameCheck = selectEmployeeBLL.DepartmentNameDuplicateCheck(departmentId, employeeId);

    if (departmentNameCheck)
    {
        MessageBox.Show("Department already have");
        return;
    }

    SelectEmployee selectEmployee = new SelectEmployee();
    selectEmployee.DepartmentIDID = departmentId;
    selectEmployee.EmployeeIDID = employeeId;

    bool aselectEmployee = selectEmployeeBLL.SelectEmployeeIsert(selectEmployee);
    if (aselectEmployee)
    {
        MessageBox.Show("save successfull");
        LoadEmployeeDepartment();
    }
}

Checked items in C# Listview


JQuery/PHP - Overlay another page on keypress

Question: I'm trying to make a page "overlay" when the user presses the keyboard key T or P. With the code below, I am able to make the page turn blank, however, I would like to be able to display another html page or other text while the other disappears. When the user presses T or P again, it returns to there previous window.
Here is my current code:
<code>$(document).keypress(function(e) {
    var key = e.which;
    if (key == 116) {
        // if the user pressed 't':
        if(!$("body").hasClass('active'))
            $("body").addClass('active');
        else
            $("body").removeClass('active');
    }
});

 <style>
    .active{opacity:0;}
 </style>
</code>
NOTE: I'm using style tags for testing purposes.
Please, if you have any suggestions on how to make one object hide, and another one appear please let me know. I would really appreciate it. A JSfiddle would be much appreciated if possible.
Thank you so much for reading!
Toby.
Comment: Maybe you can put your two different blocks of content into two different `div` tags inside the `body` tag.  Then toggle the active class (inversely) on both divs when you press button.  So when you press 't', you make `` remove active class and add active class to ``.  Then when you press again, do the opposite.  Perhaps instead of changing the opacity for the divs, you might want to toggle display from hidden to whatever and back.  That way they can occupy the same space when showing.  I'll write somethin up later tonight if you need me to.
Answer: There are a few problems with your code that are notable.
1. You are hiding the body.
Everything should be within your document body, so if you hide the whole document, you can't see anything! Put your content into separate divs so that you can hide each one independently.
2. You are not fading
In order to fade, you either have to use CSS3 transitions or use a jQuery animation.
See this example JSFiddle for an idea. Press 'T' to alternate between the red and blue divs (you'll have to click on the div to put your focus on the document). I use a placeholder class <code>.hidden</code> (which has no styles attached; it is just  a placeholder) to keep track of which div is visible and hide/show accordingly.
<code>$(document).ready(function(){

    $(document).keypress(function(e) {
        var key = e.which;
        if (key == 116) {
        // if the user pressed 't':
            if($(".red").hasClass("hidden"))
            {
                $(".red").removeClass("hidden").animate({
                    opacity: "1"
                }, 500).css("z-index", 1);
                $(".blue").addClass("hidden").animate({
                    opacity: "0"
                }, 500).css("z-index", 0);
            }
            else
            {
                $(".blue").removeClass("hidden").animate({
                    opacity: "1"
                }, 500).css("z-index", 1);
                $(".red").addClass("hidden").animate({
                    opacity: "0"
                }, 500).css("z-index", 0);
            }
        }
    });

});
</code>
JSFiddle
Comment: This is close to perfect.
The only last problem I am having is that it "reloads" the attributes on the page. For example, I have a game running on the page, when they press "t" it hides perfectly. When they press "t" again it restarts the "code" for the game. When I set the opacity down, it did not do this. Any suggestions to keep them loaded but just hide them in the background?
Thank you so much!
Comment: @user2957677 What is it missing?
Comment: Sorry, I pressed ENTER by accident :).
Comment: You could try this fiddle: http://jsfiddle.net/ER9gF/5/ The only thing that will be an issue here is z-indexing. Notice the way I set the CSS of the z-index whenever T is pressed. The red div will never be able to receive clicks while it is below the blue one, so you'll have to set the z-index of the visible element to be the highest.
Comment: That doesn't seem to work either :(.
You can see the "test" at http://imdoingwork.com/blabla.php.
Notice how if you press "play" wait for the game to load. Press "t", then notice how the game goes back to the "play" menu. The game is getting reset. Any ideas?
Thanks again for the help.
Comment: Sorry, I think I may have got this working. I'll keep you posted. Thanks SOOO much for this.
Comment: Hello, I was wondering if you can help me get this working cross browser/ customize it abit. I can pay you for your services if you wish, if you're interested please add me on skype (mellor12345) or email me at firstname.lastname@example.com.


Ray tracing scene with 2 lights and sphere

Question: I'm writing my implementation of ray tracer and I've got result which you can see at this image.

So you can see that some dark parts are overlapping. And I have them even in the part where it should be bright in my opinion. There are two lights one from above and the second one from right-bottom corner.
And I have two questions. Is it right? I really tried to google some references but failed. I'm not still sure that results in my imagination are correct ones.
And the second one where does it come from?
I use usual lambertian shading model and have something like this in my code:
pixel = (0, 0, 0)
normal = get normal of sphere in point of intersection;
normal = unit vector of normal;
for each light from light_set {
    light = unit vector of light;
    pixel = pixel + diffuseColor * max(0, scalar multiplication of light and normal);
}

I'm really struggling to find out the reason where this strange thing is coming from. But couldn't find it.
UPD0: added some of my real code. The part which is described here is next:
Material mat = surfaces[closestSurfase]->getMaterial();
Color pixel = Color(0, 0, 0);
Vector3f normal = surfaces[closestSurfase]->getNormal(point).getUnitVector();
Vector3f view = -ray.getDirection().getUnitVector();
for (size_t i = 0; i < lights.size(); ++i) {
    Vector3f normal_light = lights[i]->getDirection().getUnitVector();
    Vector3f specVect = (normal_light + view).getUnitVector();
    float intenst = lights[i]->getIntensity();
    pixel = pixel + mat.getDiffuse() * std::max(0.0f, normal_light.dotMultiply(normal)) * intenst;
}
result->setPixel(x, y, pixel);

Or you can find more here: https://github.com/minebv/ray_tracer/tree/lambertian_shading_fix/src
Described above is from Camera's method getRender.
UPD1: It looks like the problem in the mixing colors in gamma space instead linear one, as answered @PaulHK .
But I've still some kind of problem. Here you can see 2 renders.

At the left one I make all work after transformation all colors into linear space, I mean it's like this in my code:
pixel = pixel + mat.getDiffuse().toLinear() * std::max(0.0f, normal_light.dotMultiply(normal)) * intenst;

At the right one I make transformation after multiplying:
pixel = pixel + (mat.getDiffuse() * std::max(0.0f, normal_light.dotMultiply(normal)) * intenst).toLinear();

And I didn't forget to make pixel into gamma space again after all job.
As for me, the right one is more correct. But then there is a question: why should I make multiplication on angle into gamma space? Or is it my incorrect way to think about what is right?
UPD3:it looks like the whole thing really was about mixing colors in gamma space instead of linear one. Here is result with ambient light.

Also about overlapping lights, it was my incorrect way of thinking. I finally found reference material where they have the same thing. Found it at blender docs.
Thank everyone for answers.
Comment: It does look weird. Could you put some of your actual code for us to see? Pseudo code shows your intent, which looks decent, but the problem might be in some subtle issue of the math or a typo (:
Comment: @AlanWolfe updated my question, added some real code.
Answer: I think what you're describing is what happens when you mix colours in gamma space. You should be using linear colour space when mixing.
When reading colours of lights and materials, convert them from gamma->linear using the inverse gamma function.
colourLin = pow(colourLight, 2.2);
... do lambert calculation here and accumulate in 'colour' variable ..

// On output (linear->gamma conversion)
gl_FragColor = pow(colour, 1.0/2.2);

There is an in depth chapter in GPU Gems on this topic: The Importance of Being Linear.
Comment: Done it. It looks like the problem is really with hamma. But I still has a question. There are to results of my ray tracing. In the first one I
Comment: Sorry for kind of spamming. Didn't use to sending commentary with Enter button. There is continuation. In the left one I make at first gamma to linear conversion and then multiplying it on the max(0, scalar multiplication of light and normal) and after that summing results in pixel. And convert results into gamma space again. At the right one I convert colour into linear space only after multiplying it on on the max(0, scalar multiplication of light and normal). I don't quite get the reason why  should I multiply in the gamma space. ![img](http://i.imgur.com/7WRCFb0.png)
Comment: The most important thing is the output is converted to gamma (meaning your light accumulation is linear). Because your inputs are constant colours it doesn't affect shading as much as the output conversion.
Comment: I'd be interested to see your new image output if you can post an update
Comment: Don't forget, you picked the orange/green colours by eye (presumably) using a gamma-space monitor, so likely these are the correct/intended colours.
Comment: I understand it. Don't have any complaints about color. Just about dark parts at the left part of the second image in the updated post. The right one is good without them. But why should I make transformation to the linear space after multiplication.
Comment: I think the left image is the correct one looking at the function, although you may need to adjust your light colours to something a bit darker.
Comment: Could your colors be overflowing?
Comment: Nope, I clamp to 1.0f every component when it becomes more than 1.0f. I thought about this case that's why I specially check it in my tests.
Comment: A couple of *very minor* points: 1) The monitor/display system is probably using sRGB which is a slightly different curve to the pow(colour, gamma_val)   (BUT you might be able to avoid that with https://stackoverflow.com/q/56204242/626644 )   2) if you are concerned about the performance, you *might* be able to get away with the approximation of using "2" for the gamma power. You can then use squaring and square roots which are relatively cheap.


Why is WPF flickering on me?

Question: I am getting very strange flickering on a WPF application of mine.  It only happens with alpha blended content, only on my computer, and only with WPF applications.  At least I haven't noticed it with anything else. It's really annoying! Has anyone else dealt with this weirdness?
Comment: Is your whole window transparent, or just some of the content inside your window?
Comment: The latter; just some of the content inside the Window.  It seems to happen whenever I use opacity other than 100%.  I should also say that the Silverlight version of the application does not exhibit these problems.
Answer: Try disabling hardware acceleration to see if that resolves the issue.  If it does, try updating your video card drivers and turning back on hardware acceleration.  For more details, see here:
http://msdn.microsoft.com/en-us/library/aa970912.aspx
Comment: That site is out of date.  There is no such registry entity as "Avalon.Graphics".  I did a search for "DisableHWAcceleration" and found nothing.  Care to update?
Comment: You have to create the entry, as it's not there by default.  Yes, I know, it's a rather ugly hidden feature, but so it goes.  It's really only intended for diagnostics.
Comment: I have to create "Avalon.Graphics" as well?
Comment: I suppose I have to restart as well?  Is there a service that I can restart?
Comment: I did so and it worked for a little while, but the flicker is back.  :(
Comment: I gave you the answer, but this still happens to me from time to time, just less now.

Why is WPF flickering on me?


Warning message while rendering LaTeX in Inkscape

Question: I installed pdflatex-full.
When I try to export a math expression using LaTeX in Inkscape 1.1 (with Extension -> Render -> Mathematics -> LaTeX (pdflatex) (in Inkscape 1.2, it is Extensions -> Render -> Formula (pdflatex))), I get the following warning message.
/usr/share/inkscape/extensions/inkex/command.py:73: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
  from distutils.spawn import find_executable

Since I am not using Python 3.12 (This issue is present on Ubuntu 22.04 and 22.10), this warning is does not help much, and it is extremely annoying when I need to generate many LaTeX expressions in Inkscape.
How to suppress this warning?
Answer: This workaround is based on this answer.
Open the file /usr/share/inkscape/extensions/inkex/command.py, and add the following lines after python imports os and system.
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)

Restart Inkscape, and the problem should be gone (unless the file is rewritten by a future update of Inkscape).


How to make a 1:1 type map of an object literal with a new type of value as a function return implicitly?

Question: Currently I'm able to get a union of the key and values of each object literal passed into a function.
e.g.
interface StaticClass<T = any> {
  new (...args: any[]): T
}
type RecordOfStaticClasses = Record<string, StaticClass>;
type RecordOfInstances<T extends RecordOfStaticClasses> = Record<keyof T, InstanceType<T[keyof T]>>;

const transformObjLiteral = <T extends RecordOfStaticClasses>(input: T): RecordOfInstances<T> => {
  return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, new value])) as RecordOfInstances<T>;
}

// Transformation
class Cat {
  asleep: boolean;
}
class Zebra {
  hoofLength: number;
}
transformObjLiteral({ myCat: Cat }).myCat.asleep // works if only 1 key is added
transformObjLiteral({ myCat: Cat, myZebra: Zebra }).myCat.asleep // Error: Property 'asleep' does not exist on type 'Cat | Zebra'!

As can be seen from above, it works well when only a object literal with 1 key is passed. However when adding two keys it cant get specific due to the possibility of a Union type. I know I can use Generics (e.g. transformObjLiteral<{ myCat: Cat }>({ myCat: Cat })) but I hope to accomplish this implicitly based on the argument by itself. Is this posible?
Answer: Instead of using a Record, use a mapped type directly to keep the association between individual keys K and their InstanceType<T[K]>.
type RecordOfInstances<T extends RecordOfStaticClasses> = {
  [K in keyof T]: InstanceType<T[K]>
}

Playground
Comment: Thank you for sharing this and providing a playground!


list files and folders of the root partion

Question: My root partion is full and I am going to clean up it a bit. But I have confused with partitions and folders. I.e. deleting unneeded files in home directory doesn't increase / partition size but if I list it, system shows another picture.
Filesystem      Size  Used Avail Use% Mounted on
udev            7,8G     0  7,8G   0% /dev
tmpfs           1,6G  1,7M  1,6G   1% /run
/dev/sda8        19G   17G  468M  98% /
tmpfs           7,8G  722M  7,1G  10% /dev/shm
tmpfs           5,0M  4,0K  5,0M   1% /run/lock
tmpfs           7,8G     0  7,8G   0% /sys/fs/cgroup
/dev/loop0      140M  140M     0 100% /snap/slack/24
/dev/loop1       55M   55M     0 100% /snap/core18/1754
/dev/loop4      129M  129M     0 100% /snap/sweethome3d-homedesign/9
/dev/loop5      145M  145M     0 100% /snap/slack/25
/dev/loop6       97M   97M     0 100% /snap/core/9436
/dev/sda2        96M   81M   16M  84% /boot/efi
/dev/sda10       28G  6,1G   21G  23% /home
tmpfs           1,6G   64K  1,6G   1% /run/user/1000
/dev/loop7       55M   55M     0 100% /snap/core18/1880
/dev/loop2       97M   97M     0 100% /snap/core/9665
/dev/sda7        15G   14G  1,7G  89% /media/alex/SASHA
alex@alex-HP-ProBook-430-G4:~$ df /root/
Filesystem     1K-blocks     Used Available Use% Mounted on
/dev/sda8       19091584 17619740    478976  98% /
alex@alex-HP-ProBook-430-G4:~$ df /
Filesystem     1K-blocks     Used Available Use% Mounted on
/dev/sda8       19091584 17619740    478976  98% /
alex@alex-HP-ProBook-430-G4:~$ sudo mount /dev/sda8 /mnt
alex@alex-HP-ProBook-430-G4:~$ cd /mnt/
alex@alex-HP-ProBook-430-G4:/mnt$ ls
bacula-console.conf.ucftmp-iatbDRUGJi  bacula-director.conf.ucftmp-iiJ0w1gZEH  bacula-fd.conf.ucftmp-3B2f7qUh3a  bacula-sd.conf.ucftmp-nBESqCvQnZ  bin  boot  cdrom  dev  etc  home  initrd.img  initrd.img.old  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  snap  srv  sys  tmp  usr  var  vmlinuz  vmlinuz.old
alex@alex-HP-ProBook-430-G4:/mnt$

Its not clear what takes 17G of /dev/sda8 partition and what folders belong to it
Answer: First standard cleanup & update.
sudo apt-get update
sudo apt-get upgrade
apt-get autoremove
sudo apt-get autoclean

Autoclean cleans up the downloaded archives (.gz or .tar) files used to install things. Autoremove cleans libraries that are no longer needed.
Then we can start search for large folders with du.
Size of apt caches (often an issue)
sudo du -sh /var/cache/apt/archives

find ~/.cache/ -depth -type f -atime +365

Delete all old cache entries, you can change to any number of days.
find ~/.cache/ -type f -atime +365 -delete

I also delete the older logs if no issues.
find /var/log/ -type f -atime +10  -name *.gz* -print -exec rm {} \;

houseclean journalctl over 10 days
journalctl --vacuum-time=10d

Then if not typical cache we can search.
cd / or cd /home
sudo du -hc --max-depth=1

Or and then for largest folder change from / to that folder - /var as an example and keep drilling down:
sudo du -hx --max-depth=1 / 2> /dev/null
sudo du -hx --max-depth=1 /var 2> /dev/null

I once forgot to mount my backup and it put the entire thing into /. I just barely had room, so system did not crash but root was almost full.
You also can check for large folders & files:
sudo du -h --max-depth=1 / | grep '[0-9]G\>'   # folders larger than 1GB
sudo find / -name '*' -size +1G    # files larger than 1GB

or install ncdu and drill down from / (q to quit):
sudo ncdu /

Answer: Disk partition sizes are normally fixed, so it doesn't really matter how many files are in there - the size will remain the same until you manually change it.
To see what's in /dev/sda8 you can run:
sudo sfdisk -l | grep ^/dev

and the last 2 columns will show the size and type (what's contained) in the partition.


Why is this C# code not working? I am trying to read the output of a shell to TortoiseHG (Mercurial)

Question: I am trying to get mercurial to run in a shell from my C# wpf application. My purpose is to retrieve the output into a string so that I can parse it.
Unfortunately for me, it seems that hg.exe (from tortoiseHg), does not return anything via the code below. Other .exe's appear to work, as seen in the comments below;
My Code is below;
`
        string workingDir = "";
        string filename = "";
        string param = "";

        //This works
        workingDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        filename = "unrar.exe";
        param = "";

        //this works
        workingDir = "c:\\program files\\WinRar";
        filename = "unrar.exe";
        param = "";

        //this works
        workingDir = "C:\\Program Files (x86)\\TortoiseHg";
        filename = "docdiff.exe";
        param = "";

        //this does not work. I get a null returned. Why?
        workingDir = "C:\\Program Files (x86)\\TortoiseHg";
        filename = "hg.exe";
        param = "";

        //this does not work. I get a null returned. Why?
        workingDir = "C:\\Program Files (x86)\\TortoiseHg";
        filename = "hg.exe";
        param = "help";

        string retVal = "";
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.WorkingDirectory = workingDir;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.FileName = filename;
        proc.StartInfo.Arguments = param;
        proc.Start();

        System.IO.StreamReader reader = proc.StandardOutput;
        retVal = reader.ReadToEnd();
        System.Windows.MessageBox.Show(retVal);`

If anyone could suggest why this code does not work, or alternatively another method of retrieving the output of mercurial command lines, I would be very appreciative.
Thank you
Comment: It might be writing to standard error?
Comment: (Shameless plug) Hi, I have started working on a Mercurial command line wrapper, that will parse and convert all Mercurial output and commands into more C#-y syntax. If you're interested, you can follow the project here: http://bitbucket.org/lassevk/mercurial.net
Comment: any final solution with full source code sample working about it ?
Answer: Your code works for me (tested with TortoiseHg 2.0.2), provided that I pass the full path to the executable:
proc.StartInfo.FileName = "C:\\Program Files (x86)\\TortoiseHg\\hg.exe";

Answer: My guess is there is output going to standard error.
This page talks about how to do it:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx
Answer: I think you might be needing a
proc.WaitForExit();

before your read to end call? Unless the process is interactive, then you have a different problem.
Answer: You might consider handling the Process.OutputDataReceived and ErrorDataReceived events:
proc.ErrorDataReceived += delegate(object o, DataReceivedEventHandler e)
  {
      if (e.Data != null) { /* e.Data is the string from the process */ }
  };
proc.OutputDataReceived += delegate(object o, DataReceivedEventHandler e)
  {
      // ...
  };

Be sure to call proc.BeginErrorReadLine() and proc.BeginOutputReadLine() after starting the process.
Comment: any final solution with full source code sample working about it ?


When is 'Challenging Smite' a viable option for top laners

Question: I saw some top laners who use smite and teleport as spells and (if I'm correct), it's becoming pretty regular and although I don't play as a top laner, maybe when I have to adjust, I know I may find this useful.
My questions are when and who :
When to use it / what are some of the conditions needed since it was told that this strategy isn't always going to be useful in every top laner,
Who are the champions that will really take advantage of this?
Comment: thanks for asking this question and not just try to copy LCS players :-)
Answer: This is a thing you need to know about before using it. I've seen a lot of people playing it in the wrong situation and on the wrong champs. Even if you pick it in the right situation it's not easy to execute.
What are the advantages of Toplane smite?

You can buy Cintderhulk which is probably the best scaling tank item in the game.
Challenging Smite offers you great dueling potential.
Securing jungle objectives is extremely safe and easy with 2 Smites.
You can easily get a level advantage by switching between lane and jungle.
You can counterjungle.

What are the disadvantages of Toplane Smite?

You are  sacrificing either Flash or Teleport
Counterpicks to your champion are about twice as effective because of your lack of flash
You will have to play passively in most cases up until midgame.
It's extremely situational and difficult to pull off.
Your jungler and midlaner have to play accordingly.

Now the 2nd and 4th and 5th point of the negative aspects are the most important ones which make this tactic not all too effective in soloqueue. Your jungler will have to leave either Gromp, Wolves or Krugs to you and your midlaner has to make sure that the enemy midlaner doesn't roam top all too often. Also if you get counterpicked you're going to have a hard time since you usually have to play passive and Smite doesn't provide you with any defensive or offensive values that are comparable to a Flash up until mid-late game.
The champions it works on are also rather limited. To be considered Viable  the champion has to meet at least three of the following criteria.
The champion...

Scales extremely well with bonus HP (Scaling on spells or built-in
Resistances)
Deals a lot of AOE Damage while standing in the enemy team or sunfire is normally built on him.
Has built-in escapes or is able to survive 2-man ganks without flash.
Would greatly benefit from a level advantage.

Now this limits the champion pool for a Smite Toplane quite heavily: Here are the ones where it's ok to run smite (with the points that apply from above).

Dr. Mundo: (1,2,3 past lvl six,4)
Gnar (1,3,4)
Hecarim (2,3,4)
Jax (1,3,4)
Malphite (1,2,3 past lvl six,4)
Nautilus (1,2,3)
Renekton (1,2,3,4)
Shen (1,2,3)
Shyvana (1,2,3,4)
Volibear (1,2,4)
Zac (1,2,3,4)

Now this is the list but again you and your team have to play accordingly and the best champions are obviously the ones who fulfill all 4 points. The ones with 3 met criteria might work if played very well but generally you shouldn't do it if you don't play them very often.
Just keep in mind that you will always have to play passively for a very long time until you have Cinderhulk and/or survival. Toplane Smite is heavily mid-lategame oriented and will put your whole team at a disadvantage during early levels. Also only build Challenging smite. The other ones aren't good while laning.
Comment: @DropDeadSander-EUW Flash and TP are just far too important on Garen to be replaced by Smite.
Comment: Garen (1,2,3) ?
Comment: Played with a Olaf smite top and he did very well even if I didn't give him my Gromp (as WW), we were a late game force.
Comment: Can't Poppy be included too?
Comment: @Randomizer No. There's basically no point in buying it on poppy except for the HP maybe.
Answer: The focus is on Cinderhulk rather than smite.  It is 100% gold efficient at 600 pre-Cinderhulk health (so basically any character), not including the immolate passive (which is the big reason people want it).  Its immolate burns for 9 less damage than Sunfire, but increases based on time in combat to as much as 8 more damage/second than Sunfire.
It is good on any character that wants a cheaper Sunfire Cape, but can afford to not have flash.  This typically applies to tanks/bruisers, particularly those with mobility (think Renekton).
Both Stalker's Blade (chilling smite) and Skirmisher's Sabre (challenging smite) are viable build paths, depending on whether you are having trouble chasing your lane opponent or winning trades, respectively.
Comment: You have the two smites reversed. Chliling smite aids in chasing your lane opponent, while challenging smite strengthens your duelling potential.
Comment: @Schism Good point.  Not sure how I mixed it up.
Answer: This is extremely good on tanks that want a sunfire cape as you can buy the Cinderhulk enchantment and be set. This is a very efficient way to play. This works best on champs that can afford to not take flash as they have alternate escapes.
Note: For most cases you will use the Rangers Trailblazer
E.G. Jax's Q
You can also use the stalkers blade If you are ahead but want a slow to help with chasing.
Build Skirmishers Sabre when you are playing an attack speed champ like Fiora or Warwick. Actually a Youtuber named Foxdrop has actually created guides on Warwick and Fiora top with smite.
Never EVER build the Poachers knife. As of patch 5.7 the item is just not worth it, and also you will be in lane so you will not be able to counter jungle.
Hope this helps!
Comment: the foxdrop guides are extremly outdated. Skirmishers has been nerfed very hard


How to waterproof foam and pipes coming up through concrete ground

Question: I have a bundle of foam and pipes coming up through the concrete ground in my backyard for my HVAC equipment.  There is no conduit and the pipes and foam is all in ground contact and the concrete was poured around the bundle.

How can I waterproof this and weather-seal it?  When it rains the foam in the ground gets wet and I'm not sure if it gets absorbed down into the ground as a wick - or if it's a closed cell and it doesn't matter?
In any case, I was going to replace the rubber insulation but I also want to protect it from water so the foam that's embedded in the concrete doesn't get wet.
Can I just spray outdoor foam around it without having the expanding foam crush the pipes as it dries?  Or is there an easier or better-looking alternative?  The pipe only comes up a few inches before it elbows... so I'm not sure how I can make an enclosure that would fit and also not let it get wet from groundwater.
Answer: It's closed cell foam (or should be) - so water getting into it should not be an issue -  worry more about the gnawed-off sections and get to replacing them, perhaps with a metallic over-wrap to slow down having them gnawed off again.


C programming TEXT FILE not reading whole line

Question: Here is the input from TEXT FILE :
19 BISON-BURGER 10 15.000000
10 BRAISED-COD 5 17.000000
23 MOJITO 8 11.000000
3 IRISH-COFEE 6 2.300000
7 LAMB-SHOULDER 8 23.000000

The output came out from compiler after input being key in was :
10 BRAISED-COD 5 17.000000
3 IRISH-COFEE 6 2.300000
7 LAMB-SHOULDER 8 23.000000

Why the compiler skipping some of the lines ? Is there any changes I need to make?
Please help. Thank you so much.
Here is the full code :
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>

struct product
{
    int quantity, reorder, i, id;
    char name[20];
    float price;
};

    int main()
    {
    FILE * fp;

    int i=0;
    struct product a;
    system("cls");

    char checker;

        do
        {
        fp = fopen("addproduct.txt","a+t");
        system("cls");

        printf("Enter product ID : ");
        scanf(" %d", &a.id);

        printf("Enter product name : ");
        scanf(" %s", a.name);

        printf("Enter product quantity : ");
        scanf(" %d", &a.quantity);

        printf("Enter product price : ");
        scanf(" %f", &a.price);

        fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
        printf("Record saved!\n\n");

        fclose(fp);

        printf("Do you want to enter new product? Y / N : ");

        scanf(" %c", &checker);
        checker = toupper(checker);

        i++;

        system("cls");
        }

        while(checker=='Y');

        if(checker == 'N')
        {
        fp = fopen("addproduct.txt","r");

        while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
            {
        fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price);
        printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
            }

        fclose(fp);

        }

        return(0);
}

Comment: Learn how to use a debugger. Then you can step through the code line by line to see what it's really doing, while monitoring variables and see how they change.
Comment: Because you read the line twice: once in the `while` condition, and again in the body of `while`. That does not read the same line, it reads another one.
Comment: Why do you keep opening and closing the output file each time through the input loop? Why not just open it once before the loop, and then close it after the loop ends?
Comment: @FredK okay cool. already change it. thanks :)
Answer: You're reading two lines from the file on each iteration of the output loop.  Get rid of the extra scanf:
    while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
    {
        printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
    }

Answer: You're calling fscanf() twice each time through the while loop. First in the while condition, then in the body of the loop. You're only printing the variables read by the second one, so the lines read by the first fscanf() are being ignored. Get rid of the second fscanf().
while(fscanf(fp, "%d %s %d %f", &a.id, a.name, &a.quantity, &a.price)==4)
{
    printf("%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
}


Update table A by Joining Table B and Table A

Question: I have table A, Table B
My database looks some thing like this
Table A
key1
key2
key5
key6
Table B
key3
key4
Data in A.key2 is same as data in B.key3 and A.key5 has same data as B.key 4
I want to update key1 in Table A to another row in table A based on some condition on key6 of table A
I want to update some rows in Table A with Values which I would get by joining Table A with Table B.
I tried running a query like
UPDATE table A set a.key1 = c.key1 FROM A a JOIN B b ON a.key2 = b.key3 JOIN A c ON b.key4 = c.key5 WHERE A.key6 = somevalue;

sql throws an error -
column a of relation A does not exist
Comment: Please provide sample data, desired results, a clear explanation of what you are trying to do and a *single* database tag.  I removed the incompatible tags as a favor.
Answer: This is the correct syntax for Postgresql:
UPDATE A a
SET key1 = c.key1
FROM B b
JOIN A c ON b.key4 = c.key5
WHERE a.key2 = b.key3  AND a.key6 = somevalue;

Comment: Worked perfectly with a small change
instead of A.key6
I had to use a.key6


VBA in Excel - use loop counter to reference cells

Question: I have cells that are either "True" or "False". I have names for these cells so that it's easier for me to reference in my codes. For Example, instead of saying cell "A1" I say cell "Apples". The cell names are:
Apples
Oranges
Onions
Potatoes
Bananas
In a separate worksheet I have under column A:
Apples
Oranges
Bananas
This range of cells is named "Fruit". So this list is meant to be a list of the cell names I want to check.
I want to use a for loop to check if each cell referenced under in the range "Fruit" is true. This is my code:
For Each item In [Fruit]
    If Worksheets("Inventory").Range(item).Value = True Then
        --Do stuff--
    End If
Next item

I keep getting an error when trying to reference the cell. How can I do this? Is it possible for me to use the counter to reference the cell?
Answer: close...
For Each item In [Fruit]
    If Worksheets("Inventory").Range(item.Value) = True Then
        '--Do stuff--
    End If
Next item


What is Reverse Proxy and why should I use it with Node.JS?

Question: Ryan Dahl recommends using Node.JS behind a reverse proxy (i.e nginx). Well.. what is reverse proxy? Any why should I use it with node.js? Is it wrong that my Node.JS app will serve all the content and all the traffic?
Thanks in advance.
Comment: Newbie, have a look at this articles - https://medium.com/intrinsic-blog/why-should-i-use-a-reverse-proxy-if-node-js-is-production-ready-5a079408b2ca
Answer:
what is reverse proxy?

Try to look at wiki article.

why should I use it with node.js?

If you are using node.js only for a certain parts/functionality of your application and other stuff is served by different web application framework for example, then reverse proxy can be used to determine which requests go to node.js and which go to the other framework. This way your application can run on the same port and act to clients as a standalone system. Without it you will probably have to server incoming requests separately for node.js and other framework on different ports (if they are both on the same machine for example). There are also other use cases of reverse proxies, like load balancing.

Is it wrong that my Node.JS app will
  serve all the content and all the
  traffic?

No, it's not wrong. It's specific to you and your needs or scenario.
Answer: http://en.wikipedia.org/wiki/Reverse_proxy - reverse proxy servers will lower the load on your application server.


Morris charts positioning on a cell phone

Question: I'm trying to figure out how I can get my Morris charts to be responsive on a mobile phone. I want them to go underneath each other when on a small screen. Any ideas?

Your activities:

What others do:

Following is the .js part.
$.getScript('http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js',function(){
$.getScript('http://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.0/morris.min.js',function(){
      Morris.Donut({
        element: 'user_activity-donut',
        data: [
         {label: "Jogging", value: 50},
         {label: "Sailing", value: 20},
         {label: "Walking", value: 15}
        ]
      });
      Morris.Donut({
        element: 'global_activity-donut',
        data: [
         {label: "Jogging", value: 30},
         {label: "Sailing", value: 5},
         {label: "Walking", value: 65}
        ]
      });
});
});

Comment: If I where you I should use css `media query`. When On small screen (your phone) `display` the charts as `block` and while on a big screen `display` them for example `inline-block`. Take a look here: http://www.w3schools.com/CSS/css_mediatypes.asp .
Comment: is Morris charts related at all to Morris Dancing?
Answer: Add this css to your head tag

<link rel="stylesheet" href="https://www.cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" />

then add the folowing after the labels and values
resize: true,
redraw: true,
Example:

Morris.Donut({
        element: 'user_activity-donut',
        data: [
         {label: "Jogging", value: 50},
         {label: "Sailing", value: 20},
         {label: "Walking", value: 15}
        ]
resize:true,
redraw:true,
      });


How To Name A Boat With No Gravity

Question: In minecraft I want to summon a boat with a specific name and the no gravity tag, which gets rid of gravity for the boat. This is easy separately, but I can't figure out how to do them together.
This is what I have so far:
<code>/Summon Boat [{NoGravity:1}Name:boat]
</code>
Comment: Please explain more.
Comment: @Jim Jones Im trying to sommo a boat with the no gravity tag, wich gets rid of gravity and a name, which are easy seperatly but I can't figure out how to get them together, this is what I have so far: /Summon Boat [{NoGravity:1}Name:boat]
Answer: This is fairly simple. If the boat is already existing you can stand within 5 blocks of it and execute:
<code>/entitydata @e[type=Boat,r=5] {NoGravity:1,CustomName:Name,CustomNameVisible:1}
</code>
If you want it in a summon command, use:
<code>/summon Boat ~ ~ ~ {NoGravity:1,CustomName:Name,CustomNameVisible:1}
</code>

How To Name A Boat With No Gravity


Multiprocessing Pool with timings or Process with maximum cores?

Question: I do not know if I understand multiprocessing correctly but for what I need it is basically doing thousands of small requests to a server. To simplify that I started testing out a little bit with just having a list of tasks and making it calculate on each item in that list some small thing.
The issue with requests to servers are that you do not want to spam the server or get potentially black listed.
For this i need a timing, which fits perfectly with multiprocessing.Process().
On the other hand whenever I use that with multiple 1000 processess it sometimes crashes, or at least crashes all other running programs.
For this I would need a Pool of Processes, wheer mulitprocessing.Pool() fits perfectly.
Am I missing something or is there a way for me to get best of both worlds?
Here some example code I am trying out for this:
import time
import multiprocessing

def foo(para):
    # do something very lightweight
    print(para*2)

parameters = [] # a long populated list of values, can be up to 100k processes long

# test Process
for para in parameters:
    Process(target=foo, args=(para)).start()
    time.sleep(0.06) # my rate limit in this case

# test Pool
with multiprocessing.Pool() as pool:
    pool.starmap(target=foo, zip(parameters))

The issue I am facing is that I am either getting banned from requesting or that I crash my device. Any help would be greatly appreciated. And please enlighten me if I am missing something about multiprocessing. I am new to this.
Comment: What does "banned from requesting" have to do with the code you've shown? My guess is that you're trying to implement some kind of web crawler. That's a different matter altogether. As a general rule (there will always be exceptions) use multiprocessing for CPU-intensive work and multithreading for I/O based operations (including web requests).
Comment: If you are rate-limited to one request every 60ms, you hardly need any multiprocessing, even straight Python should be able to do that, so I don't see what multiprocessing is buying you.
Comment: @LancelotduLac oh thank you. I actually did not know that. I will read a little bit more into multithreading. Is that also possible with the pythons multiprocessing or some other import?
Comment: @MarkSetchell just an example. Can be a lot faster than that, i just tried to make it simpler.
Answer: Pathos is a great library to do that (pip install pathos) using the processingPool(processlimit) method. Here is an example on how u could use a pool :
from pathos.multiprocessing import ProcessingPool as Pool
import time

start = time.perf_counter()

def function(arg):
    arg = arg + 5
    time.sleep(1)
    return arg

def main():
    argumentlist = [20, 136, 176, 228, 403, 433, 491, 543, 559, 575, 724, 760, 776, 792, 808, 860, 1035, 1051, 1067, 1083, 1177, 1193]

    pool = Pool(4) #the argument here is the number of processes you limit your pool to
    results = pool.map(function, argumentlist)
    for result in results:
        print(result)

    return results

if __name__ == '__main__':
    main()

    end = time.perf_counter()
    print(f"Finished in {round(end-start, 2)} second(s)")

That was concerning limiting the number of processes runing at a time. But in your case you would have to check the maximum number of request/hour authorised by the api you are using, create a break before that limit and continue were you left off after an amount of time.
If Retrieving the information requested takes a lot of time then multiprocessing isn't the right choice. You need to use multithreading.
Here is the tutorial that taught me how to use multithreading. I think you will be able to learn what you want to know from it
https://www.youtube.com/watch?v=IEEhzQoKtQU


Overcomplete matrix eigendecomposition

Question: I have something that looks similar to an eigenvalue decomposition, $$K = U^T \Sigma \, U$$ where $U \in \Bbb R^{d \times n}$ and the diagonal $\Sigma \in \Bbb R^{d \times d}$. Matrix $K$ is full rank and $U^TU = I_n$ is the identity in $\Bbb R^{n \times n}$. Oddly, $d$ is much larger than $n$, $d \gg n$. I would like to know the eigenvalue decomposition of $K$ efficiently. Are there any tricks to do it efficiently?
Comment: Does $\Sigma$ have positive diagonals?
Comment: Yes it does and K is positive semi definite
Answer: If $\Sigma$ is positive semi-definite, we may define the matrix $\Sigma$ as
$$
\Sigma = P^t \Gamma^2 P
$$
where $P$ is a permutation matrix and the $m \times m$ diagonal matrix $\Gamma^2$ is positive definite.  Then the matrix $K$ can be written in the form
$$
K = W^t \Gamma^2 W = (\Gamma W)^t (\Gamma W)
$$
where $m \le d$,
$$
W = PU = P_{11} U_1 + P_{12}U2
$$
$$
P = \left[ \begin{array}{cc}
       P_{11} & P_{12} \\
       P_{21} & P_{22}
     \end{array} \right] , \;\;\;
  U = \left[ \begin{array}{c}
       U_1 \\
        U_2
       \end{array} \right] .
$$
The matrix $W$ is an $m \times n$ matrix and $P_{11}$ is an $m \times m$ matrix.
The eigenvalues of the matrix $K$ are given by the singular values squared of the matrix $\Gamma W$. The corresponding eigenvectors are given by the right singular vectors of $\Gamma W$.
The SVD of $\Gamma W$ is usually computed in two steps:
Step 1: Compute the QR-factorization of $\Gamma W$:
$$ QR = \Gamma W
$$
where the $n \times n$ matrix $R$ is upper triangular. The matrix $Q$, which has orthonormal columns, is not explicitly computed. Only $R$ is required.
Step 2: Compute the  SVD of $R$,
$$
R = \Phi S \Psi^t
$$
where $\Phi^t \Phi = \Psi^t \Psi = I$ and $S$ is the singular value matrix. This can be done without explicitly computing $\Phi$. The required eigenvectors are given by $\Psi$. The eigenvalues of $K$ are given by the squares of the singular values.
The nominally expensive part is computing the SVD of $R$ but $R$ is a small $n \times n$ matrix and hence inexpensive.
If it is known that $m$ is nearly equal to $d$, then  the reduction using the permutational matrix can be skipped. In that case, we proceed by computing the $QR$-factorisation of $\Sigma^{\frac{1}{2}}U$ instead of $\Gamma W$.
Comment: First, you should compute eigenvalue decomposition of $K$, not the SVD. Secondly, the complexity of the QR-factorisation is O($m n^2$) . If $m<d$ then there is an advantage in doing the permutational reduction. With BLAS-3 operations, QR goes faster than the complexity indicates. Thirdly, since we are not forming the matrix $K$ explicitly and working with a Cholesky type factorisation, there is an accuracy improvement. Due to this "square-root" algorithm and we do not have a numerically damaging $A^tA$ or $AA^t$ type step. Finally, this algorithm works when $U$ is not an orthogonal matrix.
Comment: Thanks but I think you misunderstood the question. In the case I am interested in d is larger than n and hence I have an over complete decomposition. Naively I could orthognalise U but that would be as costly as performing regular svd.
Comment: Sorry for the misunderstanding your question. I have revised the answer.
Comment: Thanks @Vini for the detailed answer. However, is there any computational advantage to doing this over directly computing the svd of K, as the QR factorisation I assume will cost O(n^3)

Overcomplete matrix eigendecomposition


Canonical link in head of home page on Rails

Question: I'm trying to have a line in the head of my home page for my rails site.  This should be:
<link rel="canonical" href="http://negotiatus.com" />

On my personal dev copy of the site, it appears perfectly in the head of the home page.  However, on the production version of the site it does not.  I believe it has something to do with Rails precompiling stuff, but I could be wrong.
If someone could point me in the right direction here that would be great
Relevant part of the home view:
<% content_for :for_head do %>
<link rel="canonical" href="http://negotiatus.com" />
<% end %>

In my application.html.erb:
<% if content_for? :for_head %>
<%= yield :for_head %>
<% end %>

It shows up if I inspect the source of my local dev copy, but doesn't show up if I view the source of the production version (hosted on heroku).
Comment: Show your layout code.
Comment: done, added the relevant parts
Comment: Now it works... sorry to waste time
Answer: I retried precompiling everything, then committed and pushed everything again, now it works.
Sorry for wasting anyone's time.


Spring Boot loads component before its dependant bean

Question: I have a weird behavior in my project using Spring. I have this structure:
Main-Spring-Project
  |_Depends on Library A
     |_Depends on Library B

Now... there is an @Autowired in a component in A which injects a component which is in B.
When I have all 3 projects opened in my development environment and start de main project, everythin works fine. But if I remove the project A and leave B, it all crashes when starting saying:
Field factory in [class in A] required a bean of type '[class in B]' that could not be found.

so... I suspect it is loading A, before B.
What I don't understand is why it works perfect if I have both projects open, and why it crashes when I have A closed (main project is using its JAR)
By the way... if I remove A and B, everything works perfect again.
Comment: After removing project A try doing project (main) clean build and then deploy. It may be because of old references.
Comment: Make sure all these are under `@ComponentScan`
Comment: They are... and if they weren't, it wouldn't work with the source projects either
Answer: No Spring doesn't make a mistake during the context loading.
This behavior makes sense : the class is just not available at runtime.
Here you work with snapshot/current development source code/compiled classes of  library B since library B makes part of your current development code.
It means that  the dependencies/classes of library B needed during the run of the application doesn't depend on Maven for retrieving them but for what your IDE has access : the library A and B projects.
To avoid that you should install (mvn clean install) the B dependency in your local Maven/Gradle repository but that may be not practical if you need to repeat the task 20 days a day because the B source code changes 20 days a day.
Note that if you didn't use your IDE, you would be constraint to  install the dependency at each modification.   So finally, it is not so bad at all. No ?


Sums of complex numbers - proof in Rudin's book

Question: I have one question about a proof in Rudin's book:
If $z_1 ..., z_N$ are complex numbers then there is a subset $S$ of
$ \{1,..., N \}$ for which $|\sum_{k \in S} z_k| \ge \frac{1}{\pi} \sum_{1}^N |z_k|$
Proof:
Write $z_k = |z_k| e^{i \alpha_k}$.
For $\phi \in [- \pi, \pi] $ let  $\ \ S(\phi):= \{ k | \cos (\alpha_k - \phi)>0 \}$.
Then $|\sum _{S(\phi)} z_k| = |\sum_{S(\phi) } e^{-i \phi} z_k| \ge Re(\sum_{S(\phi) } e^{-i \phi} z_k) = \sum_1^N |z_k| \cos ^+ (\alpha_k - \phi) $.
Could you tell me why the two equations hold (the inequality is quite obvious) and what $\cos ^+$ stands for?
Answer: $\cos^+$ is the positive part of the cosine. Generally, for a real-valued function $f$, we have the positive and negative parts of $f$:
\begin{align}
f^+(x) &= \max \{ 0, f(x)\} = \begin{cases} f(x) &, f(x) \geqslant 0 \\ 0 &, f(x) < 0,\end{cases}\\
f^-(x) &= \max \{ 0, -f(x)\} = \begin{cases} -f(x) &, f(x) < 0 \\ 0 &, f(x) \geqslant 0. \end{cases}
\end{align}
Note that both, the psoitive part and the negative part are non-negative (somewhat confusing at first), and we have $f(x) = f^+(x) - f^-(x)$ as well as $\lvert f(x)\rvert = f^+(x) + f^-(x)$.
We have the first equality
$$\left\lvert \sum_{k\in S(\phi)} z_k\right\rvert = \left\lvert \sum_{k\in S(\phi)} e^{-i\phi}z_k\right\rvert$$
since $\lvert e^{-i\phi}\rvert = 1$, and every term in the sum is multiplied with the same factor, so that means the entire sum is multiplied with $e^{-i\phi}$, which has modulus $1$. Since $\lvert ab\rvert = \lvert a\rvert\cdot \lvert b\rvert$, multiplying with a number of modulus $1$ doesn't change the modulus.
The second equality comes from writing $z_k$ in polar form, so
$$e^{-i\phi}z_k = e^{-i\phi} \lvert z_k\rvert e^{i\alpha_k} = \lvert z_k\rvert e^{i(\alpha_k-\phi)},$$
and taking the real part gives
$$\operatorname{Re} \left(e^{-i\phi}z_k\right) = \lvert z_k\rvert\cos (\alpha_k-\phi).$$
Since for $k\in S(\phi)$ we have $\cos (\alpha_k-\phi) = \cos^+(\alpha_k-\phi)$, and $\cos^+(\alpha_k-\phi) = 0$ for $k\notin S(\phi)$, we have
$$\sum_{k\in S(\phi)} \lvert z_k\rvert \cos (\alpha_k-\phi) = \sum_{k\in S(\phi)} \lvert z_k\rvert \cos^+ (\alpha_k-\phi) = \sum_{k=1}^N  \lvert z_k\rvert \cos^+ (\alpha_k-\phi).$$


"vdpau-va-driver" has unmet dependencies on Ubuntu 16.04, any official resolution?

Question: Kodi 18.1 on almost all the TV channels lags. It wasn't lagging a year ago, when I checked on a given machine (default 16.04 install and it doesn't counts what quality does the video have, nothing else is running in the background).
Maybe I can see some vdpau-va-driver related issues:
user@asdf:~$ kodi
libva info: VA-API version 0.39.4
libva info: va_getDriverName() returns 0
libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/i965_drv_video.so
libva info: Found init function __vaDriverInit_0_39
libva error: /usr/lib/x86_64-linux-gnu/dri/i965_drv_video.so init failed
libva info: va_openDriver() returns -1
Failed to open VDPAU backend libvdpau_i965.so: cannot open shared object file: No such file or directory
user@asdf:~$

on package level:
root@asdf:~# apt-get install va-driver-all
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 va-driver-all : Depends: vdpau-va-driver but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
root@asdf:~#
root@asdf:~#
root@asdf:~#
root@asdf:~# apt-get install vdpau-va-driver
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 vdpau-va-driver : Depends: libva-driver-abi-0.39 or
                            libva-driver-abi-0.31 but it is not installable
E: Unable to correct problems, you have held broken packages.
root@asdf:~#
root@asdf:~#
root@asdf:~# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial
root@asdf:~#
root@asdf:~# apt-get dist-upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
root@asdf:~#
root@asdf:~#
root@asdf:~#
root@asdf:~# grep ^[a-z] /etc/apt/sources.list /etc/apt/sources.list.d/*
/etc/apt/sources.list:deb http://at.archive.ubuntu.com/ubuntu/ xenial main restricted
/etc/apt/sources.list:deb http://at.archive.ubuntu.com/ubuntu/ xenial-updates main restricted
/etc/apt/sources.list:deb http://at.archive.ubuntu.com/ubuntu/ xenial universe
/etc/apt/sources.list:deb http://at.archive.ubuntu.com/ubuntu/ xenial-updates universe
/etc/apt/sources.list:deb http://at.archive.ubuntu.com/ubuntu/ xenial multiverse
/etc/apt/sources.list:deb http://at.archive.ubuntu.com/ubuntu/ xenial-updates multiverse
/etc/apt/sources.list:deb http://at.archive.ubuntu.com/ubuntu/ xenial-backports main restricted universe multiverse
/etc/apt/sources.list:deb http://archive.canonical.com/ubuntu xenial partner
/etc/apt/sources.list:deb http://security.ubuntu.com/ubuntu xenial-security main restricted
/etc/apt/sources.list:deb http://security.ubuntu.com/ubuntu xenial-security universe
/etc/apt/sources.list:deb http://security.ubuntu.com/ubuntu xenial-security multiverse
/etc/apt/sources.list.d/intellinuxgraphics.list:deb https://download.01.org/gfx/ubuntu/16.04/main xenial main #Intel Graphics drivers
/etc/apt/sources.list.d/nodesource.list:deb https://deb.nodesource.com/node_8.x xenial main
/etc/apt/sources.list.d/nodesource.list:deb-src https://deb.nodesource.com/node_8.x xenial main
/etc/apt/sources.list.d/skype-stable.list:deb [arch=amd64] https://repo.skype.com/deb stable main
/etc/apt/sources.list.d/skype-stable.list.save:deb [arch=amd64] https://repo.skype.com/deb stable main
/etc/apt/sources.list.d/team-xbmc-ubuntu-ppa-xenial.list:deb http://ppa.launchpad.net/team-xbmc/ppa/ubuntu xenial main
root@asdf:~#

The question: how to resolve this dependency issue officially?
Already tried to use video driver updater via 01.org, but it stops because of the dependency issue. Dependency issue was there before the 01.org try too!
Google doesn't brings up any solution. Let's have one!
Comment: Please run `sudo apt update` (ensure that you do not have any error output here), and add output of `apt-cache policy va-driver-all mesa-va-drivers` to the question.
Answer: I encountered the same dependency conflict and investigated this a bit using the following commands

checking package dependencies

debian -> ubuntu -> xbmc (current policy)
use apt-cache depends va-driver-all (depends on)
use apt-cache rdepends va-driver-all (is dependency of)

show package installed

use apt-cache show libva1

Note: For the short version scroll to the bottom of this entry.
The following passage is created so that it may serve as a reference for how to use apt-cache apt-get to resolve dependency conflicts. This is by no means a complete guide and it was my first investigation of apt conflicts, so if I misused or missed something please leave a comment, I am happy to learn!
INVESTIGATION:
What was confusing to me was that in the reference here (for debian) the dependency is either mesa-va-driver or vdpau-va-driver. Since I am using ubuntu and requiring the ubuntu version of this package, I need the repository here (ubuntu). Somehow in the development process to ubuntu the dependency is only on the vdpau-va-driver. I have however already installed the mesa-va-driver, which apparently breaks vdpau-va-driver, if I interpret the subsequent apt-cache depends mesa-va-drivers output correctly.
Edit: Stumbled across a great resource from the archlinux wiki that summarises the video acceleration libraries neatly. see here
~ $ sudo apt-cache depends mesa-va-drivers
mesa-va-drivers
  Depends: libva1
  Depends: libc6
  Depends: libdrm-amdgpu1
  Depends: libdrm-nouveau2
  Depends: libdrm-radeon1
  Depends: libdrm2
  Depends: libelf1
  Depends: libexpat1
  Depends: libgcc1
  Depends: libllvm6.0
  Depends: libsensors4
  Depends: libstdc++6
  Depends: libx11-xcb1
  Depends: libxcb-dri2-0
  Depends: libxcb-dri3-0
  Depends: libxcb-present0
  Depends: libxcb-sync1
  Depends: libxcb-xfixes0
  Depends: libxcb1
  Depends: libxshmfence1
  Depends: zlib1g
  Breaks: vdpau-va-driver
  Replaces: vdpau-va-driver
  Enhances: libva1

The actual linked repository and its dependencies then can be seen using apt-cache policy vdpau-va-driver and is linked to the original ubuntu archive
sudo apt-cache depends vdpau-va-driver
vdpau-va-driver
  Depends: libc6
 |Depends: libgl1-mesa-glx
  Depends: <libgl1>
    libgl1-mesa-glx
  Depends: libvdpau1
  Depends: libx11-6
 |Depends: <libva-driver-abi-0.39>
  Depends: <libva-driver-abi-0.31>
  Enhances: libva1
~ $ sudo apt-cache policy vdpau-va-driver
vdpau-va-driver:
  Installed: (none)
  Candidate: 0.7.4-5
  Version table:
     0.7.4-5 500
        500 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages

Where the installation of vdpau-va-driver with sudo apt-get -o Debug::pkgProblemSolver=yes install vdpau-va-driver
~ $ sudo apt-get -o Debug::pkgProblemSolver=yes install vdpau-va-driver
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 vdpau-va-driver : Depends: libva-driver-abi-0.39 or
                            libva-driver-abi-0.31 but it is not installable
E: Unable to correct problems, you have held broken packages.

fails due to the missing libva-driver-abi-0.39.
Note: Here is libva-driver-abi-0.39 a virtual package of libva1 which I already have installed. The corresponding apt-cache policy libva1 output
~ $ apt-cache policy libva1
libva1:
  Installed: 1.7.3~xenial
  Candidate: 1.7.3~xenial
  Version table:
 *** 1.7.3~xenial 500
        500 http://ppa.launchpad.net/team-xbmc/ppa/ubuntu xenial/main amd64 Packages
        100 /var/lib/dpkg/status
     1.7.0-1ubuntu0.1 500
        500 http://archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages
     1.7.0-1 500
        500 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages

shows that I have installed libva1 for kodi using the manually to my apt source list added repository http://ppa.launchpad.net/team-xbmc/ppa/ubuntu xenial/main. see
So the available version vdpau-va-driver is linked to the archive ubuntu version of libva1, which is 1.7.0-1 while the kodi repository from team-xbmc has already version 1.7.3 from which it seems that the link of the vdpau-va-driver to the ubuntu archive version requires either the virtual package libva-driver-abi-0.31 or libva-driver-abi-0.39 from libva1 but the team-xbmc version seems not to provide it, or atleast my apt package manager can't find it.
In conclusion the policy output shows  the following chain
mesa-va-drivers (ubuntu)
libva1 (xbmc) -> va-driver-all (xbmc) -> vdpau-va-driver (ubuntu) -> libva-driver-abi-0.31 or - 0.39 (ubuntu) -> libva1 (ubuntu) -x-> libva1 installed (xbmc)
~ $ apt-cache policy mesa-va-drivers vdpau-va-driver va-driver-all libva1
mesa-va-drivers:
  Installed: 18.0.5-0ubuntu0~16.04.1
  Candidate: 18.0.5-0ubuntu0~16.04.1
  Version table:
 *** 18.0.5-0ubuntu0~16.04.1 500
        500 http://archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages
        100 /var/lib/dpkg/status
     11.2.0-1ubuntu2 500
        500 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages
vdpau-va-driver:
  Installed: (none)
  Candidate: 0.7.4-5
  Version table:
     0.7.4-5 500
        500 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages
va-driver-all:
  Installed: (none)
  Candidate: 1.7.3~xenial
  Version table:
     1.7.3~xenial 500
        500 http://ppa.launchpad.net/team-xbmc/ppa/ubuntu xenial/main amd64 Packages
     1.7.0-1ubuntu0.1 500
        500 http://archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages
     1.7.0-1 500
        500 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages
libva1:
  Installed: 1.7.3~xenial
  Candidate: 1.7.3~xenial
  Version table:
 *** 1.7.3~xenial 500
        500 http://ppa.launchpad.net/team-xbmc/ppa/ubuntu xenial/main amd64 Packages
        100 /var/lib/dpkg/status
     1.7.0-1ubuntu0.1 500
        500 http://archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages
     1.7.0-1 500
        500 http://archive.ubuntu.com/ubuntu xenial/universe amd64 Packages

I suspect that the xbmc repository http://ppa.launchpad.net/team-xbmc/ppa/ubuntu xenial/main causes some dependency conflicts or is missing the virtual package, but could also be the package manager and some misconfiguration locally.
DETERMINE DEPENDENCIES:
However with the following output of apt-cache rdepends va-driver-all the problem causing package can be investigated about what it actually affects on your system
~ $ apt-cache rdepends va-driver-all
va-driver-all
Reverse Depends:
 |libva1
 |libva1
 |libva1
~ $ apt-cache depends libva1
libva1
  Depends: libc6
  Breaks: vlc-nox
 |Recommends: va-driver-all
  Recommends: <va-driver>
    i965-va-driver
    mesa-va-drivers
    vdpau-va-driver

PACKAGE REMOVAL:
Here it shows that only libva1 wants this package va-driver-all but only as a recommend, meaning it should not break something or still work without it. Therefore removing the package is done using
sudo apt-get remove va-driver-all
TL/DR: The conclusion is to investigate the dependency and if nothing depends on the problem causing package removing it. See the last two command listings for how to investigate whether to remove it.


php - generate non linear urls

Question:
Update:
Ok.. I have read a lot of solutions...
Thank you so much everybody. I think I
will keep it simple and avoid the
encryption and just rely on two fields
matching in the database. I can keep
the id as it is (sequential) but add
for example a timestamp (with :
removed). Then I can put both through
the youtube style url generator...
leaving me with a really short, unique
and not easily guessed url. e.g
before the youtube url gen blah.com?id=10345&s=134025
after blah.com?id=H2s&s=tL2s
I log the unique views to each id anyway...
so I will record unsucessful ones too
and if a user hits 10 non matching
url's in an hour then I can block his
ip (I know a proxy will evade
this...but it makes it more
difficult).
What do you think?

This may sound like a bit of an odd question... what I am looking to achieve is a way to generate an id to be used in a url which can not be guessed or calculated. What I mean is it is not id=1, id=2...
I was looking at a youtube style script here. Which has a padding option, but the padding is so obvious with urls like wTTTa and b666o. I considered MD5 ing the id... but thats hardly foolproof and makes for rather long urls.
The solution must be url based (can't be cookie or session based) and before you panic and think that I am trying to work out a way to secure my admin page - i am not, its part of a game I am developing.
Comment: Maybe you should use a greater base than 16 (hexadecimal) like 64. That will decrease the length for MD5 values from 32 characters (4 bit/character) to only 22 characters (6 bit/character).
Answer: I would probably tackle this by getting a timestamp, then MD5'ing the stamp, and then running a substr() to get the last 4-8 characters (depending on your preference). Compare the ID that is generated with those that have already been created (with a simple MySQL table) to guarantee the ID's uniqueness.
You may also want to salt the timestamp with the ID, or with an MD5 of the ID to further increase its uniqueness.
Answer: What if you md5 the id and a random string
<code>$id = md5( $id . uniqid( mt_rand(), true ) );
</code>
That should make it unguessable.
Then check the database to see if that id exists.
<code>$db = mysql_connect('localhost', 'username', 'password');
mysql_select_db( 'table' );
$id = 223;

do {

    $unique_id = substr( md5( $id . uniqid( mt_rand(), true ) ), 0, 8 );
    $q = mysql_query( sprintf( "select id from ids where id='%s'", intval($unique_id) ) );
    $c = mysql_num_rows( $q );

} while ( $c > 0 );

echo $unique_id;
</code>
That's the only way to guarantee uniqueness, while limiting the number of characters in the id
Answer: What about Generating One-Time URLs with PHP?
Answer: Just use random() from this class,
https://gallery.svn.sourceforge.net/svnroot/gallery/trunk/eval/gx/kohana/kohana/helpers/text.php
It generates random strings in different format. You can just use that as ID. I use this on my URL,
<code>  random('distinct', 10)
</code>
Comment: Uniqueness is guaranteed by database. If duplicate key, we keep generating new ones. Our database has over 3 million records now and that logic hasn't been triggered yet.
Answer: If you want it to be unique, I think you're going to have to hash it in some way. You could concatenate a sequential id with some other identifier for the page (eg title).
Answer: what about using slugs?, we always replace IDs with slugs, so we have nicer URLs both for your users and search engines and also doesn't give away DB keys.
slugs are normalized and unique strings like the one on this very same question: "php-generate-non-linear-urls"
Answer: I'm not a PHP guy, but it sounds like you need a randomly generated GUID.
This could help but I'm not too sure of the complexity of the output.
Alternatively, you could try a random string generator if PHP has one, or you could roll your own using a random number generator. If you want to 100% guarantee its uniqueness, you would probably want a look-up table, or make it some expression of the current date/time in millis.
Answer: Take a look at create_guid() from SugarCRM.
It really create unique id's.
It's in include/utils.php (a round line 1300)
Answer: You need to generate an "unguessable key". If you generate 20 (or even 12 or so) characters of base64 characters, you should be just fine for most systems.
Work through the basic math to make sure you are comfortable with it. Given 64^20 possible keys, how long will it take a hacker to stumble upon a valid one? Well, how many can they guess per second, and how many will you have? Many sites use this technique to provide URLs.
Some advice on using these:

I would think about whether you can make these "temporary" in some way. Perhaps they only need to exist for a month, or a few months, and then need to be renewed by the creator?
I would recommend that you keep your regular IDs in your database, and add this as a second key that you can access records by. Internally use sequencial IDs, since that will be convenient, and only use the unguessable keys when generating and processing URLs.

You CAN use something like the links above:
http://www.oreillynet.com/pub/a/php/2002/12/05/one_time_URLs.html
(In Ruby and Java, there are libraries for this. I'm not sure about PHP. See http://api.rubyonrails.org/classes/ActiveSupport/SecureRandom.html.)

php - generate non linear urls


Including categorical features along with text in wordvec approach- Python

Question: My data has mix of text and categorical features. It looks like:
cr_id   description                  business type                       status
    1   More robust system required secured loan    system  rejected
    2   More robust system required secured loan    system  rejected
    3   grant access to all products    mortgage    system  rejected
    4   EDAP Scenario   secured loan    regulatory           accepted
    5   grant access to all products    secured loan    regulatory  accepted

Now on description column I am applying word2vec approach. As a result I get a trained vector of 300 columns. Now my question is how to include categorical features in the model too. I mean how to combine the output of word2vec and one-hot coded vectors as they are of different shape.Code used to form wordvec is:
def review_to_wordlist(review, remove_stopwords=False):
    """
    Convert a review to a list of words. Removal of stop words is optional.
    """
    # remove non-letters
    review_text = re.sub("[^a-zA-Z]"," ", review)

    # convert to lower case and split at whitespace
    words = review_text.lower().split()

    # remove stop words (false by default)
    if remove_stopwords:
        stops = set(stopwords.words("english"))
        words = [w for w in words if not w in stops]

    return words

def review_to_sentences(review, tokenizer, remove_stopwords=False):
    """
    Split review into list of sentences where each sentence is a list of words.
    Removal of stop words is optional.
    """
    # use the NLTK tokenizer to split the paragraph into sentences
    raw_sentences = tokenizer.tokenize(review.strip())

    # each sentence is furthermore split into words
    sentences = []
    for raw_sentence in raw_sentences:
        # If a sentence is empty, skip it
        if len(raw_sentence) > 0:
            sentences.append(review_to_wordlist(raw_sentence, remove_stopwords))

    return sentences

train_sentences = []  # Initialize an empty list of sentences
for review in data['description']:
    train_sentences += review_to_sentences(review, tokenizer)

model_name = 'train_model'
# Set values for various word2vec parameters
num_features = 300    # Word vector dimensionality
min_word_count = 3   # Minimum word count
num_workers = 3       # Number of threads to run in parallel
context = 10          # Context window size
downsampling = 1e-3   # Downsample setting for frequent words
print 1
if not os.path.exists(model_name):
    # Initialize and train the model (this will take some time)
    model = word2vec.Word2Vec(train_sentences, workers=num_workers, \
                size=num_features, min_count = min_word_count, \
                window = context, sample = downsampling)
    print 10
    # If you don't plan to train the model any further, calling
    # init_sims will make the model much more memory-efficient.
    model.init_sims(replace=True)

    # It can be helpful to create a meaningful model name and
    # save the model for later use. You can load it later using Word2Vec.load()
    model.save(model_name)
else:
    print 11
#     model = Word2Vec.load(model_name)
    model=KeyedVectors.load(model_name)

def make_feature_vec(words, model, num_features):
    """
    Average the word vectors for a set of words
    """
    feature_vec = np.zeros((num_features,),dtype="float32")  # pre-initialize (for speed)
    nwords = 0
    index2word_set = set(model.wv.index2word)  # words known to the model

    for word in words:
        if word in index2word_set:
            nwords = nwords + 1.
            feature_vec = np.add(feature_vec,model[word])

    feature_vec = np.divide(feature_vec, nwords)
    return feature_vec

def get_avg_feature_vecs(reviews, model, num_features):
    """
    Calculate average feature vectors for all reviews
    """
    counter = 0
    review_feature_vecs = np.zeros((len(reviews),num_features), dtype='float32')  # pre-initialize (for speed)

    for review in reviews:
        review_feature_vecs[counter] = make_feature_vec(review, model, num_features)
        counter = counter + 1
    return review_feature_vecs

clean_train_reviews = []
for review in data['description']:
    clean_train_reviews.append(review_to_wordlist(review, remove_stopwords=True))
trainDataVecs = get_avg_feature_vecs(clean_train_reviews, model, num_features)

Now I can use these traineddatavecs to any classifier for prediction of status. Now as stated above I am confused how to include/append the categorical fetaures such as type with the trainedDataVecs as they are of different shapes.
Edit: As required to understand the problem better, the trainedDatavecs looks like below:
array([[-0.02591809, -0.04678563, -0.0401891 , ..., -0.00907444,
        -0.02070936, -0.02332937],
       [ 0.00098296, -0.00293253,  0.04667222, ...,  0.00685261,
        -0.01234391, -0.03822058],
       [ 0.01843361, -0.01345504, -0.01359649, ..., -0.04710409,
         0.04892955,  0.02135875],
       ...,
       [ 0.0304883 ,  0.08515919,  0.01928426, ..., -0.00903708,
        -0.00333895,  0.07550056],
       [ 0.01843361, -0.01345504, -0.01359649, ..., -0.04710409,
         0.04892955,  0.02135875],
       [ 0.01843361, -0.01345504, -0.01359649, ..., -0.04710409,
         0.04892955,  0.02135875]], dtype=float32)

Its dimensions are (40, 300) and the input training data has dimension of (40,5). 300 columns are coming from the number of features argument.
Comment: How will you encode categorical data? Are you planning to use dummy columns?
Comment: yes one-hot encoding(dummy column) is the first thing which strikes my mind. Issue is as stated above how to create final attribute vector comprising both word2vec output and categorical data.
Comment: how about appending categorical attributes as plain words at the end of description and so you also end up learning representations for them
Comment: @vumaasha Not sure whether it would make sense. To be honest I also thought the same early on.
Comment: why do you think it wouldn't make sense? i would give it a try and see if it helps
Comment: Because these are two different columns. Just appending categorical variable to free text column would not carry any practical significance.
Answer: Looks like trainDataVecs is just a numpy matrix. You can generate the dummies and try concatenating them.
dummies = pd.get_dummies(df['business type']).iloc[:, 1:] # take n-1 columns
dummies = dummies.as_matrix()
X = np.concatenate((trainDataVecs, dummies), axis=1)

Dummify the columns
Create numpy matrix
Concatenate them by column axis

Note:
There might be a dimension issue. Please post how trainDataVecs will look like in that case and I can update to reflect.
Comment: Vivek I would post the sample later. But as far I remember the array has trained vector has dimensions of 20×300. Number of columns come from the fact that we have given number of features as 300.
Comment: I have provided the trainedDataVec output and its dimension. Please try if you can incorporate the same in your response.
Comment: @user2906657 can you try the code posted? It should be concatenating `40x300` to `40x(n-1)` where `n` is the number of categories you have in the categorical column


$\lim_{x \to 2} \frac{\cos{\left(\frac{\pi}{x}\right)}}{x-2}$ without using De L'Hospital

Question: $$\lim_{x \to 2} \frac{\cos{\left(\frac{\pi}{x}\right)}}{x-2}$$
This limit is supposed be found without L'Hospital's Rule, but I have not been able to get close to the answer using conjugates, squares, Pythagorean Identity, half angle formulas or Squeeze Theorem. For each attempt, I expected at least one of  the well-known limits $\lim_{x \to 0} \frac{\sin{x}}{x}$ or $\lim_{x \to 0} \frac{\cos{x} - 1}{x}$ to come into use. They frequently did in my attempts but did not go anywhere. I have also been experimented substitutions but in vain.
How can this be solved without using L'Hospital's Rule?
Comment: Someone did downvote all answers, but s/he forgot to do downvote the question $;)$.
Comment: @Nosrati: I am OP and I did not mark a single answer down, so please be more hesitant to pass judgement
Comment: I didn't say you are downwoter! I said that for fun dear. Anyway I did delete my answer. $:)$ @hanti
Comment: @hatinacat2000 Please recall that if the OP is solved you can evaluate to accept an answer among the given, more details [HERE](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)
Answer: By definition of derivative, if $f(x)=\cos\left(\frac\pi x\right)$, then$$\lim_{x\to2}\frac{\cos\left(\frac\pi x\right)}{x-2}=f'(2)=\frac\pi4.$$
Comment: intuition is a gift+
Comment: @StammeringMathematician I've edited my answer. Thank you.
Comment: Answer should be $\pi/4$.
Comment: IMO, using this trick is a little cheating. There is very little difference between $(f(x)-f(x_0))/(x-x_0)\to f'(x_0)$ and $(f(x)-f(x_0))/(x-x_0)\to f'(x_0)/1$.
Answer: As an alternative, without derivatives, we have that
$$ \frac{\cos{\left(\frac{\pi}{x}\right)}}{x-2}
= \frac{\frac{\pi}2-\frac{\pi}{x}}{x-2}\frac{\sin{\left(\frac{\pi}2-\frac{\pi}{x}\right)}}{\frac{\pi}2-\frac{\pi}{x}}
=\frac{\pi(x-2)}{2x(x-2)}\frac{\sin{\left(\frac{\pi}2-\frac{\pi}{x}\right)}}{\frac{\pi}2-\frac{\pi}{x}}=$$
$$=\frac{\pi}{2x}\frac{\sin{\left(\frac{\pi}2-\frac{\pi}{x}\right)}}{\frac{\pi}2-\frac{\pi}{x}}\to \frac{\pi}4\cdot 1 =\frac{\pi}4$$
Answer: This expression corresponds with the definition of the derivative. Recall that $$f'(x) = \lim\limits_{y\to x}\frac{f(y)-f(x)}{y-x}$$ Using the fact that $\cos\left(\frac{\pi}{2}\right) = 0$, this expression turns out to be the derivative of $\cos(\frac{\pi}{x})$ at $x = 2$.
EDIT: Sorry, used the wrong function.
Answer: With $\dfrac\pi x=\dfrac\pi2-t$,
$$\lim\limits_{x \to 2} \frac{\cos{\left(\dfrac{\pi}{x}\right)}}{x-2}=\lim\limits_{t \to 0}\frac{\pi-2t}4\frac{\sin{\left(t\right)}}{t}.$$
No need to say more.
Comment: Edit: success after more substitutions
Comment: Can you please show your work? I have tried your substitution but am not able to get this result. Also, how did you come up with this substitution?
Comment: @hatinacat2000: this is elementary algebra. And seeing the shape of the expression ($0/0$ with a trigonometric function), I understood that it could be turned to $\sin t/t$ by an appropriate transform.
Comment: I can get $\frac {sin {t}}{t} $, but not $(\pi - 2t)/4$


Does fishing in a different direction cause problems?

Question: I'm using an AFK fish farm and noticed that about over half the loot I get from fishing gets stuck behind a hopper (I'm using Panda's design, modified by Kabood). In my first farm, I fished East, and at least most of the loot I collected was collected by hoppers (I'm pretty sure all of it was collected, but I never did check to see if anything got stuck since it ran so smoothly). I had to move the farm, and now I fish South.
As earlier mentioned, about half the loot I collect never makes it to the hoppers; it gets stuck behind one of them. Since the old design worked pretty much perfectly, does fishing in a different direction affect how well I can fish? I'm on 1.11.2.
I am also 90% sure the design I currently have is the same to the old one. I did add some blocks on the side and lighting above the farm for decorative purposes.
The farm:

Where items get stuck:
Comment: Can you provide some images of your farm, as well as the original design? Also, what version of Minecraft are you playing?
Comment: Added the pics and version, but I don't have any pics of the original design.
Comment: Is that a fence post below the water?
Answer: Since AFK Fishing farms exploit glitched mechanics (i.e. the constant "non-casting" against certain objects), it's difficult to pin down exactly whether or not your facing (north, south, etc.) has anything to do with it, without extensive testing. From my experience however, I don't believe it is the case.
As for why the items are getting caught, I might suggest the place where you are standing could possibly have something to do with it. All of the AFK Fishing Farm designs I have seen, suggest standing with the water at head height. So try standing one block lower, and see if that has any effect.
My other suggestion is to replace the fencepost beneath the water. Fence posts are odd blocks; they have thinner, and taller hitboxes than normal blocks - it's 1.5 blocks tall, and .5 blocks wide, effectively creating an area wehere items can hit it and get knocked "off-course", as you can see from my very basic depiction here. The hit box for a normal block, vs a fence post.

I would suggest that unless it is absolutely essential, replace it with a normal block.
Comment: I replaced the cobblestone wall with an upside down half slab and so far everything is working perfectly :) I'll accept your answer if things continue to work as smoothly as they have been.


Mouse flickering on one monitor

Question: I've done quite a bit of googling to find a solution to this but couldn't find anything. I have two monitors, an LG one and a Samsung one and my mouse disappears and flickers on the Samsung one. Also I'm using a Logitech Preformance MX mouse. I just freshly installed the latest LTS version of Ubuntu. I have two Nvidia Gefore GTX470 graphics cards and one monitor is plugged into each of them. I heard about a fix with an Unknown monitor showing up in the display setting but I'm not seeing that. Any help is greatly appreciated.
Update: I've tried to change the drivers I've using, it's fixed the flickering but my second monitor is nolonger recognized. :(
Answer: The second GeForce card cannot be used to run a second monitor using the newer NVidia drivers (this has nothing to do with Ubuntu but with NVidia itself.)
There are ways around that, but they're all ugly (and complicated).
You can still use the secondary card using CUDA for video rendering, FPU computation, ...
Sorry to be the harbinger of bad news...

Mouse flickering on one monitor


Negation of uniqueness quantification in first-order logic

Question: I need to make the denial of the following logical expression, but it complicates the unique existence quantifier.
$$\exists !\; n \in \mathbb{N}, \forall \; m\in \mathbb{N} ; (m\cdot n)=m$$
Any contribution works.
Comment: $$\neg \exists !\; n \in \mathbb{N}, \forall \; m\in \mathbb{N} ; (m\cdot n)=m$$:P
Comment: I suspect Bram is only half joking....that is the best answer to the question you asked.  A joke might be "it isn't possible to negate a tautology, no matter what I do it is still true".
Comment: negate the equivalent expression that uses ordinary existential and universal quantification
Comment: The negation is: there exists 2 (differents) elements that hold the property or there is none element holding the property
Comment: Sure, means denying existence, or denying uniqueness.
Comment: I like the humor +1. It reminded me of the horseshoe principal for integrals @Bram28
Answer: The negation is: there exist 2 (different) elements that hold the property or there is none element holding the property, that is:
$$\big(\exists n_1,n_2\in\mathbb{N},n_1\neq n_2,\forall m\in\mathbb{N}: (m\cdot n_1)=m,\; (m\cdot n_2)=m\Big)\vee\big(\forall n\in\mathbb{N},\exists m\in\mathbb{N}: (m\cdot n)\neq m)\Big)$$
Comment: You should put the "or" inside the formula, otherwise it could be misunderstood and interpreted as an alternative answer.
Comment: following your suggestion @Taroccoesbrocco, to avoid misunderstood I edited my answer witting $\vee$ instead of $or$.
Comment: Thank you very much @yemino!
Comment: Thank's @Taroccoesbrocco
Answer: $$\exists !\; n \in \mathbb{N}, \forall \; m\in \mathbb{N} ; (m\cdot n)=m$$ is equivalent to
$$\exists \; n \in \mathbb{N},[ \forall \; m\in \mathbb{N} ; (m\cdot n)=m \; \wedge \neg\; \exists \;n'\in \mathbb{N}(\forall \; m\in \mathbb{N} ; (m\cdot n')=m \wedge n\neq n') ]$$
which is the same as
$$\exists \; n \in \mathbb{N},[ \forall \; m\in \mathbb{N} ; (m\cdot n)=m \; \wedge \forall \; n'\in \mathbb{N}(\forall \; m\in \mathbb{N} ; (m\cdot n')=m\implies n=n')]$$
equivalently
$$\exists \; n \in \mathbb{N} \; \forall\; n'  \in \mathbb{N}[\forall \; m\in \mathbb{N} ; (m\cdot n')=m\iff n=n']\tag {*}$$
Now if we negate this$(*)$, we get
$$ \forall\; n \in \mathbb{N} \;\; \exists\; n'\in \mathbb{N} \;[\forall \; m\in \mathbb{N} ; (m\cdot n')=m\iff n\neq n']$$
Comment: +1 I like how you derived this systematically!
Comment: Wow! Mercy @Leyla Alkan
Answer: Similar to Leyla's answer, but using a somewhat less confusing notation IMHO.
$\exists !\; n \in \mathbb{N}, \forall \; m\in \mathbb{N} ; (m\cdot n)=m$
is equivalent to:
$\exists n:[n\in \mathbb{N} \land \forall m:[m \in \mathbb{N} \implies m\cdot n=m]$
$\land \forall n':[n'\in \mathbb{N} \implies [\forall m:[m\in \mathbb{N}\implies m\cdot n' = m] \implies n'=n]]]$
The negation is:
$\forall n: [n\in \mathbb{N}\land \forall m:[m\in \mathbb{N} \implies m\cdot n=m]$
$\implies\exists n':[n'\in \mathbb{N}\land [\forall m:[m\in \mathbb{N} \implies m\cdot n'=m] \land n'\neq n]]]$


Do MassTransit or nServiceBus support MSMQ over HTTP transport?

Question: I understand it's available since MSMQ 3.0, is it available via any of the .NET ESBs?
Is this possible with other MQ transports (ActiveMQ, etc)?
Thanks,
E.
Answer: NServiceBus use msmq as its main transport but does not support the http option for Msmq.  Can you elaborate on what you're trying to achieve? Perhaps the NServiceBus gateway component is what you need?
http://docs.particular.net/nservicebus/gateway/
Hope this helps!
Comment: We expect some services, while still integral parts of overall system, to reside in physically dispersed locations, possibly behind firewalls (to be close to the resources they will work with).
Comment: Ok, then the gateway is definitely an option for you. Have you read the docs?
Comment: What about Mass Transit? Do you have any info on it?
Answer: MassTransit does not support MSMQ over HTTP in any way. RabbitMQ only requires a single port open for communication but it is not the HTTP (80 or 443) port.


Evaluating the limit: $\lim\limits_{x \to \infty} \sum\limits_{n=1}^{\infty} (-1)^{n-1}\frac{x^{2n-1}}{(2n)! \log (2n)}$

Question:
How to evaluate the limit:
  $$\lim\limits_{x \to \infty} \sum\limits_{n=1}^{\infty}  (-1)^{n-1}\frac{x^{2n-1}}{(2n)!\log (2n)}$$

I have tried to break the sum into even and odd $n$ and estimate each sum to be $\sim \frac{e^{x}}{\log (4x)}$ by estimating the summations in the range $\sum\limits_{x/c \le n \le cx} \frac{x^{4n}}{(4n+s)!\log (4n+s)}$ with the trivial bounds while $e^{-x}\sum\limits_{n > cx} \frac{x^{4n}}{(4n+s)!\log (4n+s)}$ and $e^{-x}\sum\limits_{0 \le n < x/c} \frac{x^{4n}}{(4n+s)!\log (4n+s)}$ both decay exponentially for arbitrary $c > 1$ as $x \to +\infty$ ($s=2,4$). The precise estimates I have used are similar to here.
However, I suppose stronger asymptotics will be required for calculating the limit of their difference. Any help/hint is appreciated. Thanks!
I am not much acquainted with the Laplace method or probabilistic interpretations (I'd appreciate it some references are mentioned, should the answer involve advanced tools like them.)

Machinato suggests that $f(z)=\sum_{n=2}^{\infty} \frac{(-1)^n z^{n-1}}{n! \log n}$ approaches $\log z$. This seems to be true! As evidence, here are plots of the real (red) and imaginary (blue) parts of $f(e^{2+i \theta})$, for $-\pi<\theta<\pi$. For comparison, the red and blue dashed lines are the real and imaginary parts of $\log z = 2+i \theta$. It's not clear from this image whether the limit holds for all $\theta$, but for $-\pi/2 < \theta < \pi/2$ the fit is very good.

I'm offering a bounty for a proof of this bizarre behavior. I imagine the precise formulation is that, for $\theta$ fixed in $(-\pi,\pi)$, we have $\lim_{R \to \infty} f(R e^{i \theta}) - \log R = i \theta$ but I'll certain accept other asymptotic results of a similar flavor. (For $\theta = \pi$, it is easy to see that $f(-R)$ grows faster than any power of $R$, so it can't mimic $\log R$.)
After some more experimentation, I suspect the limit only holds for $-\pi/2<\theta<\pi/2$. Here are plots of $\mathrm{Im}(f(r e^{i \theta}))$ for $\theta = \pi/3$ (first plot) and $2 \pi/3$ (second plot), with $0 < r < 10$. In each case, the dashed line is at $\theta$. Convergence looks great in the first one, terrible in the second.
Comment: My money is on $\frac{\pi}{2}$. It's just a guess from computing it for $x=  2000$ with $3000$ terms in the series and using $1000$ digits in the calculation. The result is $1.57066$
Comment: Tried it for $x=10^4$ for which it starts to become really slow as we need a precision of $\sim 4500$ digits in the calculation and we need to sum $\sim 14000$ terms before they start to become irrelevant. The sum here evaluates to $1.5707792 = 0.999989 \cdot \frac{\pi}{2}$.
Comment: I have strong numericel evidence that the complex function $$f(z)=\sum_{n=2}^{\infty}(-1)^n\frac{z^{n-1}}{n! \ln n}$$ behaves when $|z|\to \infty$ as $\ln z$. From this your original sum is just $$\lim_{x\to \infty} \mathrm{Im} f(ix) = \lim_{x\to \infty} \mathrm{Im} \ln(ix) = \frac{\pi}{2}$$
Comment: Here's a possible method of proof that could resolve this problem:

Define $$F(s,z)=\sum_{n=2}^{\infty}\frac{z^{n-1}n^{-s}}{n!\log n}.$$ Then we want to understand $F(0,z)$ for large $z$. Notice that $$F(s,z)=s\int_{2}^{\infty}\frac{x^{-s-1}}{\log x}\sum_{2\leq n\leq x}(-1)^{n}\frac{z^{n-1}}{n!}dx.$$ Letting $s=\frac{1}{z}$, the ranges of $x$ in the integral should be such that the sum over $n$ is approximately a truncated exponential. Hence $$F\left(\frac{1}{z},z\right)\approx \frac{e^{-z}+z-1}{z^2}\cdot \int_2^\infty \frac{x^{-1-1/z}}{\log x} dx.$$
Comment: The integral $$\int_2^{\infty} \frac{x^{-1-1/z}}{\log x} dx = \log z+O(1)$$ for $z$ large, by the techniques in this answer https://math.stackexchange.com/a/1584514/6075 and this answer https://math.stackexchange.com/a/1584507/6075 and so we expect as $z\rightarrow \infty$ the function $F\left(\frac{1}{z},z\right)$ will behave like $\log z$, and hence by Machinato's argument we get a final value of $\frac{\pi}{2}$ for the limit of the original integral.

With such an approach, there are a lot of technicalities that would need to be worked out exactly, but I think it has some hope of working.
Comment: Hm, I fact much challenge computing this numerically.  Very interesting series...
Comment: I was playing with the concept of writing it as a contour integral of $\frac{(-z)^{s-1}}{\Gamma(s)\log(s)(\cos(2\pi s)-1)}$, and then trying to take the contour the other way.  But I was working on this for too long and have to go back to work!
Comment: @Winther Cool! Any heuristics for that? :-)
Comment: I was worried about convergence issues with this approach, but I think maybe the cos will overcome the power in the numerator.  I would have to think about this more.  Also, the branch cut of the logarithm would probably be better chosen on the negative real axis.
Answer: EDITED. It suffices to prove the following claim.

Proposition. Assume that $f(z) = \sum_{n=2}^{\infty} a_n z^n$ has radius of convergence $R$ and define
$$ F(z)
= \sum_{n=2}^{\infty} \frac{n a_n}{n-1} z^n
= z \int_{0}^{z} \frac{f'(w)}{w} \, dw. $$
Then for all $|z| < R$, we have
$$ \sum_{n=2}^{\infty} \frac{a_n}{\log n} z^n
= \int_{0}^{1} \int_{0}^{\infty} \frac{t^{s-1}}{\Gamma(s)} F(z e^{-t}) \, dtds. $$

Proof. The proof is a straightforward computation:
\begin{align*}
\int_{0}^{1} \int_{0}^{\infty} \frac{t^{s-1}}{\Gamma(s)} F(z e^{-t}) \, dtds
&= \sum_{n=2}^{\infty} \frac{n a_n}{n-1} z^n \int_{0}^{1} \int_{0}^{\infty} \frac{t^{s-1}}{\Gamma(s)} e^{-nt} \, dtds \\
&= \sum_{n=2}^{\infty} \frac{n a_n}{n-1} z^n \int_{0}^{1} \frac{ds}{n^s} \\
&= \sum_{n=2}^{\infty} \frac{a_n}{\log n} z^n.
\end{align*}

In our case, we can set $f(z) = 1 - \cos z$ and consequently $F(z) = z \operatorname{Si}(z)$, where $\operatorname{Si}(z)$ is the sine integral. Then for real $x$, we have
\begin{align*}
\sum_{n=1}^{\infty} \frac{(-1)^{n-1}}{(2n)!\log(2n)} x^{2n-1}
&= \int_{0}^{1} \int_{0}^{\infty} \frac{t^{s-1}}{\Gamma(s)} e^{-t} \operatorname{Si}(x e^{-t}) \, dtds \\
&\hspace{3em} \xrightarrow[x\to\infty]{} \quad
\frac{\pi}{2} \int_{0}^{1}\int_{0}^{\infty} \frac{t^{s-1}}{\Gamma(s)} e^{-t} \, dtds
= \frac{\pi}{2}
\end{align*}
where the limiting procedure can be easily justified by the dominated convergence theorem.
Similarly, setting $f(z) = e^{-z} - 1 + z$ gives $F(z) = z (\log z + \gamma + \Gamma(0,z))$ for $\operatorname{Re}(z) > 0$, where $\Gamma(s, z)$ is the upper incomplete gamma function. Plugging this back, we obtain
$$ \sum_{n=2}^{\infty} \frac{(-1)^{n}}{n!\log n} z^{n-1}
= \log z + \gamma - \frac{1}{2} + \int_{0}^{1} \int_{0}^{\infty} \frac{t^{s-1}}{\Gamma(s)} e^{-t} \Gamma(0, z e^{-t}) \, dtds. $$
Note that the last integral vanishes if we let $z \to \infty$ along the cone $|\arg(z)| \leq \frac{\pi}{2} - \delta$. So this again confirms numerical observation made by Machinato.
Comment: May I ask the difference between $|\arg(z)|\le\frac\pi2-\delta$ and $|\arg(z)|<\frac\pi2$? If there is none, any reason for such a preference?
Comment: @SimplyBeautifulArt, To be honest, I do not know how the incomplete gamma function behaves if we do not impose Stolz angle condition. So I chose a safer way :)
Comment: =P Okay then. Was just curious.
Comment: If $t>0$, then $${\rm e}^{ - t} \Gamma (0,z{\rm e}^{ - t} ) = {\rm e}^{ - t} E_1 (z{\rm e}^{ - t} ) \sim z^{ - 1} \exp ( - z{\rm e}^{ - t} )
$$ as $z\to\infty$ and $\left| {\arg z} \right| \le \frac{3}{2}\pi  - \delta  < \frac{3}{2}\pi$.


How to boost speed for CI pipeline with bazel build and test?

Question: My CI pipeline has build and test stage using bazel, when the pipeline runs, bazel do full rebuild for build and test everytime. I want to boost speed of the pipeline, is there any idea?
I think if bazel has some options for setting different output directory for build and test, then build and test stage not affect each other, so it no need do full rebuild then. So is there some options for doing this?
Answer: If your CI has a persistent disk, you can use --disk_cache=/path/to/dir to keep state, even after clean builds and Bazel server shutdowns.
There is also support for remote caching over HTTP via on-prem machines or cloud solutions like Google Cloud Storage.
For even faster builds, especially for very large builds, Bazel has the ability to send build actions to remote machines via remote execution.

How to boost speed for CI pipeline with bazel build and test？