text:
Q: A countable open base implies that any open covering has a countable subcovering. Proposition: If metric space $M$ has a countable open base, then any open covering of $M$ admits a countable subcovering.
Definition: A collection of open subsets $\{U_i\}$ of $M$ is called an open base of $M$, if every of open set $O\subseteq M$ is expressible as $O=\bigcup_i U_i$.
Proof Attempt:
Let $\{\Omega_i\}_{i\in I}$, where $I$ is an arbitrary indexing set, be an open cover of $M$; that is $M \subseteq \bigcup_{i=1}^\infty \Omega_i$ and for all $i \in I$, $\Omega_i$ is an open set. First, we show that $\forall i\in I$, $\Omega_i \cap M$ is open relative to $M$. Let $x\in \Omega_i \cap M$, then there exists $\epsilon \gt 0$ such that $N_\epsilon (x)\subseteq \Omega_i$. But, if $N_\epsilon (x)\nsubseteq \Omega_i \cap M$, then it must be that there exists $n\in N_\epsilon (x)$ such that $n \notin M$. Relative to $M$, it does not affect whether $\Omega_i \cap M$ is open in $M$. What cannot be is $n \in M$ and $n \notin \Omega_i$. So, at any rate, $\Omega_i \cap M$ is open in $M$. Now, suppose $M$ has a countable open base $\{\mathscr{O}_k\}_{k=1}^\infty$. Thus, $\Omega_i \cap M=\bigcup_{k=1}^\infty \mathscr{O}_k$. Consider that $\{\Omega_i\cap M\cap\mathscr{O}_k\}_{k=1}^\infty$ is countable $\forall i \in I$, it covers $M$, and $\forall i\in I$, $\Omega_i\cap M\cap\mathscr{O}_k\subseteq\Omega_k$. Therefore, $\bigcup_{i=1}^\infty(\bigcup_{k=1}^\infty\Omega_i\cap M\cap\mathscr{O}_k)$ is a countable subcovering of an arbitrary open covering of $M$, because the union of countable set is countable.

A: I noticed some inaccuracies in your attempt that you should think about:

*

*You 'waste' a lot of time proving things related to relative open vs. open. This is not necessary here, since $M$ is the only metric space you are considering and everything happens inside $M$. In particular $\Omega_i \cap M = \Omega_i$ etc.

*Also
$$ \Omega_i \cap M=\bigcup_{k=1}^\infty \mathscr{O}_k $$ will not be correct in general, because the right side is equal to $M$.

*Moreover, $\{\Omega_i \cap M \cap \mathscr{O}_k\}_k$ does not cover $M$ but $\Omega_i$.

*You correctly noted in the beginning that $I$ is arbitrary, but in the end you index the $\Omega_i$ by $i \in \Bbb{N}$, in which case there was nothing to prove from the start.

*$\{\Omega_i \cap M \cap \mathscr{O}_k\}_{k,i}$ is not a subcover of $\{\Omega_i\}_i$ in general. Recall that a subcover of $\{\Omega_i\}_{i \in I}$ is of the form $\{\Omega_{l}\}_{l \in L}$ for some $L \subseteq I$.
A better way to proceed is to prove the following statements:

*

*Every $\Omega_i$ is the union of some of the $\{\mathscr{O}_k\}_k$, say $\Omega_i = \bigcup_{k \in J_i}\mathscr{O}_k$ where $J_i \subseteq \Bbb{N}$.

*The set $J = \bigcup_{i \in I} J_i$ is countable.

*The set $\{\Omega_{k} \:|\: k \in J\}$ is a countable cover of $M$.

*For each $k \in J$ there exists $i_k \in I$ such that $\mathscr{O}_{k} \subseteq \Omega_{i_k}$. Choose one $i_k$ for each $k \in J$.

*The set $\{\Omega_{i_k} \:|\: k \in J\}$ is a countable subcover of $\{\Omega_i\}_i$.


text:
Q: Unable to copy img using canvas I've a PNG captcha image and I want to create a duplicate so as to remove it's transparency because then the captcha resolver(ocrad.js) function works.
But the problem is that the following function is almost working properly but the captcha image gets moved and resized.
How to keep the captcha image's same dimension?
I've tried setting canvas width to same as that of img element, but does not work.
function copy(pic) {

    var canvas = document.createElement('canvas');

    var context = canvas.getContext('2d');

    context.fillStyle = '#fff';  /// set white fill style
    context.fillRect(0, 0, canvas.width, canvas.height);

    context.drawImage(pic, pic.width, pic.height);
    var dataURL = canvas.toDataURL();
    document.getElementById('cimage').src = dataURL;

    alert(OCRAD(document.getElementById('cimage'))); //decode it
}

So if I enter the following code in Google Chrome's Console on this page, you'll see that Captcha image(in the center) moves somewhere which is what I don't want:
pic = document.getElementById('cimage');
var canvas = document.createElement('canvas');

canvas.width = pic.width;
canvas.height = pic.height;

var context = canvas.getContext('2d');

context.fillStyle = '#fff';  /// set white fill style
context.fillRect(0, 0, canvas.width, canvas.height);

context.drawImage(pic, pic.width, pic.height);
var dataURL = canvas.toDataURL("image/jpeg");
document.getElementById('cimage').src = dataURL;

A: Set canvas element size before drawing the image. The element's default size is 300x150 pixels:
var canvas = document.createElement('canvas');
canvas.width = pic.width;
canvas.height = pic.height;

Additionally, you are using drawImage wrong - the two first arguments are for position, not size. As canvas is already the correct size using the code above, you just need to place the image at origin (0, 0):
context.drawImage(pic, 0, 0);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nested items control. But child item control should display based on specific condtion in wpf WPF: In Items control, I want to display another items control. But, I want to display the child items control values only for specific set of items of parent items control based on some conditions as shown in the image below. Please let me know, how can we do this.
Nested items control with specific condition
More details:
I've an items control, based on items in the items control; I will draw rectangular boxes in UI. I.e. each item in the items control represents one rectangular box and all these rectangular boxes are represented in sequence (one after the other in UI).
Now, I've one more collection of numbers (such as 10,20,30,40 etc.). These numbers I want to represent as time scale below particular consecutive rectangular boxes. i.e. Let's say, I've 10 items in my parent items control then there will be 10 rectangular boxes represented in the UI. Now, I want to represent one time scale at the bottom of 4th and 5th rectangular box only based on my parent item type (i.e. 4th and 5th box will have one common time scale from 10 to 100 (it's not independent time scale i.e. one horizontal line below 4th and 5th items i.e. horizontal line starts below 4th and ends below 5th Item. and this line shows values 10 to 100 in sequence)).
Similarly, I might need to represent the one more common time scale below 8th, 9th and 10th items only (i.e. this horizontal line starts with 10 and might end with value 200.).
This diagram explains details

A: The basic idea would be, to have a sub-collection with part of the items and common attached extra information instead of stretching the extra information over a range of items.
I suppose you have a viewmodel, holding your items. You can implement a collection of subitems and a single item with a common base class (ItemBase below)
public class ItemBase : BaseViewModel
{
}

public class SubItemCollection : ItemBase
{
    private IEnumerable<ItemBase> _SubItems;
    public IEnumerable<ItemBase> SubItems
    {
        get { return _SubItems; }
        set { _SubItems = value; NotifyPropertyChanged(); }
    }
    private string _CommonText;
    public string CommonText
    {
        get { return _CommonText; }
        set { _CommonText = value; NotifyPropertyChanged(); }
    }
}

public class LeafItem : ItemBase
{
    private string _Text;
    public string Text
    {
        get { return _Text; }
        set { _Text = value; NotifyPropertyChanged(); }
    }
}

I use BaseViewModel as a base class, where things like INotifyPropertyChanged are handled.
In your XAML, define a template for each item-type as a resource. For the collection type, display additional information below the items
<Window.Resources>
    <DataTemplate DataType="{x:Type local:LeafItem}">
        <Border Margin="3" Padding="3" BorderThickness="1" BorderBrush="Red" VerticalAlignment="Top">
            <TextBlock Text="{Binding Text}"/>
        </Border>
    </DataTemplate>

    <DataTemplate DataType="{x:Type local:SubItemCollection}">
        <StackPanel>
            <ItemsControl ItemsSource="{Binding SubItems}" BorderBrush="Green">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
            <Separator BorderBrush="Blue" BorderThickness="1"/>
            <TextBlock Text="{Binding CommonText}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

Finally, somewhere in your XAML, populate a list of ItemBase elements
    <ItemsControl ItemsSource="{Binding Items}" BorderBrush="Green">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <DockPanel LastChildFill="False"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

You can test this with the following data context:
public class MyViewModel : BaseViewModel
{
    private ItemBase _Items;
    public ItemBase Items
    {
        get { return _Items; }
        set { _Items = value; NotifyPropertyChanged(); }
    }
}

public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
        {
            data = new MyViewModel();
            data.Items = new ItemBase[]
            {
                new LeafItem()
                {
                    Text="Item 1"
                },
                new SubItemCollection()
                {
                    SubItems = new ItemBase[]{
                        new LeafItem()
                        {
                            Text="SubItems 2.1"
                        },
                        new LeafItem()
                        {
                            Text="SubItems 2.2"
                        }
                    },
                    CommonText = "Extra"
                },
                new LeafItem()
                {
                    Text="Item 3"
                }
            };
            DataContext = data;
        }
    }
// ...


text:
Q: Jenkins remote deploy I am trying to implement Jenkins for automating the deployment of a node application.
I am really new to this Jenkins setup. In my case, I have one server for Jenkins. I created a freestyle project in Jenkins and configured bitbucket and scm polling. It works perfectly.
But now Jenkins is deploying to the Jenkins server itself. But I need to deploy this to another remote server.
How to fix this?

A: To build jobs on remote host, you need to perform below steps:

*

*Add node:

*

*Manage Jenkins > Manage Nodes > New Node.

The next step is to set the node name and then you will be asked for remote server details.
After clicking the save button it should try to launch the slave machine.
Reference:
https://support.cloudbees.com/hc/en-us/articles/227834227-How-to-create-a-new-node-

*Mention newly created node into your job configuration:

*

*Set the "Restrict where this job can be run" check box in your job configuration and specify the name of your slave (which you have mentioned in step 1)


text:
Q: $\prod_{I=0}^{24} \frac{n- i - 1}{n - i}$ have closed form? I am evaluating the closed form of
$\prod_{I=0}^{24} \frac{n- i - 1}{n - i}$ where $n > 25 \in N$
I can see that I cam get closed form of this if I do multiplication 25 times. Yet, I would like to know whether it is possible to get the form by other ways.

A: Observe
\begin{align}
\frac{n-1}{n}\frac{n-2}{n-1}\cdots \frac{n-24}{n-23}\frac{n-25}{n-24} = \frac{n-25}{n}
\end{align}
or
\begin{align}
\prod^{24}_{i=0} \frac{n-i-1}{n-i} =&\ \exp\left(\sum^{24}_{i=0}\left[\log(n-i-1)-\log(n-i) \right] \right)\\
=&\ \exp\left(\log(n-25)-\log(n) \right)  = \frac{n-25}{n}
\end{align}
by Telescoping sum.

