text:
Q: a function that counts object from an array into a table I have made this function witch works fine, but I want it to have another look. I want a table around every single word but right now it's around the whole text. The reason is that the variable is short the short version so its gonna be much bigger. It has to work in HTML
I am new to coding so I would like something vanilla javascript, i hope somebody can help me! :)

  var markers = [
      {
        type:"Chocolate",
        name:"KitKat",
        group:"candy",
        icon:"candy",
        coords:[5246,8980],
      },
      {
        type:"Fruit",
        name:"Orange",
        group:"fruits",
        icon:"fruis",
        coords:[9012,5493],
      },
      {
        type:"Fruit",
        name:"Banana",
        group:"fruits",
        icon:"fruis",
        coords:[9012,5493],
      },
      {
        type:"Food",
        name:"Rice",
        group:"foods",
        icon:"foods",
        coords:[6724,9556],
      },
      {
        type:"Food",
        name:"Meat",
        group:"foods",
        icon:"foods",
        coords:[6724,9556],
      },
      {
        type:"Food",
        name:"Beam",
        group:"foods",
        icon:"foods",
        coords:[6724,9556],
      },
      {
        type:"Liquid",
        name:"Water",
        group:"liquids",
        icon:"liquids",
        coords:[6724,9556],
      },
      {
        type:"Liquid",
        name:"Coffe",
        group:"liquids",
        icon:"liquids",
        coords:[6724,9556],
      },
    ];

    function counter(){
    var count = {}

    for (var i = 0; i < markers.length; i++) {
      count[markers[i].type] = count[markers[i].type] + 1 || 1;
    }
    document.getElementById('data').innerHTML = JSON.stringify(count);
    }
    counter();

A: If you want to have a "table-look", then you have multiply ways to do it -
1) Use some framework;
2) Do it by your own;
Some example for you:
import "./styles.css";

const markers = [
  {
    type: "Chocolate",
    name: "KitKat",
    group: "candy",
    icon: "candy",
    coords: [5246, 8980]
  },
  {
    type: "Fruit",
    name: "Orange",
    group: "fruits",
    icon: "fruis",
    coords: [9012, 5493]
  },
  {
    type: "Fruit",
    name: "Banana",
    group: "fruits",
    icon: "fruis",
    coords: [9012, 5493]
  },
  {
    type: "Food",
    name: "Rice",
    group: "foods",
    icon: "foods",
    coords: [6724, 9556]
  },
  {
    type: "Food",
    name: "Meat",
    group: "foods",
    icon: "foods",
    coords: [6724, 9556]
  },
  {
    type: "Food",
    name: "Beam",
    group: "foods",
    icon: "foods",
    coords: [6724, 9556]
  },
  {
    type: "Liquid",
    name: "Water",
    group: "liquids",
    icon: "liquids",
    coords: [6724, 9556]
  },
  {
    type: "Liquid",
    name: "Coffe",
    group: "liquids",
    icon: "liquids",
    coords: [6724, 9556]
  }
];

/* I split all drawing stuff to separate functions, to make it easier for you to watch progress */
// draw header
const drawHeader = data => {
  const headers = Object.keys(data[0]);
  const thead = document.createElement("thead");
  const tr = document.createElement("tr");
  thead.append(tr);
  headers.forEach(el => tr.append(drawCol(el)));
  return thead;
};

// draw column
const drawCol = data => {
  const td = document.createElement("td");
  td.innerHTML = data;
  return td;
};
// draw row
const drawRow = data => {
  const tr = document.createElement("tr");
  const keys = Object.keys(data);
  keys.forEach(el => tr.append(drawCol(data[el])));
  return tr;
};
// sraw it all together
const drawTable = data => {
  const table = document.getElementById("app");
  const theader = drawHeader(data);
  table.prepend(theader);
  const tableBody = document.getElementById("tbody");
  const rows = data.forEach(m => tableBody.append(drawRow(m)));
  return rows;
};

drawTable(markers);

html

some styles
body {
  font-family: sans-serif;
}

td {
  padding: 10px;
}

thead td {
  font-weight: bold;
}

And you'll get something like this:

Working example:
https://codesandbox.io/s/mystifying-night-dbwvk
The main goal here, is to manipulate DOM by hands, that is pretty boring, and not too efficient (Thats btw, one of reasons, why frameworks so popular).
As we can see, we need to write pretty much code just to form a row and place result to table. If you decide to use filters as on your picture, worktime grows exponentially.


text:
Q: Using a CursorAdapter with two different ContentProviders I would like to display a list of contacts.
I would like to pull those contacts from Android's contacts ContentProvider (as defined by ContactsContract) as well as a table of contacts managed by my own app (for which I've also defined a ContentProvider).
Ideally I would like to produce a single Cursor that represents a union of queries from both sources.
If I had full access to Android's contacts table, I would use a SQL UNION. As it is, I believe that that is impossible/bad practice to perform a raw SQL query on a database that doesn't belong to your own app.
Alternatively, is there a straight forward way to define a CursorWrapper extension which would iterate over one cursor before moving onto the next?
I would accept any means of ending up with a single Cursor object for these two sources or an elegant outline for an implementation of an Adapter which would deliver the same result.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to **FIX** a value to the DBGrid's header heigth? When the user selects the header of my grid, I would like to bold the column header of the grid.
I use the following code to achieve this:
procedure TForm1.DBGrid1TitleClick(Column: TColumn);
var I: Integer;
begin
  //Prevent multiple clicks!
  if fsBold in Column.Title.Font.Style then
    Exit;

  for I:= 0 to Column.Collection.Count-1 do
    (Column.Collection.Items[I] as TColumn)
            .Title.Font.Style := [];
  Column.Title.Font.Style := [fsBold];
end;

This code is working fine.
In the OnFormCreate I've defined the following header height:
type
  DBGridHack = class(TDBGrid);

procedure TForm1.FormCreate(Sender: TObject);
begin
  DBGridHack(DBGrid1).RowHeights[0] := 45;
end;

When I click in the Title, the procedure InternalLayout.MeasureTitleHeights changes the size back to the original.
Thus, every time I change the font style I need to redefine the value for RowHeight[0].
The code would look like this:
procedure TForm1.DBGrid1TitleClick(Column: TColumn);
var I: Integer;
begin
  //Prevent multiple clicks!
  if fsBold in Column.Title.Font.Style then
    Exit;

  for I:= 0 to Column.Collection.Count-1 do
    (Column.Collection.Items[I] as TColumn)
            .Title.Font.Style := [];
  Column.Title.Font.Style := [fsBold];

  //Every time!!
  DBGridHack(DBGrid1).RowHeights[0] := 45;
end;

There is another issue when the user redefine the Column's width, in this case the RowHeight[0] also returns to the original value. The only way I imagine to solve this, is to inherit DBGrid and override ColWidthsChanged, but how much more methods will I have to override?
Why this happens?
Is this a bug, or is my code bugged?
Is there a way to workaround this?
In a simple question.
How to FIX a value to the DBGrid's header heigth?

A: It seems like if I override the Paint procedure, it will work as expected.
I don't know if there is side effects about this solution.
This is the code for the custom DBGrid. Please if this is not a good solution I would appreciate if you state it so.
TDBGrid1 = class(TDBGrid)
  private
    FTitleFixedHeight: Integer;
    function CheckHeaderFixed: Boolean;
  protected
    procedure Paint; override;
  public
    { Public declarations }
  published
    property TitleFixedHeight: Integer read FTitleFixedHeight write FTitleFixedHeight;
  end;

function TDBGrid1.CheckHeaderFixed: Boolean;
begin
  Result := (TitleFixedHeight <> 0) and (RowHeights[0] <> TitleFixedHeight);
end;

procedure TDBGrid1.Paint;
begin
  if CheckHeaderFixed then
  begin
    RowHeights[0] := TitleFixedHeight;
  end;
  inherited;
end;


text:
Q: What does Smart Checkout in IDE Intellij IDEA's tool Version Control do? My project is using git as vcs tool. This question is about the integrated Version Control tool.
In development,our branch promise is:

*

*Branch master is running to supply stable and formal service.

*Branch staging is running in a test environment.

*Developing Branches. If there are new requirements, checkout new branch from master. After developing, we will merge the branch into staging for testing. If new code passes tests, we will merge it into master eventually.

Yesterday, I did such procedures:
I found a bug in my project. So I modified some code. But I found the branch is staging.As expected, I stash the code in staging and checkout a new branch B from master. Then I recheckout branch staging and stash pop after which I click IDEA's Panel ↘  to checkout branch B, IDEA ask me to confirm checkout or not. I chose Smart Checkout then continued my development in new Branch B and made a commit.
When I merged B to staging, I cannot find new features from B. I must cherry-pick the commit just from B. Why ? What did Smart Checkout do? It seemed to mark the something as unmodified.

A: The Intellij idea help page mentions the following about switching between branches:

When multitasking, you often need to jump between branches to commit
unrelated changes.
In the Branches popup or in the Branches pane of the Git tool window, select the branch that you want to switch to under Local
Branches and choose Checkout from the list of available operations.
What happens next depends on whether there are conflicts between your local changes that you have not committed yet, and the branch
that you are going to check out:
If your working tree is clean (that means you have no uncommitted changes), or your local changes do not conflict with the
specified branch, this branch will be checked out (a notification will
pop up in the bottom-right corner of the IntelliJ IDEA window).
If your local changes are going to be overwritten by checkout, IntelliJ IDEA displays a list of files that prevent you from checking
out the selected branch, and suggests choosing between Force Checkout
and Smart Checkout.
If you click Force Checkout, your local uncommitted changes will be overwritten, and you will lose them.
If you click Smart Checkout, IntelliJ IDEA will shelve uncommitted changes, check out the selected branch, and then unshelve
the changes. If a conflict occurs during the unshelve operation, you
will be prompted to merge the changes.


text:
Q: How to connect to wifi with local access only? I need to connect to my modem through local only, while the other computers continue to have both local and internet connectivity.
Is this possible?
My OS is Windows 7 64bit

A: On windows 7 Home Premium:
Start - Control Panel - Firewall - "Advanced Settings"
This will open up "Windows Firewall with Advanced Security" Window
Click on "Outbound Rules" and "New Rule"
Rule Type: Custom
Program: All Programs
Protocol and Ports: Any
Scope: Any IP Address (both local and remote)
Action: Block the connection
Profile: Domain and Private (Untick Public)
Name: Make a name for this rule

Click on Finish

And now you have an outbound Rule that blocks All Application from accessing any IP on any Port on Domain and Private (Home or Work or Private Networks)


text:
Q: Border disclosure in a grid I am currently looking for rationale to the following phenomenon:

*

*ASP.NET

               one column

               two column

               three column

Based on the above code, one could see each column separated by a vertical line.

*ASP.NET (Core) MVC
After migrating to a MVC Framework, similar code was not displaying the vertical line used a a column separator.
As a way around, I've added a CSS, and while slightly amending the code to:
/* add column separator */
#divider .border {
border-right: 1px solid #ddd;
}

                  one column

 test

                  two column

 test2

                  three column

Given the lack of improvements following online searches too, I am consequently curious to know any reason.
Thanks in advance.
Best.

