text:
Q: Given a book with $100$ pages and a $100$ lemmas, prove that there is some lemma written on the same page as its index
A book consists of 100 pages and contains 100 lemmas and some images. Each lemma is at most one page long and can't be split into two pages (it has to fit in one page). The lemmas are numbered from 1 to 100 and are written in ascending order. Prove that there must be at least one lemma written on a page with the same number as the lemma's number.

If lemma no. $1$ is written on page $1$, then it is proved. Let's assume lemma no. $1$ is written on page  $k, k>1$. Then on at least one page there must be $2$ lemmas. Let's assume that always on page $k+i$ we have lemma no. $i+1$ and so on. Then the last $100-k-i$ lemmas must fit on the last page, which means that there will be at least one lemma (number $100$) on page $100$.
But I don't know how to express it in a more mathematical way!
Any help?

A: For each page $i$ assign a number $p(i)$ that defines the highest number of lemma printed on all pages starting from page 1 up to page $i$ (inclusive). So if we have lemmas 3, 4 and 5 printed on page 12, with page 13 having images only: $p(12)=p(13)=5$.
We have the following sequence:
$$p(1), p(2), \dots, p(100)=100\tag{1}$$
If $p(1)\ge1$ it means that lemma 1 is printed on the first page and we are done.
Let us consider a case when $p(1)=0$ (which basically means that the first page is reserved for images only).
The sequence of page numbers $i$ is strictly increasing and the sequence of values $p(i)$ is non-decreasing. Both sequencies have the same number of items (100), with $p(1)<1$ and $p(100)=100$.
Because of that we must have a pair of consecutive pages $i,\space j=i+1$ such that:
$$p(i)<i$$
$$p(j)\ge j$$
This basically means that lemma $j$ is not printed on page $i$ or on any other page before it. It is actually printed on page $j$ and this completes the proof.

A: Slight rephrasing of Oldboy's argument:
Let $a_i = i - p_i$, where $p_i$ is the page number of lemma $i$.
Then $a_1 \leq 0$, $a_{100} \geq 0$, and $a_{i+1}-a_{i} \leq 1$. Thus $a_i$ must be $0$ for some $i$.

A: Consider the path of points $(L, p(L))$ where lemma $L$ is on page $p(L)$. Plot that path on the grid of lattice points $(x,y)$ for $1 \le x, y \le 100$. The path starts on or above the diagonal at point $(1, p(1))$ and ends on or below the diagonal at point $(100, p(100))$.
Following that path, you move to the right one step at a time as the lemma count increases. You may stay at the same horizontal level since many lemmas can appear on a page. Vertical steps can be longer, if pages of images intervene. Since you start out above the diagonal, you can't cross it for the first time on a vertical step. Since in order to end up on the other side of the diagonal you must cross it once, that must be a horizontal step, so you have landed on it on the way to the other side.
(This doesn't exactly answer your question, which calls "expressing [your proof] in a more mathematical way". I might be wrong, but I don't think that's possible.)

A: Here's a slightly amended proof by induction, which I hope will make the induction step more obvious.
Let $P_n$ be the proposition that for a book with $n$ sequentially numbered pages and $n$ or more sequentially numbered lemmas, at least one lemma is on a page with the same number as the lemma.
Suppose $P_n$ is true for some $n=k$, and consider the case of $k+1$ pages and $k+1$ lemmas. To avoid being on its own-numbered page, lemma $k+1$ has to be somewhere in the first $k$ pages, and to keep the lemmas in sequence, no other lemma can go on page $k+1$.
We therefore have to fit all $k+1$ lemmas onto the first $k$ pages. By $P_k$, this puts at least one of them on its own-numbered page.
So wherever lemma $k+1$ is, at least one lemma is on its own-numbered page.
Clearly this remains true if we add more lemmas without adding more pages. That is, with $k+1$ pages and $\ge k+1$ lemmas, at least one lemma is on its own-numbered page: ie $P_{k+1}$ holds. That is, if $P_n$ is true for $n=k$, it is also true for $n=k+1$.
Now consider the case of $1$ page and $\ge 1$ lemmas. Clearly lemma 1 is on page 1, so $P_1$ is true. Therefore, by induction, $P_n$ is true for all $n\ge 1$.
Finally, putting $n=100$ proves the case in the original question.

A: This is a special case of the Knaster-Tarski fixed point theorem (or a corollary thereof):

Theorem. Every increasing function from a certain set to itself has at least one fixed point

This is sometimes given as a nice exercise in real analysis courses, in the following form: Fixed point of a monotone on [0,1].

A: We claim more generally that a book of $n$ pages and $n$ lemmas numbered $1$ through $n$ has at least one lemma on a page matching its number.
Proof by induction on $n$:  The case $n=1$ is obvious.  Now suppose the statement is true for some $n$, and suppose we have a book of $n+1$ lemmas and $n+1$ pages.  If lemma $n+1$ is on a page numbered less than $n+1$, then lemmas $1$ through $n$ must be on pages $1$ through $n$, and there must be at least one lemma on a same-numbered page by the inductive hypothesis.  If not, then lemma $n+1$ is on page $n+1$, and we're done.

A: Another proof, this time not by induction.
[Edit:  on being tidied up, this turned out to be basically an expanded version of the other proofs that don't use induction.]
Consider a book of $k$ lemmas and $k$ pages.
For $1\le n \le k$ and $ n\in\mathbb N$, let

*

*$p_n$ be the page number of the $n$th lemma

*$D_n=n-p_n$ be the difference between the lemma number and its page number.

We are asked to prove that for some $n$, $D_n=0$.
Suppose we have assigned pages to the first $n$ lemmas. The next lemma can be on either the same page as lemma $n$ or a later page, i.e.
$$p_{n+1}\ge p_n$$
from which
$$D_{n+1}\le D_n+1$$
That is, $D_n$ can't increase by more than $1$ between one lemma and the next.
If the first lemma is on the first page ($p_1=1$), or the last lemma is on the last page ($p_k=k$), we already have a lemma on its own-numbered page. So we need only consider the case where $p_1>1$ and $p_k<k$, making $D_1<0$ and $D_k>0$.
$D_n$ must therefore increase from a negative value to a positive one somewhere between $n=1$ and $n=k$. But it can only increase in steps of $1$. So for $D_n$ to change sign, there must be a value of $n$ for which $D_n=0$, ie for which lemma $n$ is on page $n$.
There is therefore at least one lemma on a page with  the same number as the lemma.


text:
Q: spark-submit is throwing java.lang.ClassNotFoundException: SparkPIIDetector I have a simple java spark application (SimpleApp.jar) that I am trying to run using the below command in Windows environment
spark-submit.cmd --class SimpleJar --master local SimpleApp.jar

which keeps throwing
java.lang.ClassNotFoundException: SimpleApp
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at org.apache.spark.util.Utils$.classForName(Utils.scala:225)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:686)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

The directory structure of my project is like this
SimpleApp
- infrastructure (AN ANSIBLE MODULE)
- SimpleApp (A MAVEN MODULE)
- - src
- - - main
- - - - java
- - - - - SimpleApp.java
- - - - resources
- - pom.xml

And inside the POM I am using the shade plugin to build my uber jar like so
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.3</version>
                <executions>
                    <!-- Run shade goal on package phase -->
                    <execution>
                        <id>SimpleAppId</id>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <!-- add Main-Class to manifest file -->
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>SimpleApp</mainClass>
                                </transformer>
                            </transformers>
                            <shadedClassifierName>SimpleApp</shadedClassifierName>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

Could someone please advise what is being missconfigured here.
Is this something that has to do with the environment being windows?
I am able to deploy this on AWS EMR with no issues.
In addition, this may also be useful
unzip -p SimpleApp.jar META-INF/MANIFEST.MF

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Built-By: <author>
Created-By: Apache Maven 3.3.9
Build-Jdk: 1.8.0_191
Main-Class: SimpleApp

A: There was a version mismatch between the spark running on my machine and the dependency I was using in my application. Once I have changed to the newest version of spark everything worked smoothly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing href value to another page using html and javascript
As mentioned above, i need to create a class="donate" that will be used in anchor tag which will  redirect and pass the value of href to my another page i.e -mysite.com/donate.html,
where donate.html will be able to grab that href value .
so that when user click on " continue to download"  will be able to download the
file .
Please let me know whether is it possible or not .
I would prefer HTML and javascript only . as I don't host webpages i use blogger .
I've seen similar concept in templateism.com, something like:
www.templateism.com/p/preview.html?=www.templateism.com/10/2010/anypost.html

A: you can use the link like:
mysite.com/donate.html?www.yoursite.com.otherpage.html

and then using javascript:
var href = document.location.href;
var link = href.split('?')[1];

A: Basically you need to pass the value you required in querystring like mysite.com/donate.htm?key=value.
On donate.htm page you can use this function mentioned here How can I get query string values in JavaScript? to fetch the value you supplied in querystring by passing the key.

A: You can use the JavaScript (jQuery required) code below to attach a click event handler to all links with the donate class.
JS on page1.html and page2.html
$(document).ready(function() {
    $('a.donate').click(function() {
        // Retrieve the href value and store it in a variable.
        var href = $(this).attr('href');

        // Redirect a user to the desired page and passes the href value in query string.
        window.location.href = 'http://example.com/donate.html?href=' + href;

        // Ensure the original click event handler is not triggered.
        return false;
    })
});

After clicking a link the user will be redirected to the donate page where you can parse the query string and obtain the value of the href (which is what was in the  on the previous page).
There are many ways to parse the query string but the following quick&dirty code should work for you.
JS on donate.html
var location = document.location.href;
var queryString = location.split('?')[1];

// In the href variable is now what you are looking for.
var href = queryString.substr(5);

A: Here try this For example...... This is your html code

As Ashkan said, use his javascript to parse the previous url from it...
Paste this code on donate.html

Hope this helps;


text:
Q: How to add plugin to blog I just created a new blog and I'd like to add a plug-in to the blog.
I am following this tutorial on how to do it, but on my admin screen there is no "Plugins" option (under "Appearance").
What am I doing wrong?  What can I do to get my desired plugin for my blog?

A: You can't add plugins on wordpress.com, only on self-hosted sites.


text:
Q: Lenovo P50 is not booting from NVMe SSD I bought Lenovo P50 recently with regular HDD and decided to have NVMe now. I put the NVMe without pulling the HDD out. I used the EaseUS Todo to clone the Windows to NVMe drive. It copied successfully. Then I pulled out the HDD, but the laptop will not boot from the NVMe drive. Is there anything that I am missing?

A: Did you clone just the Windows partition, or the whole Windows drive? Also, did you clone any other partitions that are on the same HDD?
Here's a very brief breakdown of what has to be done to successfully clone Windows (other than copying the Windows system partition), depending on the way it was installed:

*

*Installed in UEFI mode: Clone the EFI System Partition (ESP) exactly, making sure to get the filesystem type flag, etc. exactly mirrored to the new drive

*Installed in BIOS mode: Clone the Boot Sector exactly, byte for byte

If you did one of those things and it still won't boot, you should go back and boot Windows on the HDD side and verify that you can "mount" (via Disk Management) the NVMe drive and make sure it works for reading and writing files off of the copied Windows system partition. If that doesn't work, it's probably hardware issue, or the copy of the Windows partition failed and you should try it again (likely filesystem damage from an incomplete copy).


text:
Q: Force open camera on action_get_content intent to avoid some bugs When using the following code to select a picture from my gallery, I also have the option to take a new picture, when I do it saves it (in the default image gallery) and I can select that image.
Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(
                Intent.createChooser(intent, "Select Picture"),
                PICK_IMAGE);

My ultimate goal is to have two options "select from gallery" and "take picture".  My question - is there a way to boot the camera automatically via the above Intent, possibly with some extras?
And I don't mean using the camera intent:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");

While testing with the camera intent I have been running into two main bugs: Ok button bug and the small image return, so I was wondering if my other method is possible.  Probably not, but its worth a shot..?

A: As far as I know, the answer is no.  The best method is getting the Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); to play nicely.  Even if it were possible, the user interaction would be unintuitive and confusing as there would be no "accept photo" button/interaction.


