text:
Q: Completion of the real numbers On the real line $\mathbb{R}$ endowed with the Euclidean topology, I may put different metrics, inducing the same topology, but inducing different completions. For example if one considers the standard Euclidean distance you get $\mathbb{R}$ itself, if I see $\mathbb{R}$ as $(0,1)$ and I consider the induced metric, then I get $[0,1]$, similarly I can get $S^1$, and similarly I can get $\mathbb{R}_{\geq 0}$.

What are all the possible completions of $\mathbb{R}$ respect to a metric compatible with the Euclidean topology?

A: Edit: I've written a much simpler version of the proof of the main theorem.
I will show that every completion of $\mathbb{R}$ is obtained by joining $\mathbb{R}$ to a "space at infinity", which the line "converges" to on its ends.  The examples of the topologist's sine curve (together with an interval along the $y$-axis) and a spiral converging to a circle given by MartianInvader are good examples of this phenomenon.
To make this precise, let $X$ be a completion of $\mathbb{R}$, and define the space at infinity to be the complement $X-\mathbb{R}$.  We will prove several facts about this situation.

$\mathbb{R}$ is dense and open in $X$, and the inclusion $\mathbb{R}\to X$ is an embedding.

MartianInvader proved that $\mathbb{R}$ embeds densely.  To show that $\mathbb{R}$ is open, consider an open interval $(a,b)$.  The corresponding closed interval $[a,b]$ is compact and hence closed in $X$, so $[a,b]$ must be the closure of $(a,b)$.  But $\mathbb{R}$ is embedded in $X$, so there exists an open set $U\subset X$ so that $U\cap \mathbb{R} = (a,b)$.  Since $\mathbb{R}$ is dense in $X$, the interval $(a,b)$ must be dense in $U$, from which it follows that $U=(a,b)$.  Thus every open interval in $\mathbb{R}$ is open in $X$, and it follows that $\mathbb{R}$ is open in $X$.
Note that $\mathbb{R}$ being open means that some portion of $X$ really "looks like" $\mathbb{R}$. That is, $X$ really is a line with stuff attached to the ends.

The space at infinity is a complete, separable metric space.

Since $\mathbb{R}$ is open in $X$, the space $X-\mathbb{R}$ at infinity is closed in $X$. Since $X$ is complete, it follows that $X-\mathbb{R}$ is complete.
As for separability, observe that $X$ is separable, since $\mathbb{Q}$ is dense in $X$.  Then $X$ is second countable, so $X-\mathbb{R}$ must be second countable, and hence separable.

So which complete, separable metric spaces are possible?  From the topologist's sine curve and the spiral, it is clear that a closed interval and a circle are possible.
It is not hard to realize the unit square $[0,1]^2$ as the space at infinity.  For example, if $\gamma\colon [0,1]\to[0,1]^2$ is a closed space-filling curve, let $S_\gamma$ be the following subset of $\mathbb{R}^3$.
$$
S_\gamma \;=\; \bigl\{\bigl(x,\gamma(1/x-\lfloor 1/x\rfloor)\bigl) \;\bigl|\; x\in (0,\infty)\bigr\} \cup \bigl(\{0\}\times [0,1]^2\bigr)
$$
The following picture shows a portion of this set in the case where $\gamma$ is the Moore curve.

The set $S_\gamma$ can be thought of as a variant on the topologist's since curve, with $\gamma$ playing the role of the sine function.  Then $S_\gamma$ is closed in $\mathbb{R}^3$ and hence complete, and has a closed square as its space at infinity.
A similar construction shows that any metric space $X$ that is a continuous image of the unit interval $[0,1]$ can be the space at infinity, which by the Hahn-Mazurkiewicz theorem includes all compact, connected, locally connected metric spaces.  However, these are not the only possibilities.  For example, the set
$$
X \;=\; \left\{\left.\left(x,\frac{\sin(1/x)}{x}\right)\right| x\in (0,\infty)\right\} \cup (\{0\}\times \mathbb{R})
$$
is a completion of $\mathbb{R}$ that has another copy of $\mathbb{R}$ as the space at infinity, and $\mathbb{R}$ is not a continuous image of $[0,1]$.
It turns out that any complete, separable metric space can be the space at infinity for a completion of $\mathbb{R}$.  (Edit: The proof of this provided below is completely different from my original version using the Baire space.)  To prove this, we will start with the following Lemma.

Lemma. Any complete, separable metric space can be the space at infinity for a completion of the natural numbers $\mathbb{N}$.

Proof: Let $M$ be a complete, separable metric space, and let $D$ be a countable dense subset of $M$.  Let
$$
p_1,p_2,p_3,\ldots
$$
be a sequence in $M$ that visits each point of $D$ infinitely often, and extend the metric on $M$ to a metric on $\mathbb{N} \cup M$ as follows:

*

*If $n\in\mathbb{N}$ and $q\in M$, then $d(n,q) \;=\; \dfrac{1}{n} + d(p_n,q)$.

*If $m,n\in\mathbb{N}$ and $m\ne n$, then $d(m,n) \;=\; \dfrac{1}{m}+\dfrac{1}{n} + d(p_m,p_n)$.
It is easy to check that this defines a metric on $\mathbb{N}\cup M$. Since the sequence $p_1,p_2,\ldots$ hits each point of $D$ infinitely often, each point of $D$ lies in the closure of $\mathbb{N}$, and hence all of $M$ lies in the closure of $\mathbb{N}$.  Clearly each point in $\mathbb{N}$ is isolated in $\mathbb{N}\cup M$, so the inclusion $\mathbb{N}\to\mathbb{N}\cup M$ is an embedding.  Finally, it is not hard to show that $\mathbb{N}\cup M$ is complete under the given metric.

Theorem. Any complete, separable metric space can be the space at infinity for a completion of $\mathbb{R}$.

Let $M$ be a complete, separable metric space, and let $\mathbb{Z}\cup M$ denote a completion of $\mathbb{Z}$ whose space at infinity is isometric to $M$.  (We proved in the Lemma that $\mathbb{N}$ has such a completion, but $\mathbb{N}$ is homeomorphic to $\mathbb{Z}$.)  We will use $\mathbb{Z}\cup M$ to construct a completion of $\mathbb{R}$ with the same space at infinity.
The construction is simple: for every $n\in\mathbb{Z}$, we will glue in a geodesic segment from $n$ to $n+1$, and the union of these segments will be the desired copy of $\mathbb{R}$.  That is, we extend the metric on $\mathbb{Z}\cup M$ to a metric on $\mathbb{R}\cup M$ in the following way:

*

*If $x,y\in\mathbb{R}$ lie in the same interval $[n,n+1]$, we define
$$
d(x,y) \;=\; \frac{|x-y|}{d(n,n+1)}.
$$

*If $x\in [n,n+1]$ and $p\in M$, we define
$$
d(x,p) \;=\; \min\biggl(d(x,n)+d(n,p),\;d(x,n+1)+d(n+1,p)\biggr).
$$

*Finally, if $x,y\in\mathbb{R}$ lie in two different intervals $[m,m+1]$ and $[n,n+1]$, we define
\begin{align*}
d(x,y) \;=\; \min\biggl(&d(x,m)+d(m,n)+d(n,y), \\
&d(x,m)+d(m,n+1)+d(n+1,y), \\[6pt]
& d(x,m+1)+d(m+1,n) + d(n,y),\\
&d(x,m+1)+d(m+1,n+1)+d(n+1,y)\biggr).
\end{align*}
It's easy to check that this defines a metric on $\mathbb{R}\cup M$, and that the inclusion $\mathbb{R}\to \mathbb{R}\cup M$ is an embedding.  Clearly $\mathbb{R}$ is dense in $\mathbb{R}\cup M$, since every point of $M$ is a limit point of $\mathbb{Z}$.  It is not hard to show that $\mathbb{R}\cup M$ is in fact complete, so $\mathbb{R}\cup M$ is a completion of $\mathbb{R}$ with $M$ as the space at infinity.

A: Any complete metric space with a dense embedding of $\mathbb{R}$.
Here's a sketch of the proof:  Any space that is a completion of $\mathbb{R}^1$ obviously has such an embedding (the inclusion).  And if a metric space $X$ has a dense embedding of $\mathbb{R}^1$, then the induced metric on $\mathbb{R}^1$ must complete to $X$ (some sequence of points in $\mathbb{R}^1$ converge to any point in $X$, and since the topology is induced by the metric this sequence will be Cauchy).
This is a huge class of spaces, and includes:

*

*Open, closed, and half-open intervals

*The circle, the circle with a line segment attached, the figure eight, and two circles joined by a line segment

*Interesting constructs in $\mathbb{R}^2$ like the topologist's sine curve described by Abraham Frei-Pearson or an infinite spiral that approaches a circle (together with the circle)

Basically, if you can start "scribbling" with a pen in some Euclidean space, and scribble forever without crossing back over your path, the closure of the space you end up scribbling in will be a metric completion of $\mathbb{R}$.


text:
Q: Mudar todo tipo de re requisição mantendo os parâmetros e URL via htaccess Estou quebrando a cabeça a horas tentando entender o tal do htaccess
Minha necessidade é a seguinte, eu tenho um diretório raiz do meu sistema, e cada usuario acessa o sistema pela URL www.meudminio.com.br/nomedousuario
Mas eu preciso que internamente seja carregado www.meudminio.com.br/sistema/index.php, sem revelar ao usuario, e sem trocar a URL, mesmo interagindo com o sistema, se ele tentar acessar:
www.meudminio.com.br/nomeusuario/contas?id=20 seria www.meudminio.com.br/sistema/contas?id=20
O htaccess pode me ajudar nessa?

A: Deixe seu .htaccess com apenas isto:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

Depois programe na index.php as rotas que o sistema terá. Veja este artigo: http://rberaldo.com.br/urls-amigaveis-sem-htaccess-usando-slim/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google maps Javascript API usage statistics does not show I am currently using the google Geocoder service from the Google Maps JavaScript API in a few applications.
For months I was receiving usage statistics in my API manager, but for the last 2 months it has gone dark usage screenshot.
I know that the service is still working, and I know that we are receiving around 500 -1000 geocode requests per day across 3 apps... But as we add geocoding functionality to more maps, or if we hit a peak day (we have one or two per year) I am worried that I will come close to my 25,000/day limit.
Anyone know why I lost my usage stats? I have tried the "send feedback" form... This error did occur around the time that I moved my API key from my personal gmail account to our organizations account.