A: The below adjustment has eventually worked, although it's not perfect since the height of vertical lines is proportionate to the numbers of rows used in each column.
N.B: I may thus use, as a way around, empty rows to ensure a certain symmetry while remaining opened to more robust suggestions.
CSS
.border-right {
border-right: 1px solid #ddd;
}

ASP.NET (Core) MVC

                  one column

 test

                  two column

 test2

                  three column


text:
Q: React textarea component with lines validator I have a TextArea component so the user needs to paste/edit lines up to 5000. I have some simple rules (line length, allowed characters, words number) so each line should be validated.
Ideally, I need to show line numbers and highlight lines that are valid/invalid.
The number of max lines is too high so a simple get/set all lines does not work - it is too slow.
I can handle keyup event, but in addition to this, there will be a copy/paste, select a part of the text and press a key to edit it, etc.
To avoid inventing the wheel, is there a component that can properly handle lines and apply some validation logic to the changed lines only?


text:
Q: Loop through dict key equals to list than put in new list I have a rather large dictionary right now that is set up like this:
largedict = {'journalname':{code: 2065},'journalname1':{code: 3055}}

and so on and so on. And another dictionary:
codes = {3055: 'medicine',3786: 'sciences'}

And I want to loop through largedict, compare it's code value to the keys in codes. Then either add all journalname key/value pairs that match the code to a different dictionary, or delete all that don't from largedict.

A: new_dic = {journal_name : journal_body for journal_name, journal_body in largedict.items() if journal_body["code"] in codes}


text:
Q: gaussian integral solution..error in logic? Why oh why have I never seen anyone mention the apparent flaw in the logic of solving this integral by squaring it?? When you make the second integral integrable over y, yes y is just the name of the variable so it be du, dt, etc. anything BUT when you change to polar coordinates x and y have specific and DIFFERENT definitions.. x=rcos theta and y=rsin theta..Thus x and y do NOT euqal each other and therefore e^-x^2 times e^-y^2 is NOT the same as the square of e^-x^2..because when you square something it means you multiply it by ITSELF and sin theta does not always equal cos theta..Therefore the integral e^-x^2 dx does NOT equal the integral e^-y^2dy..only when theta equals 45 degrees or some multiple of it do the sin theta and cos theta terms equal and cancel each other and thus the x and y exponents would be equal and this would work..andOtherwise has no one ever aksed wy they cant solve it using e^-2rcos theta^2 ...by truly squaring the e^-x^2 integral..I don't see any flaw in my reasoning so can someone please explain if and why I am wrong..does it have to do with the power series expression for pi happening to work only for angles where cos theta and sin theta are equal or cancel each other?? Please someone answer Thanks in advance.

A: Answering by a finite analogy with integrals replaced by sums.
Surely you know that
$$
S=\sum_{n=1}^3n=1+2+3=6,
$$
and also that
$$\sum_{m=1}^3m=1+2+3=6=S.$$
Notice that there is no need to declare that $(m,n)$ should be on the
line with $\phi=\pi/4$. We never studied $m$ and $n$ together here.
It should not be a surprise that the double sum
$$
\sum_{n=1}^3\sum_{m=1}^3mn=36=\left(\sum_{n=1}^3n\right)\left(\sum_{m=1}^3m\right)=S^2.
$$
Let's check:
$$
\sum_{1\le m.n\le 3}mn=(1+2+3)+(2+4+6)+(3+6+9)=6+12+18=36=S^2.
$$
This was just the distributive law of multiplication and addition of integers at work.
Do notice that we can compute the last sum also by grouping together the terms, where $m+n$ is a constant:
$$
\sum_{1\le m,n\le 3}mn=(1)+(2+2)+(3+4+3)+(6+6)+(9)=36.
$$
Here the second group $2\cdot1+1\cdot2$, the third group $3\cdot1+2\cdot2+1\cdot3$ et cetera.
Basically that's what happening here. Except that in this case we were unable to calculate the value of $S$ directly, but we are able to calculate the value of $S^2$ after writing it as a double sum, and then regrouping according to the value of $x^2+y^2$. There are tons of technical details, because we are dealing with an integral: convergence, Jacobian, et cetera. But the basic idea is similar.

A: Which of the following is equal to $\left[\int_a^b f(x)\,dx\right]^2,$
$$
\int_a^b\left[f(x)\right]^2\,dx\qquad\text{or}\qquad\int_a^bdx\int_a^bdy\,f(x)f(y)?
$$
If you answered the first one, then that is at the root of your difficulties in understanding the computation of $\int_{-\infty}^\infty e^{-x^2}\,dx.$  If that is indeed the problem, I would recommend trying some examples where you can compute all three integrals by hand, such as $f(x)=x^2$ with limits $a=0,$ $b=1.$
It should be said that your statement that $x\ne y$ is right, as is your statement that $e^{−x^2}\ne e^{−y^2}.$  In fact, how could they be equal in general?  Both $x$ and $y$ are variables, so they can take different values, which will generally not be the same.  When the integrals $\int_{-\infty}^\infty e^{-x^2}\,dx$ and $\int_{-\infty}^\infty e^{-y^2}\,dy$ are performed (taking a Riemann-sum point of view), $x$ and $y$ independently take on all the values between $-\infty$ and $\infty.$  While the variables and the integrands are not equal, the integrals are equal, since, as you pointed out, $x$ and $y$ are just different names for the integration variable.
It doesn't make sense to replace the variable $x$ in $\int_{-\infty}^\infty e^{-x^2}\,dx$ with $r\cos\theta.$  This replacement only makes sense in the context of the double integral $\int_{-\infty}^\infty dx\int_{-\infty}^\infty dy\, e^{-(x^2+y^2),}$ where $y$ would be replaced by $r\sin\theta$ at the same time.  Since the $x$-axis corresponds to $\theta=0,$ it would make sense to replace $x$ with $r\cos 0,$ but this just amounts to renaming $x$ to $r.$


text:
Q: Xml Parsing using state machines Is it a good practise to implement xml parsing in a state machine? If yes what are the major states we have to handle?

A: Well, if you're writing your own parser "from scratch" - then you should probably make such kind of a sandwich:

*

*plain text string

*SAX-type callbacks

*Code, that builds DOM, based on previous level

So level 1 can (and should) be done in an FSM, I would do it with a set of states like Initial, InTagName, InAttrName, InAttrValue, InCDATA, etc. There won't be too many, just a couple page switch statement.
Still, there's still plenty of work in case you need correct schema/namespace/xpath/etc support.
So why not just take an existing solution?


text:
Q: Live meeting recordings get saved as separate Audio and Video files I am trying to record a Live meeting session. It gets saved as separate Audio and Video files which makes it impossible to open them in Windows Media player.
But when I open the file from Live Meeting Recording Manager, it opens the video in Browser and works well.
So can some one advise me how to save both the audio/video in same file and also to merge the audio and video for existing saved sessions ?

A: I don't have a Live Meeting license and I'm unfamiliar with it, but merging audio and video streams from separate files is trivial, if you have a bit of disk space available. I suggest you merge them in a matroska container, using mkvtoolnix, but there are many other container formats and software packages available for this purpose.

A: Use the Live Meeting Converter tool, it takes all those files and combines them.


text:
Q: Using MVC style, where is the best place to call my query functions? I am wondering about best practices here.
MVC (Model - View - Controller) patterns involve separating components of your program that model the data, manipulate those models, and display those results to the user (usually through the UI) in some way.
What about a function that takes the model data and inserts it into a database? For example I have an object called a GameBoard, and I also want the ability to insert the state of this board into the SQL database for storage / historical purposes. I have a class that holds all my query functions. I am not asking where to store the query calls themselves -- again those are all encapsulated in one class.
But where would I call these functions from? Would this sort of functionality make the most sense to make it as a method of GameBoard? Or should it be part of the controller classes?

A: In ideal world, class that performs GameBoard state persistence should listen to game events:

*

*UI button is clicked

*Controller invokes some Model method (increment counter by one)

*Model updates its internal state

*Model notifies all listeners, that are interested in state change events

*Controller receives event and updates the UI

*DB Component receives event and saves GameBoard state to database

When user clicks UI button to update view with database data:

*

*UI button is clicked

*Controller loads the data and invokes model update method

next 3-4-5 steps are the same

A:
But where would I call these functions from?

In the controller. Usually the controller has dependencies to model objects for input and outout. E.g.

Depending on your architecture you might introduce an application service below the controller.
Details at https://www.link-intersystems.com/blog/2013/07/20/the-mvc-pattern-implemented-with-java-swing/

A: Following are the points for MVC.

*

*Make a strong separation between presentation (view & controller)
and domain (model).

*Divide GUI widgets into a controller (for reacting to user stimulus)
and view (for displaying the state of the model).

*Controller and view should (mostly) not communicate directly but
through the model- Observer Synchronization.

where would I call these functions from?

You should call these functions from your domain model (model).
Further Reading martin fowler


text:
Q: Is it true that $\lim_{n \to \infty} {(P(\forall i,j\leq n \text{ } [X_i, X_j] = e))}^{\frac{1}{n}} = P(X_1 \in Z(G))$?
Suppose $G$ is a group. $\{X_n\}_{n = 1}^{\infty}$ is a sequence of i.i.d. random elements of $G$ satisfying the condition that
$$\forall H \leq G, \qquad P(X_1 \in H) = \begin{cases}
   \frac{1}{[G:H]} & \quad \text{if $[G:H]$ is finite}\\
   0  & \quad \text{if $[G:H]$ is infinite}
 \end{cases}$$
Is it true that
$$\lim_{n \to \infty} P(\forall i,j\leq n, \ [X_i, X_j] = e)^{\frac{1}{n}} = P(X_1 \in Z(G)) \ ? $$