text:
Q: Why the view constructor is not called every time I create a new viewmodel? I am using WPF with model-view-viewmodel pattern. I have a ResultsView and ResultsViewModel which are connected like this:
            <DataTemplate DataType="{x:Type VM:ResultsViewModel}">
                <VW:ResultsView/>
            </DataTemplate>

In my main window I have some kind of paged setup where MainContent property stores the current page (ViewModel instance).
I create the page like this
MainContent = new ResultsViewModel();

ResultsView is based on UserControl, it also has a handler for Loaded event which does some UI initialization stuff.
Everything works fine while the user is navigating between different pages.
But if the user opens the ResultsView two times in a row, the ResultsView constructor is not called the second time, and also Loaded event is not called. It seems that now I have the same old ResultsView instance attached to the new ResultsViewModel()!
Why WPF does not create a new View each time I create a new ViewModel? Is there some way I can force WPF to discard the old view if the old viewmodel is destroyed?

A: <DataTemplate x:Shared="False" DataType="{x:Type VM:ResultsViewModel}">
    <VW:ResultsView/>
</DataTemplate>

A: See Kent's answer for practical work-around for your issue.
That said, it's a good practice to only instantiate the View once, as there is overhead associated with constructing the Visual Tree and setting up all of the bindings.  Generally the View/ViewModel should be designed so that you can swap out the underlying ViewModel without the View caring or even noticing (other than DataContext changing and therefore all binding values being re-evaluated.)  If you currently have logic in your Loaded event that prepares for a specific ViewModel, consider registering for notification of when DataContext changes instead (see this example).


text:
Q: Call decorated class method upon __init__() I am trying to return a dataframe (that is the result of a function concatenating two dataframes) upon class initialization. Since I cannot use the decorator directly upon the init, I have to call the decorator upon a separate method and pass this to init.
Unfortunately, the desired resulting dataframe is not returned when I instantiate the class?
I have tried wrapping the function using functools 'wraps' however I am still not getting the desired result, despite no errors being thrown
from functools import wraps

# the decorator function
def join_results(func):
  @wraps(func)
  def join_df_wrapper(*args, **kwargs):
    close_df.columns = map(str.lower, close_df.columns)
    close_df.set_index(pd.to_datetime(close_df.dates))
    model_preds_df.columns = map(str.lower, model_preds_df.columns)
    model_preds_df.set_index(pd.to_datetime(model_preds_df.dates))
    return func(*args, **kwargs)

class BackTestModelPNL(object):
  """test decorator"""

  def __init__(self, close_df: pd.DataFrame, model_preds_df: pd.DataFrame):
    self.close_df = close_df
    self.model_preds_df = model_preds_df
    self._initial_df = self.return_init_df()

  @property
  def initial_df(self):
    return self._initial_df

  # call decorator
  @join_results
  def return_init_df(self, *args, **kwargs):
    return self

# test that the class inits and returns joined results dataframe
df = BackTestModel(close_df, model_preds_df)

The Class is called without error but the desired result (the joined dataframe) is not returned when the class is instantiated

A: __init__() should always return None.
https://docs.python.org/3/reference/datamodel.html#object.init

Because new() and init() work together in constructing objects
  (new() to create it, and init() to customize it), no non-None
  value may be returned by init(); doing so will cause a TypeError
  to be raised at runtime.

You can do this using property which is a more pythonic way. The return_init_df() function can compute your initial data frame.
# Define class
class BackTestModel(object):
  def __init__(self, close_df: pd.DataFrame, model_preds_df: pd.DataFrame):
    self.close_df = close_df
    self.model_preds_df = model_preds_df
    self._initial_df = self.return_init_df()

  @property
  def initial_df(self):
    return self._initial_df

# test that the class inits and returns joined results dataframe
df = BackTestModel(close_df, model_preds_df)
inital_df = df.initial_df


text:
Q: How can I restores Nautilus' old open with context menu? On Ubuntu prior to 16.10 Nautilus provided the following open with context menu:

Under Ubuntu 16.10 it now looks as follows:

How can I restore the old open with context menu for quicker access to the applications?

A: There is no way to enable the old Open With version in Nautilus 3.20. There's no possibility to do it by changing it in the Preferences, there is also no option to do it using the dconf-editor tool.
That is due to how Nautilus 3.20, as part of the GNOME 3.20 desktop environment was designed. As there is no plugin available in the repositories to add this feature, you'll have to use it 'as it is'.
Of course it might be possible to tune the software by changing the code ... but this might break some other things and the main functionality still exists, you just have to make a few clicks more.

A: Another solution for Gnome >= 3.20, like Gnome 3.38 with Ubuntu 20.10, is to use nautilus-open-with-menu that bring a automatic list of applications to open-with.


text:
Q: what's difference about git branch -d  and git branch -D  I an newer about git. after I merge my branch from another branch, I found something wrong. Now my status is I have commit these changes from merging, but not push into the origin/mybranch. So I just wanna delete my local branch. Then I use git branch -d mybranch. However, it failed. It told me that I cann't delete my local branch. After searching goolge, I found the command git branch -D mybranch, and used it to delete my branch successfully. So could anyone told the difference about these two commands ?

A: The -D is a force-delete and the -d will provide a warning before deleting if the branch has not been merged into its upstream branch

A: You can find the answer using git help branch. (Because it is regarding the git branch command.)
There you find:
-d
--delete

    Delete a branch. The branch must be fully merged in its upstream branch, or in HEAD if no upstream was set with --track or --set-upstream.
-D

    Delete a branch irrespective of its merged status.

Usually you do git branch -d. - If git complains, you should think again and if you are sure you do not need any commits from that branch anymore you can do git branch -D to delete it anyway.


text:
Q: Ghci error: No instance for Show This works in the ghci
data MyList a = Empty | Cons a (MyList a) deriving (Show, Eq, Read, Ord)

let x = Cons(21, Cons(12, Empty))

However when I type:
Prelude> x