text:
Q: Neural network and logistic regression not yielding output for certain inputs I am working on a project on gesture recognition(in c# language). In some part I had to use neural networks using the sigmoid activation function. I am using the aforge.net(http://www.aforgenet.com/) library for the same.
The system developed gets trained when I use a certain part of the training data. However when I use a different portion of the training set I give ans as NaN(not a number). Initially I thought it would be due to some variable overflow. However the system supports large number of inputs from one section of the training data and doesn't support as much as one inputs from the other section. Now this makes me reach a conclusion that something is wrong with that input. However I am not able to what may be probably wrong.
I have tried fitting a logistic regression function which yielded similar results.
Are there any constraints while modelling the input. Any help would be appreciated.

A: If you get NaNs there might be lots of reasons. But it is certainly part of the library, not of neural networks per se.
One tip is to make sure that your input data does not contain extreme values. Thus, make sure to scale them either to have mean 0 and unit variance, or scale them between 0 and 1.
If that does not solve your problem, contact the author of the library.


text:
Q: Javafx : Navigate to Pages I am trying a JavaFX2.0 application in reference to Ensemble sample. Like Ensemble, I also want to show different pages but based on clicks made on center page. I don't have any Tree, Toolbar, etc. Just want a set of pages to be displayed based on a particular selection. Example: my main page may have 6 buttons, on clicking btn1 I want Page1, Page2 on btn2 click and so on. On Page1, I will again have some buttons and a Return to return back to the previous page. In normal Java, we could achieve this easily using CardLayout. Add all paged to cards and show the desired page.
Looking at Enemble project, I saw that all the samples pages like "AnchorLayout, ColorButton, etc" they all extend Sample. And Pages class has members of AllPagesPage, SamplesPage, DocPage, etc which all are shown in TreeView on left side.
I added Sample that extends Pane, create another class DataPane that extends Sample. A 3rd class that has the reference of all Panes :
public class AllPagesPage {
HashMap<String, Sample> pages = null;
private static String DATAPANE = "DATAPANE";

public AllPagesPage() {
    pages = new HashMap<String, Sample>();
    addPages();
}

private void addPages() {
    pages.put(DATAPANE, (Sample)new DataPane());
}

public Sample getPage(String page) {
    if (pages.containsKey(page))
        return (Sample) pages.get(page);

    return null;

}

}

To store the refernce based on name I have used HashMap. Now in my application class, how do I setup the page as DataPane ?
    @Override
public void start(Stage primaryStage) {
    primaryStage.setTitle("Hello World");
    Group root = new Group();
    Scene scene = new Scene(root, 300, 250);
    /*
    Button btn = new Button();
    btn.setLayoutX(100);
    btn.setLayoutY(80);
    btn.setText("Hello World");
    btn.setOnAction(new EventHandler<ActionEvent>() {

        public void handle(ActionEvent event) {
            System.out.println("Hello World");
        }
    });
    root.getChildren().add(btn);
    *
    */

    primaryStage.setScene(scene);
    primaryStage.show();
}

// Should be called as gotoPage(AllPagesPage.DATAPANE),
// on this command everythign else should be removed and contents of DataPane should come up.
public void goToPage(String page) {

}

DataPane just contains code from AnchorPaneSample in Constructor. Nothing more or no other functions - ONLY constructor.
How should I get the stage and set pages on call to gotoPage(String page) method ???

A: Just create an area where you want to see your panes and change them:
public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    private Pane pagesArea;
    private AllPagesPage pages = new AllPagesPage();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World");
        VBox root = new VBox();
        Scene scene = new Scene(root, 300, 250);

        Button btn = new Button();
        btn.setText("Open DataPane");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent event) {
                goToPage(AllPagesPage.DATAPANE);
            }
        });
        root.getChildren().addAll(btn, pagesArea = new StackPane());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public void goToPage(String page) {
        Pane pane = pages.getPage(page);
        if (pane != null) {
            pagesArea.getChildren().clear();
            pagesArea.getChildren().add(pane);
        }
    }
}

You may want to update your AllPagesPage class:

*

*validation in getPage() is redundant, HashMap will do it for you

*instead of static Strings you may want to use enum for better flexibility (it will allow iteration, plain comparison, easier refactoring and other)


text:
Q: Can we write code inside CollectionDefinition class public class MyFirstFixture : IDisposable
{
    public MySecondFixture()
    {
        // Some initialization
    }

    public void Dispose()
    {
        // Some cleanup
    }
}

[CollectionDefinition("MyCollection")]
public class MyCollectionDefinition : ICollectionFixture<MyFirstFixture>
{
    //Can I add code in this section?
}

[Collection("MyCollection")]
public class TestClass1
{
    [Fact]
    public void TestMethod1()
    {
        // Do some testing
    }
}

Here I have defined MyFirstFixture and created a collection definition with CollectionFixture and that collection name is being used in tests.
Can I write the code in the CollectionDefinition section as well? Will that get executed whenever the collection is mentioned in a test?

A: Just look at the documentation:
https://xunit.net/docs/shared-context
There is an example:
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
    // This class has no code, and is never created. Its purpose is simply
    // to be the place to apply [CollectionDefinition] and all the
    // ICollectionFixture<> interfaces.
}


text:
Q: How do I distribute a ruby interpreter with my application
Possible Duplicate:
Distributing Ruby/Python desktop apps

For python, we have things like py2exe, py2app, freeze.
I only want a runnable application; it can even not be an exe or an app.
I just want to distribute the ruby/python interpreter with all the libraries and my application to the user. It's more like an embedded version of application.
Is there any tools like this for ruby (and for python, maybe)?
It's better if it is cross-platform, including OSX, windows and linux.

A: If you use jruby, you can compile it to an executable JAR. See this answer: Create deployable jruby JAR file.

A: Shoes lets you package Ruby apps for three platforms.
The OneClick Ruby Application Builder can build standalone .exe files for Ruby scripts.
Disclaimer: I have not used either of these tools, so I cannot vouch for their usability or stability.


text:
Q: Modelling with Unbalanced dataset I am working with a fairly unbalanced dataset (event class < 5% - it's a binary classification problem). To deal with this imbalance, I am trying out various techniques such as Oversampling the minority class (as well as synthetically generating samples using SMOTE), Under-sampling the minority class etc.
The problem that I am facing is, there is really no linkage between the performance measure than I get on my training sample (synthetically balanced) vis-a-vis what I get on my test sample. I am aware that oversampling can lead to inflated measures of performance, but the difference is stark (I am looking at Kappa statistic - On my training sample, I am getting a value in the range of 0.6-0.7, whereas on the test set it drops to less than 0.1). So my questions are:
a) Is there something than I can do to reduce this deviance between train and test perf. measures? I have been trying out different "ratios" (event/non-event ratio) while sampling, but this hasn't really helped.
b) Given this huge difference, is oversampling even a valid technique to pursue, in this particular case?
c) Finally, I had also tried the other recommended approach for dealing with unbalanced classes (by providing class weights, where the algorithm permits this functionality). This reduces the difference between train/test sets, but then the performance measures are not good for both of these sets! And hence, I was trying out the sampling techniques.

A: In general, artificially biasing the sampling of parts of the train set (either directly, by weighting, or by synthesis), is problematic.
Virtually every classifier also learns the a-priori label distribution. In Naive Bayes this can be seen very directly. In other techniques (e.g., logistic regression, classification trees, etc.), this appears too indirectly.

The cases where oversampling/overweighting makes sense, are different:
The Wikipedia entry, for example, states

The usual reason for oversampling is to correct for a bias in the original dataset. One scenario where it is useful is when training a classifier using labelled training data from a biased source, since labelled training data is valuable but often comes from un-representative sources.

and sites as an example a sample where ~67% are male, whereas they are known to compose ~50% of the population.
A different case where overweighting (possibly by oversampling) is when the missclassification penalties are unequal.

Two things to note when dealing with highly imbalanced data:

*

*When tuning parameters (using the train set), it might be important to use stratified cross validation.

*It pays to ensure that the train set and test set are prepared by a stratified split as well. For highly-imbalanced data, you might also need to make the test set larger than you usually do, in order to reduce test noise.


text:
Q: Bootstrap 3 dynamic carousel doesnt slide Please help. when i use the default carousel,

    ...

    ...

...

slide does work, but when i while looped the

...
 so the images will be dynamic, it doesnt slide anymore. instead, the images just stacked each other as seen here:
image here
Here is my code:

      <?php
        $x = new DB();
        $y= $x->selectWithCount(0,'tblimagecarousel',null,null);
        // var_dump($y);
        $numofimages = $y->fetchColumn();
        // echo $numofimages;
        for($x=0;$x<$numofimages;$x++)
        {
          echo "

";
        }
       ?>

    <?php
      $x = new DB();
      $y= $x->select(0,'*','tblimagecarousel',null,null);

      while($row = $y->fetchObject()){
        echo"

        img."' alt='".$row->title."' width='100%' height='345'>

".$row->title."

".$row->description."

";

      }
    ?>

      Previous

      Next

A: I looked at your code your issue is in your loop
the carousel can only have ONE item with the active class at a time (if you only want one to show)
this does not contain the php portion you will have to construct your loop to NOT add the active class (possibly add the active class to the 1st item after)
HTML

Image one

Image Description 1

Image two

Image Description 2

Image three

Image Description 3

Image four

Image Description 4

    Previous

    Next

CSS
    body{background-color:#ccc;}
.item{height:400px;}

js
$(document).ready(function(){
  $('#myCarousel').carousel();
 //this will add the active class to the first item
  $('.carousel-inner div.item:first-of-type' ).addClass( "active" );
})

You can view a fiddle HERE


text:
Q: Valgrind(memcheck) not showing all contexts My last context/error I see in my valgrind output file is...
==3030== 1075 errors in context 61 of 540:
==3030== Syscall param ioctl(SIOCETHTOOL,ir) points to uninitialised byte(s)
==3030==    at 0x7525248: ioctl (syscall-template.S:84)
==3030==    by 0x686A2A7: ??? (in /lib/libpal.so)
==3030==  Address 0x96cf958 is on thread 16's stack
==3030==  Uninitialised value was created by a stack allocation
==3030==    at 0x686A20C: ??? (in /lib/libpal.so)

...but I don't see error contexts 62 - 540. My first thought was maybe in closing the program, valgrind crashed, but after this context it printed the ERROR SUMMARY
ERROR SUMMARY: 9733 errors from 540 contexts (suppressed: 0 from 0)

I don't think it's because we came across a frame without debug info because I can see this exact same issue get hit the first time at the very beginning of my output file. Or maybe the printing of error contexts specifically, is halted when a stacktrace has missing debug info?
Any ideas? Need an additional command line argument for valgrind? I know in helgrind it'll quit after seeing 1000000 errors(something like that) but it explicitly tells you what it's doing.

A: So for my version of valgrind I also executed helgrind and saw all contexts(647) as expected. I think the problem above is simply a result  of valgrind coming across a frame with no debug symbols and saying, "If there's no debug info, I'm moving on"
All of my logs I'm producing end with this same libpal frame at various context numbers 100-something, 200-something, etc.


text:
Q: Kml creation error Recently I've been reading regards the simplekml module that python 2.7 has. So far I've found this to create a point:
import simplekml
kml = simplekml.Kml()
kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)])
kml.save("botanicalgarden.kml")