What have I tried so far?
If we accept an additional supposition, that the events $\{\forall i \leq p, \ X_i \in C_G(X_p) \}$ and $\{\forall i \leq q, \ X_i \in C_G(X_q) \}$ are independent for any natural $p \neq q$. Then we can see, that
$$P(\forall i,j\leq n, \ [X_i, X_j] = e) = \prod_{i = 1}^{n} P(\{\forall j \leq i, \ X_j \in C_G(X_i) \}).$$
Now, let's see, that on one hand
\begin{align*}
&P(\{\forall j \leq i, \ X_j \in C_G(X_i) \}) \\
&= P(X_i \in Z(G)) + (1 - P(X_i \in Z(G))P(X_1 \in C_G(X_i))^{i - 1} \\
&\leq P(X_1 \in Z(G)) + (1 - P(X_1 \in Z(G))\left(\frac{1}{2}\right)^{i - 1} \\
&= \frac{1}{2^{i - 1}} + \left(1 - \frac{1}{2^{i - 1}}\right)P(X_1 \in Z(G)) \\
&= P(X_1 \in Z(G))\left(1 - \frac{1}{2^{i - 1}} + \frac{1}{2^{i - 1}P(X_1 \in Z(G))}\right)
\end{align*}
and on the other hand
\begin{align*}
&P(\{\forall j \leq i, \ X_j \in C_G(X_i) \}) \\
&= P(X_i \in Z(G)) + (1 - P(X_i \in Z(G))P(X_1 \in C_G(X_i))^{i - 1} \\
&\geq P(X_1 \in Z(G)) + (1 - P(X_1 \in Z(G))P(X_1 \in Z(G))^{i - 1} \\
&= P(X_1 \in Z(G))^{i - 1} + \left(1 - P(X_1 \in Z(G))^{i - 1}\right)P(X_1 \in Z(G)) \\
&= P(X_1 \in Z(G))\left(1 - P(X_1 \in Z(G))^{i - 1} + P(X_1 \in Z(G))^{i - 2}\right)
\end{align*}
So, we have
\begin{align*}
&P(X_1 \in Z(G)) \\
&= \lim_{i \to \infty} P(X_1 \in Z(G))\left(1 - P(X_1 \in Z(G))^{i - 1} + P(X_1 \in Z(G))^{i - 2}\right) \\
&= \lim_{n \to \infty} \left( \prod_{i = 1}^n P(X_1 \in Z(G)) \left(1 - P(X_1 \in Z(G))^{i - 1} + P(X_1 \in Z(G))^{i - 2} \right) \right)^{\frac{1}{n}} \\
&\leq \lim_{n \to \infty} P(\forall i,j\leq n, \ [X_i, X_j] = e)^{\frac{1}{n}} \\
&\leq \lim_{n \to \infty} \left( \prod_{i = 1}^n P(X_1 \in Z(G)) P(X_1 \in Z(G)) \left(1 - \frac{1}{2^{i - 1}} + \frac{1}{2^{i - 1}P(X_1 \in Z(G))} \right) \right)^{\frac{1}{n}} \\
&= \lim_{i \to \infty} P(X_1 \in Z(G))\left(1 - \frac{1}{2^{i - 1}} + \frac{1}{2^{i - 1}P(X_1 \in Z(G))} \right) \\
&= P(X_1 \in Z(G)).
\end{align*}
However, I do not know how to prove that the events in our supposition are always independent (or is there a counterexample?). And neither do I know, how to prove the main statement of the question without using the aforementioned supposition.

A: I believe $S_3$ is a counterexample. Let $H< S_3$ be the unique subgroup of index $2$. Then $H$ is abelian, and for every $n$ we have $$P(\forall i,j:[X_i,X_j]=e)^{1/n} \geq P(\forall i: X_i\in H)^{1/n}=\frac{1}{2}.$$ This means the limit on the left (if it exists) is at least $1/2$. On the other hand, $Z(S_3)=\{e\}$, so $P(X_1\in Z(S_3))=P(X_1=e)=1/6$.
For general $G$, a similar argument should show that
$$
\liminf_{n\to\infty}P(\forall i,j\leq n:[X_i,X_j]=e) \geq \max_{\substack{H\leq G\\H\text{ abelian}}}\frac{1}{[G:H]}.
$$

A: For finite $G$, the bound given in Julian Rosen's answer is the exact limit, i.e. I claim that
$$
\mathrm P(\forall i,j\le n,\ [X_i,X_j] = e)^{1/n}\to \max_{\text{abelian }H \le G}\frac{1}{[G:H]} = \max_{\text{abelian }H \le G}\mathrm P(X_1 \in H). \tag{$\ast$}
$$
Indeed, denoting by $\mathcal A$ the collection of abelian subgroups of $G$,
$$
\limsup_{n\to \infty} \mathrm P(\forall i,j\le n,\ [X_i,X_j] = e)^{1/n} \le \limsup_{n\to \infty}\biggl(\sum_{H\in \mathcal A} \mathrm P(\forall i\le n,\ X_i\in H)\biggr)^{1/n} =\\
= \limsup_{n\to \infty}\biggl(\sum_{H\in \mathcal A} \mathrm P(X_1\in H)^n\biggr)^{1/n} = \max_{H\in \mathcal A} \mathrm P(X_1\in H).
$$
Since by Julian Rosen's answer,
$$
\liminf_{n\to \infty} \mathrm P(\forall i,j\le n,\ [X_i,X_j] = e)^{1/n}\ge  \max_{H\in \mathcal A}\mathrm P(X_1 \in H),
$$
we arrive at $(\ast)$.

In order for (a modification of) the argument to work, it is enough to assume that for some $n\ge 1$, $\sum_{H\in \mathcal A^*} \mathrm P(X_1\in H)^n<\infty$, where $\mathcal A^*$ is the collection of all maximal abelian subgroups of $G$.


text:
Q: The 1.0/sites API call is not returning all stackexchange sites Version 1 of the /sites API call does not appear to be returning all sites currently in the StackExchange network.
Compared to calling version 2 of the API with a large page size, the list of sites in v1 is getting truncated after Salesforce Meta.

A: From the API 1.1 docs:

The V1.x family of APIs is obsolete, having been replaced by the V2.x family.
New applications should use V2.1, and existing applications should migrate to V2.1 as well.
Existing API V1.x endpoints are still supported, but we are no longer creating new ones for new Stack Exchange sites. (emphasis mine)

Presumably, Salesforce was the last Stack Exchange site created when API 1.0/1.1 was still active, but newer sites are not getting their API endpoints created.
The original announcement on StackApps regarding the deprecation of API 1.x can be found here. (Oddly enough, it looks like Libraries was supposed to be the last site created with an API 1.0 endpoint, but the deadline was apparently extended).


text:
Q: preferredContentSize not working for an iphone app As I know popovers are meant for iPads but I'm trying to implement one in an iPhone app.
I need to show popover (with certain size) view controller PopoverVC in my main view controller HomeVC
Here is how I call popover in my HomeVC:
- (IBAction)optionsAction:(UIBarButtonItem *)sender {
    CBOptionsPopoverViewController *optionsViewController = [[CBOptionsPopoverViewController alloc] initWithNibName:CBOptionsPopoverNibIdentifier bundle:nil];
    optionsViewController.delegate = self;
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    optionsViewController.preferredContentSize = CGSizeMake(width, 100.0);
    self.optionsPopover.popoverContentSize = CGSizeMake(width, 100);
    [self presentViewController:optionsViewController animated:YES completion:nil];
}

And here is what I do in PopoverVC class:
- (instancetype)init {
    if (self = [super init]) {
        self.modalPresentationStyle = UIModalPresentationPopover;
        self.popoverPresentationController.delegate = self;
    }
    return self;
}

- (UIModalPresentationStyle) adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationPopover; //You have to specify this particular value in order to make it work on iPhone.
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    self.preferredContentSize = CGSizeMake(width, 100.0);
}

The problem is that it covers my whole screen, but I need only certain size.
May be there are some issues with the fact that I'm doing the app for iPhone? or adaptivePresentationStyleForPresentationController where i return UIModalPresentationPopover ?
EDIT:
I also added this:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"yes");
        self.modalPresentationStyle = UIModalPresentationPopover;
        self.popoverPresentationController.delegate = self;
    }
    return self;
}

But didn't help.
According to the comment. I used debugger and all 4 functions from PopoverVC are being called.
Also when I debug and do "po self.preferredContentSize" it shows that size is 320x100. Even when it's full screen (after user sees the page not before). That means that it just doesn't listen to the preferredContentSize


text:
Q: Can i remove some numbers with PHP that my code is getting from SOAP document? I have some PHP code that works perfect and it gets information through SOAP. I need to show my clients the prices of some products but instead of '€3,56' it gives '€3,560'. Is there a way that i can get rid of the last number? I can't change anything in the SOAP document so i can only fix it with PHP.

A: You said Is there a way that i can get rid of the last number? so if you want to remove last one you can use mb_substr there is an example
<?php

$a = "$3,560";
$b =mb_substr($a, 0, -1);
print_r($b);
?>

A: You could slice off the '0' with a string method ( substr('string', 0, -1 ) or you could turn it to a number and use modular division ( num % 10 ).
For the first answer, the 0 is the starting index and the -1 is the length (counting backwards from the end because you wish to strip off the last character).


text:
Q: iPhone App backgrounding with MPMusicPlayer I'm working on an iPhone iOS4 application that incorporates playing music from the user's iPod library.  I also want to keep track of what songs have been played and be able to change the song randomly, even while in the background.  So I set the music player using:
[self setMusicPlayer: [MPMusicPlayerController iPodMusicPlayer]];

Now, I want this application to continue to run and play music in the background, so I have set:
Required background modes: App plays audio

The problem I'm having is that my application loses control when it is moved into the background (when applicationDidEnterBackground is called, ie. on app switches).  Since I'm using the iPodMusicPlayer the music continues to play but my app does not have control and therefore can't track or change the song.
Now, the Apple documentation states that your application should continue to execute in the background using this required background modes tag, but mine does not.  Is it because I'm using MPMusicPlayer?  Is there any way to get around it?  Any ideas?
PS. I'm also trying to get the remote locked and multitasking iPod controllers to work with my application.  I'm using the code below, but remoteControlReceivedWithEvent never gets called!  Does it work with MPMusicPlayer? I've only seen it with AVAudioPlayer.
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    NSLog(@"remoteControlReceivedWithEvent");
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlTogglePlayPause:
            NSLog(@"Play Pause");
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            NSLog(@"Next");
            break;
        default:
            break;
    }
}

- (BOOL)canBecomeFirstResponder {
    NSLog(@"canBecomeFirstResponder");
    return YES;
 }

- (void) viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

A: You are correct. Your iPhone app will not run in the background while using MPMusicPlayerController. This will also prevent you from receiving remote control events.
If you want to play audio from the iPod library and have your app continue running in the background, you must use the lower-level AVPlayer class.


text:
Q: Can't store Files in public folder in Laravel 8 i'm trying to store pdf, txt... in DB
but i get this error:
Method Illuminate\Validation\Validator::validateCsv,txt,xlx,xls,pdf does not exist.
but when i add required|mimes this error i get:
The file must be a file of type: pdf, xlx, csv, txt, doc.
here the code:
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'file' => 'required|mimes:pdf,xlx,csv,txt,doc'
        ]);
        $name = $request->file('file')->getClientOriginalName();
        $path = $request->file('file')->store('public/files');
        $save = new File;
        $save->name = $name;
        $save->path = $path;
        return redirect('file-upload')->with('status', 'File Has been uploaded successfully');

    }

my blade code:

      <form method="post" enctype="multipart/form-data" id="upload-file" action="{{ url('store') }}" >

                      <input type="file" name="file" placeholder="Choose file" id="file">
                        @error('file')

{{ $message }}

                        @enderror

                  <button type="submit" class="btn btn-primary" id="submit">Submit</button>

      </form>

how can i fix it?

A: Use File to put content
\File::put(public_path('storage'). '/public/files/'. $file);


text:
Q: RDLC report export correctly from chrome browser, but not render RDLC report get export correctly from chrome browser, but not render.
Same report get render and export correctly into firefox browser.

A: Not all browsers or versions are supported. You must use a browser that has script support enabled. If the browser cannot run scripts, you cannot view the report.
Source:
Browser Support for ReportViewer Web Server Controls
It's also possible that a layout fix might solve your problem:
Gotcha: Reporting Services Viewer bugs on Google Chrome


text:
Q: Dockerfile: Bash export statement not working I use dockerfiles to create a container. I know docker, but my bash understanding is very very limited. I know this question is probably a duplicate, but I don't understand what to search for.
Issue
The step RUN export A_NUM=$(echo ${A_VERSION} | head -c 3) does not work. Even though in bash it perfectly works. I tried:

*

*setting ENV A_VERSION=$A_VERSION

*replicating my issue in bash (by going into the built container)

Any export statement in the dockerfile seems to be futile - can anybody explain this?
Setting
I have app_A and app_B. When I configure app_B I need to take the chosen version of app_A into account. A simplified dockerfile looks like this:
FROM openjdk:8-jdk-slim

ARG A_VERSION=3.1.3
# RUN install app_A with A_VERSION
# RUN install app_B

WORKDIR /HOME/A_USER
USER A_USER

# RUN set some environment variables for app_A

RUN export A_NUM=$(echo ${A_VERSION} | head -c 3)
RUN echo $A_NUM

RUN if awk 'BEGIN {exit !('$A_NUM' >= '3.2')}'; then export path_A="/opt/Name_A"; else export path_A="/usr/local/Name_A"; fi

# RUN Use B_VERSION to set some environment variables for app_B

A: Each RUN is a separate bash process, with its own environment variables. You must run all your bash commands in a single RUN:
RUN export A_NUM=$(echo ${A_VERSION} | head -c 3) \
    && echo $A_NUM \
    && if awk 'BEGIN {exit !('$A_NUM' >= '3.2')}'; then export path_A="/opt/Name_A"; else export path_A="/usr/local/Name_A"; fi

Moreover, you will save disk space because each RUN creates an image.


text:
Q: Accepting payment on behalf of someone else I have organizations who have users that pay to join.  I need to be able to accept payments on my rails app and send the money(minus a potential charge that goes to me) to the organization's bank account.
Currently I have only found services to accept payments(fee #1) and then separate services that distribute payments(fee #2).  I am looking for a service that is easy to implement and combines these steps; preferably wrapped up in a nice ruby gem.

A: I suggest Stripe, I've implemented it before, the documentation is very clean and the gems worked fine
How you could use it:

*

*Organizations needs to create an account on stripe

*You will implement in your platform a way to organizations login on stripe through your platform, when they do that they will create a permission to your platform to receive payment in their behalf

*You can set a value you will receive for each transaction

*Stripe will distribute the money automatically after each payment


text:
Q: sql BEGIN creates error I'm trying to update my datebase depending on whether a row already exists or not.
In my php file I create this string:
 IF EXISTS(SELECT updown
              FROM voted_source
              WHERE ID = ? AND userID = ?)
                BEGIN
                    UPDATE voted_source
                    SET updown = TRUE
                    WHERE ID = ?;

                    UPDATE source
                    SET score_up = score_up + 1,
                        score_down = score_down - 1
                    WHERE ID = ?;
                END;
                ELSE
                BEGIN
                    INSERT INTO voted_source (ID, userID, updown)
                    VALUES (?, ?, TRUE);

                    UPDATE source
                    SET score_up = score_up + 1,
                        score_down = score_down - 1
                    WHERE ID = ?;
                END

And I call this using pdo like so:
$pdo = new PDO('mysql: host='.$servername.';dbname='.$db, $user, $pass, array(
        PDO::ATTR_PERSISTENT => true
    ));
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $pdo->beginTransaction();

    $stmt = $pdo->prepare($sqlString);
    $stmt->execute([$sourceID, $userID, $sourceID, $sourceID, $sourceID, $userID, $sourceID ]);

    $pdo->commit();

    $pdo = null;

This returns the error:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near 'BEGIN UPDATE
  voted_source SET updown = TRUE WHERE ID = '1'at line 4' in voteSource.php:74 Stack trace: #0 voteSource.php(74): PDOStatement->execute(Array) #1 {main} thrown in voteSource.php on line 74;

The user has the rights to SELECT INSERT and UPDATE. Any help is greatly aprreciated.

A: It looks like you have copy-and-pasted your code from a stored procedure example you found somewhere and then altered it to your needs. From the MySQL manual, section "13.6.1 BEGIN ... END Compound-Statement Syntax" (see here):

BEGIN ... END syntax is used for writing compound statements, which can appear within stored programs (stored procedures and functions, triggers, and events). [...]

I am understanding this in the sense that BEGIN ... END can not be used in normal queries, but only in stored procedures and functions, triggers and events; hence the error message. In your situation, you don't need them, so just leave them away.
Furthermore, from the MySQL manual, section "13.6.5.2 IF Syntax" (see here):

IF search_condition THEN statement_list
        [ELSEIF search_condition THEN statement_list] ...
        [ELSE statement_list]
  END IF

So you really should add END IF in a new line at the end of your $sqlString.


text:
Q: PHP's crypt function (STD_DES) in javascript Is there an implementation of the crypt function in PHP written in javascript?
I only need the STD_DES version eg.
PHP:
<?php
    echo crypt('test', 'SO') . "\n";
    // SOVYikZv1wMH.
?>

JS:
console.log(PHP_crypt('test', 'SO'));
// SOVYikZv1wMH.

I have tried to use CryptoJS, but it doesn't seem to work the same way:
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/tripledes.js">
</script>
<script>
    var encrypted = CryptoJS.DES.encrypt('test', 'SO');
    console.log(encrypted.toString());
    // U2FsdGVkX1/VopEwWoWNH8SrvmdvM1O9
</script>

Note: I know DES is not secure, I shouldn't use it and X is way more secure than DES.

A: I have copied the relevant part of the code from http://dmr.ath.cx/misc/pwd/pwd.js, where it is implemented.
Usage:
des_init();
console.log(descrypt('test', 'SO')); // => SOVYikZv1wMH.

The code can be found here.


text:
Q: java.lang.ClassCastException: ListActivity cannot be cast to DatePickerDialog I'm having problems to implement this Material DatePicker due to the Context call that I should probably be doing wrong.
The sample from GitHub works just fine because the Dialog is being created by an Activity.
However, at this particular case, I'm working with a Fragment attached to a ListActivity.
This is how I'm calling it:
Calendar now = Calendar.getInstance();
DatePickerDialog dpd = DatePickerDialog.newInstance(
(DatePickerDialog.OnDateSetListener) getActivity(),
now.get(Calendar.YEAR),
now.get(Calendar.MONTH),
now.get(Calendar.DAY_OF_MONTH)
);
dpd.show(getFragmentManager(), "Datepickerdialog");

This line (DatePickerDialog.OnDateSetListener) getActivity() is generating the issue. It is declared as MainActivity.this in the sample, but I can't use ListActivity.this or something similar.

Logcat
Process: kva.ihm, PID: 16218
      java.lang.ClassCastException: kva.ihm.ParameterListActivity cannot be cast to
  com.wdullaer.materialdatetimepicker.date.DatePickerDialog$OnDateSetListener
              at kva.ihm.ParameterDetailFragment$49.onItemClick(ParameterDetailFragment.java:3839)

A: Your activity should implement DatePickerDialog.OnDateSetListener for handling callback void onDateSet(DatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth); from DatePicker.
Or you can handle it using anonim class:
DatePickerDialog dialog = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
    @Override
    void onDateSet(DatePickerDialog dialog, int year, int monthOfYear, int dayOfMonth) {
        //Your code.
    }
}, year, monthOfYear, dayOfMonth);

A: Silly mistake.
As previously mentioned by @Selvin in the comments, the interface call was implemented, therefore, it was wrongly associated by Android Studio auto imports.
TIP: Do not trust evil auto imports. :)


text:
Q: RewriteRule without changing the address in the browser I'm trying to make an address redirect to another one without actually changing the URL in the browser address bar.
User go to /path/page.php and see what is displayed on /path/index.php.
In the address bar the URL remains /path/page.php.
This is the code for the redirection:
Options +FollowSymLinks
RewriteEngine On
RewriteRule page.php index.php [NC]

I'm wondering if I need to use [P] for this task :/

A: [P] is a proxy flag, you need it only for silent redirection to another domain or web-server (in this case Apache works like HTTP proxy). In your case page.php and index.php reside on the same server, so [P] flag is useless.


text:
Q: R: random sample of columns excluding one column I may have discovered one of the problems in the code posted previously,  "R: using foreach() with sample() procedures in randomForest() call" and it relates to the script I was using to draw a random subsample of columns from a dataframe.
The fake data (below) has 19 columns, "A" through "S" and I want to draw a random subset of 5 columns, but I want to exclude the third column, "C", from the draw.  Simply excluding the third column from the first argument of sample() call does not work (i.e., some of the samples contain the 'C' column). I'm hoping someone has a suggestion on how to do this. This is the script that does not work:
randsCOLs= sample(1:dim(FAKEinput[,c(1:2,4:19)])[2], 5, replace=FALSE)
#randsCOLs= sample(dim(FAKEinput[,c(1:2,4:19)])[2], 5, replace=FALSE) - also doesn't work
out <- FAKEinput[,randsCOLs]

FAKEinput <-
data.frame(A=sample(25:75,20, replace=T), B=sample(1:2,20,replace=T), C=as.factor(sample(0:1,20,replace=T,prob=c(0.3,0.7))),
    D=sample(200:350,20,replace=T), E=sample(2300:2500,20,replace=T), F=sample(92000:105000,20,replace=T),
    G=sample(280:475,20,replace=T),H=sample(470:550,20,replace=T),I=sample(2537:2723,20,replace=T),
    J=sample(2984:4199,20,replace=T),K=sample(222:301,20,replace=T),L=sample(28:53,20,replace=T),
    M=sample(3:9,20,replace=T),N=sample(0:2,20,replace=T),O=sample(0:5,20,replace=T),P=sample(0:2,20,replace=T),
    Q=sample(0:2,20,replace=T), R=sample(0:2,20,replace=T), S=sample(0:7,20,replace=T))

A: It looks like excluding the dim() call will work, if I'm not mistaken.
randsCOLs = sample(FAKEinput[-3], 5, replace=FALSE)

A: Here is a more general approach (in case the C column is not the 3rd column)
FAKEinput[sample(which(names(FAKEinput) !='C'),5, replace=FALSE)]

Or you could use setdiff
FAKEinput[sample(setdiff(names(FAKEinput),'C'), 5, replace=FALSE)]

Or by changing the OP's code of 1:dim and assuming that C is the column 3
FAKEinput[sample((1:dim(FAKEinput)[2])[-3], 5, replace=FALSE)]


text:
Q: Clickonce Bootstrapping OpenXML 2.5 I am using OpenXML to edit an XLSX file in my winform app.  Currently I am going to install OpenXML SDK 2.5 on each persons computer (which is only about 10 people).  But would like to bootstrap it to my ClickOnce deployment package so in future do not have to remember to install it separately.  Was wondering if anyone could guide me on how to do this?
Thank you,
Brad

A: Just add DocumentFormat.OpenXml.dll to your ClickOnce package. This is the only dependency you need.
Regards,
Michael


text:
Q: Reply to sender adres e-mail PHP Here is my code for a email form. It works very great - sends everything to my adress e-mail. There is one problem and my question. How I can make it I can reply to the e-mail received from the form? I mean, user type his e-mail adres in e-mial box so I would like to simple reply it, so sender should be as author e-mail. For now it's myname@mydomain-where-i-have-my-website.com. It should be take this form 'email'. I'm a BIG php noobie.
HTML code