I get this error:
No instance for (Show (MyList (Integer, MyList (Integer, MyList a0) ->
MyList (Integer, MyList a0)) ->
MyList (Integer, MyList (Integer, MyList a0) ->
MyList (Integer, MyList a0)))) arising from a use of `print'

A: You are using the wrong syntax for function application. The following code does what you want:
let x = Cons 21 (Cons 12 Empty)

The reason for this is that the Cons constructor is a curried function, but you are treating it as an uncurried function.
Curried functions
Consider the following function adding two integers:
add :: Int -> (Int -> Int)
add = \x -> (\y -> x + y)

Here we say add is a function, which takes an argument x of type Int and returns a function,
which takes an argument y of type Int and returns x + y of type Int.
We can apply this function for example as (add 1) 2 evaluating to 3.
Function application is left-associative in Haskell, which means that we don't need the parentheses
in (add 1) 2 and can simply write add 1 2.
The function type constructor -> is right-associative in Haskell, which means that we don't need the parentheses in add :: Int -> (Int -> Int) and can simply write add :: Int -> Int -> Int.
Also we don't have to explicitly define add using lambdas and can use the following notation:
add :: Int -> Int -> Int
add x y = x + y

Encoding multi-parameter functions as single-parameter functions returning single-parameter functions is quite common in Haskell. This approach has the nice property, that we can also partially apply a function. For example the following function takes a single Int and adds 2:
add2 :: Int -> Int
add2 x = add 2 x

But we can also partially apply add and simply write:
add2 :: Int -> Int
add2 = add 2

This is also called point-free notation, where parameters are referred to as points.
Uncurried functions
An alternative encoding of multi-parameter functions can be done using tuple-values, i.e.
add' :: (Int, Int) -> Int
add' (x, y) = x + y

We can invoke this function for example as add' (2, 3), which constructs the pair (2, 3) :: (Int, Int) and passes it as a single argument to the add' function.
Uncurried <-> Curried
In the standard library are two functions to convert functions between the two styles.
curry :: ((a, b) -> c) -> a -> b -> c
curry f x y = f (x, y)

uncurry :: (a -> b -> c) -> (a, b) -> c
uncurry f (x, y) = f x y

For example curry add' gives us add, and uncurry add gives us add'.
Back to explaining ghci's rambling
Note that we could also write the uncurried application as add'(2, 3), which together with partial application and polymorphism explains why let x = Cons(21, Cons(12, Empty)) doesn't directly lead to an error, but ghci subsequently says misterious things about the evaluation of x.
What happens here is that (12, Empty) is pair of type (Int, MyList a) for some type a.
This pair is then used as the first argument in Cons (12, Empty), so we get a partially applied function which takes
a MyList (Int, MyList a) and appends (12, Empty) as an element to this list.
The same happens for Cons(21, Cons(12, Empty)) where we partially apply a pair of 21 and the before mentioned partial function. In the end we tell ghci to print a function, which it cannot display and hence complains about a missing Show instance for the corresponding function type.


text:
Q: Could not able to parse text and Image from PDF file I have gone through tika Documentation. I find a solution to extract text. but it does not print return image.
.java File
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.ocr.TesseractOCRConfig;
import org.apache.tika.parser.pdf.PDFParserConfig;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;

public class Imageextractor3 {

     public static void main(String[] args)
                throws IOException, TikaException, SAXException {
            Parser parser = new AutoDetectParser();
            BodyContentHandler handler = new BodyContentHandler(Integer.MAX_VALUE);

            TesseractOCRConfig config = new TesseractOCRConfig();
            PDFParserConfig pdfConfig = new PDFParserConfig();
            pdfConfig.setExtractInlineImages(true);

            ParseContext parseContext = new ParseContext();
            parseContext.set(TesseractOCRConfig.class, config);
            parseContext.set(PDFParserConfig.class, pdfConfig);
            //need to add this to make sure recursive parsing happens!
            parseContext.set(Parser.class, parser);

            File file=new File("C://Users//Vaibhav Shukla//Desktop//8577.00.pdf");
            System.out.println(file);

            FileInputStream stream = new FileInputStream(new File("C://Users//Vaibhav Shukla//Desktop//pdfs//hh.pdf"));
            Metadata metadata = new Metadata();
            parser.parse(stream, handler, metadata, parseContext);
            System.out.println(metadata);
            String content = handler.toString();
            FileOutputStream fos=new FileOutputStream("C://Users//Vaibhav Shukla//Desktop//pdfs//hd.doc");
            fos.write(content.getBytes());
            System.out.println("===============");
            System.out.println(content);
            System.out.println("Done");
        }

}

I need suggestion how to add functionality which can detect the image in pdf file

A: A quick solution to convert extract images which are embedded in pdf.
public void extract(File file) throws IOException {
 PDDocument doc=new PDDocument().load(file);
 Iterator<PDPage> itr=doc.getDocumentCatalog().getPages().iterator();
 while(itr.hasNext())
 {
    PDResources res=itr.next().getResources();
    Iterable<COSName> cName=res.getXObjectNames();
    Iterator<COSName> citr=cName.iterator();
        while(citr.hasNext())
        {
            String imageName= citr.next().getName();
            System.out.println(imageName);
            COSName cosName=COSName.getPDFName(imageName);
            PDImageXObject im = (PDImageXObject) res.getXObject(cosName);
            File ff = new
            File("C://Users//workspace//Desktop//pdfs//"+imageName+".png");
            BufferedImage bi=im.getImage();
            ImageIO.write(bi,"png",ff);
        }

 }}


text:
Q: How to set/check for a unique value in a column with CHAR (1) = y/n I'm not very strong in SQL statements but I would like to know about a thing I'm willing to know.
Imagine a "visible" column that holds 'y' or 'n' values. Is it possible to have only a single 'y' without launching a pre-query that updates this table to 'n' value for all rows before setting the desired row to 'y'?
Thanks in advance.

A: Assuming you want to set row with ID 123 to be visible, you can do the following. The first query will not update all rows, only the row(s) that are already set to Y:
update MyTable set Visible = 'N' where
Visible = 'Y';
update MyTable set Visible = 'Y' where
ID = 123;

Another approach is, rather than making Visible a flag, make it a VisibleDate column. Then set that column to the current date for the row you want to be visible. Then, to determine which row is currently visible, select the max date from the VisibleDate column to find the row.

A: You might consider another approach for what you are doing.  Imagine that your table has a primary key (it should) called id.
Create a table called Visible:
create table Visible (id int)

Now, you can create the flag by the following query:
select t.*, (case when v.id is not null then 'Y' else 'N' end) as VisibleFlag
from table t left outer join
     Visible v
     on t.id = v.id

You can wrap this query in a view, to simplify other coding.
This gives you the ability to set one row to visible, without affecting other rows.  The performance should be quite good, since looking up one row in a table, using the primary key is a fast operation.  You can also use a similar table for other types of flags, but you have to specify the name of the flag in each row.


text:
Q: JUnit list of methods to be executed I am trying to get the number of methods to be executed by JUnit for the current test class. For example if the entire test class is run by maven I should get lets say 10, but if I want to run 3 tests of that class from IntelliJ, I would like to get that number, does anyone know how and if I can achieve this?
What I am looking for would be a JUnit "context" object that has this information prior to executing a test class.
If that is not possible I would like to know if we can register a callback method that would be called automatically by JUnit after running all the tests.

A: What I think you're looking for (though it's tough to tell) is the TestWatcher JUnit @Rule. It allows you to hook in some custom logic at each point in the lifecycle of each individual test. You can use it to get information when each test starts and accumulate your own information about how many and which tests ran.


text:
Q: Ivy, Maven - Map transitive dependency Let's say we have bunch of artefacts, all of which have a child/transitive dependency on
artefact{group=zambia, id=zebra}

For reasons beyond my comprehension, some smart fella updated whatever used to be called artefact{group=zambia, id=zebra} to
artefact{group=africa, id=hello-zebra}

leaving a whole bunch of artefacts losing their child references to {zambia:zebra}
Let's also say that for reasons beyond my explanation, I am unable to get those parent artefacts pom or ivy.xml updated to instead having dependency on {africa:hello-zebra}.
Question:
Is there a way in my pom and/or ivy.xml to redirect any transitive dependencies on {zambia:zebra} to {africa:hello-zebra}?

A: I don't know about Ivy but for Maven check this article out:
http://maven.apache.org/guides/mini/guide-relocation.html
It looks like uploading a pom.xml to your repository for your old artifact with a relocation element might do the trick:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>zambia</groupId>
  <artifactId>zebra</artifactId>
  <version>????</version>
  <distributionManagement>
    <relocation>
      <groupId>africa</groupId>
    </relocation>
  </distributionManagement>
</project>


text:
Q: Why do univariate indefinite integrals carry the $\mathrm {d}x$? I understand that the $\mathrm {d}x$ sort of comes from the $(x_i-x_{i-1})$ term in the Riemann sums of the integrals (just like the $\mathrm dg$ for Riemann-Stieltjes integrals), but when working with indefinite integrals, there are no Riemann sums, so there's no point in carrying a $\mathrm {d}x$ for any heuristic/pedagogic purpose.
Thus, why do we even add the $\mathrm dx$ in $\int f(x)\,\mathrm d x$? Just to explain the change of variables theorem (saying "$\mathrm dx=g'(u)\,\mathrm du$")?

A: TL;DR: because $\newcommand{\d}{\mathrm d}\DeclareMathOperator{id}{id}\displaystyle\int$ is the inverse of $\d$, not $'$.

Let
$$\d f(x)=f'(x)\Delta x\tag{1}\label{eqn1}$$
for some linear increment $\Delta x$.
Also let $$\id:\:\mathbb R\to\mathbb R$$
be the identity function such that $$\id(x)=x;\tag{2}\label{eqn2}$$
plug $f=\id$ into $\eqref{eqn1}$ to see
$$\d\id(x)=\id'(x)\Delta x=\Delta x\tag{3}\label{eqn3}$$
(here the fact that $\id'(x)=1$ is being used); now take the LHS and RHS of $\eqref{eqn3}$:
$$\d\id(x)=\Delta x$$
and use $\eqref{eqn2}$ on the LHS to see
$$\d x=\Delta x,$$
so that $\eqref{eqn1}$ rewrites as
$$\d f(x)=f'(x)\,\d x.\tag{4}\label{eqn4}$$
Additionally, you can observe the following geometrical interpretation.
$\hskip{70 pt}$
Here $y=f(x)$, $\mathfrak T=f'(x)$ and $\d x$ is some arbitrary increment for which $\d y=\d f(x)$ provides the best linear approximation at point $P=x$.
Now, your question. The symbol $\displaystyle\int$ is defined as the inverse of the symbol $\d$:
$$\d\int\Phi=\Phi\tag{5}\label{eqn5}$$
for any $\Phi$. As with many, many other operations, the inverse here is multivalued (compare with $(\,\cdot\,)^2$, for which the inverse has two values: $-\sqrt{\,\cdot}$ and $\sqrt{\,\cdot\,}$), i.e. there generally are more than one $\int\Phi$ such that $\d\int\Phi=\Phi$, and incidentally you can prove that all of them differ by a constant, meaning that although $\d$ cancels with $\int$ cleanly when $\d$ comes first, we otherwise have that
$$\int\d\Phi=\Phi+C\tag{6}\label{eqn6}$$
holds for any constant $C$, as you can easily prove via differentiation of both sides, the fact that $\d C=0$ and $\eqref{eqn5}$ to cancel $\int$.
Taking the antiderivative may be represented with the use of the symbol $\displaystyle\int$. Let's say, we want the primitive $f$ of $f'$. Return back to $\eqref{eqn4}$:
$$\d f(x)=f'(x)\,\d x$$
and notice if we take the inverse of $\d$ of both sides:
$$\int\d f(x)=\int f'(x)\,\d x,$$
we can use $\eqref{eqn6}$ to cancel $\d$ out on the LHS, which gives us
$$f(x)+C=\int f'(x)\,\d x,$$
a very familiar identity.
Also, $\eqref{eqn4}$ may be of use when integrating to perform "$u$-substitution" without actually substituting anything:
$$I=\int x\cos\left(x^2\right)\,\d x=\frac12\int\cos\left(x^2\right)2x\,\d x=\frac12\int\cos\left(x^2\right)\,\d\left(x^2\right),$$
which just uses $\eqref{eqn4}$ to have $2x\d x=\d\left(x^2\right)$. You can now put $u=x^2$ if it pleases your eye:
$$I=\frac12\int\cos(u)\,\d u,$$
but this is in no way necessary, as you can (knowing that $\sin'=\cos$) directly go to
$$I=\frac12\int\cos\left(x^2\right)\,\d\left(x^2\right)=\frac12\sin\left(x^2\right)+C.$$
The chain rule also gets very intuitive with this notation.

A: Because $\int f(x,y)\, dx$ is different from $\int f(x,y)\, dy$
In more advanced text, I have seen $\int f$ being used.

A: Since the indefinite integral is defined as the set of antiderivatives of $f$, that is,
$$F: I⊆ℝ\rightarrow ℝ$$ such that $F$ is differentiable and it holds that:
$$\frac{dF(X)}{dx}=F'(X)=f(x) ∀ x\in I$$
 $$dF(X)=f(x)dx$$
then the symbol for the integral comes naturally.

A: The primary reason for this is because integration is defined* on differential forms. In that context, we have that if $F'(x)=f(x)$ then $dF(x) = f(x)\,dx$. Intuitively, this is expressing that the change in $F$ is proportional to the change in $x$. That is, it marks that we take derivatives with respect to variables, not just in a vacuum. This has the convenient consequence that change of variables like $dx = g'(u)\,du$ are actually formal statements, with the usual notion of equality.
In a sense, $dx$ gives the right structure to $\mathbb R$, whereas if you integrated with a different differential form - like $u$ - you'd be integrating with respect to some kind of 'squished up' structure. For instance, with $du=2dx$ we get that our integrals $\int f(x)\,du$ come out twice as big as they're supposed to, because if we rewrite this, we see that $\int f(u/2)\,du$ - and we get $2F(u/2)+C=2F(x)+C$ because when we integrated with $du$, we made $x$ move slower than the variable $u$ that we integrated, so we counted everything too much. This isn't wrong, but it makes the point that our differential forms are telling us how much we 'weight' each point of the domain, and $dx$ is giving us the proper weighting.
This isn't to say that you couldn't omit the symbols and really just work on functions $\mathbb R\rightarrow\mathbb R$ in the obvious way - and in some contexts, it's useful to do this - but there is certainly some sense in including the $dx$ terms, as they do express something.
*There are sometimes other notions of integration. For instance, in measure theory, one often has that $dx$ specifies the measure you're using. That is, if you have something like:
$$\int f(x)\,dx$$
the function $f$ assigns values to each point in the space $\mathbb R$ and the term $dx$ says we integrate with respect to Lebesgue measure. This is as opposed to integrating with respect to, say, counting measure, where we just sum up the non-zero values of $f$, or any number of other measures. This is just a more general notion of weighting the domain.


text:
Q: Devise Registration controller/page behavior
*

*Is there a way to avoid :require_no_authentication callback to be called?

*

*Adding before_action :authenticate_user! in the controller does nothing. I guess its because of the :require_no_authentication in Devise source code that is being prepended to the callback chain.

*When signed in, can we change the behavior and actually access the registration page?

Thanks in advance!

A: It's easy enough to do. You can just create your own controller to override the behaviour:
In app/controllers/users/registrations_controller.rb:
class Users::RegistrationsController < Devise::RegistrationsController
  skip_before_action :require_no_authentication
end

In routes.rb you need to specify to Devise to use your controller:
devise_for :users, controllers: {
  registrations: "users/registrations"
}

I've made some assumptions about your Devise setup, but this should give you the general idea.


text:
Q: How to solve "short write" error when writing to CSV I've been encountering this issue that I can't seem to figure out what's happening. I have code that appends some information to a CSV. The information comes from multiple threads and the CSV is logging times.
At some point during program execution, the code will start spitting out "short write" instead of writing to the CSV.
Printing the data to be outputted, there seems to be no difference in "good" writes and "short" writes and once the "short write" error stops, it continues that until the program is restarted.
This code is called each time a CSV write is desired.
        output := []string{time.Message, strconv.FormatInt(time.Duration, 10)}
        fmt.Println(output)
        err := writer.Write(output)
        if err != nil {
            fmt.Println("An error encountered ::", err)
            fmt.Println("writer.Write error")
            logMessage(err.Error())
        }
        writer.Flush()

Looking at my output, this is the point where it starts the short write.
[message1 21]
[message2 207]
[message3 79]
An error encountered :: short write
writer.Write error
short write

And here's my output in the CSV
message1,21
message2,207
ssage2,207

So it seems like the short write is coming from that second line but why is it writing my message twice, and why is it "short writing" the message? There are hundreds of successful messages then the error just seems to occur suddenly.
Looking at the code, the place to call the CSV writer functionality only hits once, so I'm really stuck on why this is happening.

A: The application has a data race on writer. Use a sync.Mutex to ensure that only one goroutine accesses the writer at a time.
mu.Lock() // <-- Lock to prevent concurrent write and flush.
output := []string{time.Message, strconv.FormatInt(time.Duration, 10)}
fmt.Println(output)
err := writer.Write(output)
if err != nil {
  fmt.Println("An error encountered ::", err)
  fmt.Println("writer.Write error")
  logMessage(err.Error())
}
writer.Flush()
mu.Unlock() // <-- Unlock.

Run the race detector on the application and fix any reported problems.

A: I guess you are using writer with buffer(like bufio). This error would happen when a groutine is writing data to buffer and the other is trying to flush.
Just simply add a locker in the critical section.
mu.Lock()
// critical section
mu.Unlock()


text:
Q: Result Cache size in Snowflake Result Cache in Snowflake is quite useful.
One use case which I am trying is to run the User's query post Batch Load in the datawarehouse so that the result is cached. And when after 2-3 hours when the Business Users would run the same query maybe using the most smallest warehouse the data will be returned from cache.
But I need to understand what is the volume capacity of the result cache. Can we get to know anyhow how much rows result cache can store.
Lets suppose a user query pulls a million rows. Will Snowflake store all the million rows in result cache. Or lets say 100 million rows.
Once the capacity is breached where will be the data stored. And how do we know the capacity and when it was breached

A: There is no practical limit on the size of the result set cache. The limit is on time, which is 24 hours since the last use of a result set:

Each time the persisted result for a query is reused, Snowflake resets
the 24-hour retention period for the result, up to a maximum of 31
days from the date and time that the query was first executed. After
31 days, the result is purged and the next time the query is
submitted, a new result is generated and persisted.

https://docs.snowflake.com/en/user-guide/querying-persisted-results.html
Some additional considerations:

*

*Running the same query does not guarantee use of the result set cache. There are 8 criteria that must be met, and even then it's not guaranteed to use the result set cache. https://docs.snowflake.com/en/user-guide/querying-persisted-results.html#retrieval-optimization

*To guarantee using the result set cache, instead of running the same query within 24 hours, you can run select * from table(result_scan('019caf93-0500...'));

*If you don't do any processing/filtering of the result set and just do a select *, it doesn't even need a running warehouse.

*Note that if you run a query as in #2, if the data in the underlying table(s) changes, it will not change the results. Running the original statement that generated the result set again will do that (table changes is one of the 8 criteria in point #1), but will be less likely to reuse the results.

*If you use the result_scan function, you can treat it like any table and join it with other tables, filter it, run functions on it, etc. Doing anything other than a simple unfiltered select will require a running warehouse. The warehouse size could possibly be substantially smaller than the one used to create the result set in the first place. For example, a complex query could digest results, and then someone may use the result set through the result_scan function to filter by rows or perform a simpler query against the pre-processed result from the main query.


text:
Q: jquery regex negate letters I am trying to validate a contact number field, with that I am not allowing any letters.
JS FILE
$(document).ready(function() {
    //var regex = /[^\d]/;
    var regex = /[^a-zA-Z]/;
    $('#contact_num').blur(function() {
        if(regex.test($(this).val()) == true) {
            alert('valid');
        } else {
            alert('invalid');
        }
    });
});

HTML FILE
Contact Num: <input type="text" id="contact_num" />

My regex here seems to return valid if the letters comes with the digits, which must be false.
DEMO

A: You are only checking a single character, though you are very close. You need anchor characters on the side.
var regex = /^[^a-zA-Z]+$/;

A: If you don't allow only letters but allow any other characters then you should reverse your regexp and your condition:
var regex = /[a-zA-Z]/;
...
if( !regex.test($(this).val()) ) {

http://jsfiddle.net/PYwLJ/3/


text:
Q: Generating random string based on some hex I have a md5 checksum in python; like s = '14966ba801aed57c2771c7487c7b194a'.
What I want is to shorten it and make it a string in the form 'a-zA-Z0-9_.-', without loosing entropy of my random md5 checksum.
The output have to be pronounceable, so I cant just do binascii.unhexlify(s). Nor can I do base64.encodestring(s) and cut it because then I will loose entropy.
Any ideas on how to solve this without mapping an insane number (256) of hex pair (00->FF) to different letters?
The reason I want this is to be able to say a whole md5 checksum over the phone, but use the whole alphabet+numbers+some special characters.

A: I'm going to play fast and loose with your requirements a little and take a shot at something which I think might help you.
Reading over what you've written, the requirement that stands out to me is a way to read a message digest over the phone.
To that end, you might want to look at Bubble Babble.  Bubble Babble is designed to encode a digest (or other things) into a pronounceable string:

ASCII Input       Encoding
------------------------------------------------------------------
`' (empty string) `xexax'
`1234567890'      `xesef-disof-gytuf-katof-movif-baxux'
`Pineapple'       `xigak-nyryk-humil-bosek-sonax'