This displays the name Kirstenbosch at the coordinates listed. I've been wondering if this can be extended as it only displays the name.
For example how would I edit the code above to display on the kml screen.
Name
Coordinates
Population
Average age

I've tried adding population =,average age= to the code but It won't display it only displays the name. Can extra information be displayed on the kml?? Can anyone show me how to display the below list on the kml screen in google earth for the following as an example??
['Kirstenbosch',18.432314,-33.988862, 150000, 32]

Which correlates to name coordinates population and average age

A: Google's description suggests that a placemark can have:

a description that appears in the "balloon" attached to the Placemark.
a name
a point

You can add this information in python using
pnt = kml.newpoint(name="Kirstenbosch", coords=[(18.432314,-33.988862)])
pnt.description = 'population: 150000 age: 32'


text:
Q: Word Document Replace Text and save to a new file I've seen a few topics over the web of how to replace text in a Word Document, but my real question is the following: Is Interop the best option? Is there any other (better) option?
Here is an example of a topic I've read LINK.
I'm trying to arrange something that will work great on a Web Server, so I'm asking too if you guys could provide some code to get me started.
Thanks!

A: This is a very difficult question to answer since it involves that much opinions about which is best, in any definition of best.
As a starter I would definitely go for VSTO / interop since it is easier to go, and is integrated with and maintained by the developer of both products (Office and Visual Studio).
If your require it to run on a server (with ASP.NET for example) you should NEVER use VSTO / interop.
Why?
This is what Microsoft says about it.
Office interop is not built to run on a server as a process. It is too heavy, and depends on the UI capabilities for rendering, etc. You could use Open XML for Word or EPPlus for Excel for example.


text:
Q: Is this a correct way to solve this high school coordinate geometry question? Here's the question:

Given point $A$: $(-3;-1)$
  Given point $B$: $(3;7)$
Given point $Z$: $(x;0)$
Find the $x$ coordinate of point $Z$ so that the angle of view of AB segment is $90$ degrees at point Z, so Point Z has a $90$ degrees interior angle.
The answer is $4$ and $-4$.

Here's the way I did it, is it correct?

*

*$AB$ segment has length of $10$.

*So to make $ABZ$ a right triangle, one method we can use is that $AZ$ segment and $BZ$ segment must have the length of $\sqrt{50}$, because then $\sqrt{50}^2 + \sqrt{50}^2 = 10^2$. (Which is the length of $AB$)

*So in that case triangle $ABZ$ would be an isosceles right angled triangle and indeed there would be a $90$ degrees interior angle at point $Z$.

*Then, I used distance formula to calculate the $x$ coordinate of point $Z$ so that $AZ$ and $BZ$ segments would have a length of $\sqrt{50}$.

So that's how I got $4$ and $-4$, and these are the correct answers.
I know there are many possible solutions to solve this problem, but is my method correct?

A: First of all, the
angle of view of a line segment are two arcs and Z are on these arc and also it is on a line, that is the $y=0$ line. Your task is to figure out the formula for the arcs and then find the intersections of $y=0$ on it. Edit: hint, you need to use the Central Angle Theorem to find the centre of the arc/circle.
I do not understand why $ABZ$ is a right triangle in the first place.
You claim

So to make $ABZ$ a right triangle, one method we can use is that $AZ$ segment and $BZ$ segment must have the length of $\sqrt{50}$, because then $\sqrt{50}^2 + \sqrt{50}^2 = 10^2$. (Which is the length of $AB$)

This is wrong. If AZ and BZ equal length and the angle at Z is 45 degrees then the other two angles of triangle is (180-45)/2.

A: your method is correct. Good job sorry it took so long,  it's hard to review things not in math Jax I highly recommend you learn

A: It is incorrect
First of all,
$Z(x, 0)$
Now for every possible value of x, a line can be made that is intersecting line AB at $45 $ degree.
i think you mean point $A$ and $B$ is seen at $45$ degrees.
i got the answer this way.
$m_1$ = $\frac{7+1}{3+3}$
$m_1$ = $\frac{4}{3}$
$tan 45$ = $\frac{-m_1 + m_2}{1 + m_1*m_2}$
$1 + m_1*m_2$ = ${ + m_2 -m_1}$
$1 + \frac{4}{3}*m_2$ = ${+m_2 -\frac{4}{3}}$
$3 + 4*m_2$ = ${-4 + 3*m_2}$
$m_2$ = ${-7}$
$m_2$ = $-7$
$\frac{7-y}{3-x}$ = $-7$
$7x +y -28$ = $0$
Now it is given that y = $0$
$7x - 28 $ = $0$
$x$ = $+4$
Do the same for $A$.

A: So all the fuzz here resulted from some unsharp definitons (where is the angle, what angle).

You can try out different $x$ values here.


text:
Q: Why does it show the tag's type when I use getElementById method in javascript and html I used getElementById method to return the tag's element but it returns the tag's type ?!

<!DOCTYPE html>

    <title>Title</title>

    <button onclick="bonef();">1</button>

It shows "[object HTMLParagraphElement]1" but I want "1" !

A: Don't use getElementById any more, Instead use the querySelector:
let label = document.querySelector("#textlabel");

I think this is what you want to do:
function bonef(){
   let a = document.querySelector("#textlabel")
    a.innerHTML += "1";
  }