A: $$\begin{align}
\prod_{i=0}^{24}{n-i-1\over n-i}
&=\left(n-1\over n \right)\left(n-2\over n-1 \right)\left(n-3\over n-2 \right)\cdots\left(n-24\over n-23 \right)\left(n-25\over n-24 \right)\\
&={1\over n}\left(n-1\over n-1 \right)\left(n-2\over n-2 \right)\cdots\left(n-24\over n-24 \right)(n-25)\\
&={n-25\over n}\\
&=1-{25\over n}
\end{align}$$


text:
Q: htaccess and URL rewriting I have a list of URLs such as,
http://www.mywebsite.com/page.php?genus=A_GENUS&species=A_SPECIES&id=12345.
I would like to write a .htaccess which permanently redirects visits to this form of URL to the following URL,
http://www.mywebsite.com/species/A_GENUS/A_SPECIES.
Is it possible to do this without having to manually list each species in the database?
I've tried to look it up but my head is in WordPress-Custom-Post-Type land and as such my brain isn't functioning properly. Any help would be greatly appreciated.
EDIT: Clarification
Currently my .htaccess is completely empty. I am re-writing my website to use an entirely new CMS and this new URL format. The old URL format will cease to exist but all of the information will still be used.
We are quite highly ranked for a lot of species on Google and I would like visitors from there to be able to view the information they require despite the URL format changing.
These changes haven't occurred yet (still using a Sandbox environment for the new version of the site) and I'd like to make the URL changes just before I "go live" with the new version.
EDIT 2: New site .htaccess
The contents of the new site's .htaccess looks like this in its entirety:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sandboxfolder/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /sandboxfolder/index.php [L]
</IfModule>

# END WordPress

EDIT for Garmen's answer
RewriteEngine On
RewriteBase /sandboxfolder/
RewriteCond %{QUERY_STRING} genus=([a-zA-Z0-9-]+)&species=([a-zA-Z0-9-]+)
RewriteRule ^profile.php$ /species/%1/%2 [R=302]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /sandboxfolder/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /sandboxfolder/index.php [L]
</IfModule>
# END WordPress

Not sure if I've used RewriteBase correctly there, but it doesn't appear to function with or without it.
Regards,

A: RewriteEngine On
RewriteCond %{QUERY_STRING} genus=([a-zA-Z0-9-]+)&species=([a-zA-Z0-9-]+)
RewriteRule ^page.php$ /species/%1/%2? [L,R=302]

This one assumes a very specific order of query string parameters. So be warned. Also it assumes the names only contains plain letters, numbers, or dashes.
Change 302 to 301 when you are done testing. I used 302 because 301's are aggressively cached by browsers, making debugging very difficult.
EDIT: You should add this above the other rewrite rules you have, or it will not work.
EDIT 2: added a ? at the end to remove the querystring. And L flag to prevent further execution.


text:
Q: problem with kb4011645 and how to uninstall this patch today I've installed KB4011645 update for SharePoint Server 2016. And now I regret it and wants that update to be removed. Could someone here know how to do that? According to this SharePoint Server 2013 – Can you uninstall patches?, you can't do it.
Why I wants this patch to be removed. This patch made me unable to open any docx from SharePoint library.
Before this patch I was able to open it.
Edited to Add more information on the problem
I've written my problem to msdn. Here's the problem and summary.

*

*The problem still exist even after running SP configuration wizard (see point 2nd).

*the problem didn't appear after doing iisreset. Word asked for credential to open the document.

*but if I closed word and reopened the same document, It failed again. And this time it didn't ask for credential.

*checking on fiddler log, it did receive 401.

A: You cannot uninstall sharepoint patch. Only way to deal with that is to have full VM and DB backup to restore to point in time before the update.
Please note that running psconfig is necessary after the CU Upgrade. Always run it using the Gui as per Stefan Grossner recommendation: https://blogs.technet.microsoft.com/stefan_gossner/2015/08/20/why-i-prefer-psconfigui-exe-over-psconfig-exe/

A: The problem got resolve after I did Reset Internet Explorer Settings and also checked Delete personal settings under Internet Options Advanced tab and restart windows.
I guest I must had made something wrong in setting the internet options and those patch made it even worst or better.
reference thread: https://social.technet.microsoft.com/Forums/office/en-US/3670082d-c7b2-44cb-9ee4-180e88c3f2dc/microsoft-word-error-when-trying-to-open-a-document-in-sharepoint-2013-could-not-open?forum=sharepointgeneral#f20772f5-26ad-4971-bf04-cc91ce122784


text:
Q: How to run QT platform plugin on windows I use Anaconda3 5.2.0 and jupyter notebook(python3)(Window10)
I made a file through 'pyinstaller'.
But when I play file that I made, It has some Error.\
there are qwindows, qoffscreen, qminimal, qdirect2d .dall in platforms folder
=============================================================================
qt.qpa.plugin: Could not load the Qt platform plugin "windows" in "" even though it was found.
This application failed to start because no Qt platform plugin could be initialized.
Reinstalling the application may fix this problem.
Available platform plugins are: minimal, offscreen, windows.
===========================================================================
The list that I tried

*

*conda update qt

*Copy
Anaconda3\Library\plugins\platforms
folder to
Anaconda3

*reinstall Anaconda3

*reinstall PyQt5

A: I had a similar problem. With Anaconda, you need to bundle the platforms directory with your frozen application. I do it as follows:

def get_include_files():
    file_list = []
    d = os.path.abspath('C:\Anaconda2\envs\py3k\Library\plugins\platforms') #You need to change this
    file_list.append(d)
    #file_list.append('images')
    return file_list

Then in setup.py, just add these files as follows:

'build_exe': {
  'include_files': get_include_files()
 },


text:
Q: Possible to pass a non-void function pointer as a void function pointer? Say I have a function foo() which accepts a pointer to a void function as a parameter.
void foo(void (*bar)(int)) {
    bar(5);
}

If I have a non-void function f(int)
bool f(int i) {
    // ...
    return true;
}

Is there a way to cast f in such a way that it can be passed to foo() without warnings?
My current solution is to define a function void g(int i) {f(i);} and pass g to foo, but this seems inefficient to me.  It seems like there should be a way to cast f in such a way that its return value is thrown out.
If this isn't possible, why not?

A: Sorry if I'm missing the point, but this compiles without warnings with gcc, even with -Wall:
typedef void (*p_bar) (int);

void foo (p_bar bar)
  {
  bar(5);
  }

int f (int i)
  {
  printf ("In f(), arg=%d\n", i);
  return 1;
  }

int main()
  {
  foo ((p_bar)f);
  }

I can see why this is a suspicious cast but, in fact, I suspect that it will work fine for integers on most modern compilers. Integers are nearly always returned in a register.
But, as I say, maybe I'm missing something.


text:
Q: Postman pre-request script: Can't access header from response I am writing the following pre-request Script to get my JWT for authentication:
pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err, res, typeof res);
    if(err === null){
        console.log(res.header)
        // var authHeader = res.header.find(v => {v.key === 'Authorization'})
    }
});

This is what the console output currently looks like:
null, {id: "4ba2b741-316e-454d-b896-eab3aef74ae2", status: "OK", code: 200…}, object
undefined
OK

// If you enlarge the opbject it looks like the following:

id: "4ba2b741-316e-454d-b896-eab3aef74ae2"
status: "OK"
code: 200
header: [10] <--- There are my headers ?!
stream: {…}
cookie: [0]
responseTime: 121
responseSize: 0

The problem is I can not access the header array the script always tells me it is undefined, same if I try the access the cookie array. But I can access every other single property, maybe it's because header and cookie are arrays? I don't know. Any ideas what I am doing wrong and how I can get my Authorization header?

A: I think the Problem must be a bug, my workaround is to stringify and parse the object as json, than the headers are accessible.
r = JSON.parse(JSON.stringify(res))


text:
Q: String casting and Unicode in golang I am reading Go Essentials:

String in Go is an immutable sequence of bytes (8-bit byte values)
This is different than languages like Python, C#, Java or Swift where
strings are Unicode.

I am playing around with following code:
s := "日本語"
b :=[]byte{0xe6, 0x97, 0xa5, 0xe6, 0x9c, 0xac, 0xe8, 0xaa, 0x9e}
fmt.Println(string(b) == s) // true

for i, runeChar := range b {
    fmt.Printf("byte position %d: %#U\n", i, runeChar)
}

//byte position 0: U+00E6 'æ'
//byte position 1: U+0097
//byte position 2: U+00A5 '¥'
//byte position 3: U+00E6 'æ'
//byte position 4: U+009C
//byte position 5: U+00AC '¬'
//byte position 6: U+00E8 'è'
//byte position 7: U+00AA 'ª'
//byte position 8: U+009E

for i, runeChar := range string(b) {
    fmt.Printf("byte position %d: %#U\n", i, runeChar)
}

//byte position 0: U+65E5 '日'
//byte position 3: U+672C '本'
//byte position 6: U+8A9E '語'

Questions:

*

*From where does Golang get Unicode for encoding byte array when custing to string? How does rune form? Does Golang compiler get Unicode from text file encoding during compilation?

*What are advantages and disadvantages of implementing String like a byte array, instead of utf-16 chars array like in Java?

A: You are quoting from a weak, unreliable source: Go Essentials: Strings. Amongst other things, there is no mention of Unicode codepoints or UTF-8 encoding.

For example,
package main

import "fmt"

func main() {
    s := "日本語"
    fmt.Printf("Glyph:             %q\n", s)
    fmt.Printf("UTF-8:             [% x]\n", []byte(s))
    fmt.Printf("Unicode codepoint: %U\n", []rune(s))
}

Playground: https://play.golang.org/p/iaYd80Ocitg
Output:
Glyph:             "日本語"
UTF-8:             [e6 97 a5 e6 9c ac e8 aa 9e]
Unicode codepoint: [U+65E5 U+672C U+8A9E]

References:
The Go Blog: Strings, bytes, runes and characters in Go
The Go Programming Language Specification
Unicode FAQ: UTF-8, UTF-16, UTF-32 & BOM
The Unicode Consortium


text:
Q: Boot disk not found - can this be a software issue? I have an Acer Aspire laptop, and I installed a new SSD. It worked with no issues, at which point I installed Windows 8, and started getting boot messages of media test failure, check cable and No bootable device -- insert boot disk and press any key.
I thought maybe it was a software problem, like Windows 8 hosed the machine. However, after awhile, I tried again, and it booted perfectly. It would give me the boot error maybe 10-12 times in a row, then it would successfully boot, and run without issue. I've since installed Windows 10, and the machine has the same exact issues.
When I open the BIOS, most of the time it doesn't even recognize that there is a hard disk.
My assumption was that there was a problem with the disk, or the disk cable, or the connection. I took it to Frys Electronics, and they say everything is physically fine - it passed diagnostics everywhere. They think it's a software issue, and are talking about refreshing the OS.
I think they're full of it, but is there any way that what I'm describing could be a software issue? I'm considering just buying a new SSD since they're cheap, but I'd like to go through free options first...