Here's a Python implementation: http://code.activestate.com/recipes/299133-bubblebabble/

A: Since you want the "number" (yes, a md5 hash is nothing but a base16 number, we can of course convert that to base-something to shorten the string) to be pronouncable over the phone, I suggest avoiding mixed upper- / lowercase.
And when we only allow [0-9A-Z], we can simply use the builtin int() with Base36 for decoding.
See:
>>> def encode(num):
        import string
        ALPHABET = string.digits + string.ascii_uppercase
        tmp = []
        while num:
            num, rem = divmod(num, len(ALPHABET))
            tmp.append(ALPHABET[rem])
        return ''.join(reversed(tmp))

>>> import hashlib
>>> the_hash = hashlib.md5('test').hexdigest()
>>> decimal_representation = int(the_hash, 16)
>>> encoded = encode(decimal_representation)
>>> the_hash
'098f6bcd4621d373cade4e832627b4f6'
>>> decimal_representation
12707736894140473154801792860916528374L
>>> encoded
'KDISMNX5MOYU6Q6PZT8TQDPY'
>>> decimal_representation == int(encoded, 36)
True
>>> hex(int(encoded, 36))
'0x98f6bcd4621d373cade4e832627b4f6L'

You could of course use a longer alphabet to shorten the resulting string, but then you'd have to write your own decode() function. Should not be too hard, though.

A: *

*short answer: you can't

*longr answer:
a md5 hashsum contains 128 bits of information, so to store that you also need 128 bits. the closest you get from that to a human readable form would probably be to base64 encode it, that will leave you with 22 characters (24 with padding). that's probably as short as it gets.*