text:
Q: How to optimize this AspNetIdenty/Entity Framework generated query? When we look into our database, this query is eating a lot of resources:
(@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000))SELECT
    [Project1].[Id] AS [Id],
    [Project1].[Email] AS [Email],
    [Project1].[EmailConfirmed] AS [EmailConfirmed],
    [Project1].[PasswordHash] AS [PasswordHash],
    [Project1].[SecurityStamp] AS [SecurityStamp],
    [Project1].[PhoneNumber] AS [PhoneNumber],
    [Project1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
    [Project1].[TwoFactorEnabled] AS [TwoFactorEnabled],
    [Project1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
    [Project1].[LockoutEnabled] AS [LockoutEnabled],
    [Project1].[AccessFailedCount] AS [AccessFailedCount],
    [Project1].[UserName] AS [UserName]
    FROM ( SELECT
        [Extent1].[Id] AS [Id],
        [Extent1].[Email] AS [Email],
        [Extent1].[EmailConfirmed] AS [EmailConfirmed],
        [Extent1].[PasswordHash] AS [PasswordHash],
        [Extent1].[SecurityStamp] AS [SecurityStamp],
        [Extent1].[PhoneNumber] AS [PhoneNumber],
        [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
        [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled],
        [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
        [Extent1].[LockoutEnabled] AS [LockoutEnabled],
        [Extent1].[AccessFailedCount] AS [AccessFailedCount],
        [Extent1].[UserName] AS [UserName]
        FROM [dbo].[AspNetUsers] AS [Extent1]
        WHERE (@p__linq__0 IS NULL) OR (( CAST(LEN(@p__linq__0) AS int)) = 0) OR (( CAST(CHARINDEX(UPPER(@p__linq__1), UPPER([Extent1].[UserName])) AS int)) > 0)
    )  AS [Project1]
    ORDER BY row_number() OVER (ORDER BY [Project1].[UserName] ASC)
    OFFSET 0 ROWS FETCH NEXT 2147483647 ROWS ONLY

Query plan https://www.brentozar.com/pastetheplan/?id=SyAARIuDU
It looks like this is Entity Framework-generated query for AspNetIdentity. I failed to find out which code is corresponding to this query. Any idea how to look it up?

A: This code is generating such query.
var users = _userManager().Users.Where(u => string.IsNullOrEmpty(usernameToMatch) || u.UserName.Contains(usernameToMatch)).OrderBy(u => u.UserName).Skip(pageIndex * pageSize).Take(pageSize);

Thank https://stackoverflow.com/users/134204/panagiotis-kanavos for being right and persistent. I was looking at the wrong place.
Lessons to be learned: Or condition in Entity Framework - or generally - SQL - is a bad idea.


text:
Q: json mime-type on 2003 server issue Here is my issue:

*

*I have a solution working on a 2003 server with iis 6

*And every time I deploy the solution I have to configure the MIME type on the iis.

I have implemented this in my web.config, but it doesn't seem to work properly.
    <staticContent>
  <remove
            fileExtension=".json" />
  <mimeMap
            fileExtension=".json"
            mimeType="application/json" />
    </staticContent>

Is there a global way of setting this up?

A: I think I found a solution to the problem, add this code on top of the other and it worked.
 <system.web>
    <staticContent>
      <remove
                fileExtension=".json" />
      <mimeMap
                fileExtension=".json"
                mimeType="application/json" />
    </staticContent>
  </system.web>

The issue was that the <system.webserver> not allways works on 2003 server, therfore the <system.web> was needed also.


text:
Q: How much csv parsing can/should be processed in the front-end? I am about to:

*

*create a web interface where the user can type in email addresses, which are then sent up to the server in one json bulk, which is then used for messaging these users.

*I also have the requirement to be able to upload a csv file with a long list of email addresses. The problem is that the number of email addresses can be very large. We're talking about in the thousands or even more.

Theoretically I can either parse the csv file in the front-end and send the email addresses up in a json object (as I already have the api for the first use case where the email addresses are typed in and sent as a json), or I could upload these csv files to our db and do their parsing on the server side.

*

*Should consider processing the csv files in the front-end at all?

*What should be a "safe" number of items for processing in the front-end without breaking anything, or ending up with a heavily compromised user experience?
Can anyone comment from experience? Thanks

A:
What should be a "safe" number of items for processing in the
  front-end without breaking something, or ending up with a heavily
  compromised user experience?

This depends on the user's machine.
No one here would be able to give you a definitive answer on your question.

Anyway, you can use the Web Workers API
Web Workers allow you to create long running asynchronous threads in the background without heavily affecting/freezing your UI. You can show a spinner indicating that the CSV is being processed. Meanwhile your users would be able to interact with the UI just fine.
That's your best bet where supported.

Should consider processing the csv files in the front-end at all?

String parsing is usually a process that is optimised by modern browsers in some cases. If you move the computation to the server you need to scale your server to meet demands for the calculations as more and more users use your web-app.
You could get playful with it and detect the processing capabilities of the user's machine - if capable, use Web Workers, if not use the server to do this.
The most comprehensive way to do this is by defining a Browser Test Matrix and test for yourself.
You can even emulate bandwidths you want to target/test, specifically, using Network Throttling in Chrome Dev Tools


text:
Q: Spring Data JPA - While saving duplicate Composite Key doesn't get any error I am developing Spring Boot JPA Composite key example using Postgres. In this example, when I'm trying to save record, why I dont see any exceptions or constraint violation exception?
SongId.java
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Embeddable
public class SongId implements Serializable {
    private static final long serialVersionUID = 1L;

    private String name;
    private String album;
    private String artist;
}

Song.java
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Song {
    @EmbeddedId
    private SongId id;

    private int duration;
    private String genre;
    private LocalDateTime releaseDate;
    private int rating;
    private String downloadUrl;
}

SongsRepository.java
public interface SongsRepository extends JpaRepository<Song, Long>{

}

MainApp.java
@SpringBootApplication
public class CompositeApplication implements CommandLineRunner{

    public static void main(String[] args) {
        SpringApplication.run(CompositeApplication.class, args);
    }
    @Autowired
    private SongsRepository repo;

    @Override
    public void run(String... args) throws Exception {
        SongId songId1 = SongId.builder().name("John").album("AlbumA").artist("ArtistA").build();

        Song song = Song.builder().id(songId1).downloadUrl("http://www.gmail.com").duration(23)
                .genre("MyGene").rating(1).releaseDate(LocalDateTime.now()).build();
        Song song2 = Song.builder().id(songId1).downloadUrl("http://www.gmail.com").duration(23)
                .genre("MyGene").rating(1).releaseDate(LocalDateTime.now()).build();

        try {
            repo.saveAll(Arrays.asList(song, song2));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Edit-1:
I changed SongsRepository.java to
public interface SongsRepository extends CrudRepository<Song, SongId>{}

and main Method code.
@Override
    public void run(String... args) throws Exception {
        SongId songId1 = SongId.builder().name("John").album("AlbumA").artist("ArtistA").build();

        Song song = Song.builder().songId(songId1).downloadUrl("http://www.gmail.com").duration(23)
                .genre("MyGene").rating(4).releaseDate(LocalDateTime.now()).build();
        Song song2 = Song.builder().songId(songId1).downloadUrl("http://www.yahoo.com").duration(25)
                .genre("Sample Testung").rating(2).releaseDate(LocalDateTime.now()).build();

        repo.saveAll(Arrays.asList(song, song2));

    }

Logs:
2019-07-03 19:56:31.901  INFO 5420 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 46ms. Found 1 repository interfaces.
2019-07-03 19:56:32.265  INFO 5420 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-07-03 19:56:32.378  INFO 5420 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-07-03 19:56:32.415  INFO 5420 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-07-03 19:56:32.466  INFO 5420 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.3.10.Final}
2019-07-03 19:56:32.467  INFO 5420 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-07-03 19:56:32.600  INFO 5420 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-07-03 19:56:32.747  INFO 5420 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
2019-07-03 19:56:32.895  INFO 5420 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2019-07-03 19:56:32.899  INFO 5420 --- [           main] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@4ad3d266
Hibernate:

    drop table if exists composite.song cascade
Hibernate:

    create table composite.song (
       album varchar(255) not null,
        artist varchar(255) not null,
        name varchar(255) not null,
        download_url varchar(255),
        duration int4 not null,
        genre varchar(255),
        rating int4 not null,
        release_date timestamp,
        primary key (album, artist, name)
    )
2019-07-03 19:56:33.350  INFO 5420 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@41ad373'
2019-07-03 19:56:33.352  INFO 5420 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-07-03 19:56:33.404 DEBUG 5420 --- [           main] .c.JpaMetamodelMappingContextFactoryBean : Initializing JpaMetamodelMappingContext…
2019-07-03 19:56:33.410 DEBUG 5420 --- [           main] .c.JpaMetamodelMappingContextFactoryBean : Finished initializing JpaMetamodelMappingContext!
2019-07-03 19:56:33.557 DEBUG 5420 --- [           main] o.s.d.r.c.s.RepositoryFactorySupport     : Initializing repository instance for com.example.repository.SongsRepository…
2019-07-03 19:56:33.603 DEBUG 5420 --- [           main] o.s.d.j.r.query.JpaQueryFactory          : Looking up query for method findBySongId_AlbumAndSongId_ArtistAndSongId_Name
2019-07-03 19:56:33.604 DEBUG 5420 --- [           main] o.s.d.jpa.repository.query.NamedQuery    : Looking up named query Song.findBySongId_AlbumAndSongId_ArtistAndSongId_Name
2019-07-03 19:56:33.606 DEBUG 5420 --- [           main] o.s.d.jpa.repository.query.NamedQuery    : Did not find named query Song.findBySongId_AlbumAndSongId_ArtistAndSongId_Name
2019-07-03 19:56:33.646 DEBUG 5420 --- [           main] o.s.d.r.c.s.RepositoryFactorySupport     : Finished creation of repository instance for com.example.repository.SongsRepository.
2019-07-03 19:56:33.713  INFO 5420 --- [           main] com.example.CompositeApplication         : Started CompositeApplication in 2.59 seconds (JVM running for 3.333)
2019-07-03 19:56:33.722 DEBUG 5420 --- [           main] stomAnnotationTransactionAttributeSource : Adding transactional method 'saveAll' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Hibernate:
    select
        song0_.album as album1_0_0_,
        song0_.artist as artist2_0_0_,
        song0_.name as name3_0_0_,
        song0_.download_url as download4_0_0_,
        song0_.duration as duration5_0_0_,
        song0_.genre as genre6_0_0_,
        song0_.rating as rating7_0_0_,
        song0_.release_date as release_8_0_0_
    from
        composite.song song0_
    where
        song0_.album=?
        and song0_.artist=?
        and song0_.name=?
Hibernate:
    insert
    into
        composite.song
        (download_url, duration, genre, rating, release_date, album, artist, name)
    values
        (?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
    update
        composite.song
    set
        download_url=?,
        duration=?,
        genre=?,
        rating=?,
        release_date=?
    where
        album=?
        and artist=?
        and name=?
2019-07-03 19:56:33.773  INFO 5420 --- [       Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2019-07-03 19:56:33.776  INFO 5420 --- [       Thread-4] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-07-03 19:56:33.779  INFO 5420 --- [       Thread-4] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

A: Change:
public interface SongsRepository extends JpaRepository<Song, Long>

to
public interface SongsRepository extends JpaRepository<Song, SongId>

A: Spring Data Jpa Repository functionality is implemented via the SimpleJpaRepository class containing following save(..) method:
@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

Thus the Spring Jpa Data Repository save(...) method merges an already existing entity.
Opposed to that the naked EntityManager#persist() throws an exception if invoked with already existing entity.
The problem might be solved by adding custom behavior to Spring Data Repository/ies.
Alternatively : you can follow this
The easiest (and least invasive) way to work around this is probably by making sure the id only gets set right before the persist. This can be achieved in a @PrePersist callback:
@Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    @Entity
    public class Song {
        @EmbeddedId
        private SongId id;

        private int duration;
        private String genre;
        private LocalDateTime releaseDate;
        private int rating;
        private String downloadUrl;

    @PrePersist
    void initIdentifier() {
        SongId songId1 = SongId.builder().name("John").album("AlbumA").artist("ArtistA").build();
        if (id == null) {
            this.id = … songId1 // Create ID instance here.
        }
    }
    }


text:
Q: Django authentication with custom model I have a custom login authentication with mysql table, while logging in how can I compare a hashed password with a plain-password in backends.py (Working fine with plain password)?
class MyBackEnd(object):
    def authenticate(self, request, email=None, password=None):
        existing_user = RegAuth.objects.get(email=email,password=password)
        if not existing_user:
            # Checking the user Regauth Custom DB.
            user_data = RegAuth.objects.get(email=email,password=password)
            if email == user_data.email:
                user = RegAuth.objects.create_user(email=email, password=password)
                user.save()
                return user
            else:
                return None
        else:
            return existing_user

    def get_user(self, email):
        try:
            return RegAuth.objects.get(email=email)
        except Exception as e:
            return False

Login view
    def logauth(request):
    if request.method == "POST":
        email = request.POST['username']
        password = request.POST['password']

        user = authenticate(request, email=email, password=password)

        if user is not None:
            messages.error(request, 'if part : user is not  None')
            login(request, user)
            return redirect('emp')
        else:
            messages.error(request, 'else part : user is None')
            return redirect('login_url')
    else:
        messages.error(request, 'Please provide valid credentials')
        return render(request, 'registration/login.html')

A: Is there any particular reason to diverge from Django's default authentication backend? I see at least a few issues with your authenticate method;
class MyBackEnd(object):
    def authenticate(self, request, email=None, password=None):
        # 1. password should not be used to retrieve a user, a pk should suffice
        existing_user = RegAuth.objects.get(email=email,password=password)
        if not existing_user:
            # Checking the user Regauth Custom DB.
            # 2. if the query before didn't yield results, why would it atp?
            user_data = RegAuth.objects.get(email=email,password=password)
            if email == user_data.email:
                # 3. I'm not sure what flow validates this path, could you explain?
                user = RegAuth.objects.create_user(email=email, password=password)
                user.save()
                return user
            else:
                return None
        else:
            return existing_user

For reference here's Django's default authenticate backend method (notice the use of except/else syntax):
 def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a non-existing user (#20760).
            UserModel().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

It;

*

*Tries to retrieve the user, then;

*Checks the password, and;

*Validates the user's state, then;

*Returns the user object to the caller (successful authentication), or

*Does NOT return a user to the caller. (failed authentication)

Alternately (no user found), it;

*

*Instantiates a user object, and;

*Sets the password using set_password (which hashes it), then;

*Does NOT return a user to the caller. (failed authentication)

This alternate flow's usage of set_password is meant to mitigate some timing attacks see: https://code.djangoproject.com/ticket/20760
If you want to register new users, reset a user's password, or anything besides authentication, the authenticate method is not the right place.
I am aware this is not an answer to your question, but I hope it helps you and possibly others to understand the authentication flow and be critical about diverging from it.


text:
Q: regex negate numbers Currently I have this regular expression to validate letters, dash and spaces.
/^[a-zA-Z-\s]*$/

Now, I am quite confused how can this be rewritten to have a rule that it will accept everything except numbers?

A: To have anything except something, you need a negated character class
 [^\d]

A character class that starts with ^ is a negated class, \d is a predefined class that contains digits.
If you have really only digits you can shorten this further, there is also a predefined negation of \d that is \D
So [^\d] = \D
You may find this link to a regex reference on regular-expressions.info useful

A: /^\D*$/

\D matches any character that is not a digit.  The above expression matches any string that is comprised entirely of non-digits.
(This pattern matches "abc", does not match "123" or "ab2c".)

A: just use \D that has the same meaning of [^\d]
/\D/


text:
Q: Searched CASE Statement with Greater Than and Less Than Comparison I have a big calculation which will give numeric values and needs to be compared for greater than and less than
CASE big_expression
  WHEN > 0 AND <5 THEN 'Less Than 5 Days'
  WHEN > 5 AND <20 THEN 'Between 5 and 20 Days'
  -

Can this be done or I need to use the expressions every time I make a comparison

A: You can use CTE for the same
        WITH data
         AS (SELECT 1 + 2 + 5 + 9 AS big_exp
             FROM   dual)
    SELECT CASE
             WHEN big_exp > 0
                  AND big_exp < 5 THEN 'Less Than 5 Days'
             WHEN big_exp > 5
                  AND big_exp < 20 THEN 'Between 5 and 20 Days'
             ELSE 'Greater than 20 days'
           END
    FROM   data


text:
Q: Cocos2d and iPhone: Parallax Background with multiple texture atlases gives many memory warnings The problem I am trying to solve is:
I have 6 stripes which I need to move at different speed. A texture sheet of 2048*2048 is not enough and to deal with this I splitted the image in two (top and bottom half), so each stripe is exactly 960*640pixels. The general algorithm is to allocate a top and bottom half for each stripe and move them at each frame making sure to reposition them at the top of the screen when they exit the user's view. My class implementation, a direct modification of ParallaxBackground in the ShootEmUp example from this book, is giving too many memory warnings when run and analyzed using Instruments. See analysis below:
OpenGL analysis:

Activity monitor:

What concerns me is the high number of memory warnings in both analysis (24 and 5 respectively).
EDIT: Below you can find a comment which explains the solution

A: 2048x2048 is maximum possible size of texture for new devices. you can read about it in Apple OpenGL ES Programming Guide

A: Remember that Cocos2D always saves images with a width/height being a power of 2. So if your image is 960x640 pixels it'll use memory as if the image is 1024x1024 pixels.
Also remove textures you no longer need (and when outofmemory gets called).
[[CCTextureCache sharedTextureCache] removeUnusedTextures];

You can also use images in a lower quality to save memory.
[CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA4444];

Whenever you need to load higher quality images or gradients you can put it back.
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA8888];

A: Following the comment-suggestion to my question by LearnCocos2d the correct answer-solution was to simply reboot the device.. (see his comment above).
Thanks!


text:
Q: Two foreach use with a array I have a array and i use two foreach but I be only able to print the first foreach.
$test = $db->query("SELECT * FROM Test");
foreach ($test as $readTest) {
   echo $readTest["col1"];
}
foreach ($test as $readTest) {
   echo $readTest["col2"];
}

and I try with this:
$test1 = $test;
$test2 = $test;

I expect the output of $readTest["col1"] and $readTest["col2"], but the actual output is $readTest["col1"]

A: Use #fetchAll to get all your result in a conventional array. You will then be able to loop on them multiple times.

A: Why use array, when you can print this way:
$test = $db->query("SELECT * FROM Test");
while($PrintTest = $test->fetch_object())
{

echo $PrintTest->col1;
echo $PrintTest->col2;

}

Even if you want to use Arrays, you can do something like this:
$Array1 = array();
$Array2 = array();

$test = $db->query("SELECT * FROM Test");
while($PrintTest = $test->fetch_object())
{

$Array1[] = $PrintTest->col1;
$Array2[] = $PrintTest->col2;

}

And then, you can run through the array with For or Foreach


text:
Q: Does it make sense to install SSDs on server? I want to build a server hosting about 2TB+ data. Of course SSD is out of the picture in terms of the data drive. My question is: Is there any benefit to use SSDs as the boot drive? I plan to put 16G memory on it. I think most of the time the services should be loaded in memory and the server should rarely require rebooting. In this case, does it make sense to get SSD or just get a RAID1 with two SATA drives?

A: It depends on the kind of server, but generally speaking, yes, it should be a good idea.
SSD drives are best for read-only data, which is usually what servers are as opposed to workstations. So it has that going for it.
Also, the faster a file can be served, the better the server will be, and since SSD drivers are supposed to be faster, it has that going for it as well.
Finally, SSD drives usually use less power, make less noise, and generate less heat, so the server will require less electricity and cooling (which are the banes of server-rooms the world over), so it has that going for it too.
That said, again it depends on the specifics of your server and case-usage (eg, 16GB sounds good, but will the files be cached in RAM or have to be fetched from disk anyway?), as well as the actual drives in question. Overall however, yes, most servers are generally better off with SSD drives.

A: I don't think so, not at this time. They're expensive, it's a relatively new technology that's not without its own problems; Jeff Atwood has an interesting blog post about the advantages and disadvantages of using them.
Given your intended use case the need for an SSD seems even smaller. You normally see huge benefits when booting and when opening up apps, but on a data server with a lot of RAM that rarely gets rebooted there's no point in spending the extra money.

A: With this situation, an SSD boot drive will probably only improve boot time, once everything is started and in RAM (you have 16GB) it won't make any difference. Maybe if you kept a 10GB+ database on it it might help, but probably better to spend the money on more magnetic drives (possibly for redundancy).

A: I think that's a good idea.  The SSD promises greater reliability (especially important for laptops) and improved performance (no relative track-to-track seek time concerns), both of which are wonderful advantages when dealing with server problems.
Do keep in mind, however, that SSD is still very new and not immune to failures of its own.  You should research the types of problems people are experiencing with different brands and models of SSD drives before going down this path.

A: Depends on the server usage, from what you describe probably not worth it.  Where SSD's come into thier own is servers with high I/O usage like virtual server hosts.
Stick about 10 virtual machines on a server with standard drives and then compare it to one with SSD's.  Get all 10 VM's doing something and watch the SSD based server fly while the old magnectic drive one has stalling VM's as they wait for thier turn to read/write to the HD's.
Back to your original question though, why are you worried about the boot time?  Are you planning on regulary rebooting the server?  I have servers that haven't been rebooted for about 3 years which I would have thought would be reasonably normal for stable machines that just do the job they were supposed to do.

A: That's a bad idea. SSD drives give you insane iops, and that's why you pay for them: to hold data that's accessed most frequently in a random fashion. A database on a set of SSD drives can outperform (especially for read-intensive scenarios) a very expensive storage system.
Operating system boots, then practically all executables that are used are kept in RAM, everything unused is put to swap. If you plan for heavy swap use (bad idea) you could put your swap on SSD, but I'd rather use a HDD and put the difference into RAM.

A: I think it doesn't worth it most of the time.
But if you've got big computing requirements with big files (say Dailymotion / YouTube encoding videos) the read/write speed is probably important.
If your applications are doing a lot of reading, even small files, it can really boost up the performance. However, if you cache the most served data in RAM (See memcached daemon) this is not an issue anymore.


text:
Q: How can I display two rows in the same UITableViewCell? I'm trying to show two rows of text in the same Table Row of a UITableView.
Is this possible to do?
I've tried different things, but I'm not able to find anything about it or figure it out. Any help you can provide would be appreciated.
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    phonesAppDelegate *appDelegate = (phonesAppDelegate *)[[UIApplication sharedApplication] delegate];
    HLPFoundPhones *p = (HLPFoundPhones *)[appDelegate._phones objectAtIndex:indexPath.row];

    NSString *subtitle = [NSString stringWithFormat:@"Found on location (",p.x,@",",p.y,@") on date ", p.date];

    cell.textLabel.text = p._name;
    cell.detailTextLabel.text = subtitle;

    return cell;
}

A: You can see the different style in Apple's Table View Programming Guide for iOS, what you may want is the UITableViewCellStyleSubtitle (Figure 1-7 in the guide). Please have a look.
You can set the second label with cell.detailTextLabel.text = @"my text".
You've got to change this line
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

to
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

using the right style: UITableViewCellStyleSubtitle.
EDIT
To format a string like you described in your comment:
NSString *location = @"a Location";
NSString *date = @"20m ago";
NSString *subtitle = [NSString stringWithFormat:@"%@ on %@", location, date];

EDIT 2
NSString *subtitle = [NSString stringWithFormat:@"Found on location ("%f","%f") on date %@", p.x, p.y, p.date];

Please have a look at String Programming Guide / Formatting String Objects for more detail on how to format numbers etc.


text:
Q: useContext with tsx I am using the useContext hook and tsx.
const StoreContext = createContext({});

export function useStore() {
   const [store] = useContext(StoreContext);
   return store;
}

export function useDispatch() {
    const [, dispatch] = useContext(StoreContext);
    return dispatch;
}

I am getting the same error for both [store] and [dispatch].

Type '{}' is not an array type

Any idea how to fix this?

A: Tell TypeScript what is the type of your context by providing a type parameter for createContext.
Consider this example:
interface Theme {
  mode: 'light' | 'dark'
}

Thame is the shape of our context. This interface needs to go to createContext:
const StoreContext = React.createContext<Theme>({ mode: 'dark' });

const { mode } = React.useContext(StoreContext);

(mode === 'dark') || (mode === 'light') // true

Your context doesn't have to be an object. In this example, context is made of an array of numbers.
const StoreContext = React.createContext<number[]>([0]);

const [first, ...rest] = React.useContext(StoreContext);

(typeof first === 'number') // true

A: I tried to use useContext, and it didn't work. I saw recommendation to downgrade React and ReactDOM to 16.7.0-alpha-2, but that didn't work either. The solution for my problem was to wrap the component in myContext.Consumer. For class-based component, you can use yourClass.contextType = yourContext, and then you can acess features using "this.context". Please refer to this documentation: https://reactjs.org/docs/context.html


text:
Q: How to use actuallymab\laravel-comment comments system? I'm new to Laravel and I'm trying to implement a comments system on some posts. I found a package which seems well supported and I thought I could save some time by using it rather than starting from scratch.
The packing is here:
https://github.com/actuallymab/laravel-comment
There are some usage details but they don't seem quite clear enough for someone at my level.
Where I'm at:
Composer done
Migrations done
in my "User" model:
use Actuallymab\LaravelComment\CanComment;

In my "Post" model:
use Actuallymab\LaravelComment\Commentable;

class Posts extends Model {
  use Commentable;
  protected $canBeRated = true;
  //etc
}

In my PostsController I have:
public function comment()
{
  $userid = Auth::id();
  $postid = "1"; //static post id for testing

  $user = User::where('id','=',$userid);
  $post = Post::where('id','=',$postid)->first();

  $user->comment($post, 'Lorem ipsum ..', 3); // static comment for testing
}

And finally, my posts.blade:
<form action="{{ route('posts.comment') }}" method="POST">
    {{ csrf_field() }}
    <input type="text" id="commentdata"/> //not using this yet

        <input type="submit" class="btn btn-primary" value="Publish" />
        Cancel

Unfortunately, when I hit by submit button I get:
"Call to undefined method Illuminate\Database\Query\Builder::comment()"
So it seems I need to define a function in my User model? I'm not sure what to do here. I'm hoping some has used this package before.
Update 1:
I'm now using the following PostsController code:
public function comment()
{
  $userid = "1"; //static user id for testing
  $postid = "1"; //static post id for testing

  $user = User::find($userid);
  $post = Post::where('id','=',$postid)->first();

  $user->comment($post, 'Lorem ipsum ..', 3); // static comment for testing
}

The error remains as "Call to undefined method Illuminate\Database\Query\Builder::comment()"

A:
Call to undefined method Illuminate\Database\Query\Builder

You can be almost certain when you receive this error it's because you've missed out a step: you're calling a method on the query builder not the model. You need to retrieve the model(s) from the query.
Here's your current code:
$user = User::where('id','=',$userid);

You need to retrieve the first model from the results, e.g:
$user = User::where('id','=',$userid)->first();

Although you can improve this by using the find method which accepts a primary key and returns the model, e.g:
$user = User::find($userid);

Then from there you're ready to create the comment:
$user = User::find($userid);
$user->comment($post, 'Lorem ipsum ..', 3);

Example of using the trait:
<?php

namespace App;

use Actuallymab\LaravelComment\CanComment;

class User
{
    use CanComment;
}


text:
Q: Problems with jquery offset in function scrollTo(id) I am working on this site: Website
This is a one page site, where I use scrollTo(id) see the code here:
function scrollTo(id) {
  $('html, body').animate({scrollTop: $(id).offset().top - 50}, 1000);
}

The problem is, when you try an press a link when you are at the top of the homepage, the offset doesn't work and puts you almost below the section(page) you asked for.
But if you scroll to the bottom of the page, and press a link, the offset works like a charm, and it puts you right at the top of every section you ask for.
You may look into my source code, I have a js.js file that should show all the functions I am using, maybe there is some other error I haven't noticed.
really need your help :) ! hope you can see what I am doing wrong.

A: I thinks it's because of your menu.
When you're at the top of the page, your menu has a static position, witch also means that the height of the menu is added to the count of pixels for the browser to scroll to.
But when the browser has scrolled down to that position, the menu changes to a fixed position, witch then means that the height of the menu is subtracted from the top offset of the element that you want to scroll to.
In terms of code I would do simply add this little piece of CSS to the body.
body.tiny { padding-top: 60px; }

Assuming that the 60 pixels is the height of the menu. And when the menu changes to the fixed position the height will then be added to the bodys padding, pushing the content down as it was before.
This way you will also have a more smooth scroll when the menu changes it's position to fixed and reverse.


text:
Q: Embed words into array. Boolean issue. Okay so ive been trying to make a Word Search game and need to embed words into a grid. The words cant overlap or go off the edges.
Ive managed to generate a grid roughly like:
           .........X
           .........X
           .........X
           .........X
           .........X
           .........X
           xxxxxxxxxx

Im trying to make is so that if the play in the array is a ".", then the character from my word can replace the dot, and if its not a dot, then it breaks the loop.
However if i use the word dog and set my array to place 7, im getting:
            .......DOG
            .........X
            .........X
            .........X etc...

Here is my code for the function that im using to embed words in horizontally.
    int horizontal(char *myArray, char * word)
    {
         int length = strlen(word);
         int rand = 17;//rand_num_gen();
         printf("i = %d\n", rand);
         int a;
         int lettercount = 0;

         for(a=0; a < (length); a++)
         {
               if(myArray[rand] = '.')
               {
                  myArray[rand] = word[a];
                  rand++;
                  lettercount++;
               }
               else
               {
                  break;
               }
         }
         printf("lettercount = %d\n", lettercount);
         printf("length = %d\n", length);
         int success = 0;
         if(lettercount == length)
         {
              success = 1;
         }
         return success;

    }

Can anyone point out where im going wrong and possibly give me something that would work?

A: if(myArray[rand] = '.')

This line assigns the value of myArray[rand] to be '.'. If, as I expect, you are looking to compare values, you want the == operator.


text:
Q: Change start up project in visual studio 2010 I have 2 project in my solution explorer that one of this related to windows and other related to web,now i want to run web project but it runs in windows form so i want to know how to change the control to run the web project?

A: you need to make the web project the start up project. Right click on the web project and choose the Set As StartUp Project.


text:
Q: Draper gem not decorating associated model I'm following the Draper gem documentation, but the associated model is not being decorated. Here's a snippet of my top-level decorator:
module Admin
  class OrderDecorator < Draper::Decorator
    delegate_all
    decorates_finders
    decorates_association :line_item

    def amount
      model.amount.nil? ? 0 : model.amount
    end
  end
end

And here's a snippet from my association decorator:
module Admin
  class LineItemDecorator < Draper::Decorator
    delegate_all

    def options
      model.options.present? ? model.options.to_s : 'N/A'
    end
  end
end

Here's the method in the controller that calls the decorator:
  def show
    @subject = Admin::OrderDecorator.find(params[:id])
  end

It's being used in the view like so:
@subject.line_items.each do |li|
  = li.options

...etc...
The options method on LineItemDecorator is just being ignored - if it's nil, it doesn't display anything, rather than 'N/A'. I've put binding.pry in the options method and it never gets called. Can anyone see what I'm missing?
Thanks so much in advance.

A: I think you need to use plural line_items not singular line_item to make it work because that is how your association is named.
 decorates_association :line_items


text:
Q: How to create an efficient helper method that return an object given a map of field-values? One of the most tedious task when writing test class is to create test data with no particular requisites. The idea is to have a helper method that is able to return the object given a map of field-values pairs. This should be easily customisable in order to have default values that can be overridden by provided field-values pairs.
I've thought writing something like this:
public static MyCustomObject__c createMyCustomObject(Map<Schema.SObjectField, String> fieldValueMap) {
    Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get('MyCustomObject__c').getDescribe().fields.getMap();

    Map<Schema.SObjectField, String> defaultFieldValueMap = new MapMap<Schema.SObjectField, String>();
    // Populate the default field map here

    MyCustomObject__c o = new MyCustomObject__c();
    for (Schema.SObjectField field : fieldMap.values()) {
        if (fieldValueMap.containsKey(field)) {
            o.put(field, fieldValueMap.get(field));
        } else if (defaultFieldValueMap.containsKey(field)) {
            o.put(field, defaultFieldValueMap.get(field));
        }
    }

    return o;
}

I think that the main problem is the types I choose for the field-value maps: if the field type isn't compatible with the type String it throws an error. Could anyone suggest a workaround for this? Even a different approach would be appreciated.
The main requisites of this helper methods are:

*

*It should not perform any DML operation.

*It should accept an arbitrary number of field-value pairs. My idea use a maps but anything is good if it works.

*It should handle default field-value pairs. They could either be defined as attributes of the class or inside the method.

*It should return the object.

A: I would recommend creating a test data factory. It is essentially just an entire class dedicated to creating the base objects that are needed for almost every apex function (accounts, contacts, cases, etc.)
https://developer.salesforce.com/forums/?id=906F000000090j3IAA
You can create the method to return a map if you need certain values or you can just have the method insert the records and return void then query for them in each test class once you have called the method to insert them.


text:
Q: preg replace with multiple curly brackets I want to replace what is between the }string{ with }string%{
I'm adding the the % to edit a search query.
string example -
{a26f089ed1530be8648027b493a21bfd44c5fb15d632afc8f1c539c7c3da88a4}out{a26f089ed1530be8648027b493a21bfd44c5fb15d632afc8f1c539c7c3da88a4}
The 2 values between the pair of curlies changes each time {rAndows2ring}
I've tried a lot of variations and closest I've got to is;
$where = preg_replace("/\}([^}]+)\{/", "}$1%{", $where);

But that returns an extra % at the first {.
%{212190298d692385253efb2a1062006ddf3ea008e3cdc2f8b8f11884ec863202}out%{212190298d692385253efb2a1062006ddf3ea008e3cdc2f8b8f11884ec863202}

thanks in advance!

A: This works:
<?php

$oldString = '{a26f089ed1530be8648027b493a21bfd44c5fb15d632afc8f1c539c7c3da88a4}out{a26f089ed1530be8648027b493a21bfd44c5fb15d632afc8f1c539c7c3da88a4}';
echo '
oldString: ';
var_dump($oldString);
echo '
';

$newString = preg_replace('#(\{[\d\w]+\})([\d\w]+)(\{[\d\w]+\})#', '$1$2%$3', $oldString);

echo '
newString: ';
var_dump($newString);
echo '
';

?>

*

*(\{[\d\w]+\}) captures first string of digits and word characters enclosed with curly brackets.

*([\d\w]+) captures 'out', or any other string of digits and word characters in between

*(\{[\d\w]+\}) same as above


text:
Q: Adjust padding width of specific div class with Stylish? I'm trying to adjust the padding at the top of Twitter pages I visit to make up for having blocked an annoying element with an ad blocker. I've identified the html that needs to be adjusted as
div class="topbar-spacer" style="padding-top: 108px;"
My attempted fix was:

@-moz-document domain("twitter.com") {
.topbar-spacer {
    padding-top: 50px
}

but this doesn't seem to be working and I'm unsure why.


text:
Q: Disable Cloud Bigtable cluster to avoid getting billed, but without deleting data I have created a development Cloud Bigtable cluster and would like to disable this when I am not working on it to avoid getting billed, but the only option I see is to delete the cluster; doing this will require me to recreate the tables which I don't want to do.
Is there a way to disable the Cloud Bigtable cluster and enable them only during the time I work on it?

A: Unfortunately, there is not currently a way to disable a cluster and just maintain the tables and data.  You can export data if need be, or create a script using the cbt command line tool to quickly restore your cluster.


text:
Q: Assert.AreEqual and Assert.IsTrue give off two different results I have a function that returns a byte, GetByte(). I then have a unit test for this (using NUnit in Unity)
public void GetByteTest()
{
    var expected = 0b0;

    Assert.AreEqual(expected, GetByte()); // fails
    Assert.IsTrue(expected == GetByte()); // passes
}

Very confused about this, especially since the output says:
Expected: 0
But was:  0

I've also tried Assert.AreSame() but with no luck.
Any ideas?

A: While expected == GetNoteBinary() is true, since expected is declared with var, it requires a cast to byte to be compared with another byte; Assert.AreEqual is trying to compare it as int.
Assert.AreEqual((NoteBinary)expected, GetNoteBinary()); // passes

The lesson here is that Assert.AreEqual can compare different types and you must be very careful about which types you're comparing; never leave it ambiguous.


text:
Q: Extracting the 7th number from a 13 digit number I want to extract the 7th number from a 13 digit number.For instance 9111110123341, 0 would be the 7th number and then i would have a if statement saying if the number is between 0 and 5 assign an m to a new column . Is it possible in r?

A: Don't use text processing functions for numeric operations:
extract_digit <- function(x, n) floor(x / 10^(ceiling(log10(x)) - n )) -
  floor(x / 10^(ceiling(log10(x)) - n + 1)) * 10
extract_digit(9111110123341, 7:10) #extract the 7th to 10th digits
#[1] 0 1 2 3

A: You could try
number7 = substr("9111110123341",7,7)


text:
Q: No sound settings available + only one earbud working I'm super new to Ubuntu so please forgive me if the answer is already explained elsewhere. I have tried using sudo apt-get install ubuntu-desktop but no change. (These are brand new earbuds, and also happened with previous earbuds, so I know the issue isn't the earbuds.)
Using Ubuntu version 18.04.1 LTS
Update: Still working on this! Tried sudo apt-get install unity-control-center and it stopped at processing triggers for libc-bin (2.27-3ubuntu1)... and did nothing else. Sound still not appearing as an option in settings.


text:
Q: In Google Maps v3, does removing a marker from memory automatically kill any listeners? In my Google Maps v3 app, I am Creating Markers and putting them on the map. For each, I am adding an event listener on 'click' so I can show an Info Window when a user clicks on them.
I am keeping my Markers in a javascript array and use .setMap() to show/hide them on the map.  There are some cases where a user wants them deleted from the map.  In this case I do marker.setMap(null) and then delete the marker from my array.
Is it recommended to also keep an array of the event listeners on the markers so I can remove those when I delete the marker? Or will the event listener get removed from memory when it's listened-to object is removed from memory?
From an end-user standpoint, I don't think it matters to do this, but I am curious if the event listener is still in memory somewhere even though I delete the marker.  I'd like to be as tidy as possible.

A: As far as I can tell, the listeners are removed from memory.
Theoretically, this is probably because the listeners don't actively listen as such - Google Maps only stores them in the relevant feature, and then asks that feature which listeners it has when an event is fired.
Practically, I ran a test, and these are the results:
Tabs 1 and 2 create a point with 20000 listeners, and track the listeners.
Tab 3 creates a point with 20000 listeners, but doesn't track them.
Stage 1 is after they've got the listeners.
Stage 2 is after they've dropped something (tab 1: point, 2: listeners, 3: point)
Stage 3 is after they've dropped the other (tab 1: listeners, 2: point, 3: no change (listeners dropped implicitly at stage 2) )
Tab     PID     Memory (live, K) at stage...
                1       2       3
1       4643    18194   16026    8265
2       4659    18174    8155    8227
3       4676    17750    8152    8202
Memory usage in JS is absurdly hard to track, partly (I suspect) because of the automatic garbage collector. To get these results I used chrome's built in task manager, and after each major step of the experiment cycled a large chunk of memory into and then out of use to force the garbage collector's hand.
One curiosity here is that when tab 1 drops the point, it loses about 2000K memory, while when tab 2 drops the point, it gains 77K (a negligible change given the volatility of memory usage). I suspect this is because tab 1 drops a point with 20000 listeners attached, while tab 2 drops a bare point.
Here's the source I used. I'm not providing a fiddle link, because fiddle just makes tracking memory usage even harder :/
html (insert your own API key):
<!DOCTYPE html>

Welcome to MapLand, home of a single map.

<button onclick="addPts(true);">add points (store listeners)</button>
<button onclick="addPts(false);">add points (don't store listeners)</button>
--------
<button onclick="deletePts();">delete points</button>
<button onclick="deleteLs();">delete listeners</button>
--------
<button onclick="checkListenerVar();">check listener var</button>
<button onclick="cycleLargeChunk();">cycle large chunk</button>

JS (test2.js):
var uluru = {lat: -25.363, lng: 131.044};
var map;
function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
                zoom: 4,
                center: uluru
        });
}
var ptLat = uluru.lat, ptLng = uluru.lng;
var pts = []; // points
var ls = []; // listeners
var listenerVar;
function addPts(storeLs) {
        var m = new google.maps.Marker({
                position: {lat: ptLat, lng: ptLng},
                map: map
        });
        ptLng += 1;
        if (ptLng > uluru.lng + 20) {
                ptLng = uluru.lng;
                ptLat += 1;
        }
        pts.push(m);
        for (var i = 50000; i > 0; i--) {
                var l = google.maps.event.addListener(m, 'click', function () {listenerVar = i;});
                if (storeLs) ls.push(l);
        }
}
function deletePts() {
        for (var i = pts.length-1; i >= 0; i--) pts[i].setMap(null);
        pts = [];
        ptLat = uluru.lat;
        ptLng = uluru.lng;
}
function deleteLs() {
        for (var i = ls.length-1; i >= 0; i--) ls[i].remove();
        ls = [];
}
function checkListenerVar() {
        alert("Listener var is " + listenerVar + ", but is being reset to -1.");
        listenerVar = -1;
}
function cycleLargeChunk() {
        var l = [0];
        for (var i = 0; i < 26; i++) {
                l = l.concat(l);
        }
        //Force the environment to hang on to l for at least a second.
        setTimeout(function () {console.log(l.length);}, 1000);
}

A: I don't know for sure if the listeners are removed, but my guess is not.  My guess is that since the listener is still listening, even though you no longer have a reference to the object, the listener does, so it will remain in memory.  You don't need to keep a reference to the listener, you can call
google.maps.event.clearInstanceListeners(marker);

to clear all listeners before you delete it from your array.


text:
Q: How to putExtra() in Searchable Dictionary Example based on the Searchable Dictionary sample I tried to put extra data to a different activity.
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Spinner distance = (Spinner) findViewById(R.id.distanceSpinner);
    ArrayAdapter<CharSequence> adapterDistance = ArrayAdapter.createFromResource(
                this, R.array.distance, android.R.layout.simple_spinner_item);
    adapterDistance.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    distance.setAdapter(adapterDistance);
    Intent intent = getIntent();

    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            // handles a click on a search suggestion; launches activity to show word
         mapIntent = new Intent(this, Map.class);
         mapIntent.setData(intent.getData());
         mapIntent.putExtra("Distance", distance.getSelectedItemPosition());
            startActivity(mapIntent);
            finish();
        }
}

In my Map Class Distance is always zero because distance.getSelectedItemPostion() gets the initialized value.
How can I putExtra data with a click on a search suggestion?
Thanks

A: You have to register a callback on value change of distance spinner and call the intent for the starting of the Map class activity from there.
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
  @Override
  public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
    if (parent.getId() == R.id.distanceSpinner) {
      mapIntent = new Intent(this, Map.class);
      mapIntent.setData(intent.getData());
      mapIntent.putExtra("Distance", pos);
      startActivity(mapIntent);
      finish();
    }
  }
}


text:
Q: Merge github zip downloads with repo sync I was trying to download cm9 sources, but it seems like it will take forever, with endless resyncs.
Github offers repos as zip files, which can be downloaded and resumed with any download accelerator. Is there any way to extract those zips into my repo's folder and make the repo command think that they have been synced?
The reason i cannot continue with repo command's method is that, my connection keeps dropping everytime theres a gust of wind, and repo command just freezes after that.

A: You could:

*

*download the zip/tarball propose by GitHub

*git clone --bare the GitHub repo (so no checkout: it may be easier with your shaky connection)

*move the xxx.git directory (renaming it '.git') created by the clone into the uncompressed repo content from step 1.

*remove the bare attribute in the .git moved directory: git config --bool core.bare false
If a clone --bare doesn't work, then this approach would not be useful.
And a restartable clone (which was considered in 2009, even formalized as a SoC) isn't yet a reality.


text:
Q: Qt - QScrollArea widget clipping contents I'm trying to add scrolling to a drag and drop example source that I modified. The example simply draws several draggable QLabel widgets. I was modifying it in a way that a larger number of various different length widgets would be created.
I made a class that would be called by main and would contain the scrolling widget, that in turn would contain the original widget that draws the QLabels. The only method on this class is the constructor, and here's its implementation:
layoutWidget::layoutWidget(QWidget *parent) : QWidget(parent){
    QScrollArea *scroll = new QScrollArea();
    QVBoxLayout *layout = new QVBoxLayout();

    //widget that draws the draggable labels
    Widget *w = new Widget();

    scroll->setWidget(w);
    scroll->setBackgroundRole(QPalette::Light);

    layout->addWidget(scroll);

    setLayout(layout);
}

I'm using setMinimumSize() on the Widget constructor. When I run the program, only what's inside the area defined by setMinimumSize() is drawn, the rest is clipped off. Am I missing something?

A: Your widget most likely needs to resize itself to the full size to show its contents.  What is probably happening is that the minimum size you set is the only size it is getting, so it uses that.  I would suggest adding a layout to the widget to make it size dynamically based on its children, but I don't think that would work very well with draggable contents.

A: The minimum size of the widget inside the scroll area was smaller than its content, so only what's inside that area is drawn. I used larger values for setMinimumSize() and the problem was solved.


text:
Q: Dynamically generated Labels in CreateChildControls break OnPreRender Why does this work if I hardcode my controls in CreateChildControls, but not if I generate them dynamically?
You'll see under CreateChildControls, I commented out a call to CreateDynamicControls().
CreateDynamicControls looks to me to be formed correctly, and works just fine IF I comment out everything in OnPreRender.
In summary, Everything in OnPreRender fires as expected when the Labels are generated with the method under CreateChildControls, but not when I fire CreateDynamicControls,
What am I missing?
namespace Binder.BinderBuilder
{

[ToolboxItemAttribute(false)]
public class BinderBuilder : WebPart
{
    public Connector _myProvider;
    public Label SentFile0;
    public Label SentLibrary0;
    public Label SentSite0;
    public Label SentUrl0;
    public Label SentFile1;
    public Label SentLibrary1;
    public Label SentSite1;
    public Label SentUrl1;
    public Label SentFile2;
    public Label SentLibrary2;
    public Label SentSite2;
    public Label SentUrl2;

    protected override void OnPreRender(EventArgs e)
    {
        EnsureChildControls();
        if (_myProvider.SentFile != "")
        {
            if (SentFile0.Text == "")
            {
                SentFile0.Text = _myProvider.SentFile;
                SentLibrary0.Text = _myProvider.SentLibrary;
                SentUrl0.Text = _myProvider.SentUrl;
            }

            else if (SentFile1.Text == "")
            {
                SentFile1.Text = _myProvider.SentFile;
                SentLibrary1.Text = _myProvider.SentLibrary;
                SentUrl1.Text = _myProvider.SentUrl;
            }
            else if (SentFile2.Text == "")
            {
                SentFile2.Text = _myProvider.SentFile;
                SentLibrary2.Text = _myProvider.SentLibrary;
                SentUrl2.Text = _myProvider.SentUrl;
            }
            _myProvider.SentFile = "";
            _myProvider.SentLibrary = "";
            _myProvider.SentSite = "";
            _myProvider.SentUrl = "";
        }

    }
    private void CreateDynamicControls()
    {
        for (int i = 0; i <= 2; i++)
        {
            Label sentfile = new Label();
            Label sentlibrary = new Label();
            Label senturl = new Label();
            Label sentsite = new Label();

            sentfile.ID = String.Format("SentFile{0}", Convert.ToString(i));
            sentlibrary.ID = String.Format("SentLibrary{0}", Convert.ToString(i));
            senturl.ID = String.Format("SentUrl{0}", Convert.ToString(i));
            sentsite.ID = String.Format("SentSite{0}", Convert.ToString(i));

            sentfile.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            sentlibrary.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            senturl.ClientIDMode = System.Web.UI.ClientIDMode.Static;
            sentsite.ClientIDMode = System.Web.UI.ClientIDMode.Static;

            Controls.Add(sentfile);
            Controls.Add(sentlibrary);
            Controls.Add(senturl);
            Controls.Add(sentsite);
        }
    }
    // Visual Studio might automatically update this path when you change the Visual Web Part project item.
    private const string _ascxPath = @"~/_CONTROLTEMPLATES/15/Binder/BinderBuilder/BinderBuilderUserControl.ascx";
    protected override void CreateChildControls()
    {
        Controls.Clear();

        //CreateDynamicControls();

        SentFile0 = new Label();
        SentLibrary0 = new Label();
        SentSite0 = new Label();
        SentUrl0 = new Label();
        SentFile1 = new Label();
        SentLibrary1 = new Label();
        SentSite1 = new Label();
        SentUrl1 = new Label();
        SentFile2 = new Label();
        SentLibrary2 = new Label();
        SentSite2 = new Label();
        SentUrl2 = new Label();

        Controls.Add(SentFile0);
        Controls.Add(SentSite0);
        Controls.Add(SentLibrary0);
        Controls.Add(SentUrl0);
        Controls.Add(SentFile1);
        Controls.Add(SentSite1);
        Controls.Add(SentLibrary1);
        Controls.Add(SentUrl1);
        Controls.Add(SentFile2);
        Controls.Add(SentSite2);
        Controls.Add(SentLibrary2);
        Controls.Add(SentUrl2);

        BinderBuilderUserControl control = (BinderBuilderUserControl)Page.LoadControl(_ascxPath);
        control.ParentWebPart = this;
        Controls.Add(control);

    }

    [ConnectionConsumer("String Consumer", "StringConsumer")]
    public void TextBoxStringConsumer(Connector Provider)
    {
        _myProvider = Provider;
    }
}
}

A: I figured it out - I also needed to declare SentFile, SentLibrary, SentUrl, and SentSite as public Labels. CreateDynamicControls now fires with no error.


text:
Q: Cordova network information plugin regularly show offline (UNKNOWN) state I`m using cordova-plugin-network-information 1.2.0 "Network Information" in my ionic app but isOnline() function often returns FALSE when actually there is a connection (the problem as I can see only with mobile networks). As I have checked isOnline() returns FALSE because the getNetwork() returns UNKNOWN.
Any ideas?


text:
Q: Limit the height of the violin plot data within range How can I make sure that violin plot contained within it's data range? I have binary classified feature categories (1,0). Within that values can range from 0 to 1. However as you can see when binary classification is 1 (orange). There is no values beyond 0.6. How can I fix that?
for f in binary_feature_name:
    x = master_df_copy['status']
    vfig = sns.violinplot(x=f, y='value',  data = eda_cis_df, palette='Set2', cut=0)
    fig = vfig.get_figure()
    fig.savefig('./output/eda/' + f + ".png")
    plt.show()

I am expecting something like this

A: From https://seaborn.pydata.org/generated/seaborn.violinplot.html:

cut: float, optional
Distance, in units of bandwidth size, to extend the density past the extreme datapoints.
Set to 0 to limit the violin range within the range of the observed data.


text:
Q: how to migrate flutter existing app to web I have designed a mobile application using flutter, I have seen that it is compatible with the web and I would like to know how to migrate my already designed application to the web environment, I know that I must take into account the compatibility with the dependencies that I have used and already reviewed.
At the moment I have carried out the following process, but all it does is create a folder with few elements that when executed, the browser opens with a blank page, the flutter logo and a blue appbar. What procedure am I missing?

*

*flutter config --enable-web

*flutter create.

*flutter run -d chrome


text:
Q: Include dynamic info in Rails emails I have managed to get my email problem sorted so now everytime a case is created an email goes out to the specified address.
I have a usermailer.rb
def makeakase(email, name, jobno, casesubject)
      recipients email
      from "no-reply@your_rails_app.com"
      subject "FW: Kase creation from Survey Manager"
      sent_on Time.now
      body :name => name
  end

and I have the kases_controller.rb:
if @kase.save
          UserMailer.deliver_makeakase("danny@XXXXX.co.uk", "Highrise")

In the body I would like to use the tags that I use in the kase show view such as:
<%=h @kase.jobno %> - <%=h @kase.casesubject %>

but they don't work, I get the following error:
wrong number of arguments (2 for 4)

Any ideas?
Thanks,
Danny

A: Well, your makeakase(email, name, jobno, casesubject) has 4 arguments and you are passing 2:
UserMailer.deliver_makeakase("danny@XXXXX.co.uk", "Highrise")

And you are not passing @kase to Notifier
You need
  def makeakase(email, name, kase)
      recipients email
      from "no-reply@your_rails_app.com"
      subject "FW: Kase creation from Survey Manager"
      sent_on Time.now
      body :name => name, :kase => kase
  end

UserMailer.deliver_makeakase("danny@XXXXX.co.uk", "Highrise", @kase)

A: I worked this out:
In the user_mailer view you can put the <%=h @kase.jobno %> - <%=h @kase.casesubject %> tags just like you would in the show view for Kases.
Hope this helps someone else.
Thanks,
Danny


text:
Q: Ouput all possibilities, could be three int number as example belowed Given a sorted array, output all triplets such that a-b=c, the example of array is: {-24, -15, -8, -6, 0, 3, 6, 9, 17, 36}

A: I'll suggest an O(n^2) solution based on the following property: if you fix a and sequentially increase b then c is decreasing. So you can do as following:
    for( i = 0; i < arr.size(); i++ ) // index of a
    {
        t = arr.size() - 1; // index of possible c
        for( j = 0; j < arr.size(); j++ ) // index of b
        {
            a = arr[ i ];
            b = arr[ j ];
            c = a - b;
            while( t >= 0 && arr[ t ] > c ) // using monotonicity
               t--;
            if( t >= 0 && arr[ t ] == c )
            { /* output a, b, c */ }
        }
    }

A: Can be done in O(n^2) by storing all a - b in a hash table then querying the hash for each element c in the array.

A: Haskell version:
triples set =
  [[a,b,c] | a <- set, b <- set, b /= a, c <- set, c /= b && c /= a, a - b == c]

*Main> triples [-24, -15, -8, -6, 0, 3, 6, 9, 17, 36]
[[-15,-24,9],[-15,9,-24],[-6,-15,9],[-6,9,-15],[0,-6,6],[0,6,-6],[3,-6,9],[3,9,-6],[9,-8,17],[9,3,6],[9,6,3],[9,17,-8]]


text:
Q: Issue accessing "stored" values (smatr) I am trying to access values from stored results from sma in package smatr. I have done this before and am using the same kind of code, but it's not working now and I can't figure out what the issue is. For example, in the following dataframe
test2 <- structure(list(x = 1:10, y = c(1L, 4L, 9L, 16L, 25L, 36L, 49L,
64L, 81L, 100L)), .Names = c("x", "y"), class = "data.frame", row.names = c(NA,
-10L))

    x   y
1   1   1
2   2   4
3   3   9
4   4   16
5   5   25
6   6   36
7   7   49
8   8   64
9   9   81
10  10  100

I am estimating the power function exponent (or slope on log-log transformed data) using
sma1 <- sma(log10(y)~log10(x), data=test2)
summary(sma1)

which yields an exponent/slope of 2 (there are unimportant errors thrown but it's just my example). I can see how to access the various components of the fit using
str(sma1)

I want to use these components for other things. For example, I can obtain the fitted minimum x value using sma1$from and can use this in calculations like
10^as.numeric(sma1$from)

However, when I try to access the fitted exponent/slope using
sma1$coef$'coef(SMA)'[2]

it returns NULL instead of a value of 2. I've used this successfully in the past, and can't understand why it's not working here. Can anyone see what I am doing wrong?
Thanks!

A: I was finally able to get it using data.frame(sma1$coef)[2,2]. They must have changed something in the new version (?).  Anyways, I hope this helps someone some time!


text:
Q: Заменить знак * на цифру Надо в масиве a = ['*','1','2','*','*','4','*','*'] заменить * на число 1 а потом вивести масив без [] и ''

A: как вариант

*

*объединить строки которые содержатся в массиве в одну строку через 'join()'
 text = ''.join(arr)

*заменить в строке звездочки на символ 1 через replace()
 text = text.replace('*', '1')

*вывести строку посимвольно через print и *
 print(*text)

Ну и можно несколько извратов
способ 1:
print(*[i if i != '*' else '1' for i in arr])

способ 2:
print(*map(lambda i: i if i != '*' else '1', arr))

способ 3:
print(*''.join(arr).replace('*', '1'))

способ 4:
print(' '.join(arr).replace('*', '1'))


text:
Q: DiffEq: The correlation between the number of roots and the number of limiting behavior So I understand that when dy/dt is $0$, this means that $y(t)$ is a constant. But why does the number of limiting behavior depend on the roots of the differential equation. And why if $dy/dt ≠ 0$, the solution curves tend to approach or avoid the $dy/dt = 0$ solutions.
For example, the graph below is the directional field of y vs t of the equation ${dy\over dt} = y^2 - ty.$ As you can see the surround solutions seem to approach 0 or t which are roots for dy/dt = $0$.
They teach us how to calculate this equations but they don't truly teach us the meaning behind these calculations. So please excuse me if this seems trivial.

A: I think what you mean is something like this.  Consider a first-order autonomous differential equation $$\dfrac{dy}{dt} = f(y)$$
where $f$ is a continuous function.
If you have a solution $y = s(t)$ with $\lim_{t \to \infty} s(t) = L$, then $L$ must satisfy $f(L) = 0$.  This is easy to prove by contradiction: if $f(L) \ne 0$ then there are $\delta > 0$ and $\epsilon > 0$ such that either $f(y) > \epsilon$ for $L-\delta < y < L + \delta$ or $f(y) < -\epsilon$ on that interval.
Any solution that ever has $L - \delta < y < L+\delta$ will then exit that interval in time at most $2\delta/\epsilon$ and can never return...
EDIT: For a non-autonomous equation $\dfrac{dy}{dt} = f(y,t)$, all sorts of other behaviours are possible.
The isoclines $f(y,t) = 0$ are important, but usually they do not represent asymptotes of the solutions.  In your particular example you are correct, there does happen to be a solution that approaches $y=t$ asymptotically as $t \to +\infty$.
It is the separatrix between the solutions that go to $+\infty$ in finite time and those that go to $0$ as $t \to \infty$.
EDIT: Hubbard's terminology is useful: a curve $y = g(t)$ is a lower fence
if $f(g(t),t) > g'(t)$ and an upper fence if $f(g(t),t) < g'(t)$.  Thus a solution curve can cross a lower fence from below to above but not from above to below, and it can cross an upper fence from above to below but not from below to above.  A funnel is a region above a lower fence and below an upper fence; solution curves can enter a funnel, but can't leave it.  An antifunnel is a region above an upper fence and below a lower fence: a solution can leave a funnel, but can't enter it.  However, an antifunnel always contains at least one solution curve that stays within the antifunnel.
In your example, $y = t$ for $t > 0$ is an upper fence, while for any $\epsilon > 0$, $y = t + \epsilon$ for $t > 1/\epsilon$ is a lower fence; there is one solution curve that stays in the antifunnel between these fences.