Contact form

                            <form method="post" action="/kontakt.php" id="contact_form">

Subject

<input type="text" name="name" id="name"  required>

E-mail

<input type="email" name="email"  required>

Message

<textarea name="message" id="message"  required></textarea>

<input type="submit" id="submint" name="submint" value="Send">

                            </form>

PHP code
<?php
header("content-type: application/json; charset=utf-8");

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

$to = "myname@something.pl";
$subject = "Welcome";

if($name && $email && $message){
 $headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit";

 $message_body = "";
 $message_body .= "Subject: " . $name . "\n";
 $message_body .= "From: " . $email . "\n";
 $message_body .= "Message: \n" . $message . "\n";

 if(mail($to,$subject,$message_body,$headers)){
 $json=array("status"=>1,"msg"=>"
Message send.
");
 }
 else{
 $json=array("status"=>0,"msg"=>"
Faild to send.
");
 }
}
else{
 $json=array("status"=>0,"msg"=>"
The all fields are required.
");
}
echo json_encode($json);
exit;
?>

UPDATED

As I wrote in my comment. To fix I removed the all $message_body:
 $message_body = "";
 $message_body .= "Subject: " . $name . "\n";
 $message_body .= "From: " . $email . "\n";
 $message_body .= "Message: \n" . $message . "\n";

Added mail header and form content:
  $mailheader = "MIME-Version: 1.0\r\n";
  $mailheader = "Content-type: text/plain; charset=utf-8\r\n";
  $mailheader = "From: ".$email." \n\r";
  $formcontent="Subject: $name \n Message: \n $message \n" ;

And changed this:
if(mail($to,$subject,$message_body,$headers))

To this:
if(mail($to,$subject,$formcontent,$mailheader))


text:
Q: Java memory management for java docs and comments Is the commented part of the code in a java program stored in memory? If it is stored, in which part of the memory is it stored?

A: No. The commented part of the code exists only in the source code.
All comments are removed when you compile the code.
According to java language specification:

*

*/* text */
A traditional comment: all the text from the ASCII characters /* to the ASCII characters */ is ignored (as in C and C++).

*// text
An end-of-line comment: all the text from the ASCII characters // to the end of the line is ignored (as in C++).


text:
Q: Execute curl requests in parallel in bash What is the best way to execute 5 curl requests in parallel from a bash script? I can't run them in serial for performance reasons.

A: I use gnu parallel for tasks like this.

A: Use '&' after a command to background a process, and 'wait' to wait for them to finish. Use '()' around the commands if you need to create a sub-shell.
#!/bin/bash

curl -s -o foo http://example.com/file1 && echo "done1" &
curl -s -o bar http://example.com/file2 && echo "done2" &
curl -s -o baz http://example.com/file3 && echo "done3" &

wait

A: xargs has a "-P" parameter to run processes in parallel. For example:
wget -nv http://en.wikipedia.org/wiki/Linux -O- | egrep -o "http://[^[:space:]]*.jpg" | xargs -P 10 -r -n 1 wget -nv

Reference:
http://www.commandlinefu.com/commands/view/3269/parallel-file-downloading-with-wget

A: Here's a curl example with xargs:
$ cat URLS.txt | xargs -P 10 -n 1 curl

The above example should curl each of the URLs in parallel, 10 at a time. The -n 1 is there so that xargs only uses 1 line from the URLS.txt file per curl execution.
What each of the xargs parameters do:
$ man xargs

-P maxprocs
             Parallel mode: run at most maxprocs invocations of utility at once.
-n number
             Set the maximum number of arguments taken from standard input for
             each invocation of utility.  An invocation of utility will use less
             than number standard input arguments if the number of bytes
             accumulated (see the -s option) exceeds the specified size or there
             are fewer than number arguments remaining for the last invocation of
             utility.  The current default value for number is 5000.


text:
Q: Keyword search not working I am creating a simple sql search that searches terms by keywords. Only, I have to type in the full key word phase for a result to show.
index.php
$term = $_GET['q'];
$term = strip_tags($term);
$term = mysql_real_escape_string($term);

require_once("<PATHTOFILE>\\dbconnect.php");
$sql = "SELECT * FROM Search WHERE Keywords LIKE '{$term}' LIMIT 15";
$result = mysqli_query($con, $sql) or die("couldn't apply search");

Results for '<?php echo $term; ?>'

    <?php
        if($count = mysqli_num_rows($result) > 0) {
            while($row = mysqli_fetch_assoc($result)) {
    ?>

<?php echo $row['Title']; ?>

    <?php
            }
        }
        if($count = mysqli_num_rows($result) == 0) {
            ?>No Results.<?php
        }
    ?>

sql table structure:

Any idea whats wrong?

A: Firstly, you're mixing MySQL APIs with mysql_real_escape_string().
That function does not intermix with mysqli_ functions.
You need to use mysqli_real_escape_string($con,$term); placed after your connection.
Along with '%{$term}%' as stated by Lashane in comments.


text:
Q: Select2 automatically adding blank value I'm using select2 for a multiple selector. Currently this is in my HTML file:
 <%= form.select "page_request_set_ids", @multiautocomplete_set_options.unshift(""),
 {}, id: "page-request-sets", multiple: true,
 allowClear: true, data: {placeholder: "Start typing sets..."} %>

@multiautocomplete_set_options is an array of strings.
When I go to access :page_request_set_ids later, the strings I typed in are there, along with an empty string.
I've tried to remove the unshift(""), which kept my placeholder, but did not remove the issue of the blank string in :page_request_set_ids.
Any ideas?

A: Directly taken from the select documentation:
Gotcha
The HTML specification says when multiple parameter passed to select and all options got deselected web browsers do not send any value to server. Unfortunately this introduces a gotcha: if an User model has many roles and have role_ids accessor, and in the form that edits roles of the user the user deselects all roles from role_ids multiple select box, no role_ids parameter is sent. So, any mass-assignment idiom like
@user.update(params[:user])

wouldn't update roles.
To prevent this the helper generates an auxiliary hidden field before every multiple select. The hidden field has the same name as multiple select and blank value.
Note: The client either sends only the hidden field (representing the deselected multiple select box), or both fields. This means that the resulting array always contains a blank string.
In case if you don't want the helper to generate this hidden field you can specify include_hidden: false option.
So bottom line is to add:
include_hidden: false

A: For me the issue was I didn't pass the 'multiple: true' option to the select_tag in my erb/haml, and only set the option in select2 when initializing.
Make sure you have the option in both places.


text:
Q: align-middle not working in table I have problem, that align-middle class not working with bootstrap 4. How can I fix this problem? Here is my code:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

                                            Pirkimo numeris
                                            <input id="numerisId" class="form-control" name="numeris" type="text"/>

                                            Pavadinimas
                                            <input id="pavadinimasId" class="form-control" name="pavadinimas" type="text" />

                                                <input id="ieskoti" class="btn btn-danger" title="Ieškoti" type="Submit" value="Ieškoti" />
                                                <input id="trinti" class="btn btn-default" title="Išvalyti" type="submit" value="Išvalyti" />

Thanks for help in advance! :)

A: class="align-middle" works in Bootstrap 4 and vertically centers the content of an element, by applying
vertical-align: middle;

on the element.
This value makes s content align along an imaginary horizontal line placed at the (vertical) middle of s height. See #vertical-align.
The effect can only be observed on s that are not the tallest in their parent
.
Note there are a large number of scenarios in which placing align-middle class on a  does not produce an observable change. So many that enumerating them seems a waste of time. If you are trying to vertically center the contents of a  and align-middle does not work for you, please update your question with a live snippet demonstrating the problem and I'll update my answer with a specific method considering your case.

To center  contents horizontally, use class="text-center" class on the , which applies
text-align: center;

See #text-alignment.

To align a block level element inside a wider parent, use class="mx-auto" class, which applies:
margin-left: auto;
margin-right: auto;

See #horizontal-centering.

Edit after snippet was added: Even though you've applied d-flex class to the
, your s still have display:table-cell. If you want to use flexbox centering on them give s the following classes:
Ta daaa!

... where .align-items-center centers vertically and .justify-content-center centers horizontally.
However, in this case you're using flexbox on
 markup, which makes little to no sense. Considering your usage, you're probably better off using .form-groups.


text:
Q: 'Set as startup project' setting dissapearing I have a solution with a bunch of projects in it.  The 'startup' project is a ASP.NET MVC Web Application.
I set it as the startup project (by right clicking on it in Solution Explorer and selecting 'set as startup project'.  The project title goes bold and everything works fine for a while.
Then I will be editing one of the supporting projects, and come to click the 'Start Debugging' button, and bang - the 'project of this type cant be started' message.
I then check, and the web project is no longer set as the startup project. And so on....
Anyone know why this is happening?

A: Try to close you solution, delete YourSolution.suo file in solution's root directory and open it again.

A: This can happen if the projects in the solution do not have unique ids.
Each project file has an entry like this:
ProjectGuid = "{36910E05-3D05-4AC0-B90C-94F8F776CE5F}"

If you created your supporting projects by file-copying your startup
project, they will still have the same id. The easiest way to check
this is to open the solution file with a text editor. You'll know,
that you have a problem, if you see two projects with different names,
but the same id:
Microsoft Visual Studio Solution File, Format Version 8.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Project1", "Project1.csproj", "{BAC18E5A-710F-4E5A-8DE3-822CE1AA5D38}"
    ProjectSection(ProjectDependencies) = postProject
    EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Project2", "Project2.csproj", "{BAC18E5A-710F-4E5A-8DE3-822CE1AA5D38}"
    ProjectSection(ProjectDependencies) = postProject
    EndProjectSection
EndProject

Another symptom of this problem is, that you can not define
dependencies between projects (i.e. Visual Studio keeps "forgetting"
them).
To fix the problem, simply edit your project files to have unique ids
and adjust your solution file accordingly.


text:
Q: Retaining a UIViewControllers's.view, then release VC, VC gets dealloc'd? I'm creating a bunch of UIViewControllers for managing several custom Objects. Though I don't really need Direct access to the `UIViewController' anymore from where it was created. I want to add the viewController.view to my Master UIViewController's view.   I then release the subViewController.   The SubViewController has a gesture Recognizer in in, when I go to perform a gesture I get a Message sent to deallocated Instance.
Here is my code.
[...snip...]
    for (int elementForPageTypeIndex = 0 ; elementForPageTypeIndex < elementsOnPage; elementForPageTypeIndex ++){

            IoUIElementPickerElementButtonViewController * element = [[IoUIElementPickerElementButtonViewController alloc] initWithNibName:@"IoUIElementPickerElementButtonViewController" bundle:nil];

            pageColumn = (elementForPageTypeIndex)%2 ;
            pageRow = roundf((elementForPageTypeIndex)/2);

            CGRect elementFrame= CGRectMake(kElementPickerColumnLeftOffset + (element.view.frame.size.width + kElementPickerColumnSeperation)*pageColumn + pageIndex*kElementPickerColumnPageOffset,
                                            kElementPickerRowTopOffset +  (kElementPickerRowSeperation + element.view.frame.size.height) * pageRow,
                                            element.view.frame.size.width,
                                            element.view.frame.size.height);

            [element.view setFrame:elementFrame];

            SysCDElement *ourCDElement = [elementsForPage objectAtIndex:elementForPageTypeIndex + maxElementsPerPages * pageIndex];

            [scrollViewContent addSubview:element.view];
            [element release];

    }
[...snip...]

Right after the release, The element's dealloc is run.  I thought that if I retained a viewController's View that the ViewController itself would also be retained?
Thanks,

A: Nope. It would be pretty scary if retaining the UIViewController's view also magically retained the UIViewController.
The rule of thumb is, if you need something to stay alive, you retain it. Don't ever release it if you still need it. Counting on some other class to retain it isn't dependable. If you want the controller to stay around, don't release it.


text:
Q: Meteor - Update packages in production How can I update my packages on production ? "mrt update before ./meteor.sh deploy" makes any difference on the bundle send to the server ?
I'm using meteor.sh to deploy and don't know if is there any update on the packages before goes into production.

A: You are doing it correctly. When you create a bundle, it outputs a .tgz file containing all of the required dependencies. Therefore, in order to update any of the dependencies on the production server you need to re-bundle after updating.
You can prove this to yourself by comparing the file size and content of two bundles which only differ by a single mrt update.


text:
Q: Index not improve speed in couchbase 4.5 I have below query
SELECT day,count(DISTINCT campaignId) campaigns
FROM Inheritx use index(daily_type_1)
where _type='DailyCampaignUsage'
group by day

I have below index
 `CREATE INDEX `daily_type_1` ON `Inheritx`
(`_type`,`day`,(distinct (`campaignId`))) WHERE (`_type` = "DailyCampaignUsage")`

it is taking 3s and I habe 52k data whare _type= "DailyCampaignUsage"
how I Can improve it's speed ?

A: Modify your index as follows.
CREATE INDEX `daily_type_1` ON `Inheritx` (campaignId,`day`)
WHERE (`_type` = "DailyCampaignUsage");

Keep the index in this answer. Modify your query as follows.
SELECT day,count(DISTINCT campaignId) campaigns
FROM Inheritx use index(daily_type_1)
where _type='DailyCampaignUsage'
and campaignId is not null
group by day;


text:
Q: How to make a shape with left-top round rounded corner and left-bottom rounded corner? I want to make a shape with with left-top rounded corner and left-bottom rounded corner:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#555555"/>

    <stroke android:width="3dp"
            android:color="#555555"
            />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp"
             />

    <corners android:bottomRightRadius="0dp" android:bottomLeftRadius="2dp"
     android:topLeftRadius="2dp" android:topRightRadius="0dp"/>
</shape>

But the shape above didn't give me what I want. It gives me a rectangle without any rounded corners.

A: This bug is filed here.
This is a bug of android devices having API level less than 12.
You've to put correct versions of your layouts in drawable-v12 folder which will be used for API level 12 or higher.
And an erroneous version(corners switched/reversed) of the same layout will be put in the default drawable folder which will be used by the devices having API level less than 12.
For example: I had to design a button with rounded corner at bottom-right.
In 'drawable' folder - button.xml: I had to make bottom-left corner rounded.
<shape>
    <corners android:bottomLeftRadius="15dp"/>
</shape>

In 'drawable-v12' folder - button.xml: Correct version of the layout was placed here to be used for API level 12 or higher.
<shape>
    <corners android:bottomLeftRadius="15dp"/>
</shape>

A: try this
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/upkia"/>
<corners android:radius="10dp"
    android:topRightRadius="0dp"
    android:bottomRightRadius="0dp" />
</shape>

A: It looks like a bug http://code.google.com/p/android/issues/detail?id=939.
Finally I have to write something like this:

 <stroke android:width="3dp"
         android:color="#555555"
         />

 <padding android:left="1dp"
          android:top="1dp"
          android:right="1dp"
          android:bottom="1dp"
          />

 <corners android:radius="1dp"
  android:bottomRightRadius="2dp" android:bottomLeftRadius="0dp"
  android:topLeftRadius="2dp" android:topRightRadius="0dp"/>

I have to specify android:bottomRightRadius="2dp" for left-bottom rounded corner (another bug here).

A: While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).
So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

A: From the documentation:

NOTE: Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific
  corners to not be rounded, a work-around is to use android:radius to
  set a default corner radius greater than 1, but then override each and
  every corner with the values you really want, providing zero ("0dp")
  where you don't want rounded corners.

E.g. you have to set an android:radius="<bigger than 1dp>" to be able to do what you want:
<corners
    android:radius="2dp"
    android:bottomRightRadius="0dp"
    android:topRightRadius="0dp"/>

A: You can also use extremely small numbers for your radius'.
<corners
  android:bottomRightRadius="0.1dp" android:bottomLeftRadius="2dp"
 android:topLeftRadius="2dp" android:topRightRadius="0.1dp" />

A: for others there are a solution for any API level , you can place a item on top of each other example :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- my firt item with 4 corners radius(8dp)
 -->
    <item>
        <shape>
            <solid
                android:angle="270.0"
                android:color="#3D689A" />

            <corners android:topLeftRadius="8dp" />
        </shape>
    </item>
<!-- my second item is on top right for a fake corner radius(0dp)
 -->
    <item
        android:bottom="30dp"
        android:left="50dp">
        <shape>
            <solid android:color="#5C83AF" />
        </shape>
    </item>
<!-- my third item is on bottom left for a fake corner radius(0dp)
 -->
    <item
        android:right="50dp"
        android:top="30dp">
        <shape>
            <solid android:color="#5C83AF" />
        </shape>
    </item>

</layer-list>

the result with light color to show you the three items :

the final result :

Best regards.

A: This works for me
  <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/colorPrimary" />
    <corners
        android:bottomLeftRadius="0dp"
        android:radius="@dimen/dimen_5dp"
        android:topLeftRadius="0dp" />
</shape>


text:
Q: Intellij: maven install on pom changes Can Intellij IDE automatically do a mvn install on pom changes?
I have a multi-module maven project, and currently, when I make changes to the pom file, I have to do mvn install manually.
I know that I can execute Lifecycle commands automatically by setting the following options, but these are not what I wanted.

A: There is a tool called 'filewatcher'. Find more info in jetbrains docs: https://www.jetbrains.com/help/idea/using-file-watchers.html?section=Windows%20or%20Linux


text:
Q: Uncaught TypeError:Cannot read properties of undefined I created a dynamic content using ajax:
$(function(){
   $('#loadFeed').bind('click',function(){
        $.getJSON('getData.php', function(json) {
            var output="
";

            for(var i=json.posts.length-1;i>=json.posts.length-31;i--){
                output+="
";
                output+="
"+json.posts[i].shortmsg+"
";
                output+="
";
            }
            output+="
"
            $(output).appendTo('.posts');
    });
  });
});

The html codes:

I wanna click the short text, then the text will expand to show the entire text.The code to implement it was:

The error was
Uncaught TypeError: Cannot read property 'msg' of undefined .

I don't know why it recognizes msg as undefined. I defined msg in my getData.php just as what I did to the id, shortmsg. Here is my getData.php:
<?php

        // Connecting, selecting database
        $link = mysql_connect('localhost', 'root')
            or die('Could not connect: ' . mysql_error());
        mysql_select_db('my_db') or die('Could not select database');

        // Get Data
        $query = 'SELECT * FROM feed ORDER BY feed.userID ASC';

        $result = mysql_query($query) or die('Query failed: ' . mysql_error());

        //create json format text from posts
        $json=array();
        while($row=mysql_fetch_array($result)){
            $post=array('id'=>$row['userID'],'avatar'=>$row['avatar'],'postType'=>$row['postType'],'msg'=>$row['msg'],'shortmsg'=>$row['shortmsg'],'title'=>$row['title'],'type'=>$row['type'],'pic'=>$row['pic'],'link'=>$row['link']);
            array_push($json,$post);
        }

        //display it to the user
        header('Content-type: application/json');
        echo "{\"posts\":".json_encode($json)."}";

        // Closing connection
        mysql_close($link);

        return $row;

?>

Thanks!


text:
Q: Getting error while converting Json data to Object in iOS I am using an API to convert Json Data into Object data,
please visit the API I am using
Please Visit the API page which I am using
Here is the snap of my code with highlighted issues
Issues
and here is the raw code
 -(void) retrieveData{
    NSURL * url = [NSURLURLWithString:getDataUrl];

NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];

NSLog(@"JsonArray %@", jsonArray);

//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];

//Loop through our jsonArray

for (int i = 0; i<jsonArray.count; i++)
{
    NSString * yId = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"id"];
   // NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:@"id"];
    NSString * yName = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"name"];
    NSString * yDescription = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"description"];
    NSString * yImage = [[[[jsonArray objectAtIndex:i]objectForKey:@"data"]objectAtIndex:@"categories"]objectForKey:@"image"];

    //Add the city object to our citiesArray

    [yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];

     }
[self.tableView reloadData];

     }

A: Thanks @Lame, I followed your code, as it was giving me 6 to 8 errors, but I understand your code & configured error in that now here is the complete solution which works according to my requirements or (perfect answer according to my asked question)
-(void) retrieveData{
    NSURL * url = [NSURL URLWithString:getDataUrl];
    NSData * data = [NSData dataWithContentsOfURL:url];
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    NSDictionary *dataJSON = [jsonDict objectForKey:@"data"];
    NSArray *allCategoriesJSON = [dataJSON objectForKey:@"categories"];

    yougaArray = [[NSMutableArray alloc] init];

    for (int i = 0; i < allCategoriesJSON.count; i ++)
    {
        NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
        NSString *yId = [aCategoryJSON objectForKey:@"id"];
        NSString *yName = [aCategoryJSON objectForKey:@"name"];
        NSString *yDescription = [aCategoryJSON objectForKey:@"description"];
        NSString *yImage = [aCategoryJSON objectForKey:@"image"];
        [yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
    }
    [self.tableView reloadData];

A: According to your JSON response its a Dictionary type object not an array so your code should be like this,
    NSMutableDictionary *dictData = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];

    NSLog(@"JsonArray %@", dictData);

       NSArray *jsonArray=[[dictData objectForKey:@"data"] objectForKey:@"categories"];
    //setup yougaArray
    yougaArray = [[NSMutableArray alloc] init];

    for (int i = 0; i<jsonArray.count; i++)
    {

        NSString * yId = [[jsonArray objectAtIndex:i] objectForKey:@"id"];
        // NSString * yId = [[jsonArray objectAtIndex:i]objectForKey:@"id"];
        NSString * yName = [[jsonArray objectAtIndex:i] objectForKey:@"name"];
        NSString * yDescription = [[jsonArray objectAtIndex:i] objectForKey:@"description"];
        NSString * yImage = [[jsonArray objectAtIndex:i] objectForKey:@"image"];

        //Add the city object to our citiesArray

        [yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];

    }
    [self.tableView reloadData];

Hope it works for you. Let me know!!
Happy coding. :)

A: You JSON seems like this :
{
"meta": {
    "status": "200",
    "msg": "OK"
},
"data": {
    "total_pages": 0,
    "total_categories": 2,
    "current_page": 1,
    "next_page": 0,
    "categories": [{
        "id": "2",
        "name": "Articles",
        "description": "Yoga Articles",
        "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
    }, {
        "id": "1",
        "name": "Poses",
        "description": "Yoga Poses",
        "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
    }]
}
}

now replace your existing code with the code below:
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error:nil];

NSLog(@"JsonArray %@", jsonArray);

//setup yougaArray
yougaArray = [[NSMutableArray alloc] init];

//Loop through our jsonArray

NSArray *dataArray = [[jsonArray objectForKey@"data"] objectForKey:@"categories"];

for (int i = 0; i < dataArray.count; i++) {
    NSString * yId = [[dataArray objectAtIndex:i] objectForKey:@"id"];
    NSString * yName = [[dataArray objectAtIndex:i] objectForKey:@"name"];
    NSString * yDescription = [[dataArray objectAtIndex:i] objectForKey:@"description"];
    NSString * yImage = [[dataArray objectAtIndex:i] objectForKey:@"image"];

    //Add the city object to our citiesArray

    [yougaArray addObject:[[Youga alloc]initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}

[self.tableView reloadData];

Let me know if the solution works for you, also if anything comes up.

A: This is the JSON:
{
    "meta": {
        "status": "200",
        "msg": "OK"
    },
    "data": {
        "total_pages": 0,
        "total_categories": 2,
        "current_page": 1,
        "next_page": 0,
        "categories": [{
            "id": "2",
            "name": "Articles",
            "description": "Yoga Articles",
            "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
        }, {
            "id": "1",
            "name": "Poses",
            "description": "Yoga Poses",
            "image": "http:\/\/yoga.lifehealthinfo.com\/uploads\/images\/50_50\/86289272image86289272.jpg"
        }]
    }
}

Your JSON is a NSDictionary at top level! Not a NSArray!
Also, avoid doing all objectForKey:/objectAtIndex: in the same line/instruction, it's harder to read, but also harder to debug, especially when you don't know what you are doing.
Also, when there is an error parameter, use it, don't put nil.
So:
NSError *errorJSON = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJSON];
if (errorJSON)
{
    NSLog(@"ErrorJSON: %@", errorJSON);
    return;
}
NSDictionary *dataJSON = [jsonDict objectForKey:@"data"];
NSArray *allCategoriesJSON = [dataJSON objectForKey:@"categories"];
for (NSUIInteger i = 0; i < allCategoriesJSON.count; i ++)
{
    NSDictionary *aCategoryJSON = [allCategoriesJSON objectAtIndex:i];
    NSString yID = [aCategoryJSON objectForKey:@"id"];
    NSString yName = [aCategoryJSON objectForKey:@"name"];
    NSString yDescription = [aCategoryJSON objectForKey:@"description"];
    NSString yImage = [aCategoryJSON objectForKey:@"image"];
    [yougaArray addObject:[[Youga alloc] initWithYougaId:yId andYougaName:yName andYougaDescpription:yDescription andYougaImage:yImage]];
}


text:
Q: How to call to Doc2Vec from the cmd Does anyone knows of an implementation to paragraph vector algorithm or Doc2Vec that can be used from the cmd, without changing the source code?

A: Gensim have ported Tomas Mikolov's word2vec and doc2vec original concepts to Python, which implements distributed memory and distributed bag of words models, using either hierarchical softmax or negative sampling. This will work with sentences, paragraphs and documents.
You can install from this location: https://radimrehurek.com/gensim/install.html


text:
Q: Updating SOME fields in nested object without overwriting others with spread operator How to update some field in nested object without overwriting other fields in that nested object with spread operator? My function is as follows
exports.handler = ((data, context) => {
const profile = data.profile
const uid = context.auth.uid
const newRef = db.collection("user").doc(uid)

return newRef.update({
    profile: {...profile}
}).then(() => {
        return "Data updated seccusfully"
    })
})

which is suppose to update nested profile object. However the function removes also all not specified fields in that object. Is there any way to achieve update object with spread operator without removing other fields or do we have to specify each fields as the documentation says?
db.collection("users").doc("frank").update({
"age": 13,
"favorites.color": "Red"
})

My profile object contains different fields for each type of user and I'm updating the profile fileds in multiple places therefore I was hoping to simplify it like this

A: It looks like we can update some object properties without overwriting others with set method like this. Strange it doesn't work with update
return newRef.set({
    profile: { ...profile }
}, { merge: true }).then(() => {
    return "Data updated seccusfully"
})

Really appreciate all your help


text:
Q: How to divide blocks of arrays in a loop? I am trying to figure out how to take an array stalls[] and find the middle index of a continuously decreasing size.
In essence, I am taking the middle index of an array, assigning it to the boolean true, then taking the new, smaller size of an index and finding the halfway point of that (ignoring everything to the right).
In print form, it might look like
_ _ _ _ _ X _ _ _ _

_ _ X _ _ X _ _ _ _

I can't figure out how to get this to loop correctly. Any help would be appreciated!

A: Do:
  int begin = 0;
  int end = array_size
  int middle = (end + begin) / 2;

  while( ... )
  {
  // do something
     middle = middle / 2; // break in half
  }

...
The code above iterate over the first half, to iterate over the second half you just have to modify the begin variable, to:
int being = array_size / 2;

corresponding to the middle of the array.

A: A little bit vague as to what you are wanting. But this might get you closer.
public class homework
{
  public static void main(String args[])
  {
    new homework();
  }

  public homework()
  {
    boolean[] stalls = new boolean[50];

    int middle = stalls.length/2;

    for (int i = 0; i < stalls.length; i++)
    {
      stalls[middle] = true;
      middle /= 2;
    }

    for (int i = 0; i < stalls.length; i++)
    {
      if (stalls[i] == true)
      {
        System.out.print("X");
      }
      else
      {
        System.out.print("_");
      }

      System.out.print(" ");
    }

    System.out.println("");
  }
}


text:
Q: using dictionary to find min temperature among cities I am trying to make a program that finds the minimum temperature based on the data given.
This is program I have so far, but it gives random results - sometimes max, sometimes min. Could someone please help me fix it.
d = {}

for i in range(5):
    user = input("Enter city followed by temperature > ")
    if(user!='stop'):
        data = user.split()
        d[data[0]]=int(data[1])
    else:
        break

alist=[]

for k,v in d.items():
    alist.append((v,k))
    alist.sort()
    t=alist[0]
    print("The coldest city is:",t[1],t[0])
    print(d)
    break

A: I think your problem is that after you get the data into the dictionary structure, you are appending this as tuples into a list and trying to sort the tuples. It's much easier to just sort the dictionary by value. Try this.
d = {}
for i in range(5):
    user = input("Enter city followed by temperature > ")
    if(user!='stop'):
        data = user.split()
        d[data[0]]=int(data[1])
    else:
        break
#Get an ordered list of tuples sorted by the temp
d_sorted = sorted(d.items(), key=lambda x: x[1])
coldest = d_sorted[0]
print("The coldest city is:",coldest[0],coldest[1])

A: Items in a dictionary are unordered. Their order may change from run to run. But your code (starting with for k,v in d.items():) takes the first value returned by d.items(), adds it to a list, sorts the single-itemed list, get the first and only value from the list, prints it and breaks the loop.
You could use min() function instead, to find the coldest city:
coldest_city = min(d, key=d.get) # find minimum in a dictionary by value
print("The coldest city is:", coldest_city, d[coldest_city])

You could use a simple for-loop, to find a key that corresponds to a minimal value in a dictionary if you can't use min() function:
it = iter(d.items()) # get an iterator over (key, value) pairs of the dictionary
minkey, minvalue = next(it) # assume dictionary is not empty
for key, value in it:
    if minvalue > value:
       minkey, minvalue = key, value
print("The coldest city is:", minkey, minvalue)

If the lowest temperature occurs in more than one city then any of them may be chosen as the coldest city.


text:
Q: Crop the object area in an mage How to crop the object in the image by black pixel or white pixel area. I want the idea or any code for this. Bounding box is in Matlab. But here we are not have the bounding box options.

x = Import["/home/karthi/Desktop/Length/5.jpg"];
adj = Sharpen[x];
MorphologicalBinarize[x1];

I only tried this. Just I need to detect the black pixel area as bounding box

A: i = Import["http://i.stack.imgur.com/AsutA.jpg"];
tvf = TotalVariationFilter[i, Method -> "Laplacian"];
ImagePad[i, -BorderDimensions[
         Dilation[DeleteSmallComponents[EdgeDetect[tvf, .9]], 5]]]


text:
Q: Failing in adding reference to SOAP Service in C# console application I'm trying to add reference to the service located on 'http://xt-adapt-ar.just.ee:81/ariport/?wsdl'.
But getting following error and I have no idea what to do. Usually adding a reference is quite straight forward, so I'm confused.
Following message is provided by VS 2012:

The document was understood, but it could not be processed.

*

*The WSDL document contains links that could not be resolved.

*The 'documentation' element is not supported in this context.

  Metadata contains a reference that cannot be resolved:
  'http://xt-adapt-ar.just.ee:81/ariport/?wsdl'. The content type
  text/xml; charset="UTF-8" of the response message does not match the
  content type of the binding (application/soap+xml; charset=utf-8).
If using a custom encoder, be sure that the IsContentTypeSupported
  method is implemented properly.  The first 1024 bytes of the response
  were:  '...'.
If the service is defined in the current solution, try building the
  solution and adding the service reference again.

All the ideas are useful so don't hesitate to share your knowledge or experience with similar issues!
P.S Project I'm building is Console Application also .NET framework is 4.0
Case closed.
Problem was with XSD files refered from WSDL. VisualStudi tool for adding service reference was not able to access all the XSD files. But it's ok because they don't have to response for GET request.

So the workaround would be:

*

*Download WSDL and all the XSD refered from WSDL

*change URLs of XSD's in WSDL (schemaLocation urls)

*also removing tags "documentation" from XSD's was required

Thanks for your help!


text:
Q: Spreadsheet_Excel_Writer get file content I need to attach an XLS-file to e-mail via PHP.
The Problem is - Spreadsheet_Excel_Writer send a HTTP Header to a browser an then the content. Spreadsheet_Excel_Writer API has no any functions like get_content to become the file content directly. I don't want to save the file first, I just want to jump this step over, saving the content directly as attachment.
Any ideas?
Thx a lot.

A: There isn't a "write to file" method in Spreadsheet_Excel_Writer. At most you can send it directly to the client with the ->send() method. This means you COULD capture the output with PHP's output buffering, and grab the data as a string, which can then be inserted into an email (e.g. via PHPMailer's ->AddStringAttachment()).
You may want to investigate switching to PHPExcel, since Spreadsheet_Excel_Writer is essentially dead in the water, minus a few minor bug fixes. PHPExcel supports Excel 2007, while S_E_W is stuck at Excel 5.0 (early 90's). It also has a ->save() method to write to file.

A:
require_once 'Spreadsheet/Excel/Writer.php';

ob_start();

$workbook = new Spreadsheet_Excel_Writer();
$workbook->setVersion(8, 'utf-8');
$worksheet =& $workbook->addWorksheet('sheet 1');
$worksheet->setInputEncoding('utf-8');

$worksheet->write(0, 0, 'test');
$worksheet->write(1, 0, 'test2');

$workbook->close();

$sXls = ob_get_contents();

ob_end_clean();

A: Albeit the OP doesn't want to save the file first, I was looking for a means to output inline as opposed to attachment using the ::send method.
The PEAR Spreadsheet_Excel_Writer 0.1 to 0.9.4 constructor supports a $filename argument. [sic 0.1]
 and [sic 0.9.4]
When supplied, calling the Spreadsheet_Excel_Writer::close method on the instantiated object, will output the generated spreadsheet to the specified path.
$workbook = new Spreadsheet_Excel_Writer('/path/to/output/file.xls');
//...
$workbook->close();

$data = file_get_contents('/path/to/output/file.xls');
//or file_get_contents($workbook->_filename);
unlink('/path/to/output/file.xls');


text:
Q: Making all lines in a paragraph the same width regardless character count I am making a GUI for a clients website. Its a T Shirt website where they want a really simple designer with limited options.
This is fine, however one of the options they have requested is to easily make all lines the same width. This results in larger font for some lines.
The provided text is in one text field, I then use:
word-wrap: break-word;

to break that line to fill the container.
This would end up as the example on the right, instead of the left.

Would this be possible with CSS prefered but JS can be used too.

A: If you don't mind breaking each line into it's own container (span or any other...) you can do it with javascript. The key is font-size CSS attribute.
You need to calculate the widest line (use offsetWidth to get each line's width), then calculate for each line how much spare width it leaves, divide that by the length of text in the line multiply by your base font size and set the attribute.
Here's a working fiddle.

A: The BigText jQuery plugin is capable of doing exactly what you wish to do.

$('#bigtext').bigtext();
#bigtext{
  width:300px;
}

  SOME
  TOTALLY
  HIPSTER
  QUOTE
  ABOUT
  LIFE

A: You can increase the font size until the text gets wider than the parent. Have a look at this recursive function (using jQuery):
function findLargestFontSize($line){
    var oldSize = parseInt($line.css('font-size'));
    //set new size
    $line.css('font-size', oldSize + 1 + 'px');
    // check if hit the edges
    if( $line.width() > $line.parent().width() ){
        $line.css('font-size', oldSize + 'px');
        return(oldSize);
    } else {
        findLargestFontSize($line);
    }
}

And a fiddle with an example.

EDIT
I found Amit's answer to be a lot more elegant than this, so I merged with my solution. Here is another fiddle
var $target = $('#target');
var words = $target.text().split(' ');

// split words into lines
$target.empty();
for(var i = 0; i < words.length; i++){
    var $newLine = $('' + words[i] + '');
    $target.append($newLine);
    if($newLine.width() < $target.width()) {
        $newLine.css('font-size', parseInt( $newLine.css('font-size'))  * ( $target.width() / $newLine.width()) + 'px');
    }
};


text:
Q: Why does Django's HTTPResponseRedirect use the same HTTP method for PUT but not POST? I have a Django project where I'm using a view to handle different HTTP methods. The POST handled the creation of an object and then redirected to the same view as a GET (or so I thought), using Django's redirect() shortcut (HTTPResponseRedirect) to return the newly created object. This worked fine. I tried the same thing with a PUT but I fell into a redirect loop. After scratching my head for a while I stumbled across this SO answer and then I inferred that since redirect doesn't handle the POST data, the request turns into a GET.
I confirmed this by watching the logs when I do the redirect from a POST:
[15/Dec/2014 00:47:43] "POST /client/151/ HTTP/1.1" 302 0
[15/Dec/2014 00:47:43] "GET /client/151/ HTTP/1.1" 200 395

However the PUT stays a PUT and throws me into a redirect loop until it errors out.
[14/Dec/2014 23:07:36] "PUT /api/asset/6779 HTTP/1.1" 301 0
[14/Dec/2014 23:07:37] "PUT /api/asset/6779/ HTTP/1.1" 302 0
[14/Dec/2014 23:07:37] "PUT /api/asset/6779 HTTP/1.1" 301 0
[14/Dec/2014 23:07:38] "PUT /api/asset/6779/ HTTP/1.1" 302 0
[14/Dec/2014 23:07:38] "PUT /api/asset/6779 HTTP/1.1" 301 0
[14/Dec/2014 23:07:39] "PUT /api/asset/6779/ HTTP/1.1" 302 0
[14/Dec/2014 23:07:39] "PUT /api/asset/6779 HTTP/1.1" 301 0
[14/Dec/2014 23:07:40] "PUT /api/asset/6779/ HTTP/1.1" 302 0
[14/Dec/2014 23:07:40] "PUT /api/asset/6779 HTTP/1.1" 301 0
[14/Dec/2014 23:07:41] "PUT /api/asset/6779/ HTTP/1.1" 302 0
[14/Dec/2014 23:07:41] "PUT /api/asset/6779 HTTP/1.1" 301 0
[14/Dec/2014 23:07:42] "PUT /api/asset/6779/ HTTP/1.1" 302 0

Shouldn't the redirect use GET? I understand what's going on but not sure why? What gives?
EDIT
# urls.py
url(r'^$', views.put_vs_post_redirect),

# views.py
from django.shortcuts import redirect

def put_vs_post_redirect(request, asset_id):

    if request.method == 'GET':
        return HTTPResponse('Get request')
    elif request.method == 'POST':
        return redirect('/')
    elif request.method == 'PUT':
        return redirect('/')

A: As mentioned in the comments, this is entirely dependent on the client, and not all clients handle redirects in the same way. You can find a decent explanation of the redirect codes and why a 301 should drop POST data on Stack Overflow.
When working with a 301 (and often a 302) redirect, most browsers will discard POST data and make a GET request. This is mostly because browsers have always done this, and POST requests most commonly come from web forms, so it makes sense that the redirect results in a GET, allowing for the browser to display a different page without interfering. This is not the case for things like PUT or PATCH requests, as they cannot currently be sent by web forms and typically play by different rules.
If you are looking to maintain the POST data on a 302 redirect, you should consider using a 307 redirect instead. A 307 request should maintain the request method, and the request body as a result.
If you are looking to maintain the POST data in a 301 redirect, there is currently a draft for a 308 status code that would work like the 307, but be permanent.
You can force the redirect to use a GET request with a 303 redirect. It works very much like a 302, but it enforces that the request method is always a GET request. It's often used in APIs for asynchronous tasks.


text:
Q: Why is my channel undefined? I'm working on a Discord bot that will take complaints via DMs and post them in a chat room to be seen by moderators.  For some reason, the type is considered undefined.  The exact error text is this:
TypeError: Cannot read property '44640...' of undefined

The error comes from this line:
if (bot.channel[channelID].type == 1)

If the channel ID itself is considered undefined, then I believe this means the channel itself is not defined.
Here is the full code of the function:
bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `s!`
if (message.substring(0, 2) == 's!') {
    var args = message.substring(2).split(' ');
    var cmd = args[0];

    args = args.splice(2);
    switch(cmd) {
        // s!ping
        case 'ping':
            bot.sendMessage({
                to: channelID,
                message: 'Pong!'
            });
        break;

        case 'problem':
        if (bot.channel[channelID].type == 1)
        {
            var embed = new Discord.RichEmbed()
            .setAuthor(message.author.username, message.author.avatarURL)
            .setDescription(message.content)
            .setTimestamp(new Date())
            .setColor('#C735D4');
            //stores the sent message, along with the sender and the time of the message

            client.channels.get(446393832066514947).send(embed);
            //sends message to channel
        }
        // Just add any case commands if you want to..
     }
 }
});

A: If that is your entire code, I am assuming this.channel is never set anywhere, which means it will be undefined when you try to access it.
Your Client object holds a collection of Channel objects, with the channel ID as the key.
So in your snippet you should be able to say
bot.channels[channelID].type


text:
Q: Render an asp.net control from a text string I'm not sure if it is possible to render an asp.net control from a string. The string contains fragments of html code and I've tried rendering that string to a div tag setting  the following attributes: runat="server", asp panel contain, asp label control and asp literal control.
These attributes do not render the control in that text to an actual control. The result remains as a string.
I've also tried adding <% %> around the attributes but this is not accepted.
Thanks in advance.

A: You may need to instantiate your control in the code behind (e.g. new Label()) and then add that control to a placeholder control that you put on your page.

A: Literal and Label do this job. Please specify some code for more understanding.
Also you may look to http://msdn.microsoft.com/en-us/library/f93yf0ee(VS.80).aspx


text:
Q: SEDE should pick up on changes to community metadata It appears that site meta data isn't updated in SEDE. As an example, Moderators.SE was renamed to Community Building in December 2014. It is still listed in SEDE as Moderators.SE, as of July 2015.
To search for Community Building data, we need to search the "Moderators" community:

It is not listed as Community Building:


text:
Q: Unable to delete single message from inbox (Android version 4.1.2) I want to delete single message from inbox with their specific id. I picked individual message id from listview which consist of HashMap arraylist correctly now i want to delete message by this id. but i cant succeeded yet.
Delete function:
// delete inbox sms
    public boolean deleteInboxSms(String id, Context context) {
        context.getContentResolver().delete(Uri.parse("content://sms/inbox"), "_id = ?", new String[]{id});
        return true;
    }

kindly tell me is this correct uri statment or not?
Permisssions:
<uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />

A: Correct Syntax
 context.getContentResolver().delete(Uri.parse("content://sms/"+id),null, null);


text:
Q: Facebook SDK for .NET Login Button, logout code I've used the Login Button Control in the Facebook SDK for .NET in an app and I need to change the Status/state of the login button control from "Logout" to "Login" i.e., I need to logout the user manually through code.
How would that be possible??

A: Use FacebookClient.Logout to generate the logout url.
This is just a sample.
private void btnLogout_Click(object sender, EventArgs e)
{
    var fb = new FacebookClient();

    var logoutUrl = fb.GetLogoutUrl(new
                                        {
                                            next =    "https://www.facebook.com/connect/login_success.html",
                                            access_token = _accessToken
                                        });
    var webBrowser = new WebBrowser();
    webBrowser.Navigated += (o, args) =>
                                {
                                    if (args.Url.AbsoluteUri == "https://www.facebook.com/connect/login_success.html")
                                        Close();
                                };

    webBrowser.Navigate(logoutUrl.AbsoluteUri);
}

Make sure to persist the access token somewhere when you login so that you can use it to the logout too.

A: The user is not asked for his credentials because the Facebook authentication cookie is still present in the WebBrowser control.
So to completely logout the user from Facebook, you need to clear the WebBrowser cookies.
Unfortunately, there is no easy way for erasing cookies on Windows Phone 7.
On Windows Phone 8 you just need to call ClearCookiesAsync  Method
await new WebBrowser().ClearCookiesAsync();

Here is a tutorial that makes use of it:
Integrate Facebook to Your Windows Phone Application

A: I've spent many hours trawling to get this.  Many thanks Kulasangar
I modified your code slightly but it works:
var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
var accessToken = identity.FindFirstValue("FacebookAccessToken");
var fb = new FacebookClient(accessToken);

var logoutUrl = fb.GetLogoutUrl(new
                {
                    next = "https://www.facebook.com/connect/login_success.html",
                    access_token = accessToken
                });
Response.Redirect(logoutUrl.AbsoluteUri);