where does the randomness in your md5 hash come from anyway? md5 hashes arn't random, so you're probably hashing something random (what?) to get them (and by doing so you can't increase the entropy in any way, only decrease it).

*you could probably create you own way to encode the checksum using a larger range of characters from the unicode range... but that would mean you had to select a suitable set of characters that anybody will know how to pronounce...
something like ☺ ⚓ ⚔ ☂ ☏ would seem fairly clear, but some symbols like ♨ no so much...


text:
Q: Understanding Example Phaser Game Code So I have stumbled across some example game code that runs on Phaser's html 5 game engine. Below is the example code
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {
    game.load.image('someKey','someUrl');

}

function create() {
}

function update() {
}

I'm trying to figure out how phaser is able to accomplish passing in functions (preload,create, and update) to the game object by referring to the function declarations and adding images, for example, to the object via the variable name 'game'. The example provided above is what I have generally seen around the web (or at least something similar).
Below, I have started working on my own game engine (for fun) in order to imitate phaser and understand their though process. Unfortunately, I can't successfully accomplish the same effect as seen above.
My Engine.js (Phaser copycat file)
function Game(holderId,canvasOptions,functionDeclarations){
    this.test="testing";
    functionDeclarations.init();//this does not work :( because game in init() is undefined.
}

My Main.js
var game= new Game("canvas-holder",{width:1500,height:600, unit:"px"},{init:init,core:core,update:update});

function init(){
    console.log(game.test);//game is undefined. Seems like a scope issue
}

I sense this is a scoping issue. I tried looking through phaser's source code, but it contains 97k lines, and ctrl+f was of no help.

A: The Object being passed to the Phaser constructor is the game State. Look at src/core/State.js in the Phaser repo for an example State file, and descriptions as to what each function and property does.
I cannot say this enough: Don't ever try to read through the one single phaser.js file! Instead checkout the repo and go through the files one by one. They're in a logical and sane structure there, and much easier to follow the path through.
When the Phaser game is created it waits for a DOM Ready event. Only when it receives that does it then start to run through the State object, calling the functions in turn. This is why you can reference game within the preload function, and not get a scope error, because by the time it's called, it exists.
In the example above (and all those found on the Phaser examples site) game is created as a global JS object. We do this purely to keep the example code less verbose, and easy to fiddle with. In a production level game you'd rarely actually do this though. Look in the Phaser repo, 'resources' folder at the Project Templates, there are better structured alternatives in there.

A: In your code, init uses game. game is defined by the Game constructor, which attempts to call init before it's done (and thus, before game is assigned). This results in a circular dependency and game will be undefined during the init call.
One way to solve this problem is to delay the execution of init. Using setTimeout(functionDeclarations.init, 0) instead of a direct call to init, you'll finish the constructor, assign the correct value to game and execute whatever else might be in your JS file. Once all that is done, init will be called and everyone will be happy.


text:
Q: general Java design of consuming an async web service i need to consume a batch web service where I send a unique id to identify myself, then the service sends back a unique response id that I am to use some minutes later to get the info I need.
in general, what is a good way to keep track of the response id and call the service again at some later time to get the real response?

A: The easy solution is to stick the ID and timestamp a map* or list, then have a loop in a separate thread that wakes up and processes all IDs older than a certain age. (Make sure that the map or list is thread-safe.) However, if your app goes down and gets relaunched, it will lose track of pending requests. If you must handle that case, use a database.
*
One specific solution is to use a SortedMap keyed by timestamp. You must make sure every timestamp is unique so you should expect not to put more than one element per millisecond into the map. Then to put an ID into the map, let the timestamp be System.currentTimeMillis(), and while the timestamp is already a key in the map, increment it. Then put the (timestamp, ID) pair into the SortedMap. This solution is convenient because the loop thread can just read elements of the SortedMap from the beginning until they are too new and then stop, because all the oldest elements are at the beginning of the map.


text:
Q: Why is the magnetization inside a diamagnetic material antiparallel to the external field Let's say I have a constant magnetic field and I dive into it a diamagnetic material. Griffiths says that in the presence of a magnetic field, matter becomes magnetized and it will be found to contain many tiny dipoles with a net alignment along some direction.
However, what's exactly the link between the alignment of those dipole and the way that the external magnetic field induces a current to the atoms which produces a magnetic field in the opposite direction (Lenz's law).
How exactly the magnetic field aligns those dipoles and what exactly are the loops of those dipoles, are they the "path" of electrons?
I think those 2 questions is what I'm missing to fully understand the link between the 2 statements if there is a link.


text:
Q: Firebase authentication resend verification code in iOS How can i resend phone number auth verification code using firebase api?
What i did try:
//Receiving verfication id and request for verification code
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationID, error) in
  if let error = error {
    self.showMessagePrompt(error.localizedDescription)
    return
  }
}

let credential = PhoneAuthProvider.provider().credential(
    withVerificationID: verificationID,
    verificationCode: verificationCode)

//Verify verification code
Auth.auth().signIn(with: credential) { (authResult, error) in
  if let error = error {
    let authError = error as NSError
    return
  }
}

A: Call requestOtp() method on resend OTP button click.
import FirebaseAuth

func requestOtp() {
        let phNo = "Your phone number"
        PhoneAuthProvider.provider().verifyPhoneNumber(phNo, uiDelegate: nil) { (verificationID, error) in
            if let error = error {
                print(error.localizedDescription)
                return
            }
            // Sign in using the verificationID and the code sent to the user
            // ...
            UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
        }
}

.
Verify Code with Auth:
func verifyNumberWith(verificationCode: String) {
        let verificationID = UserDefaults.standard.string(forKey: "authVerificationID")
        let credential = PhoneAuthProvider.provider().credential(
            withVerificationID: verificationID ?? "",
            verificationCode: verificationCode)

        Auth.auth().signIn(with: credential) { (authResult, error) in
            //Do your actions.
        }
    }

If you face any problem in the above code, please let me know in comment.
Happy to help!


text:
Q: Using MPI, a message appears to have been recieved before it has been sent In my test program below I am sending a message from one process to another. The trace printfs seem to indicate what the message is being received before it is sent, why is this so?
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
/* Run with two processes */
void main(int argc, char *argv[]) {
    int rank, i, count;
    float data[100],value[200];
    MPI_Status status;
    MPI_Init(&argc,&argv);
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    printf("before if:%d\n",rank);
    if(rank==1) {
        printf("in if:%d\n",rank);
        for(i=0;i<100;++i) data[i]=i;
        MPI_Send(data,100,MPI_FLOAT,0,55,MPI_COMM_WORLD);
    } else {
        printf("else:%d\n",rank);
        MPI_Recv(value,200,MPI_FLOAT,MPI_ANY_SOURCE,55,MPI_COMM_WORLD,&status);
        printf("P:%d Got data from processor %d \n",rank, status.MPI_SOURCE);
        MPI_Get_count(&status,MPI_FLOAT,&count);
        printf("P:%d Got %d elements \n",rank,count);
        printf("P:%d value[5]=%f \n",rank,value[5]);
    }
    MPI_Finalize();
}

/for running the program for 8 processes i got the following result.
how could process 0 recieve before process 1 sends/
- RESULT:

-before if:4\n
-before if:8\n
-else:8\n
-before if:0\n
-else:0\n
-P:0 Got data from processor 1\n
-P:0 Got 100 elements \n
-P:0 value[5]=5.000000 \n
-before if:1\n
-in if:1\n
-before if:2\n
-else:2\n
-before if:5\n
-else:5\n
-before if:6\n
-else:6\n
-before if:7\n
-else:7\n  -before if:9\n  -else:9\n  -else:4\n  -before if:3\n  -else:3\n
*/