A: The "no bootable device" failure has always historically indicated whether or not the system found a disk with a bootable partition present.
At boot, the BIOS will obtain a record of all devices that could potentially contain bootable media. It will go through this list in a particular order, and once it finds one containing a Master Boot Record (MBR) partition with bootable code, it loads it and starts executing it, eventually loading the operating system or whatever other software you might be running.
There are multiple reasons why you might get the error you are seeing, though:
You have a faulty connection to the drive and/or it is underpowered.
This could happen if your SATA cable is faulty or has a loose connection, either to the motherboard or the drive itself. It could also be that the drive is underpowered or not powered at all. Check all connections between the drive and the motherboard and PSU. Ensure that connections are tight and that cables aren't kinked or stretched. Try different SATA and power cables to see if there's any difference.
You have a faulty SATA port on the motherboard.
These headers are soldered onto motherboards and can experience strain or stress as you dig around inside of it. You might put strain on a cable and pull it such that the soldering cracks or breaks. The electric connection between the contacts could still occur, but it will be unreliable, as moving the device around, or atmospheric conditions, could change the conductivity of the space between them (or how large it is). If there are other SATA ports available, try switching to one of those. Chances are at least one of them will work. If not, either they are all broken or are all working fine and the reason for your problem lies elsewhere.
You have some buildup of dust.
I've seen dust do all sorts of strange and mysterious things to computers. It carries static, and can interfere with the electronics inside a computer. Anything is on the table when dust is involved. Give it a good shot of compressed air and see if anything changes. It doesn't even have to be particularly dusty or visible to still have an effect.
The drive is actually faulty.
It seems you've ruled it out, already. But it's good to ensure that the drive actually responds to reads and writes correctly. This is the only reason that can be detected by testing the disk, physically. Everything else can happen regardless of the physical health of the device.
There is a misconfiguration in the BIOS.
The BIOS is software, and can be configured. It has to know how to talk to the onboard devices and where to look for bootable partitions. You can often configure the list of where it looks for a bootable device, and the order. Only until it checks the whole list will it report the error you're seeing. Make sure that it's actually trying to boot from your SSD at all. And make sure that the BIOS settings are persisting between boots. (If they are not persisting, you might have a faulty motherboard or may need to replace the CMOS battery, if you have one.)
Additionally, you should make sure that whichever mode the BIOS is accessing the drive in (RAID, AHCI, PCI, etc) is the same mode that was set when installing the operating system. Usually computers are shipped with AHCI as the default. If you change this setting, oftentimes the computer will fail to boot properly. Additionally, if you're in RAID mode, you might need to run a separate configuration to set up your RAID volumes. (I suspect this isn't the issue if it's a laptop.)
The operating system installation could be hosed.
Pretty simply, if the operating system wasn't installed properly, or someone tried to reconfigure it and messed up, the operating system just would fail to load. Since it isn't finding a bootable device at all, it's possible that the MBR could have been damaged itself. If the operating system's files became corrupted, but the MBR was loaded just fine, you would likely see an OS-level error, rather than your BIOS-level message.
Addendum:
I wrote this from the perspective of building a desktop computer, but laptops also apply. They have a different form factor, but the general principles all still apply. Given your issue is intermittent, I'm leaning more towards a loose/faulty SATA connection (port or cable), power, or a faulty drive. I don't know what Fry's does to test, but often I suspect places like that do a bare minimum or just brute-force, opting to reinstall the OS if it's any more complicated than a simple fix, or just replacing the device completely. I've seen one shop (not Fry's) even do a simple test by plugging a drive into an existing computer and seeing if it was detected by Windows by showing up in My Computer (a horribly limited test method). SMART tests are also not reliable methods in cases of drive failure. It will catch some reasons but not all.

A: Sounds like an intermittent hardware problem.  As Ben suggested.  Since it's a laptop you can't really test with a new SATA cable and port on the board.  As a guess I'd say that the SSD has failed.  As easy test would be to swap in the old drive, or use a linux live CD and see if it's mountable.

A: Did you just upgrade the OS to a new higher OS? If do, then better to refresh your operating system by reformatting first, then install new OS, deep reformat will be better.


text:
Q: Spring WS - generate documentation like .NET webservices There are any way to generate a documentation page for my spring webservices?
This can be like .NET does in his defaults asmx pages ou another way if exists.


text:
Q: Why is WebView blocking my ExpandableListView's expansion? I've been working with ExpandableListViews before and I know about checkBoxes, Buttons, etc.
It is essential to setFocusable to false for any of these widgets that could be found on the XML that will serve as a groupView of our list, othervise, clicking on the group cell will not expand the group, since these widgets will steal focus from it.
BUT, If I put WebView in my GroupView, and setFocusable & setFocusableInTouchMode to false, I will still NOT be able to expand the group.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="91dp"
android:background="#ffffff">

<ImageView
    android:layout_width="30dp"
    android:layout_height="91dp"
    android:id="@+id/sth_cell_img_correct"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/icon_checked" />

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginRight="20dp"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:id="@+id/webView2" />

</LinearLayout>

But, if I remove WebView from the XML, I can expand / shrink cells with no trouble whatsoever.
There must be some other thing I should do here.
Som other attribute should be set to false, or something like that, but I cannot figure out what exactly.
Does anyone has a clue ?


text:
Q: Get data from different collections (.files , .chunks and master data) in MongoDB I am trying to upload the user details along with picture in the mongoDB using GridFS and multer. I need to get the data along with all the pictures to be displayed in the tabular form in client side(using angular).
The problem is the picture is getting stored in user.files and user.chunk collections, where as the other data like userID, userDesignation, userName is stored in user collection. How could I retrieve the data from both the collections in one GET userData API?
there is a option for merge the data using $lookup but that needs to have a common key in both the collections, whereas in my case there is common key.


text:
Q: Computer algebra errors In the course of doing mathematics, I make extensive use of computer-based calculations. There's one CAS that I use mostly, even though I occasionally come across out-and-out wrong answers.
After googling around a bit, I am unable to find a list of such bugs. Having such a list would help us remain skeptical and help our students become skeptical. So here's the question:
What are some mathematical bugs in computer algebra systems?
Please include a specific version of the software that has the bug. Please note that I'm not asking for bad design decisions, and I'm not asking for a discussion of the relative merits of different CAS's.

A: Analytical Number Theoretic Functions in Mathematica are (sometimes) unreliable.

*

*http://fredrik-j.blogspot.com/2010/01/zeta-evaluation-with-riemann-siegel.html

*http://fredrik-j.blogspot.com/2009/08/torture-testing-special-functions.html

*http://fredrik-j.blogspot.com/2009/07/another-mathematica-bug.html

*http://fredrik-j.blogspot.com/2009/06/meijer-g-more-hypergeometric-functions.html
https://code.google.com/archive/p/mpmath/ is part of Sage --- https://www.sagemath.org/ --- hence you can double check Mathematica values there.
(sorry, I'm not allowed to post hyperlinks...)

A: This might get fixed in the future, but at the time of this writing, Wolfram Alpha gets apparently sometimes confused by logarithms of complex numbers:
Wolfram Alpha -- $\log(1+ \frac{1}{2}i) - \log(1 - \frac{1}{2} i)$
For reference, should the problem get fixed: it claims that
$2i = 2i\cot^{-1}(2) \approx 0.9272$.
Curiously, the numerical approximation is correct, but the symbolic form seems to be wrong.

A: In 1999, when I first bought an HP49G, whose major selling point was a CAS, I thought I'd try summing the harmonic series $\sum_{n=1}^\infty \frac{1}{n}$.  I was a bit surprised to see the result 1151.8697216.
Now, I wouldn't have been too surprised if it had handled an infinite sum by just adding up "a lot" of terms until the partial sums seemed to be converging, but knowing how slowly the harmonic series grows, it wasn't plausible that it could have actually summed enough terms to get to 1151.8697216.
It turned out that it knew how to numerically compute the discrete antiderivative $\Psi(m) := \sum_{n=1}^m \frac{1}{n} \approx \ln m + \gamma$, and in the particular mode that it happened to be in, it would replace $\infty$ with the largest floating-point number it could represent, which was just under $10^{500}$.  Indeed, $\Psi(10^{500}) \approx 500\ln 10 + \gamma \approx 1151.8697216$.
The story has a happy ending: after changing some flags, it returned $+\infty$.

A: If you are performing numerical computations, then a more likely source of error is in roundoff or over/underflow. In these cases, I wouldn't say that the CAS is necessarily in the wrong, just that you need to know the properties of the underlying algorithm and either recast your input or reimplement it in a more numerically robust way. In such cases, decent introductions to numerical analysis should give you a feel for the types of issues you need to worry about.
Of course, on the matter of symbolics, then there are no excuses for errors.

A: A bug, this time from MATLAB. While trying to obtain:
$$\int_0^a x^2\sqrt{-x^2+ax}\,\mathrm{d}x=5a^4\pi/128$$
through:
syms x a
assume(a>=0)
int(x^2*sqrt(-x^2+a*x),x)

MATLAB get unfocused between the imaginary algebra and gets the negative value (!):
$$-5a^4\pi/128$$
Original question in here. Tested in MATLAB R2014b at 2017-05-16.
Edit: Present in R2018a, it was already corrected in R2018b.

A: (I haven't sufficient points to post a comment to Leonid Kovalev's reply.)
The problem in the numerical integration example is that numerical integration in Maple is done using Int, not int.  The correct command should be
evalf(Int(sin(x)^44,x=0..sqrt(44)));
which should produce consistent results (and much more quickly).

A: Here's one I came across just now, in Maple 12.  The code
with(combinat):
F := fibonacci:
phi := (1+sqrt(5))/2:
G := k -> F(k+1)/phi^k;
limit(G(n), n=infinity);

returns 0.  But from the usual explicit formula for the Fibonacci numbers, which gives $F(n) \sim \phi^n/\sqrt{5}$, the output should be $\phi/\sqrt{5}$, or $(5+\sqrt{5})/10$.   Replacing  the built-in Fibonacci function with one that gives the explicit formula, and running the code
F := n -> 1/sqrt(5)*(((1+sqrt(5))/2)^n-((1-sqrt(5))/2)^n);
phi := (1+sqrt(5))/2:
G := k -> F(k+1)/phi^k;
limit(G(n), n=infinity);

gives the correct answer.  I've encountered things like this fairly frequently when using the built-in routine for Fibonacci numbers; presumably this routine doesn't "know" the asymptotics.

A: Just found this in Mathematica 7.0 for Mac OS X x86 (64-bit) (November 11, 2008):
x=Exp[Pi Sqrt[163] ];
N[x-Round[x] ]
N[x-Floor[x] ]
N[x-Ceiling[x] ]
N[x - Round[x], 2]
N[x - Floor[x], 2]
N[x - Ceiling[x], 2]

The functions Round, Floor, and Ceiling are the obvious functions, while "N" converts the infinite-precision expression to a floating point number (the last three lines are aimed at 2-digit precision, while the first three should be 16-digit).
The first three calculations turn up as "-480." The last three give more correct values of -$7.5*10^{-13}, 1.0, -7.5*10^{-13}$.

A: Here are some results where different CAS give conflicting results:

*

*$\int_{y}^{\infty} \frac{e^{-x}}{x}{d x}$ for $y \in \mathbb{R}$ and $y>0$.
Wolfram Alpha gives $$\log{y}+\Gamma(0,y)$$
and sage 4.7.1 gives $$ -{\rm Ei}\left(-y\right) $$

*For all integers $n$, Coq proves $$n \mod 0 \equiv 0$$ and Isabelle (Wayback Machine) proves $$n \mod 0 \equiv n$$ (The proofs are just stated in theorems, I can give the exact theorems if needed). Interesting, both proofs doesn't seem to lead to inconsistency though AFAICT they depict the usual mod.
[Added] I am a fan of sage, but this bug annoyed me.
sage 4.7.2 incorrectly reports the girth of a 7 vertex graph:
H=Graph([(0, 1), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 6), (2, 5), (3, 4), (5, 6)])
H.girth()
4
H.is_triangle_free()
False