A: The problem here isn't that you've broken the causality of time, just that MPI makes no guarantees about the order of printing messages to the screen (see MPI - Printing in an order for more details).
MPI forwards all of your stdout and stderr back to the process that called mpiexec/mpirun before printing it to the screen (since that's where the user is connected. Those messages coming from all of the different processes can arrive in any order so you may be seeing one line saying a message was received before you get another line saying the message has been sent. The messages are still occurring in the right order, they're just getting delayed in the communication channels along the way.

A: How can you be so sure process 0 received the message before it was sent, I would consider it far more likely that the printf was buffered or delayed.
Printf is not guaranteed to be instant, in order to make it more responsive. Run this at the start of your code to prevent output buffering with printf:
setbuf(stdout, NULL);


text:
Q: Sum up every nth row in Matlab Is there any easy way to sum up every nth row in Matlab?
Lets say I have:
A =

 1     2     3
 4     5     6
 7     8     9
10    11    12
13    14    15
16    17    18

I wish to add every 2 rows, like this: row1+row3+row5, and then row2+row4+row6, so my output is:
B =

21    24    27
30    33    36

I know that it is possible to do it by sum(A(1:2:end,:)) but this is not helpful if you have large matrix and many nth rows, for loop is another option but I couldn't get it working so far. Do you have any suggestions/solutions how this could be solved with a for loop, or maybe there is a built-in function?

A: How about that?
B = cell2mat(arrayfun(@(x) sum(A(x:n:end,:)),1:n,'uni',0)')

I first thought about using accumarray but it requires a vector as input. It's still possible, if you follow this answer.
Another accumarray alternative:
[a,b] = size(A);
idx = bsxfun(@plus, 1:b,repmat([0:b:b*n-1]',a/n,1))
B = reshape(accumarray(idx(:),A(:)),b,[]).'

A: If you want to avoid arrayfun for a general n case, you can use some reshaping methods. One such approach could be this -
[M,N] = size(A); %// Get the size of A for later usage
rowd = reshape(1:M,n,M/n)'; %// Get new row indices based on every nth selection
A1 = A(rowd(:),:); %// Reshaped A that has all the nth rows packed up consecutively for easing summing up
A2 = reshape(A1,M/n,[]); %// Reshape into a matrix with the number of rows equal to number of rows in each nth grouping
out = reshape(sum(A2),[],N); %// Get the final output by summing across columns and reshaping into the N-column format as with A

A: Benchmark for all solutions
(Thanks to Amro for the Benchmark-code)
function [t,v] = nthSum()
    n = 3;
    A = randi(100,10000*n,3);

    % functions to compare
    fcns = {
        @() sum1(A,n);
        @() sum2(A,n);
        @() sum3(A,n);
        @() sum4(A,n);
        @() sum5(A,n);
        @() sum6(A,n);
    };

    % timeit
    t = zeros(6,1);
    for ii = 1:100;
        t = t + cellfun(@timeit, fcns);
    end

    % check results
    v = cellfun(@feval, fcns, 'UniformOutput',false);
    assert(isequal(v{:}));
end

function B = sum1(A,n)   %thewaywewalk#1
    [a,b] = size(A);
    idx = bsxfun(@plus, 1:b,repmat([0:b:b*n-1]',a/n,1));
    B = reshape(accumarray(idx(:),A(:)),b,[]).';
end

function B = sum2(A,n)  %thewaywewalk#2
    B = cell2mat(arrayfun(@(x) sum(A(x:n:end,:)),1:n,'uni',0)');
end

function B = sum3(A,n) %Dennis Jaheruddin
    B=zeros(n,size(A,2));

    for k=1:n
        B(k,:)=sum(A(k:n:end,:),1);
    end
end

function B = sum4(A,n) %Luis Mendo
    B = squeeze(sum(reshape(permute(A, [1 3 2]), n,[] ,size(A,2)), 2));
end

function B = sum5(A,n) % Bentoy13
    [k,l] = size(A);
    B = sum(reshape([A',zeros(l,mod(-k,n))],l,n,ceil(k/n)),3)';
end

function B = sum6(A,n) % Divakar
    [M,N] = size(A);
    rowd = reshape(1:M,n,M/n)';
    A1 = A(rowd(:),:);
    A2 = reshape(A1,M/n,[]);
    B = reshape(sum(A2),[],N);
end

Results for 100 runs each and a 30000x3 Matrix A
0.1616s   %// thewaywewalk#1
0.0667s   %// thewaywewalk#2
0.0499s   %// Dennis Jaheruddin
0.0211s   %// Luis Mendo
0.0791s   %// Bentoy13
0.0784s   %// Divakar

Clear winner & loser, the rest is very close.
Especially the most simple solution (for loop) by Dennis is top notch ;)
Interesting how everything changes for large row lengths
Results for 100 runs each and a 3000x1000 Matrix A
6.5646s   %// thewaywewalk#1
2.6314s   %// thewaywewalk#2
2.5939s   %// Dennis Jaheruddin
0.6412s   %// Luis Mendo
4.1996s   %// Bentoy13
1.9975s   %// Divakar

Performance along number of rows
Results averaged on 1000 runs, for input matrix size from 10 * 25 to 1e6 * 25 elements.

Data:
N               10          20          50          100         200         500         1e+03       2e+03       5e+03       1e+04       2e+04       5e+04   1e+05   2e+05   5e+05   1e+06
thewaywewalk #1     0.000282    0.000401    0.000399    0.000341    0.000276    0.000306    0.000358    0.000538    0.00109     0.0015      0.00283     0.0111  0.021   0.0427  0.112   0.224
thewaywewalk #2     7.15e-05    0.000106    0.000129    0.000137    0.000149    0.000262    0.000433    0.000929    0.00313     0.00581     0.0122      0.0289  0.0567  0.121   0.327   0.635
Divakar             3.21e-05    4.36e-05    4.65e-05    4.63e-05    4.52e-05    6.86e-05    0.000116    0.00024     0.000668    0.00179     0.00378     0.00962 0.0193  0.0442  0.116   0.245
Bentoy13            4.58e-05    6.48e-05    7.43e-05    7.31e-05    7.16e-05    0.000103    0.000192    0.000387    0.00115     0.0028      0.00585     0.015   0.0303  0.0623  0.158   0.298
Dennis Jaheruddin   3.76e-05    5.54e-05    6.07e-05    6.25e-05    6.47e-05    0.000114    0.000183    0.000376    0.000999    0.00165     0.00345     0.0162  0.0318  0.0657  0.163   0.326
Luis Mendo          7.44e-05    0.000108    0.00011     9.45e-05    7.83e-05    8.56e-05    0.000102    0.000154    0.000323    0.000452    0.000892    0.00203 0.00374 0.00741 0.0186  0.0368

For small matrices (below 1000 rows), the solution from Divakar is the fastest; for large matrices, the solution from Luis Mendo is clearly the best one.

A: Even if there is already an accepted answer, let's try to do this differently.
The idea here is to reshape the original matrix into a 3D array in order to sum up along one dimension. But we have to take care about the fact that the size of A may not be a multiple of n.
Let's begin with some notations:
[k,l] = size(A);

In order to reshape, we must have k=n*x (x integer). If it's not the case, we must pad A with rows of 0. If k=n*x+y, y being the reminder of the euclidian division of k by n, we have to concatenate n-y rows of 0 to A (or 0 is y==0). Using Matlab mod function, it translates to:
A1 = [A;zeros(mod(-k,n),l)];

Recall that mod(-k,n) is positive.
Now, you want to sum rows and not columns: we want to get a 3D array with rows kept intact, and columns distributed on rows. So I must transpose the array, and reshape it:
A2 = reshape(A1',l,n,ceil(k/n));

Your result is then simply the sum along the 3rd dimension, with transposing back:
B = sum(A2,3)';

As a conclusion, let's build a nearly one-liner (I left k and l apart, for clarity ... ok, for conciseness):
[k,l] = size(A);
B = sum(reshape([A',zeros(l,mod(-k,n))],l,n,ceil(k/n)),3)';

A: Permuting dimensions and reshaping:
B = squeeze(sum(reshape(permute(A, [1 3 2]), n,[],size(A,2)), 2));

A: I still think a for loop would be simple here, and probably reasonably efficient if you have long matrices:
A = [ 1     2     3
 4     5     6
 7     8     9
10    11    12
13    14    15
16    17    18];

n=2;
result=zeros(n,size(A,2));

for k=1:n
   result(k,:)=sum(A(k:n:end,:),1);
end


text:
Q: Strange behavior with trailing white-space in pre element with rtl direction? I'm working with a pre element with right-to-left direction and left-aligned text.
I'm doing so because I need a long string of text to be left-aligned, on one line, and I also need it to overflow on the left instead of the right.
The only issue I've run into with this is that for some reason any white-space that appears at the end of the string of text is shown at the beginning of the text, even though I can see in the dev window that the white-space is clearly at the end.
Why is this happening? Is there a way to get this same alignment behavior, but with trailing whitespace appearing on the correct side of the text?
I made a fiddle to demonstrate the issue.
https://jsfiddle.net/bkmu5ky5/1/
CSS:
pre {
    text-align: left;
    direction: rtl;
    border: 1px solid black; /* For demonstration purposes only */
}

JavaScript:
function addWhiteSpace() {
    document.getElementById("pre").innerHTML += " ";
}

function addLetter() {
    document.getElementById("pre").innerHTML += "a";
}

HTML:

ewafhioewiafihewiahfihewahiofdsfdsfdsfewaihofeihwofdsfdsfdsfdsasdfdsfdsf

<input type="button" onclick="addWhiteSpace();" value="Add White Space" />
<input type="button" onclick="addLetter();" value="Add Letter" />

If you click the "Add White Space" and then "Add Letter" buttons you can see the behavior I described.

A: You would encounter the same behavior many different characters, like commas and periods, too.
I see two solutions for your unusual problem:
1) to prepend every space and character to your string AND add a CSS styling of:
unicode-bidi: bidi-override;

It makes the rtl behavior consistent, but also (surprise surprise), inverses your inline content. Thus the prepending of the new content.
2) what should satisfy your needs is how, with the inputting of new text, behaves the input html element. It is aligning text to the left. It overflows to the left, too. You take away the borders and the blinking cursor and no one notices it's any different than your regular container.


text:
Q: Go to Matching Brace in Visual Studio? Is there a way in Visual Studio 2008 to go from a closing brace to its opening brace?  I've found a fair amount of stuff about highlighting the brace, but nothing about moving the cursor to it.
(VB.NET version of this Question: Keyboard shortcut for Jumping between "If/End If")

A: On my pt-BR (Brazilian Portuguese) keyboard it is actually CTRL + [.

A: On my Italian keyboard, it's CTRL + ^.

A: I found this for you: Jump between braces in Visual Studio:

Put your cursor before or after the brace (your choice) and then press CTRL + ]. It works with parentheses ( ), brackets [ ] and braces { }.  From now on you don't need to play Where's Waldo? to find that brace.

With the above shortcut, you can also hold SHIFT to select.
On MacOS, use CMD + SHIFT + \ .

A: On my Slovenian keyboard it is ALT    + Đ

A: For Visual Studio Code (as seen in their documentation), use Ctrl+Shift+\.
The setting can be found in:

File/Preferences/Keyboard Shortcut

I am using Visual Studio Code 1.8.0 . Note Visual Studio Code may behave differently for international keyboards (as seen in this answer re: German keyboard)
Hope this helps someone.

A: On a Mac use command+shift+\.
Source: a comment on this answer: https://stackoverflow.com/a/37877082/3345085.
Tested in Visual Studio Code version 1.10.2.

A: On my Dutch (Belgian) keyboard, it's CTRL + ^.

A: Goto Tools > Options > Environment > Fonts and Colors, select the "Brace Matching (Rectangle)" and change the "Item Background" to e.g. Yellow. This worked for the C# parentheses () {} and [].

A: Details that can benefit everyone (Linux/Win/Mac)
The command in the keyboard shortcuts menu/editor is editor.action.jumpToBracket there you can set it to whatever you like. There is also one called editor.action.selectToBracket which has no shortcut by default (at least on Mac).
Etc.
On the Mac editor.action.jumpToBracket starts out as Cmd+Shift+\
 and I changed it to Ctrl+] to be in line with what others say here. I did so in the hopes that I could use Ctrl+Shift+] to "Extend selection to matching bracket". That is what lead me to discover the details above. I set editor.action.selectToBracket to Ctrl+Shift+] and got exactly the behavior I wanted.

A: On a Hungarian keyboard it is Ctrl + ú.

A: A bit relevant, but for HTML tags: (since there is no built-in solution, Ctrl + J doesn't work for HTML tags : )
Here is the answer as a macro which I've built which does it (toggle), including go to focus:
Here is the demo:

And here is the code. Enjoy!
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Windows.Forms

Public Module Module2
    Sub beginToEnd()

        'Place the cursor somewhere in the beginning tag, run the macro, to select from beginning to end tag

        DTE.ActiveDocument.Selection.SelectLine()
        Dim objSel As TextSelection = DTE.ActiveDocument.Selection
        Dim topPoint As TextPoint = objSel.TopPoint
        Dim lTopLine As Long = topPoint.Line
        objSel.GotoLine(lTopLine, False)
        '  DTE.ActiveDocument.Selection.StartOfLine()
        DTE.ActiveDocument.Selection.SelectLine()
        Dim line1 As String = DTE.ActiveDocument.Selection.Text()

        If InStr(line1, "/") Then

            ' MsgBox(line1)
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
            DTE.ActiveDocument.Selection.EndOfLine()
            DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, True)
            objSel.GotoLine(lTopLine, False)
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
        Else
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
            DTE.ActiveDocument.Selection.EndOfLine(False)
            DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
        End If

        DTE.ActiveDocument.Selection.SelectLine()
        Dim line2 As String = DTE.ActiveDocument.Selection.Text()
        Dim objSel3 As TextSelection = DTE.ActiveDocument.Selection
        Dim topPoint3 As TextPoint = objSel3.TopPoint
        Dim lTopLine3 As Long = topPoint3.Line
        objSel.GotoLine(lTopLine3, False)
        DTE.ActiveDocument.Selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, False)
    End Sub
End Module

A: In Visual Studio Code on german keyboard it's ctrl+shift+^
But you have to open a file with correct extension - it's not working in new unsaved files for example.

A: Note: It also works for #if / #elif / #endif matching. The caret must be on the #.

A: If for some reason this is NOT working for you, something may have messed up your keyboard bindings (it didn't work for me).  You can re-enable the binding easy enough though - at least so I thought:
I tried this procedure:

*

*Go to menu Tools -> Options -> Environment -> Keyboard

*Scroll to, or search for the command Edit.GotoBrace

*Assign the desired shortcut (mine was empty, so I put in CTRL    + ])

*Be sure to click the "Assign Button"

I tried it, and it still didn't work. I restarted Visual Studio, and it still didn't work - well it ONLY worked for .cs files, but I need it to work for .vb files and text files, and...well ALL files!

A: On my French keyboard, it's CTRL + ^.

A: On a German keyboard it's Ctrl + ´.

A: On the Swiss-French keyboard : use CTRL + SHIFT + ^

A: On Spanish (Spain) keyboard with VS2012 is Ctrl + ¡ as stated by @Keith but if you use Ctrl + ¿ (typed as Ctrl + Shift + ¡) then goes to Matching Brace plus selects all the code within the two braces and then you can't go again to the other brace.

A: On a Spanish keyboard it is CTRL + ¿ (or CTRL + ¡).

A: I use Visual Studio 2008, and you can customize what you want this shortcut to be.
Click menu Tools -> Options -> Environment -> Keyboard. Then look for Edit.GotoBrace.
This will tell you what key combination is currently assigned for this. I think you can change this if you want, but it's useful if the Ctrl + ] doesn't work.

A: On my Danish keyboard it's CTRL + Å.

A: On a Turkish keyboard, it is Ctrl + ü.

A: And Ctrl + Shift + ] will select all of the text.

A: Use CTRL + ] to switch between them. Place the cursor at one of the braces when using it.

A: For completeness sake, on a Swedish keyboard it's  CTRL  +  å .
Also, I guess logical, but worth mentioning  CTRL  + shift +  å  (for capital Å), selects everything inside the braces and goes to the matching one.

A: On my Portuguese keyboard and SO with EN VS, it's CTRL + « to navigate to matching brace and CTRL + SHIFT + « if you intend to select the inner code.

A: June 2021
On a Mac running Windows 10 under parallels for Visual Studio 2019 and c# and with US keyboard the solution which worked for me was to edit the shortcut in"
Tools
Options
Keyboard
Edit.GoToBrace
On my system that shortcut was blank...
Press the Ctl key and the ] key and save the shortcut


text:
Q: Laravel orderBy Not Passing to View I am pulling a collection from my database table using the following code.
$profileVisits = DB::table('recently_visited')
    ->where('visitor_id',Auth::user()->id)
    ->orderBy('times_visited', 'desc')->get();

    return view('profile.index')
        ->with([
            'user' => $user,
            'posts' => $posts,
            'profileVisits' => $profileVisits,
        ]);

When I dd($profileVisits) it shows the collection with the correct descending results. However, when I pull the info into my view using the following code, it doesn't descend like it's supposed to. Is the orderBy query builder being undone or something with the "return view..." code?
Code in view...
@if (!$user->profileVisits->count())

@else
    @foreach ($user->profileVisits as $topVisits)
        <p>{{ $topVisits->getUsername() }}</p>
    @endforeach
@endif

User Model:
public function profileVisits()
    {
        return $this->BelongsToMany('App\Models\User', 'recently_visited', 'visitor_id', 'profile_id');
    }

    public function addProfileVisits(User $user)
    {
        $this->profileVisits()->attach($user->id);
    }

    public function previouslyVisited(User $user)
    {
        return (bool) $this->profileVisits()->get()->where('id', $user->id)->count();
    }

A: Actually, I just figured it out. On the User Model, I added the orderBy instead of using it in the Controller. See below.
User Model:
public function profileVisits()
{
    return $this->BelongsToMany('App\Models\User', 'recently_visited', 'visitor_id', 'profile_id')->orderBy('times_visited', 'desc');
}


text:
Q: Office Add-in disappearing from ribbon while still being installed Issue
I've had users reporting that the button for reaching our task-pane Office Add-in (on the ribbon) disappears. There are cases where multiple add-ins are enabled, but ours is the only one that is missing. Seems like it is occurring on both Mac and Windows.
When they look in the Store it still looks like it is enabled. One way to fix it is to remove the add-in and install it again, but when it happens reguraly it's annoying and users can't bother to fix it every time.

*

*The add-in is hosted on S3 in AWS

*The add-in is configured to only be visible when composing email

Question
What could be the cause of this happening? How can we fix it?

A: There is currently no known issues surrounding this. Where the Add-in is hosted, should not matter. If where your icon is cannot be reached, then your add-in will load after a certain amount of time with a default icon. (this does not sound like what is happening, but this can cause your add-in to not show up for a while)
In general, when users complain about this, it is because they have switched tabs on the ribbon. This can be confusing because add-ins are in a different location when doing an inline reply vs doing a pop-out window. (see below screenshot). Most of the time, this occurs during inline reply, and the user has clicked away from the "message" ribbon to the "Home" ribbon. Clicking back on the "message" ribbon, and the add-in should show up again. If the "message" ribbon is not there, then selecting another message, then back on the draft should put the "message" ribbon back.

Another possible explanation is that an admin has disabled the add-in, but not installed it.
If this is not what is happening, we would need more information on the repro steps. Version numbers of the Client Hosts. Version number of the server, and perhaps a copy of the add-in manifest.


text:
Q: R for loop in matrix I have two 365x1 matrix s1 and s2, mean and standard deviation vector.
I want to simulate normal distribution for a new 365x1 matrix. the code I used is
sim<-matrix(rep(NA,365),nrow=365,ncol=1)
for (i in 1:365){y<-rnorm(1,s1[i,],s2[i,])
 sim[i,]<-y[i]}

However it only generates first value. How should I fix my codes?
Thank you very much!

A: No need for a loop. rnorm is vectorised so just do this...
s1 <- sample(10,365,repl=TRUE)
s2 <- sample(3,365,repl=TRUE)
rnorm( 365 , s1 , s2 )
#[1]  5.83648500  1.64208807  0.02800676 -1.76443571  5.15361880  2.88269571
.
.
.

This will draw 365 random normal deviates using each of the values in the mean and standard deviation vectors s1 and s2 in turn.

A: The reason you're only getting one value is because in {y<-rnorm(..., you're assigning to a scalar variable y. In the next line, you try to get the value of y[i], which won't exist for i greater than 1.
HOWEVER, you don't need a loop at all. The rnorm function is vectorised, meaning it accepts vectors as arguments for the mean and standard deviation. So you can fill your sim vector with
sim <- rnorm(365, s1, s2)


text:
Q: Why is WMI so much slower tha using utilities like PsExec or PsList? I'm doing various OS management and querying tasks using WMI, but it allways take a long time for first WMI call(10 to 15s).
When I tried few tools from sysinternals I found that they are so much faster and I want to know how is this possible.
For instance how can PsList tool returns result in under 2 second and for wmi it takes at least 15 seconds. Much of this time is used for authentication and not actual work, and next wmi query for the same machine is much faster.
Is possible to see the source code of sysinternals utilites ? Do they use WMI or direct win32 api calls ?

A: WMI has a lot of overhead: authentication/authorizing access to WMI namespaces/DCOM/RPC. It is designed for easy and secure management, not for performance.
Suggested reading:
WMI: Improving your WMI application performance in fan-out scenario


text:
Q: jqmodal IE (7 or 8) flashes black before modal loaded This is killing me.  In both IE7 and 8, using jqModal, the screen flashes black before the modal content is loaded. I've set up a test app to show you what's happening.  I've taken jqModal EXACTLY from the site, no changes whatsoever, no external css that could be affecting my app.  It works perfectly in every other browser (including IE6).
http://jqmtest.heroku.com/

So, first two links are ajax calls, second is straight up inline HTML.  (I originally thought it was the ajax that was affecting it, but that doesn't seem to be the case, I then thought it was slow loading ajax, hence to two differen ajax links)
What's crazy is that the jqmodal site itself works perfectly in IE, no flashing of black, but I can't see what I'm doing wrong.  Code is straight forward
html:

Here's some inline content

    Close

Short loading modal

Longer loading modal

inline modal

Javascript:

CSS is exactly the same as the one downloaded from jqModal's site so I'll omit it, but you can see it on my app
Has anyone experienced this?  I don't get how his works and mine doesn't.

A: I think I figured out a fix for this obscure issue.
Change
o=$('

').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});

to
o=$('

').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100}).hide();

and change
h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;

to
h.o=(o)?o.addClass(c.overlayClass).prependTo('body').show():F;

A: After playing around with the source, I found a workaround.  Change line 41 (in jqModal r14) from:
if(c.modal) {if(!A[0])L('bind');A.push(s);}

to
if(c.modal) {A.push(s);}

I've also hosted the fix here along with a demo for IE7.  I'm not entirely sure what that change does since the source is minified (though I'd guess it might have something to do showing multiple modals at once), so be sure to test it out fully to make sure it doesn't break anything.

A: I tried jimyi's solution, but it wasn't fixing the problem for me.  So here's what I came up with:
In my CSS I've added a new rule
.jqmOverlay { display: none; }

and when I am popping up that particular modal dialog I do this:
$("#pleaseWait").jqmShow();   // show the modal dialog
$(".jqmOverlay").fadeIn(10);  // very quick fade-in

The fade-in works to override the CSS rule & the black flash is eliminated.
Note: I haven't tested it, but the fadeIn action might interfere with displaying a modal dialog where the overlay isn't completely transparent.


text:
Q: can't use pgxml_xpath I'm using PostgreSQL 9.1, I thought it was supposed to support this XML integration but I can't get it to work.  I try this query:
select data from ddm_table_data order by pgxml_xpath(data, '//xmltest/col1/text()', '', '');

And it comes up with the following errors:
ERROR: function pgxml_xpath(xml, unknown, unknown, unknown) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.

Am I missing something?

A:
Am I missing something?

Like the error says - there's no such function. There's one called "xpath" though.
The manuals are your friend.


text:
Q: calling a nested function in a class classdef hello < handle
        methods
            function first(obj)
                a=4;
                function second(obj)
                    a
                end
            end
        end
end

I would like to be able to call the function "obj.second".
Here is what I have tried:
>> hello_obj=hello;
>> hello_obj.first
>> hello_obj.second
No appropriate method, property, or field second for class hello.

>> hello_obj.first.second
Attempt to reference field of non-structure array.

>> hello_obj.first.hello_obj.second
Attempt to reference field of non-structure array.

Thank you

A: Use a Transient property a to skip it when saving. For the cases where Transistent can't be applied, overloading the saveobj and loadobj is a good alternative.


text:
Q: Eclipse -The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application I read all the posts regarding this error but for some reason it does not work for me...
Here is my folder structure,

I get the error as mentioned in my title,
The code of the if_tag.jsp,
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<title><c:if> Tag Example</title>

<c:set var="salary" scope="session" value="${2000*2}"/>
<c:if test="${salary > 2000}">

My salary is: <c:out value="${salary}"/>

</c:if>

The jstl libraries are located in -
C:\tomcat\webapps\ROOT\WEB-INF\lib

A: If you are running the maven project as dynamic web project on a server within eclipse, then you should follow the following steps!
open the project properties by right click on the project > properties and select Deployment Assembly.
Click add, select Java build path entries, and choose maven dependencies and then click Finish and Apply.
hope, it may work. it worked for me.

A: JSTL uses different URIs. You just need to get the right version of it.
You could download using JSTL 1.2 or download the JSTL 1.1 jars.
Javaranch has more detailed list of version/URIs.

A: I just wanted to note that if you have a project that is Maven based, and you import it into eclipse but receive this error absolute URI, then you might need to follow these directions Maven dependencies not visible in WEB-INF/lib (namely the Deployment assembly step)

A: To solve this issue copy and paste the jstl-1.2.jar file into your WEB-INF/lib folder directory. This will fix your issue.


text:
Q: SQLite3 not actually inserting I am trying to make a database for a management bot, I'm using sqlite3 to store how many warns and mutes a user receives, I have a command called viewpunishments to show how many warns and mutes a user have received, now obviously sometimes a user will have no warns/mutes so I have to make sure the column is set to 0 and not NULL, but it is not setting to zero, instead it is staying null
conn = sqlite3.connect('levels.db')
c = conn.cursor()
c.execute("SELECT mute,warn FROM lvl WHERE dID=?", (guy.id,))
selection = c.fetchone()
print(selection)

if selection == None:
    c.execute("UPDATE lvl SET mute=0 WHERE dID=?", (guy.id,))
    conn.commit()
    print("zero'd out the mutes")
    c.execute("UPDATE lvl SET warn=0 WHERE dID=?", (guy.id,))
    conn.commit()
    print("zero'd out the warns")
    print("update if not found")
    c.execute("SELECT warn,mute FROM lvl WHERE dID=?", (guy.id,))
    peeps = c.fetchall()
    print(peeps)

Pretty much I am:

*

*Setting up a connection

*Querying to see if the user has any warns/mutes

*If they don't have any (request comes back null or None)

*Make sure it is 0 and not NULL

*But it is always coming back null no matter what

What inserts into the DB, which is already created:
c.execute('INSERT INTO lvl VALUES(?,?,?,?,?)', (message.author.id, 1, 1, 0, 0))

it is set up like this,

*

*ID

*xp

*level

*mute

*warn

Here is an example of the same concept that WORKS:
c.execute("SELECT warn FROM lvl WHERE dID=?", (guy.id,))
        print(c.fetchone())
        channel = discord.utils.get(ctx.guild.channels,id=424686228395393025)
        if c.fetchone() == None:
            c.execute("UPDATE lvl SET warn=0 WHERE dID=?", (guy.id,))
            conn.commit()
        print("updated warns if not exist")
        c.execute("UPDATE lvl SET warn=warn+1 WHERE dID=?",(guy.id,))
        conn.commit()
        print("add warn")
        c.execute("SELECT warn FROM lvl WHERE dID=?",(guy.id,))
        warnings = c.fetchone()
        print(warnings)

The above has worked flawlessly with no errors

A: As written, this code won't change anything. Not because you got the UPDATEs wrong, but because you're testing this:
if selection == None:

But selection is a row, returned by fetchone—a list with two values in it. A list is never going to equal None.

If the user doesn't exist in the database at all, then you might get None. But in that case, there's nothing to UPDATE in the first place, so you can skip all of this code.
But I'm going to assume you're not looking up a non-existent user, and that your problem does actually exist.

So, the whole if part of your code never executes. You don't get the output you claim to get in the comments, you get this:
[None, None]
"update if not found"
[[None, None]]

What you probably wanted to do is test each of the values in the list.
And you probably want to test them separately—if warn is 42 but mute is NULL, you want to update mute to 0 but leave warn alone, right?
Also, you should test is None, not == None.
So:
if selection[0] is None:
    c.execute("UPDATE lvl SET mute=0 WHERE dID=?", (guy.id,))
    conn.commit()
    print("zero'd out the mutes")
if selection[1] is None:
    c.execute("UPDATE lvl SET warn=0 WHERE dID=?", (guy.id,))
    conn.commit()
    print("zero'd out the warns")

With this small change, your code now works:
[None, None]
zero'd out the mutes
zero'd out the warns
update if not found
[(0, 0)]

All that being said, there's probably a much better way to fix this.
One thing you can do is set the column type to INT NONNULL, and give it a default value of 0 instead of the default default of NULL. (I think Sqlite will ignore the NONNULL constraint, but it's still useful documentation of your intent; the 0 default is the real important part.) Then, any new rows you create will have 0 values instead of NULL values.
What about all your existing rows that already have NULL values? Let's just fix them in one go:
UPDATE lvl SET warns=0 WHERE warns=NULL
UPDATE lvl SET mutes=0 WHERE mutes=NULL

Now, all your existing rows have valid numbers, and any new rows you create will have valid numbers, so you don't need any of this code in the first place.


text:
Q: What are benefits of upgrading filesystem from ext2? I have ext2 filesystem installed on my work machine. I talk with my friend who knows linux a lot better and he said its very old and its very weird that I use so old filesystem.
I'm now trying to get it updated (I don't have root) to ext3.
are there any BIG reasons for that update? so I can point them out to helpdesk.
I'm java programmer and I work on a very big project (building the whole thing takes 50-90 minutes). it has a lot of small files that needs to be compiled and produce even more small files. so maybe an upgrade would help with the speed?
I also have problems with .... freezing. sometimes my computer is freezing and after 5-25 minutes its works again (I can't do anything, even switch to another console). can filesystem be responsible for that?
I'm looking for any reasons for upgrade, the more reasons I have the bigger chance that it will be upgraded.
P.S. How big are chances that I might lose data, because of errors in upgrade? (I have never done it on linux, but on windows its ... 4%?). I do have a UPS. please keep in mind that those people seems to not be very good since I have ext2 and its a new machine (9 months old)

A: I would bet money that your freezing problem is not due to your ancient ext2 filesystem, but that it is related to your hard drive because I bet you are running out of RAM and the system is swapping processes out to disk. You can check free memory with the free command. If you see swap used, then that explains your problem. If you want to monitor the swap usage you can run free -s 1 or run top. Get them to buy you more RAM!
It sounds like your system is certainly due for an upgrade if it is using ext2. Most Linux distributions began using ext3 by default years ago. Upgrading to a newer filesystem is advisable because it means that you will have better data integrity in the event of a system crash because of the filesystem journaling which does not exist in ext2. Note that the filesystem journaling with ext3 may actually decrease performance slightly for some operations compared to ext2, however that small performance trade-off is worth it for the improved data integrity.
On the other hand, ext3 also gives you dir_index which does not exist in ext2; that option (enabled by default in ext3) uses htree indexing for directories which speeds up accessing directories with lots of files.
Also, another area you can look to increase performance a bit in the case of lots of small files without having to upgrade anything is to modify the mount options for your filesystem to add noatime; this turns off the feature that updates the last accessed time on files that you access. There is also a nodiratime option to do the same thing for directories, but that option is turned enabled implicitly by just using noatime. For example, if your /etc/fstab file contains an entry like this for the root filesystem:
/dev/hda2 / ext2 defaults 0 0

then modify it like this:
/dev/hda2 / ext2 defaults,noatime 0 0

While it is possible to convert ext2 to ext4, you're better off copying all your files to a backup drive (you need a backup copy of your files anyway!), install the latest version of Ubuntu and then copy your files back to the newly reformatted system (make sure the installer does not preserve your old filesystems; you want to wipe out all the old stuff).
After all this, you may still want to know the differences between ext2, ext3 and ext4; this excerpt sums it up nicely:

Ext3 was mostly about adding journaling to Ext2, but Ext4 modifies
  important data structures of the file system such as the ones destined
  to store the file data. The result is a filesystem with an improved
  design, better performance, reliability and features.

A: Wikipedia covers most of this:

*

*http://en.wikipedia.org/wiki/Ext3

*http://en.wikipedia.org/wiki/Ext4
The big advantage of ext3 is journalling, which means you don't need to fsck every time you unmount uncleanly (e.g. power failure / kernel panic). ext4 makes fscking much faster, when you do need to.
It's hard to know whether ext3 or ext4 will be faster than ext2 for your use case. I know for some workloads they will be slower.
The freezing problem sounds like either thrashing or a dying hard drive.
Chance of data loss is minimal, assuming the person doing the upgrade doesn't do something stupid.

A: Ext3 has journaling but I dont think that it is good enough reason to change your existing file system. In my experience ext2 is faster than ext3, because of lack of journaling may be. Also Ext2 gives you more disk space as the journal created by ext3 takes disk space. So I wont recommend Ext3. The freezing problem you mentioned seems like a hardware issue and changing or upgrading file system wont fix it.
So if you have enough space elsewhere to backup your whole disk/partition and can afford formatting your it then go for ext4 as it has improved performance and has contiguous block allocation for large files which also improves performance.
Or if you can spend on hardware then buy your self an SSD as it will highly improve performance of compile and build.

A: I don't see any reason to use Ext2 on a new machine. But the disadvantages aren't that big if you compare it with FAT32. So I wouldn't say that it's absolutely necessary to upgrade from ext2, but I would recommend it. The advantages are not so much speed, but more data integrity. So if you system is crashing often, it might be very useful for you. There are several benchmarks out there. Usually ext2, ext3 and ext4 don't show very big differences, but in most tasks ext4 is the fastest. If you compare them to other file systems there are bigger differences (but you can't say that one wins always). I googled this benchmark, it shows that ext4 is faster than ext3 when handling many small files.
I'd recommend you definitely to upgrade to ext4 and not only to ext3, because the file system check is much more faster. When I had to wait the file system check for my 800GB ext3 partition every 30 mounts, it took like 30 minutes. With ext4 it should be like a tenth of that, so several minutes. But note that also after converting from ext3 to ext4 only for the new files after the conversion all ext4 features can be used. So if you have enough space elsewhere or on the same disc, pack everything to a tar ball or so and write them again.
You should definitely have backups of the whole machine (system and data) before doing an upgrade of your file system. But not because the process itself is very dangerous, but more because always something can go wrong and when you change your file system that would have fatal consequences. It's difficult to estimate the risk of data loss during the upgrade process, but I'm quite convinced that human errors are more likely than any other problem during the upgrade process. If you have a backup, there is not such a big deal. I've recently upgraded from ext3 to ext4 and it took like 20 minutes. If you want to know more details about the upgrading process, you can read this about upgrading from ext2 to ex3 or this about an upgrade ext2 directly to ext4.
If the computer freezes, I'd suspect some kind of heating problem first. You can try to monitor the temperature or just try to ask your self: does it ever happen soon after turning on the computer when it's still quite cold? But this is the thing your help desk should really solve. This sounds much more important than your file system.