sage 4.3 and 4.6.2 return correct value.
sage session in the notebook and a plot of the graph

A: David Bailey and Jonathan Borwein said in a talk yesterday that the most recent editions of both Maple and Mathematica give the nonsensical result $$\int_0^1\int_0^1|e^{2\pi ix}+e^{2\pi iy}|\,dx\,dy=0$$ I later verified this for Maple 17, entering int(int(abs(exp(2*Pi*I*x)+exp(2*Pi*I*y)),x=0..1),y=0..1).

A: Because the most popular systems are all commercial, they tend to guard their bug database rather closely -- making them public would seriously cut their sales.  For example, for the open source project Sage (which is quite young), you can get a list of all the known bugs from this page.  1582 known issues on Feb.16th 2010 (which includes feature requests, problems with documentation, etc).
That is an order of magnitude less than the commercial systems.  And it's not because it is better, it is because it is younger and smaller.  It might be better, but until SAGE does a lot of analysis (about 40% of CAS bugs are there) and a fancy user interface (another 40%), it is too hard to compare.
I once ran a graduate course whose core topic was studying the fundamental disconnect between the algebraic nature of CAS and the analytic nature of the what it is mostly used for.  There are issues of logic -- CASes work more or less in an intensional logic, while most of analysis is stated in a purely extensional fashion.  There is no well-defined 'denotational semantics' for expressions-as-functions, which strongly contributes to the deeper bugs in CASes.

A: There are too many to be listed on the margins of MO.
Look at the archives of the newsgroups
comp.soft-sys.math.maple, comp.soft-sys.matlab,
sci.math.symbolic, comp.soft-sys.math.mathematica.
There you can find hundreds of bugs reported.
There is a notorious CAS bug hunter who once
maintained a bug list for Maple and shows
more than 5000 disturbing observations.
(Press the Go! button.) Or go to MapleSoft and search Maple Primes.
Please don't shoot the messenger.

A: We found some interesting bugs in Mathematica's integration software on this thread.
To wit, set
integral[m_,n_] = Integrate[Log[2+Cos[2Pi x]+Cos[2Pi y]] Cos[2Pi m x] Cos[2Pi n y],
                      {x, 0, 1}, {y, 0, 1}];

Then integral[1,1] should be $1/2-2/\pi$, but Mathematica 8.0.1 returns $1/2+2/\pi$. Values for other $m$ and $n$ are also wrong (see the question linked above), as can be quickly verified by replacing the "Integrate" command with "NIntegrate".
Curiously, if one changes the limits of integration to {x,-1/2,1/2} and {y,-1/2,1/2}, then the correct answers appear.

A: The PARI/GP Thue equations solver gives wrong results when they are conditional on GRH.
Affected are at least versions 2.5.1 (latest) and 2.4.3.
? p=x^3 - 18*x^2 + 81*x + 1;a=3^3
%1 = 27
? t=thue(thueinit(p,0),a);[#t,t] \\ conditional on GRH
%2 = [3, [[0, 3], [3, 0], [19, 2]]]
? t=thue(thueinit(p,1),a);[#t,t] \\ uncoditional
%3 = [4, [[0, 3], [3, 0], [27, 3], [19, 2]]]

Found on the pari-dev mailing list http://permalink.gmane.org/gmane.comp.mathematics.pari.devel/3629.

A: In the paper The Misfortunes of a Trio of Mathematicians Using Computer Algebra Systems. Can We Trust in Them?, the authors report a bug in Mathematica (which is still present in the version 10) that happens when computing determinants of matrices with large integers as entries.
The strangest thing of this bug is that for some matrices, the determinant function can give different values. The Mathematica notebook which reproduces the bug is available here.

A: http://oeis.org/A110375

A110375   Numbers n such that Maple 9.5, Maple 10, Maple 11 and Maple 12 give the wrong answers for the number of partitions of n.

A: Over the summer I came across an elementary bug in Magma when working with congruence subgroups of SL_2(Z). The isEquivalent function, which is supposed to tell whether two points are identified by a congruence subgroup, would miss a lot of identifications. For example:

G := CongruenceSubgroup(2);                   % \Gamma(2)
H := UpperHalfPlaneWithCusps();
(G! [-11,4,8,-3]) in G;                     % Cast this matrix into \Gamma(2)

true                                        % It's really in \Gamma(2)!

(G! [-11,4,8,-3]) * (H! 3/8);               % Have the matrix act on the point 3/8

oo                                          % Magma correctly computes that it gets sent to infinity

IsEquivalent(G, H! 3/8, H! Infinity());     % Are 3/8 and infinity equivalent under the action of \Gamma(2), and specifically, can you given me a matrix representing an element of \Gamma(2) sending the former to the latter?

false
    [1 0]
    [0 1]
                                                  % Doh!

It's a pretty simple computation, and it was pretty clear what loop it was leaving out. We may have been running an old version of Magma, but anyway we reported the error to them, and they fixed it quickly, but I've never trusted computer algebra systems since!

A: As was noted for Sage, for any open source CAS you can just look up the issue tracker.  For example, here's the list if all the issues in SymPy tracker with the WrongResult label: http://code.google.com/p/sympy/issues/list?q=label:WrongResult. Most of them are pretty rare. You're much more likely to hit a bug that just gives an error when it shouldn't, or that gives an unexpected, but not technically wrong (mathematically), result.
My advice is to double check your answer in some other way. The chances of the same bug manifesting itself in two different ways are almost zero. For example, you can check a result numerically, which will use a completely different algorithm from the symbolic version. Many CASs even have built in functions that do this for you.

A: A quite serious error in Mathematica 7  in my opinion is that it thinks $ \sqrt{x^2} =x$, not $|x|$, leading for example to 2 solutions to the following differential equation:
$$ y'(x) = 2 y(x) (x \sqrt{y(x)} - 1) \quad y(0) =1$$
Mathematica happily gives the following solutions:
$$ y(x) \rightarrow \frac{1}{(1-2 e^x +x)^2}, \quad y(x) \rightarrow \frac{1}{(1+x)^2} $$
Of course, it is a theorem that there is a unique solution to a differential equation of this type, but that doesn't mean my students hand in the wrong answer in droves...
Mathematica code:
FullSimplify[DSolve[{y'[x] == 2 y[x] (x Sqrt[y[x]] - 1), y[0] == 1}, y[x], x]]

A: $2^{4^{4^4}} < 4^{4^{4^4}}$
WA: False
Update: it seems to be fixed now

A: Mathematica 7.0.1 says that Sum[1/(k*Length[Divisors[k]]), {k, 1, n}] is the harmonic number $H_n$, which is clearly wrong. The correct answer is at An elementary number theoretic infinite series

Edit:
This is less a bug and more a misunderstanding of how to use Mathematica. The culprit is that Length[Divisors[k]] for k without a value evaluates to 1 (which is consistent with how Mathematica structurally treats expressions). The correct way to express the sum is
Sum[1/(k DivisorSigma[0, k]), {k, 1, n}]

which, as expected, now remains unevaluated.

A: Wolfram Mathematica 7 routinely confuses sums with integrals.
Example 1:
DSolve[(-Log[Log[a]] f'[x] + f''[x])/(Log[a] f'[x]) == D[Sum[f[x], x], x], f[x], x]

g[x_] := f[x] /. s
g[x]

Checking the result by inserting it into the equation shows the result is incorrect:
(-Log[Log[a]] g'[x] + g''[x])/(Log[a] g'[x]) - D[Sum[g[x], x], x]

Example 2:
s=NDSolve[{0.9159460564995328*Derivative[1][f][x] == f[x]*Product[f[x], x], f[0] == 1}, f, {x, -1.9, 15}]

Plot[Evaluate[f[x] /. s], {x, -0.4, 1.5}, AspectRatio -> Automatic, AxesOrigin -> {0, 0}]

In Mathematica 8.0 this has been fixed (i.e. it will report inability to solve the equations.

A: According to Wolfram Alpha
$$ (\log{(5+i)}+\log{(5-i)})^4= 10\,000$$
When one clicks on "10 000" WA spells it as integer.

A: A friend of mine told me about his experience with Maple (version 5 or 6, I think) when dealing with matrices over $\mathbb{Q}(\sqrt{2},\sqrt{3})$. When he computed the rank and the determinant for one particular $3\times3$-matrix, he was told that the rank was 3, and the determinant was equal to zero. The answer to this paradox is, that by default, for determinants the symbolic computation methods were used for radicals, and for ranks, the floating point representations of matrix elements!
This can be thought of as either a bug or his naiveness (for not checking out how to represent elements of number fields so that floating point representations never appear), but in any case is a serious argument for treating the computer algebra software with care...

A: I don't know any interesting bugs in symbolic algebra packages but I know a true, enlightening and entertaining story about something that looked like a bug but wasn't.$\def\sinc{\operatorname{sinc}}$
Define $\sinc x = (\sin x)/x$.
Someone found the following result in an algebra package:
$\int_0^\infty dx \sinc x = \pi/2$
They then found the following results:
$\int_0^\infty dx \sinc x \; \sinc (x/3)= \pi/2$
$\int_0^\infty dx \sinc x \; \sinc (x/3) \; \sinc (x/5)= \pi/2$
and so on up to
$\int_0^\infty dx \sinc x \; \sinc (x/3) \; \sinc (x/5) \; \cdots \; \sinc (x/13)= \pi/2$
So of course when they got:
$\int_0^\infty dx \sinc x \; \sinc (x/3) \sinc (x/5) \; \cdots \; \sinc (x/15)$$=
\frac{467807924713440738696537864469}{935615849440640907310521750000}\pi$
they knew they had to report the bug. The poor vendor struggled for a long time trying to fix it but eventually came to the stunning realisation that this result is correct.
These are now known as Borwein Integrals.
A video on this topic, titled "Researchers thought this was a bug," is on the 3Blue1Brown YouTube channel here.

A: Sometimes a CAS cannot get the right branch of inverse trig functions when calculating integrals symbolically.  See for instance: https://web.archive.org/web/20160817112947/https://pantherfile.uwm.edu/sorbello/www/classes/mathematica_badintegral.pdf
Apparently this is an unsolved problem in computer algebra.

A: Wolfram alpha is saying that the series of $\sum_k\sin(2 k \arctan(k^2))$ does not converge:
https://www.wolframalpha.com/input/?i=sum+sin%282+k+atan%28k%5E2%29%29
instead it converges! Seems that mathematica is only dealing with limits of functions not with limit of sequences.
Another simpler example is $\sum_k \sin(2k \pi + 1/k^2)$:
https://www.wolframalpha.com/input/?i=sum+sin%282k+pi+%2B+1%2Fk%5E2%29
E.

A: Not a bug but a difficulty for users:
I do often not really understand how assignements work for CAS:
Given a variable $a$ with value, say, $\pi$, set $b:=a$ and set now $a$ to, say, $e$.
What is the value of $b$?
As I understand the answer depends sometimes on the context (working with symbolic variables,
vectors, floating numbers etc.) and the exact behaviour
is sometimes difficult to guess for me.

A: This story heard from Enrico Bombieri. I do not know if it qualifies, since it is not a CAS bug, and in addition it is second-hand. However it might be quite effective in casting doubt in the mind of your students, if that's your purpose :)
E.B. was doing some Riemann zeta zero crunching on his PC some years ago, the software he wrote seemed ok, and the next step was to run it on a mainframe to get some serious data. He was given the privilege to try it on the first Cray supercomputer. Most of the time results were nice, but every now and then he got really weird results. He and his coworkers spent some awful weeks trying to catch the bug. In the end, they cornered the problem: when the Cray divided 1 by 12 the result was a negative number...
EDIT: I double checked, it was not a Cray supercomputer but a computer based on an early iteration of the Pentium chip (I guess an IBM one), and the Pentium bug was also encountered by others of course. Sorry for the inaccuracy.

A: Here is an example in Wolfram Alpha.
A student had been given the assignment of finding the limit as $n$ tends to infinity of $\frac{1}{1+\frac{(-1)^n}{log(n)}}$. He had correctly arrived at the answer 1. Now he used WA to check if he was correct. WA returned 0 (the command lim n-> inf 1/(1-(-1)^n/log(n)) ). On examining the steps, it turned out that WA had manipulated a bit and used L'Hopital on the expression $\frac{log(n)}{(-1)^n+log(n)}$.
Note that if one instead asks for the limit of $\frac{1}{1-\frac{(-1)^n}{log(n)}}$ WA correctly returns 1, using the same method one usually would.

A: From the sage-support mailing list.
Sage 5.10 claims
$$\forall a,b \in \mathbb{R}, \; \sqrt{(a+b)^2}=\sqrt{a^2}+\sqrt{b^2} $$
though it contradicts it numerically for $a=1,b= -1$.
Session:
sage: var('a,b');assume(a,'real');assume(b,'real');ex=sqrt( (a+b)^2 ) - (sqrt(a^2)+sqrt(b^2));ex
(a, b)
sqrt((a + b)^2) - sqrt(a^2) - sqrt(b^2)
sage: ex.full_simplify()
0
sage: ex.subs(a=1,b=-1)
-2

A: This error affects all versions of Mathematica from 6 to 8. The result of a function depends on what letter is chosen for argument when calling it. In the simplest case it can be illustrated as follows:
in:
$A[\text{x_}]\text{:=}\sum _{k=0}^{x-1} x $
$A[k]$
$A[z]$
out:
$1/2 (-1 + k) k$
$z^2$
The correct answer is evidently, the later. This behavior affects not only sums but also integrals, so one have to check so that the letter user for the argument not to coincide with the index variable used for definition. In the case of recursion this becomes very difficult. The following example shows that moving a factor not dependent on the index variable out of the sum sign changes the result:
in:
A1[0,x_]:=1
A2[0,x_]:=1

A1[n_,x_]:=Sum[A1[-1 - j + n, x]*Sum[A1[j, k], {k, 0, -1 + x}], {j, 0, -1 + n}]
A2[n_,x_]:=Sum[Sum[A2[j, k]*A2[-1 - j + n, x], {k, 0, -1 + x}], {j, 0, -1 + n}]

A1[1,x]/.x->2
A1[2,x]/.x->2
A1[3,x]/.x->2

A2[1,x]/.x->2
A2[2,x]/.x->2
A2[3,x]/.x->2

A2[1,2]
A2[2,2]
A2[3,2]

out:
2
5
13

2
5
12

2
5
13

A: In Mathematica 7, the command
Table[DirichletCharacter[4, 2, n], {n, 0, 8}]
should return a list of values of the character with modulus 4 and index 2, evaluated at 0, 1, 2, ..., 8. Instead, it returns the decidedly non-multiplicative:
{0,1,0,-1,0,-1,0,-1,0}

A: My advice is never to trust a single CAS. I only wrote one computer aided paper: I did the programming on Mathematica / Linux, and my collaborator did it on Magma / Solaris. We also made a point of not communicating while writing the programs.

A: Here  is a very simple common bug: ask your cas to solve in x the equation a x-´b = 0. Probably, the answer would  bex =  - b/a, that is wrong if a = 0. Most cas assume implicitly that a is not zero (Mathematica is an exception).


text:
Q: Converting Parallel ForEach into PLINQ to process list of Tasks I am trying to load as many messages into a server fast as possible. I currently have this bit of code and to load 50000 messages to a MessagingServer it takes around 5 minutes. This is a list of tasks that have server name, queuename and the message to place on the queue.
  taskList.Add(new Task(() => PlaceMessageOnQueue(server, queueName, message)));

This is the current code that I have but I want to convert this to PLINQ as hopes to make this even faster.
_= Parallel.ForEach(task, new ParallelOptions()
{
MaxDegreeOfParallelism = Environment.ProcessorCount; //I have 4 Cores
},t => {
 t.Start();
 t.Wait();
Console.WriteLine(t.Status)
});

What I have so far but this isn't starting the tasks. This is the code below that I need help with.
var results = task.
.AsParallel()
.AsOrdered()
.WithDegreeofParallelism(Environment.ProcessorCount)
.ToList();

A: You can approach this by consuming the messages in parallel and selecting the result of processing the message, as in this example:
static void Main(string[] args)
{
    var messages = Enumerable.Range(0, 10).Select(i => $"Message {i}");

    var results = messages
        .AsParallel()
        .AsOrdered()
        .WithDegreeOfParallelism(Environment.ProcessorCount)
        .Select(m => PlaceMessageOnQueue("FOO", "BAR", m))
        .ToList();
}
static bool PlaceMessageOnQueue(string server, string queue, string message)
{
    Console.WriteLine($"Starting {server}/{queue}/{message}");
    Thread.Sleep(1000);
    Console.WriteLine($"Finished {server}/{queue}/{message}");

    return true; // E.g. representing success
}

Note there isn't a reason to believe this will be fundamentally faster than your last approach. You may wish to look at a producer/consumer pattern using Channels. In many use cases, channels outperform similar concurrency options in .NET.


text:
Q: How to display a property of selection object while hovering cursor over combo box item in Vaadin In my Vaadin (v.23.2.6) application I am creating a bean of class Book. This bean has set of tags.
Tags are retrieved from the database and contain two properties - tagName and tagDescription.
In my UI form I specified MultiSelectComboBox for Tags.
this.tagsField = new MultiSelectComboBox<>("Tags");
this.tagsField.setAllowCustomValue(true);
this.tagsField.setAutoOpen(false);
this.tagsField.setItemLabelGenerator(Tag::getTagName);

It is working, but I do want to display value of tagDescription when cursor is hovering over the tagName in the selection list.
What kind of event listener I can use for that purpose? Shall I use Notification or there is something else that can help me with this implementation?
Please advise.

A: While it's technically possible, you don't want to listen to hover (mouseover) events on the server. That's overkill and will lead to a lot of unnecessary network traffic. Instead, you can take care of it in the client with a Renderer. For example, using the standard HTML title attribute:
tagsField.setRenderer(LitRenderer.<Tag>of(
    "${item.name}")
        .withProperty("description", Tag::getTagDescription)
        .withProperty("name", Tag::getTagName)
);


text:
Q: I am looking for a service that can host PDF files in the local network over HTTP Problem: In the local network i have touchscreen devices with embedded HTML5 browsers (no other OS. No possibility for FTP to download a file).
I would like to host a bunch of PDF files on one machine, so each of the touchscreen devices could read the PDF files in their browsers.
An example URL would be: 192.168.1.10:86/MyFolder/MyPdfFile.pdf
At times there is no internet access, so i don't want to host them online either.

A: You mentioned that you're in Windows, but the easiest web server that I've seen works in Linux. As such, I recommend enabling WSL. Once WSL is enabled, install the php interpreter and run the following command in the directory of the PDF files that you would like to host:
php -S 0.0.0.0:8080
Then, a web server that serves that directory will be available on port 8080 of the Windows computer that serves the files in the directory that you ran that command in, so, for example, if a file is called MyPdf.pdf and the IP of that computer is 192.168.1.3, then the URL that you would use is http://192.168.1.3:8080/MyPdf.pdf. Note that the command must be running in order for the web server to be active.


text:
Q: Show progress of achievements post 5.0.4? So now that we've got account-wide achievements for all the characters, you can seemingly no longer toggle the convenient achievement tracker with the progress bar on your characters anymore.
Though this isn't really that big a deal for most achievements, it gave me a more tangible indicator of where I was in my progress in a given zone. I know that I can still Shift-click the achievement and see its header displayed on my screen, and then I can click that to see the progress bar in the Achievements window to see where I sit, but...
Is there a way that I can get the progress bar back on my screen to minimize clicks?

A: There's no built-in method to do that, since as of 5.0.4 Blizzard UI code just checks if achievement is complete (which now means "complete on any character account-wide") and doesn't even bothers with checking and drawing requirements after that.
However, the data and functions to retrieve objectives and counts are intact and return information relevant to current character, so this can be either fixed in UI by Blizzard later or implemented in an addon.
Either do it yourself or ask at some popular WoW UI programming forum in "addon ideas" section.


text:
Q: Call synchronised on a function in java Is there a way I can call synchronised (or something similar) on a block of code. For example (pseudo code),
public int getA(int id) {
    if (flag) {
        return synchronized(fetchA(id))
    } else {
        return fetchA(id)
    }
}

public int fetchA(int id) {
    if (map.get(id) == null) {
        p = generate(id)
        map.put(id, p)
        return map.get(id)
    } else {
        return map.get(id)
    }
}

In this case I want the function to take a lock on object map if flag is set to true and not take a lock otherwise. I have read that synchronised take locks only on objects. Is there any something else I can use instead of synchronised?

A: Synchronising on an Object ist exactly the right thing to do. In your case the shared object is the map.
You can do a
synchronized(map) {
    return fetchA(id);
}

The locking is some sort of contract: if you access map, then you'll have to lock it. This can be cumbersome and error prone. Hence the better option is to lock and release within the fetchA() method, like
public int fetchA(int id) {
    synchronized(map) {
        if (map.get(id) == null) {
            p = generate(id)
            map.put(id, p)
            return map.get(id)
        } else {
            return map.get(id)
        }
    }
}

This way any other method can simply call fetchA() without being aware of the need of locking.
An alternative is to declare the function synchronized. That way only a single thread at the time can enter the function.
public synchronized int fetchA(int id) { ... }

Having said this, be careful with nested locking. That's a good way to produce deadlocks.

A: To answer your direct question: just use a synchronized block:
synchronized (something) {
  return fetchA(id);
}

But your approach is not great in the first place. For one thing, there is the computeIfAbsent method which does exactly what your fetchA method does:
public int fetchA(int id) {
    return map.computeIfAbsent(id, k -> generate(k));
}

For another, it seem that flag is going to be a constant for the instance, since it doesn't make sense to access it in a synchronized way only some of the time.
So, choose a Map implementation based on the flag in the constructor:
if (flag) {
  map = new ConcurrentHashMap<>();
} else {
  map = new HashMap<>();
}

and then simply don't worry about whether you need to synchronize in your method:
public int getA(int id) {
  return map.computeIfAbsent(id, k -> generate(k));
}

A: You could use ConcurrentHashMap. But it will throw "ConcurrentModificationException" if one thread tries to modify it while another is iterating over it.
For block of code level there are four types you can use
Instance methods
enter code here
Static methods
Code blocks inside instance methods
Code blocks inside static methods

refer this for more info :Code block level synchronization


text:
Q: Error when installing Makefile: "make: *** No targets specified and no makefile found.  Stop." In short while I run the make command it says:
nir@nir:~/Downloads/xf86-video-intel-2.17.0$ make
make: *** No targets specified and no makefile found.  Stop.

I looked inside the folder-xf86-video-intel-2.17.0 and there is a file named "Makefile.in"
it supposed to be a in file, right?

A: Just remember that in order for the ./configure file to run you made need a compiler.  So do something like sudo apt-get install gcc.  then run ./configure again and should work

A: That happens because there is no file named Makefile in that directory. To create that Makefile, you need to execute
$ ./configure

The configure script determines if your system has all the dependencies necessary to compile the application. If a dependency is not found, the configure will fail and the Makefile's will not be created. To solve that, you must install all the dependencies needed by the application.
The application xf86-video-intel seems to be provided by the xserver-xorg-video-intel package, and its dependencies may be easily installed by running
$ sudo apt-get build-dep xserver-xorg-video-intel

For more information, you might want to read the README or INSTALL files.

A: The make command looks for a file called "Makefile", no extension, not "Makefile.in". Since the file is not found, make does not know what to do, and stops. (The error message is cryptic because in some rare cases, make can guess what to do without an actual Makefile.)
Read the instructions on how to compile your program. It's likely that you are required to run ./configure, first. This script will create "Makefile" based on your setup and "Makefile.in".
You can temporarily disable the Hebrew locale when looking for help online, just run
LC_ALL=C make

This will give you English messages.

A: Dont worry..
There are only some packages need to be intalled..
type "sudo synaptic" in terminal and enter..
in search box type "qt4-qmake" and mark for installation.
then same as above search" libqt4-dev" and "libxml2-dev" and do the same mark for installation simultaneously..
then apply without check the download option.
here it is....
Then go to cd netanim directory and type "make clean" and enter,
if it does not work type "qmake NetAnim.pro" and enter, it takes couple of seconds.
then type "make" and enter...
Here its done, it will take less then a minute.
 Now in netanim directory type "./NetAnim" and enter.
Here you will see animation interface.
Good luck

A: make sure you have installed this file or
sudo apt install libc6-dev

Now, you need to configure the installation file
./configure
make && make install

A: Step 1: Install the Required Dependencies
First, launch the Terminal and run the commands below to install the required dependencies and libraries.
sudo apt install autoconf automake libpcre3-dev libnl-3-dev libsqlite3-dev libssl-dev ethtool build-essential g++ libnl-genl-3-dev libgcrypt20-dev libtool python3-distutils
sudo apt install -y pkg-config
Step 2: Compile and Install
Now, run the commands below (one by one in order) to compile the source code and install Your Repo on your system.
[Before this enter you directory ex: cd folder_name]
sudo autoreconf -i
sudo ./configure --with-experimental --with-ext-scripts
sudo make
sudo make install
I hope this time problem will be solved.


text:
Q: fill between and axis equal not getting on (pgfplots) I'm trying to visualise the area under the curve in the first quadrant of a function, say f(x) = 6-2x.
\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.13}
\usepgfplotslibrary{fillbetween}

\begin{document}
\begin{tikzpicture}
\begin{axis}[axis equal,
    axis lines=middle,
    xtick={3},
    ytick={6},
    domain=0:3,
    ]
\addplot[name path=f, samples=400, blue] {6-2*x};
\addplot[name path=g, samples=400, draw=none] {0};
\addplot [color=blue!20] fill between[of=f and g, soft clip={domain=0:3}];
\end{axis}
\end{tikzpicture}

\end{document}

This code produces

as is, but if I comment out axis equal,, I get

which is closer to the desired behaviour.
Why can't fill between and axis equal get along?

A: So, I believe this to be a bug in PGFPlots.  For your particular example, there is actually another way to achieve the same effect that will work with rescale, but otherwise, it seems that changing the unit vector ratio property will, in general, break fill between.
Fix for given plot
Firstly onto addressing your particular plot, you can use the \closedcycle command which allows you to fill down to the horizontal axis.  Note that \closedcycle draws a closed shape and thus has edges at the top, bottom and sides which may not always be desirable (in which case, you might prefer fill between).  Alternatively, the filling and the desired edge can be plotted separately with:
\addplot [draw=blue] {f(x)};
\addplot [draw=none, fill=blue, fill opacity=0.2]
         {f(x)} \closedcycle;

though this is now getting somewhat convoluted.
Fortunately, in this instance this can all be avoided since the two axes can very conveniently hide everything so long as they are drawn on top using the axis on top key:
\documentclass[border=5mm, tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\usepgfplotslibrary{fillbetween}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
      axis lines=middle,
      axis on top,
      axis equal,
      ytick={6},
      xtick={3},
      samples=400,
      domain=0:3,
    ]
    \addplot [
      draw=blue,
      fill=blue,
      fill opacity=0.2
    ] {6-2*x} \closedcycle;
  \end{axis}
\end{tikzpicture}
\end{document}

Note that to draw a straight line between two points, it is generally easier to use:
\addplot [...] coordinates {
    (0, 6)
    (3, 0)
  } \closedcycle;

Both options achieve the same effect:

Bug with fill between
Now onto the issue with the filling.  The axis equal is equivalent to setting
unit vector ratio={1 1 1},
unit rescale keep size=true,

and it turns out that the issue is with unit vector ratio.  Some ratios work fine, but some other set of ratios don't seem to work.  So adding two more plots to the previous example and testing fill between
\documentclass[border=5mm, tikz]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\usepgfplotslibrary{fillbetween}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
      axis lines=middle,
      axis on top,
      % axis equal,
      unit vector ratio={2 1 1},
      ytick={6},
      xtick={3},
      samples=400,
      domain=0:3,
    ]

    \addplot [
      draw=blue,
      fill=blue,
      fill opacity=0.2
      ] coordinates {
        (0, 6)
        (3, 0)
      } \closedcycle;

    \addplot [
      name path=f,
      draw=red,
    ] {x^2 / 1.5 + sin(360 * x)};
    \addplot [
      name path=g,
      draw=black,
    ] {x^2 / 1.5};

    \addplot [color=red!20] fill between [
      of=f and g,
      soft clip={domain=0:3}
    ];
  \end{axis}
\end{tikzpicture}
\end{document}

Which generates one of the following, based on the value of the unit ratios, or based on the number of samples used.

This appears to be a bug in PGFPlots and has been reported already by Stefan Pinnow over at:

#139 [fillbetween] numerical issues with dense points


text:
Q: Limits of the strings What is the limit of this:
$a_n=\dfrac{(1!+2!+\dots+n!)}{(2 \cdot n)!}$, where n tends to infinity?
I would also like an intuitive explanation in addition to the logical one. Thanks in advance!
P.s.: Do you know where can I find the math API on this site?

A: As n tends to infinity,
$1! \le n!$, $2! \le n!\cdots $, $n! \le n!$
So numerator is upper bounded by $n n!$
Now denominator is 2n! which is $2n*(2n-1)*\ldots * (n!)$
So our equation is upper bounded by $(n*(n!)) / (2n*(2n-1)* \ldots * (n!))$
$n!$ and n cancels out
So we are left with
$1/(2*(2n-1)*(2n-2) . . (n+1))$
As n tends to infinity, it tends to 0.
So, since our upper bounds tends to 0 and our lower bound is 0, hence by sandwhich, the limit on an as n tends to infinity should be 0
QED

A: $a_n\le \frac{n\cdot n!}{2n\cdot (2n-1)!} = \frac12 \frac{n!}{(2n-1)!}\to0$.
Intuitively, $(2n)!$ is huge because you're multiplying numbers all the way to $2n$.
Also: the Math API :) (but where is the emoji API?).

A: By induction prove that,
$$a_n\le \frac{1}{n}$$

*

*for $n=1$
$$a_1 = \frac{1}{2}\le \frac{1}{1}$$
Assume that

$$a_n=\dfrac{(1!+2!+\dots+n!)}{(2 \cdot n)!}\le \frac{1}{n} $$
$$a_{n+1}=\dfrac{(1!+2!+\dots+n!)+(n+1)!}{2(n+1)(2n+1)(2 \cdot n)!}\\=\frac{1}{2(n+1)(2n+1)}\dfrac{(1!+2!+\dots+n!)}{(2 \cdot n)!}+\frac{1}{2(n+1)}\dfrac{(n+1)n!}{(2n+1)(2 \cdot n)!}$$
But $$n!\le (2n)!~~~and~~~n+1\le 2n+1 \implies\dfrac{(n+1)n!}{(2n+1)(2 \cdot n)!}\le 1 $$
By assumption $$ \dfrac{(1!+2!+\dots+n!)}{(2 \cdot n)!}\le\frac{1}{n}\le 1$$ we get
$$ a_{n+1}=\dfrac{(1!+2!+\dots+n!)+(n+1)!}{(2 n+2)!}\le \frac{1}{2(n+1)(2n+1)}+\frac{1}{2(n+1)}\le \frac{1}{n+1}$$
since $$\frac{1}{2n+1}\le 1$$

conclusion $$\forall~~n~~a_n\le \frac{1}{n}\to 0$$


text:
Q: OpenERP customized module with button object I have created a customized module i openerp with following .py file . Please help me to add first and second to get third using button object click function.
from osv import osv

from osv import fields

class test_base(osv.osv):
    _name='test.base'
    _columns={

            'first':fields.integer('First No:'),
            'second':fields.integer('Second No:'),
            'third':fields.integer('Third No:'),
             }

def get_sum(self, cr, uid, ids,context=None):

     #  please add code here to get sum of 'first' and 'second' and assign to variable 'sum'

    return {'value':{'third': sum }}

test_base()

xml
<button name="get_sum" string="Click on me to get sum " type="object"/>

A: For your code you can do onething
 def get_sum(self, cr, uid, ids,context=None):

    #  please add code here to get sum of 'first' and 'second' and assign to variable 'sum'
    sum = 0.0
    for data in self.browse(cr, uid, ids, context=context):
       sum += data.first + data.second
    self.write(cr, uid, ids, {'third': sum}
    return True

or you can make third fields as functional field and get value directly there without click on button
_columns = {
    'first':fields.integer('First No:'),
    'second':fields.integer('Second No:'),
    'third': fields.function(_sum, type="float", store=True)
}
def get_sum(self, cr, uid, ids,context=None):
        res = {}
        #  please add code here to get sum of 'first' and 'second' and assign to variable 'sum'
        sum = 0.0
        for data in self.browse(cr, uid, ids, context=context):
           sum += data.first + data.second
        res[data.id] = sum
        return res

you can not use this type return  return {'value':{'third': sum }} in button clicl event it only work in onchange method, like you set onchange on fiels second so when you enter value and press tab it onchange fire set value in field third.
hope this help


text:
Q: What is the issue in following conversion from argv[1] to char * string? I am very new to C and pointers. I am trying to convert command line argument to wchar_t * . But somehow it is not giving proper output. What am I missing?
void fun(){
    std::setlocale(LC_ALL, "en_US.utf8");
    std::wcout.imbue(std::locale("en_US.utf8"));
    char* mbstr = "f:\\mypath1\\mypath2\\mypath3";
    wstring reposPath;
    char *c_ReposPathString = (char*)mbstr;
    size_t c_ReposPathStringSize= 0;
    if(c_ReposPathString)
    {
         c_ReposPathStringSize = 2*(strlen(c_ReposPathString)+1);
    }
    wchar_t *w_ReposPathChar = new wchar_t[c_ReposPathStringSize];
    if(w_ReposPathChar)
    {
       mbstowcs(w_ReposPathChar, c_ReposPathString, c_ReposPathStringSize);
    }
       reposPath = w_ReposPathChar;

    printf("%s",  (char *)reposPath.c_str());
    free(w_ReposPathChar);
}

when I print length of w_path, it shows 1. But argv[1] has more than one character it it.

A: You can't simply re-cast a wchar_t string to a char string and expect it to work, as there may (will) be many wchar_t values that have their upper byte as zero (which will be seen as a terminator, after the cast).
So, instead of:
printf("%s",  (char *)reposPath.c_str());

which sees a 'false' nul-terminator after the f, simply print the wchar_t string for what it is:
printf("%ws", reposPath.c_str());

Also, you have a const missing in your declaration of mbstr, which should be this:
const char* mbstr = "f:\\mypath1\\mypath2\\mypath3";

and you don't need to allocate twice the number of char for your wchar_t buffer, so this will suffice:
    if (c_ReposPathString)
    {
        c_ReposPathStringSize = strlen(c_ReposPathString) + 1; // Don't need "* 2"
    }

Feel free to ask for further clarification and/or explanation.


text:
Q: store HTML object (div element) in raiseevent() method - pepper robo in pepper robo tablet I have to display a webpage in webview on button click.
how can I store an object (html div element) in raiseevent() method
eg: session.raiseevent("eventname", "htmldivelement")
python function below to load url and webview
def web_view(self):

    url = "https://www.google.com"
    try:
        self.ts.loadUrl(url)
        self.ts.showWebview()
        #self.showWebview("https://www.google.com")
    except Exception, e:
        self.logger.info("Error while loading tablet: {}".format(e))

A: You can't request to display arbitrary html on Pepper's tablet.
There are two ways you can update Pepper's tablet from Python:

*

*Load a new webpage with ALTabletService.showWebview(url)

*Have a webpage that is subscribed to an ALMemory event using the javascript SDK, and raise almemory events with information about the new tablet state (these usually pass json, but could also send html any other format - in any way, you'll have to handle it in javascript). There are some examples of that in robot-jumpstarter.


text:
Q: How to sum overlapping intervals without including overlap We have collected data in which we measured the length along a measuring tape where particular species overlapped it.  In some cases multiple species may overlap it in the same spot.  I need to figure out how much of the tape was overlapped by plants without counting the same length of tape twice when multiple plants overlap the same spot, and I need to do it grouped by vegetation type (e.g., shrub, tree, etc).  So, I'm answering the question, "how much of the tape is covered by shrubs?" for example.
E.g., imagine the dashed line is the measuring tape, and the asterisks are all different shrubs overlapping the tape.  This is what my data essentially represents right now.  If I counted the length of all the shrubs, I would get a big number, longer than the actual length of the tape...
  ***    **    *********
   ****       **     *******
----------------------------

...but this is what I need to figure out, the actual length of tape covered by any shrub:
  *****  **   **************
----------------------------

I hope that makes sense, but here are some examples to explain further if needed:
Example: Imagine I encountered Doug Fir trees that overlapped the measuring tape stretching from the 4' mark to the 10' mark and the 20' mark to the 25' mark.  I also encountered Spruce trees overlapping the tape from the 7' to 14' marks.  I need to know the total length of overlap of tree species (these are both trees), so I will need to sum the lengths of these ranges for both Spruce and Doug Fir.  However, if I just sum all the ranges normally, I will end up counting the 7' to 10' area (sum = 3') twice rather than once, where both Spruce and Doug Firs were covering the tape. So, I will need to subtract 3' from the final value so that this part of the measuring tape is not counted more than once.  So, my ranges are 6', 5', and 7', which totals 18'.  After subtracting the overlapping 3', that gives a total of 15' feet where trees overlap the tape.
Example table below.  I already have the SPECIES, START, END, TYPE, and SUM data.  What I need excel to help me compute are the values shown below the table, which are the sums after accounting for multiple-species overlap. E.g., if Shrub X overlapped from 10' to 20', and shrub Y overlapped from 13' to 25', the total overlap would be from 10' to 25' so fifteen feet of overlap.  Not 22 ft overlap, which is what it would be if you counted each of the ranges separately.)
SPECIES START(ft) END(ft) TYPE  SUM (ft)
Dogwood 40.3      40.9    Shrub   0.6
Cedar   52.8      79.5    Tree    26.7
Dogwood 50.2      55.6    Shrub   5.4
Rose    53.8      54.4    Shrub   0.6
Alder   88.2      95.5    Tree    7.3
Clover  75.8      76.2    Forb    0.4
Bunch   82.8      90.3    Grass   7.5
Poa     86.1      95.3    Grass   9.2
Sedge   99.4      100.9   Grass   1.5
Bttrcp  74.5      101.3   Forb    26.8
Elder   105.8     120.3   Shrub   14.5
Bttrcp  110.3     120.2   Forb    9.9
Cedar   90.4      99.9    Tree    9.5

SHRUB SUM   TREE SUM    FORB SUM    GRASS SUM
  20.5       38.4         35.4         14

Any guidance in figuring this out would be much appreciated!

A: Here is some pseudo code that might work. Also, this is only estimated for each TYPE. To get the whole area, repeat for each TYPE:
get_max_area(data):
    sort(data, START)
    for i <- 1 to n:
        for j <- i to n:
            if data[j][START] < data[i][START]:         // Two segments overlap
                if data[j][END] < data[i][END]:         // j is fully contained within i
                    ignore(data[j])
                else:                                   // They just overlap
                    merge(data[i], data[i + 1])
                                                        // ELSE: independent segments

    return sum(data[SUM])

Ignoring means the segment is not tested anymore. Merging means making segment a(i, j) and b(x, y) a new segment c(i, y). This is just a quick approach, and it takes O(n^2). There must be a better approach.


text:
Q: Aggregation in MongoDB to get 1 array from a list I just started to learn NoSQL. I have a table Orders, which contains a field with the type array - books inside which a field with the type string - name. I want to get the book which is the least in Orders.
So far, I was only able to display the number of equal Orders with books:
db.Orders.aggregate([ { $group: { _id: "$books.name", count: { $sum: 1 } } ])

And how to aggregate all books into 1 array of all books - I don't understand
I have:
[
    {"books":[{"name":"A"}]},
    {"books":[{"name":"A"}]},
    {"books":[{"name":"A"}, {"name": "B"}, {"name": "C"}]},
    {"books":[{"name": "C"}]}
]

I wait:
[
    {"_id": 'A', "count": 3 },
    {"_id": 'B', "count": 1 },
    {"_id": 'C', "count": 2 }
]

I take:
[
    {"_id":[{"name":"A"}], count:2},
    {"_id":[{"name":"A"}, {"name": "B"}, {"name": "C"}], count:1},
    {"_id":[{"name": "C"}], count:1}
]


text:
Q: Как нарисовать арку со смещенным центром окружности? Как нарисовать арку со смещенным центром окружности, если известно: радиус, высота, ширина нижнего основания. Проблема заключается в том, что я не понимаю как расположить (получить точки отрисовки) окружности.
Вот что получается:

А должно получится:

Реализую так:
p = {
    cx : 250, // Центр по Х
    cy : 250, // Центр по Y
    vertical : 50, // Вертикальный радиус
    horizontal : 50, // Горизонтальный радиус
    height : 100, // Высота
    width : 100, // Ширина
  }

const center_x = p.cx,
      center_y = -p.cy;

let dy = center_y + p.width/2 - p.height/2;
let d = `M${center_x + p.width/2},${center_y}
             v${p.height}
             h${-p.width}
             v${-p.height}
             a${p.horizontal},
             ${p.vertical},0,0,1,${center_x + p.width/2},0`;

A: Точку конца дуги Вы задаете в команде arc (последние 2 числа), она абсолютная для A и относительная для a, вы никак не оперируете центром окружности, дуга строится по начальной и конечной точке. Вместо этого есть флаги, которые определяют какая из 4 возможных дуг, построенных через 2 точки с заданными радиусами нам нужна.

Вот дуга щагающая на 100 вправо с радиусом 100

let r = 100, w = 100;

let d = `M 100,100 a${r},${r},0,0,1,${w},0`;

document.write(`
  <svg viewbox="0 50 300 100" height="88vh">
    <path fill="none" stroke="red" d="${d}">
  </svg>
`);


text:
Q: $M_1^2+M_2^2+M^2_3=M$ ,where $M_1,M_2,M_3$ are positive numbers and sum of any two is greater than the third, show that $2M ≤ (M_1 +M_2 +M_3)^2 ≤ 3M.$ $M_1^2+M_2^2+M^2_3=M$ ,where $M_1,M_2,M_3$ are positive numbers and sum of any two is greater than the third, show that $2M ≤ (M_1 + M_2 + M_3)^2 ≤ 3M.$
My solution goes like this:

We know that, $M_1^2+M_2^2+M^2_3\geq \Sigma M_1M_2$. Thus, $(M_1+M_2+M^2)^2=M_1^2+M_2^2+M^2_3+2\Sigma M_1M_2\leq 3M$

But I dont think, $2M ≤ (M_1 + M_2 + M_3)^2$ is true. For then, $M\leq 2\Sigma M_1M_2$, a contradiction. Is the first inequality, valid? Also, is my solution correct?

A: The one on the right is CS inequality, for the one on the left. Use: $M_1+M_2 > M_3 \implies M_1M_3+M_2M_3 > M_3^2$. Do the same for two more inequalities of the same type and add them up. Then add both sides to $M_1^2+M_2^2+M_3^2$ to complete the square.


text:
Q: How to execute only page URL and redirect to another page? I want to execute an URL then page will redirect to requested header location. But page not redirect. My previous page is showing here.
See my code-
example.php
<?php
function test() {
    $aa = 'good morning';
    //file_get_content('http://localhost/DemoProject/test.php');
    $ch = curl_init('http://localhost/DemoProject/test.php');
    curl_exec($ch);
    return $aa;
}
$text = test();
header('location:http://www.google.co.in/search?q='.urlencode($text));
?>

In test.php file I have written one pdf generated code and email function  with generate PDF file attachment. I want only http://localhost/DemoProject/test.php execute.
When I run example.php file. That page will redirect to http://www.google.co.in/search?q=good+morning this is showing current page with test.php data.
How to only execute URL not retrieve any data?

A: Try adding exit statement after the header() statement, which would then make your code look like,
<?php
function test() {
    $aa = 'good morning';
    //file_get_content('http://localhost/DemoProject/test.php');
    $ch = curl_init('http://localhost/DemoProject/test.php');
    curl_exec($ch);
    return $aa;
}
$text = test();
header('location:http://www.google.co.in/search?q='.urlencode($text));
exit;
?>

Here is the PHP documentation that states that adding exit will stop all other code execution and redirect to the URL.
http://php.net/manual/en/function.header.php
Also make sure that there is no output written before the header() is called, i.e. do not echo or have blank lines present that would get outputted before the header().

A: You can have the output not sent to the browser by setting the option CURLOPT_RETURNTRANSFER
$ch = curl_init('http://localhost/DemoProject/test.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);


text:
Q: Accessing google drive from Android I  followed steps listing at How to upload file on google drive using my android application  and  http://www.youtube.com/watch?v=Ied1CjJ0iP0  .But i am getting these errors .Please help me out .I have one more issue what if i want upload some file created my application to some user's(not added on phone) drive without user interaction
 01-29 18:48:07.925: E/Trace(5134): error opening trace file: No such file or directory (2)
 01-29 18:48:26.955: E/AndroidRuntime(5134): FATAL EXCEPTION: Thread-6566
 01-29 18:48:26.955: E/AndroidRuntime(5134): java.lang.NullPointerException
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at java.net.URI.parseURI(URI.java:353)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at java.net.URI.<init>(URI.java:204)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at com.google.api.client.http.GenericUrl.<init>(GenericUrl.java:100)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at com.google.api.client.googleapis.media.MediaHttpUploader.upload(MediaHttpUploader.java:269)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:408)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:328)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:449)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at com.example.googlevideo.MainActivity$1.run(MainActivity.java:103)
 01-29 18:48:26.955: E/AndroidRuntime(5134):     at java.lang.Thread.run(Thread.java:856)

A: This exception was because my request was not valid ;the  package name i had given in Google console didn't match with what i was using in my application.


text:
Q: Getting Constructor on type 'XX' not found. Using Pechkin plugin Im trying to make this plugin run in my ASP project. I´m familiar with C# but never tried an ASP.net project before.
I tried doing everthing exacly like in this blog here:
http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/
But Im getting stuck with the following error message: " Constructor on type 'Pechkin.SimplePechkin' not found."
The happens when I call the method to get a instance of the Pechkin : ( This one below)
var pechkin = Factory.Create(new GlobalConfig());

When I debug(F11) that line of code I step into the Pechkin code and the line that returns the error is:
ObjectHandle handle = Activator.CreateInstanceFrom(
        Factory.operatingDomain,
        location,
        typeof(SimplePechkin).FullName,
        false,
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
        null,
        new object[] { config },
        null,
        null,
        null);

Taking a look at the SimplePechkin.cs it has a constructor :
///
/// Constructs HTML to PDF converter instance from GlobalConfig.
///
/// <param name="config">global configuration object</param>
public SimplePechkin(GlobalConfig config)
{
    this._onErrorDelegate = new StringCallback(this.OnError);
    this._onFinishedDelegate = new IntCallback(this.OnFinished);
    this._onPhaseChangedDelegate = new VoidCallback(this.OnPhaseChanged);
    this._onProgressChangedDelegate = new IntCallback(this.OnProgressChanged);
    this._onWarningDelegate = new StringCallback(this.OnWarning);

    Tracer.Trace("T:" + Thread.CurrentThread.Name + " Creating SimplePechkin");

    this._globalConfig = config;

    Tracer.Trace("T:" + Thread.CurrentThread.Name + " Created global config");

    this.IsDisposed = false;
}

I think that error should not be going on, specially because if I run it on a common C# winforms test project it works ok. Maybe is because I´m a noob with ASP.net.
Can you guys please help?
Here is the link to the github Pechkin repository if someone wants to give it a try.
https://github.com/tuespetre/Pechkin
Thank you for reading!
-Roiw


text:
Q: Expected @AndroidEntryPoint to have a value. Did you forget to apply the Gradle Plugin? When I am using Hilt in android with Room I got this kinda error.
The full log is here:
home/someone/Desktop/Calculator/app/build/tmp/kapt3/stubs/debug/com/hamidjonhamidov/calculator/MyApplication.java:7: error: [Hilt]
public class MyApplication extends android.app.Application {
       ^
  Expected @HiltAndroidApp to have a value. Did you forget to apply the Gradle Plugin?
  [Hilt] Processing did not complete. See error above for details./home/someone/Desktop/Calculator/app/build/tmp/kapt3/stubs/debug/com/hamidjonhamidov/calculator/ui/main/MainActivity.java:7: error: [Hilt]

Anyone knows solution for this?

A: in the build.gradle of your Android Gradle modules apply the plugin:
apply plugin: 'com.android.application'
apply plugin: 'dagger.hilt.android.plugin'

android {
  // ...
}

see detail here

A: I had this issue after upgrading Kotlin to 1.5.20.
Adding kapt.use.worker.api=false in gradle.properties worked for me the problem
Checkout dagger issue Support for Kotlin 1.5.20

A: Fortunately, there is simple solution.
In build.gradle in database scheme, we should use arguments += instead of arguments = .
defaultConfig{
     javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
}

Or/And in buld.gradle
You should apply plugin like:
apply plugin 'dagger.hilt.android.plugin'
This solved the problem)

A: UPDATE
Upgrade Hilt to v28.1.0 and Kotlin to v1.5.21 should fix this issue
OLD ANSWER
If you are on kotlin 1.5.20, answer of Mr-wil will decrease build speed as said in official doc:

To improve the speed of builds that use kapt, you can enable the
Gradle worker API for kapt tasks. Using the worker API lets Gradle run
independent annotation processing tasks from a single project in
parallel, which in some cases significantly decreases the execution
time.

Instead, set:
kapt {
    javacOptions {
        // These options are normally set automatically via the Hilt Gradle plugin, but we
        // set them manually to workaround a bug in the Kotlin 1.5.20
        option("-Adagger.fastInit=ENABLED")
        option("-Adagger.hilt.android.internal.disableAndroidSuperclassValidation=true")
    }
}

source

A: I'm still facing the same issue in 2022
I have solved the problem by adding
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.38.1'

to build.gradle project and adding
id 'dagger.hilt.android.plugin'

to plugins in build.gradle app

A: In my case it solved by declaring plugin:
plugins {
    id("dagger.hilt.android.plugin")
}

A: This generic error message can also appear in many circumstances. As a more generic check, ensure that your module's build.gradle file, ensure that you has:
apply plugin: 'dagger.hilt.android.plugin'
at the top.

A: This was due to a bug in Kotlin 1.5.20. It is fixed in Kotlin 1.5.21.
So all you need to do is to upgrade to the latest version of Kotlin.

A: I had the same problem and it seems like there is a problem in kotlin-kapt plugin. If you guys have tried out all the above answers and didn't get resolved, please try the below code in your build.gradle(module-level) outside the dependencies{} block
kapt {
    javacOptions {
        option("-Adagger.hilt.android.internal.disableAndroidSuperclassValidation=true")
    }
}

A: Check if all these are added.In my case I had missed adding one of the below line.
In project level build.gradle
buildscript {
dependencies {
    classpath "com.google.dagger:hilt-android-gradle-plugin:2.44"
  }
}

In app level build.gradle
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}

dependencies {
implementation "com.google.dagger:hilt-android:2.44"
implementation "androidx.hilt:hilt-common:1.0.0"
kapt "com.google.dagger:hilt-android-compiler:2.44"
}

A: -In app level build.gradle---add  the following in newer versions
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

*

*In project level build.gradle
 buildscript {
     ext.kotlin_version = "1.7.21"
     repositories {
         google()
         mavenCentral()
     }
     dependencies {
         classpath "com.android.tools.build:gradle:4.2.2"
         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
         classpath 'com.google.dagger:hilt-android-gradle-plugin:2.42'

         // NOTE: Do not place your application dependencies here; they belong
         // in the individual module build.gradle files
     }

}


text:
Q: How to save data from a json array to the database MongoDB? How to save the marker coordinates received as json parameter and build it to lat and lng fields with right values? I tried to do this in many ways but it gave everyone fails. Below those that are closest in my opinion good.
#controller:
def create
  @user = User.new()
  received_json = ["{\"lat\":52.38521483550798,\"lng\":16.866459809082016}", "{\"lat\":52.40458894240522,\"lng\":16.856503449218735}", "{\"lat\":52.42605757375466,\"lng\":16.86989303662108}"]
  # objArray=JSON.parse(received_json.to_json)
  objArray=ActiveSupport::JSON.decode(received_json.to_json)

  #example 1
  objArray.each do |obj|
    @user.markers.build(obj)
  end
  # NoMethodError (undefined method `each_pair' for "{\"lat\":52.38521483550798,\"lng\":16.866459809082016}":String):

  #example 2
  objArray.each do |obj, value|
    @user.markers.build(obj=>value)
  end
  # BSON::InvalidKeyName ({"lat":52.38521483550798,"lng":16.866459809082016} - key must not contain '.'):

  #example 3
  objArray.each do |obj|
    @user.markers.build(lat:obj)
  end
  # This approach save data but in one field lat in user markers array
  # Data Saved: {"_id":"4e9eac161e7bf208280002fb","markers":[{"_id":"4e9eac161e7bf208280002fc","lat":"{\"lat\":52.38521483550798,\"lng\":16.866459809082016}"},{"_id":"4e9eac161e7bf208280002fd","lat":"{\"lat\":52.40458894240522,\"lng\":16.856503449218735}"},{"_id":"4e9eac161e7bf208280002fe","lat":"{\"lat\":52.42605757375466,\"lng\":16.86989303662108}"}]}
end

#model
class User
  include Mongoid::Document
  field :name, :type => String
  embeds_many :markers, :inverse_of => :user
end

class Marker
  include Mongoid::Document
  field :lat, :type => Float
  field :lng, :type => Float
  embedded_in :user, :inverse_of => :marker
end

A: Try the following code
def create
  @user = User.new
  received_json = ["{\"lat\":52.38521483550798,\"lng\":16.866459809082016}", "{\"lat\":52.40458894240522,\"lng\":16.856503449218735}", "{\"lat\":52.42605757375466,\"lng\":16.86989303662108}"]
  markers = received_json.collect { |attributes| ActiveSupport::JSON.decode(attributes) }
  markers.each do |marker|
    @user.markers.build(marker)
  end
  @user.save
end


text:
Q: How to change the distance from the top margin and chapter title? How decrease the distance from the top margin and chapter title only of the title page, keeping the margins of the following pages unchanged. Also, how to narrow the distance between the title of the section and the title of the chapter?
\documentclass[12pt]{report}
\usepackage[brazil]{babel}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lipsum}
\usepackage[Glenn]{fncychap}%Sonny %Conny %Lenny %Glenn %Renje %Bjarne %Bjornstrup
\usepackage{geometry, calc, color, setspace}%
\geometry{a4paper, headsep=1.0cm, footskip=1cm, lmargin=3cm, rmargin=2cm, tmargin=3cm, bmargin=2cm}

\begin{document}
\chapter{Characters}

\section{teste}
\lipsum \lipsum
\end{document}

I've already looked at a lot of questions and all the answers change not only the first page, but all of the following, as well as changing the format of my title!

A: You could do something like this. You set the tmargin value to where you want your chapter title placed and then use the \topskip to set where the rest of the text will start.
\documentclass[12pt]{report}
\usepackage[brazil]{babel}
\usepackage[latin1]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lipsum}
\usepackage[Glenn]{fncychap}%Sonny %Conny %Lenny %Glenn %Renje %Bjarne %Bjornstrup
\usepackage{geometry, calc, color, setspace}%

\geometry{a4paper, headsep=1.0cm, footskip=1cm, lmargin=3cm, rmargin=2cm, tmargin=1cm, bmargin=2cm}
\setlength\topskip{2cm}
\newcommand\newchapter[1]{\setlength\topskip{0cm}\chapter{#1}\setlength\topskip{2cm}}

\begin{document}
\setlength\topskip{0cm}\tableofcontents\setlength\topskip{2cm}
\newchapter{Characters}
\section{teste}
\lipsum \lipsum
\end{document}