INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
[sender.date descriptionWithLocale:[NSLocale currentLocale]] gives different result?
in Simulator :
"Sunday, July 20, 2014 at 7:00:42 PM Singapore Standard Time"
in Actual device:
"Sunday, 20 July, 2014 7:16:44 pm Singapore Standard Time"
Why???? | The Simulator uses your Mac's locale, which may be different to the one on your device. In particular, Mac OS X allows much greater customisation of your locale in the Language & Region system preference pane.
Even if they're both set to the same thing, it's not guaranteed the output will be the same. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, iphone, ios simulator"
} |
Память под контейнеры выделяется в стеки или куче?
как выделяется память под контейнеры vector, map в с++ | Под элементы контейнера - в куче.1 2
Под сам контейнер - так же, как для любого другого объекта, это зависит от того, как он создан:
* `new std::vector<int>` \- в куче
* `void foo() {std::vector<int> vec;}` \- в стеке
* ...
* * *
1 По умолчанию. Написав свой аллокатор, элементы можно поместить куда угодно.
2 Большинство реализаций `std::string` не выделяют буфер в куче, если в них немного элементов (не больше пары десятков). В таком случае символы хранятся в самом объекте контейнера. Насколько я знаю, другие стандартные контейнеры так не делают. | stackexchange-ru_stackoverflow | {
"answer_score": 10,
"question_score": 2,
"tags": "c++"
} |
Pegar valor de uma li angularjs ionic
<div class="list">
<li class="item" ng-click="city()" ng-repeat="seg in segmento">{{seg}}</li>
</div>
Eu tenho este codigo no meu framework ionic eu gostaria de pegar o valor da li eu ja tentei com name, ng-model alguem tem alguma sugestão? | <div class="list">
<li class="item" ng-click="city(seg)" ng-repeat="seg in segmento">{{seg}}</li>
</div>
O `seg` é o elemento selecionado, você pode passar por parâmetro. | stackexchange-pt_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angularjs, ionic"
} |
Is there an explicit relationship between the eigenvalues of a matrix and its derivative?
If we consider a matrix $A$ dependent of a variable $x$, the eigenvalues and eigenvectors satisfying the equation $$ A \vec{v}=\lambda \vec{v} $$
will also depend on $x$. If we consider the matrix $B$ such that $$B_{ij}=\frac{ \mathrm{d}}{ \mathrm{d} x} A_{ij}$$ Then, could we express the eigenvalues of $B$ in terms of the eigenvalues of $A$? I found the question very interesting and was not able to find a satisfying answer myself.
For example in the case for $2\times2$ matrices of the form $$ A=\left ( \begin{matrix} a(x) & b(x) \\\ 0 & c(x) \end{matrix} \right ),\implies B=\left ( \begin{matrix} a'(x) & b'(x) \\\ 0 & c'(x) \end{matrix} \right ) $$ I noticed that $\lambda_B(x)= \lambda_A'(x)$. But I cannot generalise it to general $2\times 2$ matrices. Not even thinking about $n\times n$ matrices...
Thank you for your help and any idea! | **It is not true in general that the eigenvalues of $B(x)$ are the derivatives of those of $A(x)$.** And this even for some square matrices of dimension $2 \times 2$.
Consider the matrix
$$A(x) = \begin{pmatrix} 1& -x^2\\\ -x &1 \end{pmatrix}$$ It’s characteristic polynomial is $\chi_{A(x)}(t)=t^2-2t+1-x^3$, which has for roots $1\pm x ^{3/2}$ for $x>0$. Those are the eigenvalues of $A(x)$.
The derivative of $A(x)$ is $$B(x) = \begin{pmatrix} 0& -2x\\\ -1 &0 \end{pmatrix}$$ and it’s characteristic polynomial is $\chi_{B(x)}(t)=t^2-2x$, whose roots are $\pm \sqrt{2} x^{1/2}$for $x>0$.
**We get a counterexample as the derivative of $1+x^{3/2}$ is not $\sqrt{2}x^{1/2}$.**
However in the special case of upper triangular matrices (that you consider in your original question) the eigenvalues of the matrix derivative are indeed the derivatives of the eigenvalues. | stackexchange-math | {
"answer_score": 4,
"question_score": 12,
"tags": "linear algebra, matrices, derivatives, eigenvalues eigenvectors"
} |
Aframe changing sky every interval
I try that my aframe-sky-component changes his image every 3sec but it´s not working. Here what i coded so far:
<script type = "text/javascript">
function startTimer(){
setInterval(function(){ nextimage(); }, 3000);
function nextimage() {
var zahl = 0;
if (zahl == 0) {
$("#skyid").attr("src","#sky_2");
zahl ++;
}
if (zahl == 1) {
$("#skyid").attr("src","#sky_3");
zahl ++;
}
if (zahl == 2) {
$("#skyid").attr("src","#sky_4");
zahl ++;
}
if (zahl == 3) {
$("#skyid").attr("src","#sky_1");
zahl ++;
}
if (zahl == 4) {
zahl == 0;
}
}
}
</script>
I guess i have some logic mistakes thx for helping :D | Each time you call `nextImage` the `zahl` is set to 0.
You can just move it to the outer scope:
function startTimer(){
setInterval(function(){ nextimage(); }, 3000);
var zahl = 0;
function nextimage() {
....
like I did here. Now its not zeroed by calling `nextImage()` so it acts like a counter.
* * *
Also i think a bit more elegant solution is having a color array:
var colors = ["blue", "red", "green", "yellow"]
function nextimage() {
$("#skyid").attr("color", colors[zahl])
zahl = (zahl < colors.length - 1) ? ++zahl : 0
//zahl is incremented until its reached the end of the array
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, timer, intervals, aframe, sky"
} |
How to get comment count from your wall posts without making a call to comments object for each post?
July 10 breaking changes introduces;
> **Removing 'count' from 'comments' Graph API connection** *We are removing the undocumented 'count' field on the 'comments' connection in the Graph API. Please request '{id}/comments?summary=true' explicitly if you would like the summary field which contains the count (now called 'total_count')*
If I pull up me/feed, sure enough, count is no longer in the comments object. But how do I get the comment count without resorting to making a graph API call to the comments object on every post?
I'm not very good with field expansion, but is there a way to get the feed to include the summary? | It is not documented anywhere, even subfields or limits, I've found this asking in developers forum. this call pull PageID/posts with custom format. In my case here is how to pull Likes count, shares count and comments count in one call.
PageID/posts?fields=comments.limit(1).summary(true),likes.limit(1).summary(true),shares
I'm not really sure if you have to mark agreed the October api changes in order to get your custom format.
hope this work for you... | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 3,
"tags": "facebook, facebook graph api"
} |
Query only returning 100 records at a time?
I am trying to export data from a database to a csv file, I am using the code below to retrieve the data from the DB, but it only returns 100 rows, how can I fix that?
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'educators';
$query = craft()->elements->buildElementsQuery($criteria);
$query->order('title asc');
$queryResults = $query->queryAll();
$educators = EntryModel::populateModels($queryResults);
foreach ($educators as $educator) {
//Write to file
} | Craft imposes a default limit of 100 for element queries. To disable this you need to specify a limit of `null`.
$criteria->limit = null; | stackexchange-craftcms | {
"answer_score": 10,
"question_score": 4,
"tags": "database, queries"
} |
now keyword in Solidity
I was unable to find any relevant documentation for the `now` keyword within the Solidity documentation, other than its usage in examples. What exactly does the `now` keyword return, how is it determined and what are the associated gas costs? I assume it is similar to Unix time. | In short `now` is just an alias for `block.timestamp` and it is the number of seconds since the Epoch as per documentation.
Beware that this value is set by miners so there is a little potential for a malicious manipulation but general nodes are meant to coordinate. | stackexchange-ethereum | {
"answer_score": 19,
"question_score": 15,
"tags": "solidity"
} |
Feynman's random walk: How does he get $⟨D^2_N⟩=N$?
In Feynman's lectures, section 6.3, I follow most of his argument about a random walk, but I miss one step. To summarize, he's discussing a one-dimensional random walk (eg, determined by coin flips), and his notation is
$N$: steps taken
$D_N$: net distance from start at step $N$ for a given trial
$D^2_N$: expected value for $D_N$ (mean square distance)
I follow him as he shows
$D^2_1=1$, and
$D^2_N=D^2_{N−1}+1$.
Then he says it follows that
$D^2_N=N$.
I suppose this last step should be easy, but it's the one I don't follow! I'd appreciate any help. TIA. | Well, $<D_2^2>=<D_1^2> +1 = 2$ and $<D_3^2>=<D_2^2> +1=3$. I'm guessing you probably follow the pattern now. | stackexchange-physics | {
"answer_score": 0,
"question_score": 1,
"tags": "homework and exercises, randomness"
} |
vscode debugger step in, step out
I'm writing a custom vscode debugger and have modified the mock debug example debugger project for my needs, and have so far got break points, continue and step over working. For continue and step over I was able to modify the protected continueRequest and protected nextRequest functions, which trigger when the respective buttons (during a debug session) are pushed. I can't seem to find any functions relating to "step in" and "step out", both default buttons shown during debugging. Also, is it possible to disable these buttons if my debugger does not support them? | 'mock debug' is just an educational debug adapter and I did not implemented `stepInRequest` and `stepOutRequest` because they would not add any new insights over the `nextRequest`.
If you want to implement them, just override the `stepInRequest` and `stepOutRequest` methods of the base class `DebugSession` (that means add the `stepInRequest` and `stepOutRequest` methods to your DebugSession subclass by copying them from the base class <
It is not possible to disable the 'step in' and 'step out' buttons but if you deem this functionality as important please file a feature request. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "debugging, visual studio code"
} |
Why my bot isn't pinging the user when mentioned in v13?
I'm sending a message and it shows up in the channel, but I don't get the red ping notification even though I'm being mentioned. This is my code
await message.guild["channels"].cache
.get(<SOME_ID>)
.send({
allowedMentions: { repliedUser: true },
content: `Welcome <@${message.author.id}> this is your channel`
});
Why wouldn't I get notified? | Just had to add `allowedMentions: { users: [message.author.id]}`
The final code would be:
await message.guild["channels"].cache
.get(<SOME_ID>)
.send({
allowedMentions: { users: [message.author.id], repliedUser: true },
content: `Welcome <@${message.author.id}> this is your channel`
});
This pings the given user. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, discord, discord.js"
} |
Exchange/Powershell - Loop array data and add result in new column and correct order
I'm attempting to add data through a loop to a new third column in an array but I'm out of luck.
I'm locating the data that I need
$DL = Get-DistributionGroup -Identity "*" | Select Name,Manag*
1. Name
2. ManagedBy
I attempt to loop through it, successfully, but I have no idea on how to add a new field here and then input it in the correct position...
$DL.Name | ForEach-Object {$DL.Members += Get-DistributionGroupMember -Identity $_ | Select Name}
1. Name
2. ManagedBy
3. Members | I'm not familiar with Exchange cmdlets, but I think you could use a calculated property for this:
$DL = Get-DistributionGroup -Identity '*' | Select-Object Name, Manag*, @{
Name = 'Members'
Expression = {Get-DistributionGroupMember -Identity $_ | Select-Object Name}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "arrays, loops, powershell, exchange server"
} |
PHP - Convert fixed number into decimal, using last 2 digits as the decimal places
I have a situation where all records in a CSV I'm parsing are currency, but the values are not separated by a decimal point. So for instance, value '1234' is actually '12.34', and '12345' is '123.45'.
I'm struggling to find a way to manually convert these values into decimals. I can't user number_format, because it will give me an output like so:
$original_num = 1234;
$formatted_num = number_format($original_num, '2', '.', '');
$formatted_num = 1234.00; //Output
The other issue is that sometimes I may have a value like '436257.5' after I combine two numbers, which is actually '436.2575' so I can't just manually push in a '.' two places from the end of the string. Should I consider formatting it differently while I'm parsing the file? | Assuming you're using integers to always represent decimals with 2 places of precision after the decimal point, you just divide with 100 to insert the dot in the right place.
What do you mean, "combine"? You mean multiply? You should renormalise after each multiplication, and never get into a situation where you're representing decimals of differing precisions (unless you keep track of the precision, which you can do but it's pain in the ass and normally unnecessary).
function multiply($a, $b) {
return round($a * $b / 100);
}
function format($a) {
return sprintf("%.2f", $a / 100);
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "php"
} |
simplification of 唻?
****
> ****
>
> :lai4
>
>
>
> ****
>
>
Does not have a simplificated version?
**ZiSea** :
!zisea
**** :
!zihai
As this ^ (above) just seems to be listed as a _variant_ | This is a simplified word, and it is a rare used word. Most people will recognize it only as (doreme), but now it's replaced mostly by or even . And the word , though it is said to be simplified version of in fact this may not be realy a word, it's never used, even can't be inputed by most Chinese IMEs. | stackexchange-chinese | {
"answer_score": 4,
"question_score": 3,
"tags": "traditional vs simplified"
} |
Passing Parameters to New Sub of a User Control
In ASP.Net, is it possible to pass parameters to the "New" constructor of a User Control class? In VB.Net:
Public Sub New(ByVal pRequiredParam As String)
'Do something with required Param
End Sub
When I use this user control in a generic ASP.Net page, it doesn't prompt me for "pRequiredParam". Of course, if this was a "normal" class, I would have to supply "pRequiredParam" when I instantiate the object. Is this not possible with a User Control? | While you can certainly create a custom constructor like the one you show in your code sample, you cannot force the designer to make use of it. How would it determine what to send as argument to the constructor?
However, you can load the control dynamically in your code-behind file, and then use whatever parameters it defines. Note though that if you want the control to also work well with the graphical designer, I think that the control need to have a public constructor that takes no parameters (but I think you get that automatically in VB.NET?) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, user controls, constructor, parameters"
} |
displaying values from mysqli with php
Here is my code:
<
On line 33 it has:
echo $value;
How can I have it that I can use it like below:
echo $value['module_name'];
echo $value['module_name_id'];
echo $value['module_image'];
Hope someone can help.
Thanks | During your final result fetch on line 13:
// Retrieve results
while ($row = $result->fetch_assoc()) {
// Add to final array via counter if valid course is found
if (in_array($row['course_name'], $courses)) {
$final[$row['course_name']][] = $row['module_name'];
}
}
Rather than storing just the column value of `$row['module_name']`, store the entire row to access it later:
$final[$row['course_name']][] = $row;
Then when you "loop through the internal values" on line 32 you can access any column you want using:
echo $value['module_name'];
echo $value['module_name_id'];
echo $value['module_image']; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, mysqli"
} |
Как произвольно разбить <ul> на columns?
Всем привет! Обычным способом можно разбить "ul" на columns, прописав в стилях списка "columns: 3". Он сделает 3 колонки, по 2 "li" в каждой. В моем случае нужно сделать это с определенных мест, чтобы выглядело это, как в прикрепленном изображении. Или же как то указать количество "li" в каждой из колонок. Прошу вашей помощи, друзья!
<ul>
<li class="list-item-1">List Item 1</li>
<li class="list-item-2">List Item 2</li>
<li class="list-item-3">List Item 3</li>
<li class="list-item-4">List Item 4</li>
<li class="list-item-5">List Item 5</li>
<li class="list-item-6">List Item 6</li>
</ul>
,
li:nth-child(6) {
-webkit-column-break-before: always;
}
<ul>
<li class="list-item-1">List Item 1</li>
<li class="list-item-2">List Item 2</li>
<li class="list-item-3">List Item 3</li>
<li class="list-item-4">List Item 4</li>
<li class="list-item-5">List Item 5</li>
<li class="list-item-6">List Item 6</li>
</ul>
Всё. | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "javascript, html, css, jquery"
} |
Alternating second power Euler sum $\sum_{k\geq 1} \frac{(H'_k)^2}{k^2}$
Question:
Evaluate
$$\sum_{k\geq 1} \frac{(H'_k)^2}{k^2}$$
Where we define the alternating harmonic number
$$H'_k=\sum_{n=1}^k\frac{(-1)^n}{n}$$
I remember seeing a closed form involving a quadrilogarithm.
I am interested in knowing the full solution, if possible. | Numerically, this is $$ -\frac{13}{8}\zeta(4)+\frac5{2}\zeta(2)\log^22+\frac1{12}\log^42+2\mathrm{Li}_4({\textstyle\frac12}), $$ from "Experimental Evaluation of Euler Sums" by Bailey, Borwein and Girgensohn.
This can be found with an integer relation algorithm applied to the sum evaluated to high precision using this integral: $$ \int_0^1\frac{\log(\frac1z)dz}{z(1-z)}\left(-\zeta(2)+\log^22+2\log(1-z)\log\left(\frac{1+z}{2}\right)+2\mathrm{Li}_2\left(\frac{1-z}{2}\right)+\mathrm{Li}_2(z)\right). $$ | stackexchange-math | {
"answer_score": 2,
"question_score": 6,
"tags": "sequences and series, special functions, polylogarithm"
} |
AppConKit3: My changes in the Java Server files get overriden
I'm playing with the AppConKit, and have created a small App so far with a couple of screens. Now I am trying to change the automatically generate Java code. However, any changes I make in the automatically Action classes (for example LoadDetailAction.java) get overwritten every time I change something in the UI. Any idea how to remedy this? | At the top of each generated class, there is a JavaDoc comment which looks like this:
/**
* @generated
*/
public class LoadDataAction {
Just remove the @generated from the JavaDoc comment and the class won't be overwritten anymore. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "java, appconkit"
} |
Roots of $Y^3 - Y + 1$ in $\mathbb{F}_3[Y]/(Y^3- Y^2 +1)$
I just solved this problem and didn't find it to be a problem at all, that why I think I overlooked something, but I can't think of anything.
I just argued that $Y^3 \equiv Y^2 - 1 \quad (\textrm{mod} \quad (Y^3- Y^2 +1))$.
So $Y^3 - Y + 1 \equiv Y^2 - Y = Y(Y-1)$ and I find the roots to be $0$ and $1$ in $\mathbb{F}_3[Y]/(Y^3- Y^2 +1)$.
Is this correct? | $\def\ff{\mathbb{F}}$Firstly, is $Y^3 - Y^2 + 1$ irreducible in $\ff_3[Y]$? If so, then you have a field extension of $\ff_3$, and let $r$ be a root of the polynomial in the field extension.
Secondly, what is the degree of the field extension, and what do you know about finite fields? All finite fields of the same characteristic and size are isomorphic (because the algebraic closure has a unique field of that size since $x^{3^3-1} = 1$ for nonzero $x$ in any such field by Lagrange's theorem).
So we expect to find all irreducible cubics' roots in any given degree 3 extension. Notice that $(x+1)^3 - (x+1) + 1 = x^3 - x + 1$ for any $x$ in the field extension, so you already know how to find all 3 roots if you have any one. $0$ is not a root, contrary to your claim, so immediately $1,2$ are not either. So you only have to try $ar^2+br$ for all possible $a,b \in [0..2]$, using the fact that $r^3 = r^2 - 1$. There could be further tricks but this works. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "ring theory"
} |
How to create a script for Exchange Powershell to modify settings for all shared mailboxes?
Following this guide: <
I must issue these commands in Exchange Powershell (Exchange Management Console):
set-mailbox <mailbox name> -MessageCopyForSentAsEnabled $True
set-mailbox <mailbox name> -MessageCopyForSendOnBehalfEnabled $True
However, I have _a lot_ of shared mailboxes. I want don't want to have to issue this command 100 times. Is there a variable and/or script I can use for `<mailbox name>` which will let me automate this process for all _shared_ mailboxes? (It's very important that I apply this to **_only_** _shared_ mailboxes, and not just all mailboxes) | To get all the shared mailboxes in your environment, use:
Get-Mailbox -RecipientTypeDetails SharedMailbox
Running those commands against the results from this command should be trivial. | stackexchange-serverfault | {
"answer_score": 2,
"question_score": 1,
"tags": "exchange, powershell, scripting, exchange 2013"
} |
XAML GridView in GridView with different orientation
(Title edited)
How to do this with XAML? Horizontal Width is fixed and must be scrollable.
Maybe GridView or another control like ItemsControl or StackPanel.
!enter image description here | Simple working example: Linking only vertical offset of two scrollviewers
And I found advanced example in 5th sample of the "XAML input and manipulations - advanced concepts": < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "xaml, windows runtime, windows store apps"
} |
Highchart: Plot negative values on negative Y Axis ans set initial value
I am trying plot area graph with multiple series data. The data consists of negative values as well , but the Y Axis does not plot values below 0. Here is the codepen for above scenario.
I want to achieve below graph , where Y AXis plots negative values on negative Y Axis and Y Axis should have some start value {which would be first value of sample data}.
=(x,y)$ be a vector field. Plottet, it looks like this:
$ it's length describes how far it is away from the origin. Is that what the length of the arrows in the plot should indicate? | A vector field $V$ on $\mathbb R^2$ maps a point **p** to tangent vectors $V($ **p** $)$. It's not necessary that this tangent vector has greater magnitude with **p** further from the origin. Let $V:(x,y)\rightarrow(1,1)$ and you will have a constant vector field that gives you arrow of same magnitude everywhere and pointing in the same direction. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "vector fields"
} |
How to fix group by and order by year and months in sql?
I'm trying to fix the order by and group by year and month format. This is my sql query
SELECT DATE_FORMAT(created_at, "%Y %b") ym
FROM `book_summaries`
GROUP BY DATE_FORMAT(created_at, "%Y %b")
ORDER BY DATE_FORMAT(created_at, "%Y %b")
But the sql query result is this:
2018 Apr
2018 Aug
2018 Dec
2018 Feb
2018 Jul
2018 Jun
2018 Mar
2018 May
2018 Nov
2018 Oct
2018 Sep
2019 Apr
2019 Aug
2019 Dec
It seems that only the year format has been ordered but not the months in it. How can I alter my query to order by `year` and then `months`? | You can `order by` the minimum date in each range:
SELECT DATE_FORMAT(created_at, '%Y %b') ym
FROM `book_summaries`
GROUP BY DATE_FORMAT(created_at, '%Y %b')
ORDER BY MIN(created_at);
Note that I also replaced the double quotes with single quotes. Single quotes are the SQL standard for strings (although some database do support double quotes as a string delimiter). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "mysql, sql, group by, sql order by"
} |
Why does this java regular expression not work?
Why does this Pattern not match the port in my URL?
public class PatternTest {
private Pattern PORT_STRING_PATTERN = Pattern.compile(":\\d+/");
private boolean hasPort(String url) {
return PORT_STRING_PATTERN.matcher(url).matches();
}
@Test
public void testUrlHasPort() {
assertTrue("does not have port", hasPort("
}
}
If I change the pattern to `Pattern.compile("^.+:\\d+/")` it does match. Why do I need the `^.+` ? | The problem is that you're using `Matcher.matches()`, which is documented as:
> Attempts to match the entire region against the pattern.
You don't want to match the entire region - you just want to find a match _within_ the region.
I think you probably want to be calling `find()` instead:
> Attempts to find the next subsequence of the input sequence that matches the pattern.
>
> This method starts at the beginning of this matcher's region, or, if a previous invocation of the method was successful and the matcher has not since been reset, at the first character not matched by the previous match. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 1,
"tags": "java, regex"
} |
Proving invariance
Suppose we have linear operators $S, T$ over a finite-dimensional $V.$ We are also given that $ST = TS.$ How can we prove that null($T - \lambda I$) is invariant under $S$ for any lambda in the field? | Let $\xi$ be inside $null(T-\lambda I)$. Then $(T-\lambda I) S \xi = TS \xi - \lambda S \xi = ST \xi - \lambda S \xi = S [(T - \lambda I) \xi] = S 0 = 0$ and so $S \xi$ is inside $null(T-\lambda I)$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "linear algebra"
} |
enter from database on javascript function declaration
I have this sentence in my page:
<img alt="Detalles Cliente"
title="Detalles Cliente" src="../images/examinar.png"
height="16" width="16" style="cursor:pointer;"
onclick="mostrarSoloLectura('${cliente.nombre}', '${cliente.telefono}',
'${cliente.direccion}', '${cliente.comentario}')" />
And each comes from values I stored in a database, well, ${cliente.comentario} is a text value that comes from a text area and may or may not include new lines, so the problem I'm getting is that when I put it inside this function and it has a new line inside it, javascript cant run the function, so, how can I pass an enter as part of a text argument in a javascript function? should I change the new line to a diferent code from the server? how can I identify to replace, the new line from the text area?
Thanks! | If new line is your only concern the you have to change the new line `\n` as `<br/>` in the server side
comentario = comentario.replaceAll("\\\n", "<br/>");
If your text area contains single quotes or any other symbols that will break the script construction then you have to escape using apache common lang package
comentario = StringEscapeUtils.escapeEcmaScript(comentario); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jsp, el"
} |
Why isnt my WPF menuItem Icon showing?
I can see my Icon in Designer View, but when I run the program it disappears. What am i missing?
EDIT: The Icon itself is 25 by 25 pixels
]`. Similarly, `ItemsControl` (ancestor of `ListBox`) is marked with `[ContentProperty("Items")]`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "wpf, xaml"
} |
Unable to remove Search service applications from the SP Farm
I wanted to remove the existing search service applications in my SP 2013 Farm. For that I directed my juniors to delete the same from central admin, but they could not delete. The entries were still there. So, they went to Sql Server and deleted all the search service application related databases using Sql Management Studio.
Now, when they came back to central admin, manage service applications page, all the search service applications were still available . When they tried to Delete the same again, but got another kind of error.
> Sorry, something went wrong Cannot open database "Search_Service_Application_DB_a995b3c88ca94d63963387a519011088" requested by the login. The login failed. Login failed for user 'mydomain1\mmuser1'
How to resume deleting the same Search service applns from Central Admin. | Try the following steps using PowerShell to remove the search service application:
1. `Get-SPServiceApplication`
2. Identify the GUID for the search service application and take a copy of it.
3. `$SSA = Get-SPServiceApplication -identity "GUIDRetrievedAbove"`
4. `Remove-SPServiceApplication $SSA`
If that doesn't work, try the following instead:
1. `$SSA = Get-SPEnterpriseSearchServiceApplication -id "GUIDRetrievedAbove"`
2. `$SSA.Unprovision(1)`
If that doesn't work, you can replace the last line above with
$SSA.Delete() | stackexchange-sharepoint | {
"answer_score": 5,
"question_score": 1,
"tags": "2013, sharepoint enterprise, searchserviceapplication"
} |
jshint not making relations between files in chrome-extension
While working on my chrome extension, those two files are called by the manifest and there are dependencies between them. But jshint wouldn't mind.
Can I give my jshint a clue that my files are linked ?
app/scripts/background.js
line 37 col 15 'WebSocketInterface' is not defined.
app/scripts/lib/wsi.js
line 3 col 23 'WebSocketInterface' is defined but never used.
2 problems
Any better option than telling jsHint to discard this kind of errors ? | In the file that uses `WebSocketInterface` (but doesn't define it) you can use a `global` directive. The `false` means JSHint will give a warning if you attempt to assign to `WebSocketInterface` (if you need to assign to it just use `true` instead):
/*global WebSocketInterface: false */
In the file that defines it but does not use it you can use an `exported` directive:
/*exported WebSocketInterface */ | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "google chrome, jshint"
} |
BeautifulSoup: Finding other elements after locating a div
Inside a page, I have the following HTML
<div class="ProfileDesc">
<p>
<span class="Title">Name</span>
<span>Tom Ready</span>
</p>
<p>
<span class="Title">Born</span>
<span>
<bxi> 10 Jan 1960</bxi>
<p>
<span class="Title">Death</span>
<span>
<bxi> 01 Jun 2019</bxi>
</span>
</p>
</div>
The following code works for extracting the ProfileDesc from the whole page
soup = BeautifulSoup(page.content, 'html.parser')
mydivs = soup.find("div", {"class": "ProfileDesc"})
I want the following output
Name: Tom Ready
Born: 10 Jan 1960
Death: 01 Jun 2019
How do I extract these after finding the ProfileDesc? | When you're pretty sure about the DOM structure:
mydivs = soup.find("div", {"class": "ProfileDesc"})
for element in mydivs.find_all("p"):
title = element.find("span")
content = title.findNext("span")
print("%s : %s" % (title.text.strip(), content.text.strip()))
Output:
Name : Tom Ready
Born : 10 Jan 1960
Death : 01 Jun 2019 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, beautifulsoup"
} |
"Based on" instead of "based off of"
I sometimes see cases where _off_ is followed by _of_ , and it sounds awkward to me. For example, I would prefer
> This story is **based on** a true story.
to
> This story is **based off of** a true story.
What do native speakers think/prefer? Should I avoid that kind of usage? | The former is certainly preferable in UK English, formal or otherwise, whereas the latter is a style usually heard in conversational American English. | stackexchange-english | {
"answer_score": 44,
"question_score": 75,
"tags": "word choice, prepositions, off of"
} |
ASP.Net MVC Submitting Ajax Form Via JQuery
I have an Ajax form that updates a div when submitted with a submit button this works fine. However I want to remove the submit button and have the form submit automatically when a user changes a selection in a drop down list.
I wrote the following JQuery for this in the dropdown change event
$("#SummaryFilterForm").submit();
The problem with this is that is does not trigger the onSubmit event of the form causing the render partial to render to a new page and not into a div in the current window.
How can I make the JQuery submit the form and also trigger the onsubmit event?
Thanks | How do you submit the Ajax request? If you use $.Ajax you can use this:
function connectDropdown() {
$("select#drpFilter").unbind('change').change(function() {
$.ajax({
type: "POST",
url: "/YourController/YourAction",
data: {
YourParameter: someValue,
},
dataType: "json",
success: function(result) {
alert('works like a charm');
//update div here
}
});
});
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, asp.net mvc"
} |
Regex to find dates before a certain year
So i have a string that has different dates and I want to only find dates on or before 1998. The format in the string is dd-mm-yyyy. This is what I have so far
Regex test = new Regex(@".*\d\d-\d\d-(18|19)\d\d");
I just don't know how can I make it so that it only finds dates on or before 1998. | Years 1000 to 1999 can be matched with `1\d\d\d`
Years 1000 to 1998 can be matched with `(1[0-8][0-9]{2}|19[0-8][0-9]|199[0-8])`
No I can't write them out that quick I used: <
Personally, I might be tempted to do in two steps, find ones in likely range (1000-1999) then actually parse them and check the actual date, particularly if your requirements get any more complex. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "c#, regex, string"
} |
Scipy optimize curve_fit weird behavior
I want to fit an exponential curve to data points, but for some reason i get weird results from the function curve_fit from scipy. Here is my code:
from scipy.optimize import curve_fit
def f(x,lambda_):
return 100*((1 - np.exp(-lambda_*np.array(x))))
x=[18.75, 30.75]
y=[48.69, 49.11]
lambda_ = curve_fit(f, x, y)[0]
plt.scatter(x, y, color='black')
xx=np.linspace(0, 40)
yy = f(xx, lambda_)
plt.plot(xx,yy)
Resulting in this plot :
:
p0 = np.random.default_rng().uniform(-10, 10)
try:
lambda_ = curve_fit(f, x, y, p0=[p0])[0]
err = ((f(x, lambda_) - y)**2).sum()
#print(err, lambda_)
if err < err_best:
err_best = err
lambda_best_ = lambda_
p0_best = p0
except Exception:
pass | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, scipy"
} |
javascript: can not use global variable in a function, to navigate the dom
beginner here... what am i missing?
i define a global variable that is a reference to an html element:
var x=document.getElementById("xxx1");
then, inside a function a try to reference that variable to navigate the dom:
x.innerHTML="dsfgfdgdf";
...doesn't work; if i define the variable inside the function it works, but i don't see how it's a scope problem... working with global variables inside functions works fine IF i don't use them in a dom context (object.property)
thanks | It's not a scope problem.
The most likely reason is that the element doesn't exist yet when you create the variable. You have to put the script element that creates the variable after the element that you want to access, as the code will run while the page is loading.
Another alternative is to declare the variable globally, and set it from the onload event that runs after the page has loaded:
<script>
var x;
function init() {
x = document.getElementById('xxx1');
}
</script>
<body onload="init();"> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, dom, variables, scope"
} |
Woocommerce PHP - Add product image to the page
I hope this isn't to vague. Please ask if you need more info.
I am creating a custom WooCommerce product page from scratch using WooCommerce's hooks. I am trying to include the product images using this
`<?php do_action( 'woocommerce_product_thumbnails' );?>`
I've found online that it has been discontinued, does anyone know how to include product images now? Note, I am looking for the main image, not the gallery.
Thanks in advance, again, let me know if you need more info. | You can retrieve the main product thumbnail by getting the `image_id` from the product object and use it in the `wp_get_attachment_image()` function:
`wp_get_attachment_image( $product->get_image_id() )`
More information on the arguments you can pass to this function here: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "wordpress, woocommerce, hook woocommerce"
} |
Adding Microsoft.EntityFrameworkCore.Tools to a ASP.NET Core project
I am creating a new ASP.NET Core project using dotnet 4.5.2 and am trying to add a reference to Microsoft.EntityFrameworkCore.Tools. In my project.json file I have these listed under dependencies:
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
Looking under References, they appear to be successfully loaded. I then added this under tools in project.json:
"Microsoft.EntityFrameworkCore.Tools": {
"imports": [ "portable-net451+win8" ],
"version": "1.0.0-preview2-final"
}
After I added that, when I build the solution I get this build error:
Could not find a part of the path 'C:\Users\(my user name)\.nuget\packages\.tools\Microsoft.EntityFrameworkCore.Tools'
I get the same error if I remove the imports line. What am I doing wrong here? | Just ran into the same issue. I fixed the issue by installing the tools package again in the package manager console:
Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
Before reinstalling the package was actually missing in the .nuget\packages.tools folder, after reinstalling it was there.
I followed the < tutorial, but I think I installed the package in the wrong order or initially forgot to reference the EF.tools package in the "tools" section of the project json. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "asp.net core, entity framework core"
} |
If $ S \subset A^{\times}$, then $S^{-1}A \simeq\ ?$ (A question related to localization of rings)
This question was asked in my quiz of commutative algebra and I was unable to solve this particular question.
So, I am posting it here.
> If $S\subset A^{\times} $ (set of all units), then $S^{-1} A \simeq\ $?
This question is from localization of rings. I have gone through results and theorems but still I am not sure how should I approach this question.
I wasn't able to attempt or start this question as I am not sure how exactly I should approach this question.
Can you please outline a solution briefly? | Localizing at a certain set $S$ means that you force the elements in $S$ to become invertible. However, if $S\subseteq A^\times$, then we are not doing anything (as they were already invertible). This can be seen quite easily in a rigorous way. Consider the map $$ \varphi : A \rightarrow S^{-1} A, a \mapsto \frac{a}{1}.$$ This is clearly a morphism of rings, so we are left to check that it is bijective.
Let $a\in \ker (\varphi)$. Then we have that $\frac{a}{1}=0$, which implies that $a=0$ as $S$ does not contain any zerodivisors.
For surjectivity, we note that $\frac{a}{s} = \frac{s^{-1}a}{1}$, which works as $s\in S \subseteq A^\times$ (hence $s^{-1}$ is well-defined). | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "abstract algebra, commutative algebra, localization"
} |
How to check an array of $curauth fields?
How do I check an array of $curauth user data? I need to check to see if one or more $curauth fields have data, and if so, print some html. This throws an array error:
<?php if ( !empty( array ( $curauth->facebook, $curauth->linkedin, $curauth->twitter)))
{ echo 'echo me if any $curauth info exists for the fields in the array above'; } ?>
**Update - this works:**
<?php if (!empty ($curauth->facebook) || ($curauth->linkedin) || ($curauth->twitter))
{ echo 'echo me if any $curauth info exists for the fields in the array above'; } ?> | Try
<?php
if ( !empty( array ( $curauth->facebook ) ) ||
!empty ( array ( $curauth->linkedin ) ) ||
!empty( array( $curauth->twitter ) ) )
{
echo 'echo me if any $curauth info exists';
}
?>
**Note:** This can be all on fewer lines, I've just put in additional line-breaks to make it all fit to avoid a horizontal scrollbar.
* * *
**Update** :
Reading up on Author Templates made me realise that once you've set the `$curauth` variable, e.g.
$curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));
you should be able to use this instead:
<?php
if ( !empty ( $curauth->facebook ) ||
!empty ( $curauth->linkedin ) ||
!empty ( $curauth->twitter ) )
{
echo 'echo me if any $curauth info exists';
}
?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "array"
} |
Spacing around inline equations
What is the parameter determining spacing and stretchability around inline equations? I want to tweak spacing exactly but cannot find where the parameters are. | the parameter is `\mathsurround` but it is usually 0pt, but you can use
\setlength\mathsurround{2cm}
to space things out a bit | stackexchange-tex | {
"answer_score": 10,
"question_score": 6,
"tags": "math mode, spacing, inline"
} |
Записать в бинарный файл
Возможно ли в java строку из нулей и единиц записать в двоичный файл? Но чтобы потом можно было прочитать этот двоичный файл, и его содержимое должно быть равно начальной строке из нулей и единиц. То есть, например, есть строка `String OPER = "00100011101";`, я её записываю в бинарный файл, потом его читаю, и в командной строке должно быть написано это: `00100011101`. | byte[] bytes = "asdasd".getBytes();
String str = new String(bytes);
А куда записывать и откуда считывать вы, наверное, сами разберетесь. | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, файлы"
} |
Common List Elements
Alright, so I have a small issue:
def common(a,b,c):
a.sort()
b.sort()
c.sort()
i = 0
j = 0
k = 0
common=False
while i<len(a) and j<len(b):
if a[i] == b[j]:
if b[j] == c[k]:
return True
else:
k = k+1
continue
else:
if i == len(a):
j = j+1
else:
i = i+1
return common
a=[3, 1, 5, 10]
b=[4, 2, 6, 1]
c=[5, 3, 1, 7]
print common(a,b,c)
Basically, it has to tell me if there are common elements in the lists. With 1 it works, but if I replace the 1's with 8's, it doesn't work anymore. | Your 'j' never increase, 1 is working because after `sort` it is the 1st element and doesn't need `j` to be increased.
My suggestion is convert your lists to sets and check the common elements using intersection(&)
def common(a,b,c):
common = set(a) & set(b) & set(c)
return True if common else False
a=[3, 8, 5, 10]
b=[4, 2, 6, 8]
c=[5, 3, 8, 7]
print common(a,b,c) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python 2.7"
} |
associate a commit with a ticket retrospectively
When committing, I used by mistake the ActifactID of ticket change instead of the ticket hash label:
fossil commit -m "Workaround X [58480ac08c]"
In `fossil ui`, it is still a clickable link and leads to the ticket. However, the check-in does not appear under "Check-ins Associated With Ticket".
Is there a way to associate a check-in with a ticket retrospectively? | On the command line, you can use 'fossil amend'. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "fossil"
} |
RFC Repository of programming RFC's with ability to direct-link sections or even lines?
Forgive me if this is the wrong place to ask this, I feel like the question is slightly off-topic even though it is also about programming.
I am inputting todo-tasks for my WebDAV-project into my issue tracker, as I read through the relevant RFC's, and it would be nice to be able to add a link in my issue text directly to the relevant text, instead of just a link to the RFC file with a section number in the issue text, and then I have to use the find function to find it.
For instance, a link like this:
* < <\-- line 1000
* < <\-- section 9.8.3
Neither of these two works, since they just post the full text files, so my question is this: Does anyone know of hosted versions of the RFC documents that contains such links? | First, a better solution would to be use a richer language for expressing links to the text-only version. It exists! RFC 5147: URI Fragment Identifiers for the text/plain Media Type. For instance:
* <
It has a (very limited) implementation and a (better?) one in the browser Amaya.
For the HTML (unofficial) versions, there is the possibiity you request at the excellent tools.ietf.org. For instance:
* < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "hosting, rfc"
} |
XML entity references
I need to represent special characters like superscripts, copyright symbols etc in XML. What's the best way to do this?
I'm confused as XML defines 5 entity references for "<" , ">" etc. I always use < and > but could, or should, I use Unicode decimal, U+003C, instead? Or will an XML processor treat these the same as if I'd typed "<" and error as it's a reserved character?
For non-reserved characters, eg the copyright symbol, is it enough to insert the Unicode (U+00A9) into the XML or should I define an entity reference in my Schema?
Thanks ;-) | > I'm confused as XML defines 5 entity references for "<" , ">" etc. I always use < and > but could, or should, I use Unicode decimal, U+003C, instead? Or will an XML processor treat these the same as if I'd typed "<" and error as it's a reserved character?
A raw `<` would be an error (since it means "Start of tag").
> For non-reserved characters, eg the copyright symbol, is it enough to insert the Unicode (U+00A9) into the XML or should I define an entity reference in my Schema?
Using the actual character is fine (and generally preferred to using an entity as it is more readable (and takes marginally fewer bytes). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "xml, unicode, entity"
} |
rtmfp open source implementation or FMS with rtmfp hosting?
Is there an open source implementation of rtmfp?
Is there FMS hosting that support rtmfp?
What is the price of FMS4 enterprise?
Thanks | I hear about $50K US. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "flash, flash media server, rtmfp"
} |
UserMessagingPlatform invalid response from server
I'm trying to add user consent into my app using UMP, as defined in < Unfortunately, each call to requestConsentInfoUpdate() results in a generic "invalid response from server" error. My AdMob account has a GDPR message defined and turned on. The only information I could find relates to creating a Funding Choices account, but this is no longer possible since Google migrates away from FC. Is there a way to show them form, or debug the issue in-depth? | Turns out, this happens when the AdMob account is still under verification. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "android, admob"
} |
Bit manipulation in C?
I have to return 1 if all the even bits in word are set to 1. The trouble for me is I can only use logical operators like `+ , >> , <<, |, ^, ~ , !`. No `if's` or `for` loops. I thinking I would want to mask it using `0x55555555` but that's where I get stuck. And its assumed this is `32bit`. | For a 32 bits word:
#include <stdint.h>
int allBitEven(uint32_t x)
{
return ( !((x & 0x55555555)^0x55555555) );
}
Since I'm playing with this question, I propose another function that may verify if all bits are odd or all bits are even only with logical operations:
int allBitEvenOrOdd(uint32_t x, int odd)
{
return ( !((x & (0x55555555<<odd))^(0x55555555<<odd)) );
}
if odd is 1 it verifies if all bits are odd, if odd is 0 it verifies if all bit are even! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -4,
"tags": "c, bit"
} |
What's the difference between SFTP, SCP and FISH protocols?
I used to think SCP is a tool to copy files over SSH, and copying files over SSH is called SFTP, which is itself a synonym to FISH.
But now as I was looking for a Total Commander plugin to do this in Windows, I've noticed that on its page it says "Allows access to remote servers via secure FTP (FTP via SSH). Requires SSH2. This is NOT the same as SCP!".
If it's not the same then what am I misunderstanding? | SFTP isn't the FTP protocol over ssh, but an extension to the SSH protocol included in SSH2 (and some SSH1 implementations). SFTP is a file transfer protocol similar to FTP but uses the SSH protocol as the network protocol (and benefits from leaving SSH to handle the authentication and encryption).
SCP is only for transferring files, and can't do other things like list remote directories or removing files, which SFTP does do.
FISH appears to be yet another protocol that can use either SSH or RSH to transfer files.
* * *
UPDATE (2021/03/09): According to the release notes of OpenSSH 8.0/8.0p1 (2019-04-17):
> The **scp** protocol is outdated, inflexible and not readily fixed. We recommend the use of more modern protocols like sftp and rsync for file transfer instead. | stackexchange-unix | {
"answer_score": 90,
"question_score": 97,
"tags": "ssh, scp, sftp, fish protocol"
} |
Abrir un Dialog() desde un archivo .JS usando un DropDownList
Hola soy nuevo programando y quisiera saber si se puede tener un Dropdown list de asp que se abra dependiendo de la seleccion, un dialog() de jquery pero que este dialog() ste dentro de un archivo comun .js
tengo un script que al colocarlo directo en la pagina abre sin problemas pero quiero usar el mismo y hacerlo "Comun" dentro de un .JS y que me abra dentro de otra pagina del mismo proyecto.
es posible?
y si se puede, necesito un ejemplo para hacerlo. | puedes hacerlo con javascript jquery
@Html.DropDownList("Sortby", new SelectListItem[]
{ new SelectListItem() { Text = "Newest to Oldest", Value = "0" },
new SelectListItem() { Text = "Oldest to Newest", Value = "1" }},
new { @onchange="CallChangefunc(this.value)" })
<script>
function CallChangefunc(val)
{
$( "#dialog" ).dialog();;
}
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
la fuente esta en el comentario que escribí | stackexchange-es_stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "javascript, html, asp.net"
} |
How to find determinant of the following $3\times 3$ matrix?
How to find the determinant of the following block matrix?
$$\begin{pmatrix} \lambda I-A & -A &-J\\\ -A& \lambda I & 0\\\ -J& 0 & \lambda I\end{pmatrix}$$
where $A$ is a $n \times n$ matrix and $\lambda$ is a scalar. $J$ is a square matrix of order $n$.
I tried using row and column operations like using $R_1\to R_1+R_2$ but I am not getting anything fruitful. What is the way out? Is there any special trick to do this? | Using the Schur complement formula for the determinant of a block matrix,$$ \det \begin{pmatrix} X & Y\\\ Z& W\end{pmatrix} = \det W \det(X- Y W^{-1} Z),$$ with the lower right $2n\times 2n$ block to be $W$ as it's simple to invert, I find that $$\det \begin{pmatrix} \lambda I-A & -A &-J\\\ -A& \lambda I & 0\\\ -J& 0 & \lambda I\end{pmatrix} = \lambda^n \det (\lambda^2 I - \lambda A - A^2 - J^2).$$
Edit; I applied the determinant formula differently and found $$\det \begin{pmatrix} \lambda I-A & -A &-J\\\ -A& \lambda I & 0\\\ -J& 0 & \lambda I\end{pmatrix} = \frac{\det(J^2)\det (2\lambda^2 I - 2A^2 - \lambda A)}{\det(\lambda I -A)},$$ which you might prefer depending on your application, @Math_Freak | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "matrices, determinant, block matrices"
} |
Where to put R files that generate package data
I am currently developing an R package and want it to be as clean as possible, so I try to resolve all WARNINGs and NOTEs displayed by `devtools::check()`.
One of these notes is related to some code I use for generating sample data to go with the package:
checking top-level files ... NOTE
Non-standard file/directory found at top level:
'generate_sample_data.R'
It's an R script currently placed in the package root directory and not meant to be distributed with the package (because it doesn't really seem useful to include)
So here's my question: Where should I put such a file or how do I tell R to leave it be? Is `.Rbuildignore` the right way to go? Currently `devtools::build()` puts the R script in the final package, so I shouldn't just ignore the NOTE. | As suggested in < it makes sense to use `./data-raw/` for scripts/functions that are necessary for creating/updating data but not something you need in the package itself. After adding `./data-raw/` to `./.Rbuildignore`, the package generation should ignore anything within that directory. (And, as you commented, there is a helper-function `devtools::use_data_raw()`.) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "r, devtools, r package"
} |
Hartshorne chapter II Example 6.11.4: why the singularity deduces a contradiction?
In this example, $X=V_+(X^3-Y^2Z)\subset \mathbb P_k^2$, and $Z=(0,0,1)$. In the end of the first paragraph of page 143, he claims that since $Z$ is a singular point, $\mathcal O_{X,Z}$ won't dominate any DVR in $\mathbb P_k^1$. But why? Could you provide a detailed explanation? Thanks! | Recall theorem I.6.1A:
> **Theorem** : Let $K$ be a field. A local ring $R$ contained in $K$ is a valuation ring if and only if it is a maximal element of the set of local rings contained in $K$, with respect to the relation of domination. Every local ring contained in $K$ is dominated by some valuation ring of $K$.
If $\mathcal{O}_{X,Z}$ dominates a DVR $R\subset k(t)$, then by the theorem we must have $\mathcal{O}_{X,Z}=R$ since $R$ is maximal with respect to the relation of dominantion. But this says $\mathcal{O}_{X,Z}$ is a DVR, which we know is equivalent to $Z$ being a regular point of $X$, which it is not. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "algebraic geometry"
} |
What is the wavelength of red light in vacuum?
According to Wikipedia,
> It has a dominant wavelength of approximately 625–740 nanometres.
However, I'm not sure in which medium this wavelength was measured. Was this wavelength measured in a vacuum? What is the wavelength of red light in a vacuum? | Loosely, it doesn't matter whether it is air or vacuum. The index of refraction of air is about $1.0003$ at visible wavelengths. That means $\lambda_{vacuum}/\lambda_{air} \approx 1.0003$. Not enough to notice.
Of course, some people are interested in precision. They would use the value in vacuum. Or perhaps the value in whatever medium light is traveling through in their case. | stackexchange-physics | {
"answer_score": 2,
"question_score": -2,
"tags": "waves, electromagnetic radiation, visible light, frequency, wavelength"
} |
Crash a kernel on purpose
Is there any way I can crash a kernel on purpose (e.g., kernel panic, blue screen, black screen, or whatever). Assume I can change any registers and have administrative privilege of the system. I would like to demonstrate this on both Windows and Linux platforms.
Thanks for any inputs! | In Linux, you must compile the kernel with the CONFIG_MAGIC_SYSRQ option, then you can crash the kernel by writing the **c** rash command into `/proc/sysrq-trigger`, or by pressing `Alt`+`SysRq`+`C`. See the documentation for details.
In Windows, you must set the `CrashOnCtrlScroll` registry key for the keyboard driver, and reboot, then you can press `Ctrl`+`Scroll Lock` to crash the kernel. See the documentation for details. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "windows, linux kernel, kernel"
} |
Closed form solution of elliptic or gaussian functions
I have often read that integrals of functions like $\exp(-\frac{x^2}{2})$ or $\frac{1}{\sqrt{1-k^2\sin^2\theta }}$ have no _closed form_ solutions. I am unable to find what closed form exactly means, though I get the rough idea that it is polynomials, trigonometric ratios, exponents, their compositions and inverses.
So, here are my two doubts:
1.Is there a proof that the integrals can't be expressed in closed from (whatever definition you assume), or is it that nobody has found them out?
2.What about functions like Bessel functions? Do they count as closed form?
Thanks in advance. | By _can't expressed in closed form_ form one usually means that it is not an elementary function.
Liouville's theorem of differential algebra proves that certain antiderivatives (of $e^{-x^2}$ for instance) are not elementary functions. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "integration, closed form"
} |
Remove unnecessary backups from TimeMachine to get space
I know that oldest backups are removed automatically when there is no space for new ones on TimeMachine. I use TimeCapsule also for sharing files on WiFi, so I’d like to free some space by removing of unnecessary backups:
* Large files which needen’t to be backed up (e. g. image previews of Lightroom over 1 GB). I have excluded them in TM preferences but they are already present in older backups keeping space forever.
* Oldest backups I know I will not need. (So to trigger the same as TimeMachine does automatically but earlier than disk gets empty). | I use this article to help me in deleting files from Time Machine:
* <
It talks about removing all the backups of a single file, maybe it's not what you're looking for, but it definitely could resolve the first issues (Lightroom previews). In practice, it's easier to delete all backups of one file or all files in one backup than it is to go in and remove only one file from one backup.
Here's a brief summary of that article:
1. Open Time Machine
2. Select the folder/file you want to delete from your backups
3. Through the "option" menu in the Finder menu bar (ctrl-click is not available in TM, don't know why) select "Delete all backups of **selectedfile** ", where **selectedfile** is (obviously!) the file you selected. | stackexchange-apple | {
"answer_score": 7,
"question_score": 20,
"tags": "time machine, backup, disk space"
} |
How to sort a file containing names with a script?
Assuming I have a file called "students" containing this:
NEWTON Isaac
MAXWELL James
EDISON Thomas
TESLA Nikola
how I am supposed to sort these names with a bash script in shell ? Do I need to use a delimiter with carriage return ? Will this support accentuated characters ?
Thanks for your time. | You can make use of the `sort` function.
$ cat stud.txt
NEWTON Isaac
MAXWELL James
EDISON Thomas
TESLA Nikola
$ sort stud.txt
EDISON Thomas
MAXWELL James
NEWTON Isaac
TESLA Nikola
To sort on last name, use the `-k` option.
$ sort -k 2 stud.txt
NEWTON Isaac
MAXWELL James
TESLA Nikola
EDISON Thomas | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "bash, shell"
} |
Get log details for a specific revision number in a post-commit hook with SharpSVN?
I'm trying to write a post-commit hook using SharpSVN but can't figure out how to get the changeset info using SharpSVN given the revision number and the path to the repo. Any ideas are much appreciated. | In hook clients you most likely want to use the SvnLookClient that directly accesses the repository. In this example (copied from another question here) I also use the SvnHookArguments class for parsing the hook arguments.
static void Main(string[] args)
{
SvnHookArguments ha;
if (!SvnHookArguments.ParseHookArguments(args, SvnHookType.PostCommit, false, out ha))
{
Console.Error.WriteLine("Invalid arguments");
Environment.Exit(1);
}
using (SvnLookClient cl = new SvnLookClient())
{
SvnChangeInfoEventArgs ci;
cl.GetChangeInfo(ha.LookOrigin, out ci);
// ci contains information on the commit e.g.
Console.WriteLine(ci.LogMessage); // Has log message
foreach(SvnChangeItem i in ci.ChangedPaths)
{
//
}
}
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "c#, svn, hook, sharpsvn"
} |
JavaFX: Window.sizeToScene() center at original position
I know `Window.sizeToScene()` will resize the window to the size that its scene needs, but the position of the window does not adjust accordingly (i.e. the stationary point is top-left corner of the window). Is there any way to make the window resize itself, and keep the window's center at the same place (i.e. make the stationary point at the center of the window)? | Do something like:
public void resize(Window win) {
double x = win.getX();
double y = win.getY();
double width = win.getWidth();
double height = win.getHeight();
win.sizeToScene();
win.setX(x + ((width - win.getWidth()) / 2));
win.setY(y + ((height - win.getHeight()) / 2));
}
The code above caches the position before the window is resized to the scene, then it moves the window the appropriate amount to keep the window centered in the same area. This code does not take into account where the window will be once it is moved/resized. You might want to add checks to make sure the window doesn't end up going off the screen. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, javafx, javafx 8"
} |
How to update opportunity records closedate as today using dml statements?
I am trying to update the all opportunity records close date as today using dml statements. Can anyone please help me | //Query all the opportunity records via SOQL.
List<Opportunity> lstOpp = new List<Opportunity>();
lstOpp = [Select id,name,stage,status,closeddate from Opportunity];
List<Opportunity> updateOpportunity = new List<Opportunity>();
if(lstOpp!=null && lstOpp.size()>0){
for(Opportunity opp: lstOpp){
opp.closeddate = system.today();
updateOpportunity.add(opp);
}
}
//Update records via DML
if(updateOpportunity!=null && updateOpportunity.size()>0){
update updateOpportunity;
} | stackexchange-salesforce | {
"answer_score": 0,
"question_score": -2,
"tags": "dml operations"
} |
2 mortgages, payoff one completely or pay some off bigger principal?
so I have two mortgages on two separate rental properties.
A. 100k remaining, 1 year left on term, 1.85% variable, 428 monthly.
B. 300k remaining, 4 year left on term, 2.54% fixed, 313. weekly.
I have 100k to pay down, which do I do and why?
eliminating A will allow me to have an extra inflow of 428 each month.
but Ill be paying more in interest over the course of the term of paying for B, so wouldnt it make sense to knock off some there? however I will have that extra 428 expense to deal with from not paying off A
I am in Canada.
Edit: It seems like the Bank of Canada plans several rate hikes this year, which will increase the variable rate. | _Mathematically_ you should pay the one with the higher interest rate, since you'll pay less interest over the remaining life of the loan.
_Practically_ I see at least three very good reasons why paying the lower-rate loan off completely may be the best move:
* It frees up that monthly payment to pay down other debts, or start/accelerate investing for retirement.
* You're only paying 0.69% extra (~2k per year) on the second loan if you pay the first one off instead.
* There's a very good chance that the interest rate of the first loan will _increase_ over the next year, or when you refinance.
Not to mention the psychological benefit of having a loan off of your mind and an extra $428/month of flexibility in your budget. | stackexchange-money | {
"answer_score": 24,
"question_score": 6,
"tags": "mortgage, canada"
} |
Passing variables containing urls in Jade Template
I am having trouble displaying a link correctly in Jade when I pass in an object.
// Story object
{
"_id" : ObjectId("55db6e1710976558828f8053"),
"author" : ObjectId("55d7a215a3695c620c586f12"),
"link" : "benjelnews.com",
"title" : "hello",
"updated" : ISODate("2015-08-24T19:18:47.589Z"),
"created" : ISODate("2015-08-24T19:18:47.589Z"),
"comments" : [ ],
"__v" : 0
}
// App.js
res.render('news', {data: story});
// News.jade
a(href=data.link)=data.title
However, the link keeps showing up as "localhost:4000/benjelnews.com" Can someone explain why my local server address keeps showing and how I can properly configure my Express or Jade template to display the correct format which is just "benjelnews.com" | Jade renders your template to this HTML:
<a href="benjelnews.com">hello</a>
Since `benjelnews.com` is not a valid URL (it doesn't start with a scheme, like ` or ` your browser interprets that as a relative path on your local webserver (which apparently is running on `
If all your links look like that, you can add the scheme in your template:
a(href = ' + data.link)= data.title
(and hope that all links are plain HTTP and not HTTPS)
Ideally, your database should contain proper URL's. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, node.js, express, pug, template engine"
} |
Is there an existing solution to AJAX timeouts with ASP.NET MVC and jQuery?
You are using ASP.NET MVC with jQuery. You make a lot of AJAX calls. You want to notify the user if they click something and the session has timed out. Does anyone have a good existing solution to this that also includes notifying the user of timeout after initiating an AJAX request?
(There are known solutions for non-AJAX ASP.NET apps that involve detecting the timeout in Global.asax and redirecting to a specific page. Redirecting the AJAX request, however, is problematic because the user either won't see it, or will see it in the wrong context.)
This is something almost every application needs so I just want to make sure I don't reinvent the wheel. Thanks! | Here's what I do: when my server detects a session timeout, it responds with the reauthentication page, and it also sets a special header in the response. For Ajax, I just have my handler look for that header, and if it sees it it forces the surrounding page (i.e., `location.href` or whatever) to reload (with an extra "nonce" parameter to make sure it bypasses the browser cache).
Note that my solution isn't specifically an ASP.NET thing. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "jquery, asp.net mvc, timeout"
} |
Using @RequiredStringValidator messageParams in Struts 2
In my message resources file i have following lines:
error.required={0} is required
labels.email=E-mail
To validate e-mail field I am using annotation validators, like this:
@RequiredStringValidator(key="error.required")
public String getEmail() {
return email;
}
My question is: how can I pass the `labels.email` resource value to the `{0}` param to the message using `RequiredStringValidator` annotation? I was trying with `messageParam` property but without any success. | Try this
@RequiredStringValidator(message = "${getText('error.required', new java.lang.String[] {getText('labels.email')})}")
The `getText()` could be used if your action extends `ActionSupport` to get the resource messages by the key specified as a parameter. It applied two times in the same expression to build your message. First time without parameter, second with the parameter and used overloaded `getText()` implementation. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "validation, annotations, struts2, ognl, messageformat"
} |
Bone constraint Limit Rotation does nothing (v3.2.1)
I have a bone with a Limit Rotation constraint on it, and it appears to be completely ineffective.
There are plenty of tutorials covering adding a constraint and mine simply isn't working. Here is one such tutorial for reference - <
So am I doing something wrong, or is this a bug?
 each folder and subfolder
The second will give you the ownership of the folders and folders (but not the ownership of the files in those folders)
Note that a directory has a size (related to the number of files in it) that is different from the size of it's contents.
I use the following words interchangeably: folder; subfolder; directory; subdirectory. | stackexchange-superuser | {
"answer_score": 3,
"question_score": 2,
"tags": "linux, unix"
} |
cocos2d. How to create a popup modal dialog (with CCLayer)
I need to make a modal dialog(inherited from CCLayer) that is showing in the center of the main layer. While it is showing, you can not press any other button outside the dialog. Just like a normal modal window in MS Windows System.
The problem is that I can not figure out how to disable the mainlayer's touch events while the dialog is showing.
Any help would be aprreciated. | Just set
self.isTouchEnabled = NO;
in the main layer while the popup is displayed. Then later set it back to YES. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "dialog, cocos2d iphone, popup, modal dialog"
} |
Bigcouch cluster configuration
I'm currently trying bigcouch and I don't quite understand how it identifies nodes within a cluster. For example, the dev cluster consists of 3 nodes listening on ports 15984/15986, 25984/25986 and 35984/35986. When we add nodes to cluster we append documents with id "[email protected]" and "[email protected]" to nodes database (see < Now where are the port numbers? How does node 1 know that nodes 2 and 3 listen on the above pots? And related question: if I want to add a node located on a different host to this cluster, how do I do that? Adding "dev1@IP" doesn't seem to work, bigcouch is not able to connect to it. | The problem has been resolved -- it appears that two bigcouch nodes must have the same magic cookie in order to communicate successfully. When a dev cluster is installed, this magic cookie is generated automatically, so it is not possible to add nodes from another cluster unless magic cookies are manually synchronised. It is neccesary to add the following line to /opt/bigcouch/rel/*/etc/vm.args:
-setcookie any_string | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "couchdb, bigcouch"
} |
Align text in spans to the bottom of Angular Material icons with CSS?
I have the following bit of code. I want to make the text in the spans line up with the bottom of the stars.
<ng-container *ngIf="starCount">
<span>Not Relevant</span>
<button
mat-icon-button
color="primary"
*ngFor="let ratingId of ratingArr; index as i"
[id]="'star_' + i"
(click)="onClick(i + 1)">
<mat-icon>{{ rating > i ? 'star' : 'star_border' }}</mat-icon>
</button>
<span>Very Relevant</span>
</ng-container>
Tried all sorts of things out in the Chrome inspector, but have made no meaningful progress. | You can use something like that:
<div *ngIf="starCount" style="display: flex; align-items: center">
<span>Not Relevant</span>
<button
mat-icon-button
color="primary"
*ngFor="let ratingId of ratingArr; index as i"
[id]="'star_' + i"
(click)="onClick(i + 1)">
<mat-icon>{{ rating > i ? 'star' : 'star_border' }}</mat-icon>
</button>
<span>Very Relevant</span>
</div> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "html, css, angular material"
} |
Is lightning case sensitive?
Is lightning case sensitive (or) is it something else that is causing this behavior? I was looking into Lightning badges on trailhead and when I tried to compile this code, as a salesforce developer I expected this code to compile ( not a good practice to have mix case).
<aura:component >
<h1 style="font-size:16px"> Camping List </H1>
</aura:component>
But the component won't compile and gives the following error:
> Failed to save undefined: markup://prao6308:campingHeader:2,45: ParseError at [row,col]:[3,45] Message: The element type "h1" must be terminated by the matching end-tag "".
Can someone please throw some light on why the compiler wont match <h1> with </H1>? | As lightning is based on aura framework which is a type of JavaScript and JavaScript is case sensitive so lightning is also case sensitive.
And from Spring 15 Release Notes it is mentioned that Lightning components are now case sensitive. | stackexchange-salesforce | {
"answer_score": 6,
"question_score": 5,
"tags": "lightning aura components, lightning"
} |
How to get a notification when windows prompt a dialog (i.e. error message)?
**the situation:**
a user tries to copy a file to a directory he doesn't have write permission in, he will be prompted with a dialog box.
**The requirement:**
In a separate unrelated process, I want to get notified when this happens.
**Possible solution paths:**
1. subscribe to a system event if one exists.
2. using hooks
Is this even possible? which of the two is the preferred path?
a code example doing this would be a life saver... | Use `SetWindowsHookEx()` or `SetWinEventHook()` to receive notifications when a window is created and about to receive focus. You can then analyze the window contents to see if it matches what you are looking for and act accordingly. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, c++, .net, windows, winapi"
} |
Conditional SQL query with count
Would it be possible to have the following:
In case `assignments.customer_id = customers.id` is `NULL` the query would be
$query = "
SELECT customers.*
FROM customers
WHERE customers.active = 0
ORDER
BY customers.event_date DESC
";
When it does exist it would become:
$query = "
SELECT customers.*
FROM customers
, assignments
WHERE customers.active = 0
AND NOT assignments.status = 5
AND assignments.customer_id = customers.id
ORDER BY customers.event_date DESC
";
Or should this be done in separate queries with an if statement in PHP?
Thank you very much for your help! | If I understand the logic correctly, you want inactive customers that have no assignment with a status of 5:
SELECT c.*
FROM customers c
WHERE NOT EXISTS (SELECT 1
FROM assignments a
WHERE a.customer_id = c.id AND a.status = 5
)
c.active = 0
ORDER BY c.event_date DESC; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "php, mysql, sql"
} |
Would future combat submarines come with jet propulsion thruster?
We currently have jet engine in flighter jet, space shuttle, some race cars but nothing underwater where breaking sound barrier(air) is concerned. I'm imagining in near future many manned electric or diesel subs perhaps nuclear sub can traveling at near 300km/h underwater using jet propulsion method or is it too much to ask for? | Are you aware of supercavitation? Currently that is used for torpedoes, not subs, but that might change in a couple of decades.
BTW, diesel submarines are actually diesel-electric. They use diesel on the surface or at snorkling depth to recharge their batteries. Pure electric subs tend to be short-range research or DSRV designs. | stackexchange-worldbuilding | {
"answer_score": 1,
"question_score": -2,
"tags": "internal consistency, technological development, underwater"
} |
Oracle SQL Developer - using foreign keys
First of, this is a pretty basic question but I cant seem to find a basic tutorial on how to use the software.
If i have a table named `COUNTRY` with the field `region_id` and then another table named `REGION` with a primary key as `region_id`.
I want to set the region_id field in `COUNTRY` table as a foreign key. Are the following steps correct?
* Go to constraints, add a new foreign key.
* Select `COUNTRY` as table
* Change local column to `region_id`
![enter image description here][1] Am I doing it correctly? if not, where am i going wrong | Yes, This is the correct procedure.
If you want your foreign key to have additional behavior (e.g., `ON DELETE CASCADE`), you can use the "on delete" drop-down in the wizard. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "oracle, oracle sqldeveloper, foreign key relationship"
} |
Obfuscate Assembly and Reflection
I want to obfuscate my assembly files (*.dll, *.exe) by **Dotfuscator**. my question is if I do this, can I still use classes and types that are in those assemblies by their original names (I mean names before obfuscation) and using `System.Reflection` methods to work with them?
_If you need more detail,please tell me_ | Obfuscation are Reflection can cause you some problem. Even if you take the suggestion to use option to not obfuscate public method, some of the reflected code may call private method. The problem is that obfuscation will change name of some code that you may need to stay the same.
If you know or can locate the region that is susceptible to be used with reflection you can use
[global::System.Reflection.Obfuscation(Exclude=true, Feature="renaming")]
This will tell the obfuscator to keep the name.
Running obfuscation with reflection require more testing that's for sure but still possible... | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 8,
"tags": "c#, obfuscation, dotfuscator"
} |
MySql - Select from - Don't Show Duplicate Words - maybe "on duplicate key"?
how can I insert "on duplicate key" in this Code to remove duplicate words? or is there a better method that you know? thank you!!
this is my code:
function sm_list_recent_searches($before = '', $after = '', $count = 20) {
// List the most recent successful searches.
global $wpdb, $table_prefix;
$count = intval($count);
$results = $wpdb->get_results(
"SELECT `terms`, `datetime`
FROM `{$table_prefix}searchmeter_recent`
WHERE 3 < `hits` AND CHAR_LENGTH(`terms`) > 4
ORDER BY `datetime` DESC
LIMIT $count");
if (count($results)) {
foreach ($results as $result) {
echo '<a href="'. get_settings('home') . '/search/' . urlencode($result->terms) . '">'. htmlspecialchars($result->terms) .'</a>'.", ";
}
}
} | `ON DUPLICATE KEY UPDATE` is used to cause an insert to update records if they already exist. It's not used for `SELECT` queries
What you want is to use the `GROUP BY` clause on your terms column to collapse it to unique values. You can use the `MAX` aggregate function to get the date of the latest record for those terms.
SELECT `terms`, MAX(`datetime`)
FROM `{$table_prefix}searchmeter_recent`
WHERE 3 < `hits` AND CHAR_LENGTH(`terms`) > 4
GROUP BY terms
ORDER BY `datetime` DESC
LIMIT $count
Make sure you have an index on the terms column, otherwise this will be a very expensive operation, especially if you're using it to make an autocomplete. You might even consider grouping your terms at insert time for best performance. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, mysql, duplicates"
} |
Relationship with parameter then use contains in Eloquent Laravel
Have the next code working properly:
$system_breeds = SystemsGroup::find($group_id)->breeds;
$breeds = Breed::select('id', 'breed')->orderBy('breed')->get()->transform(function ($breed) use ($system_breeds) {
if ($system_breeds->contains($breed)) {
$breed->active = true;
}
return $breed;
});
On every breed that exists on the system_breeds I'm adding an active property as true.
What I want to do now, is something like this:
$system_breeds = SystemsGroup::where('id',$group_id)->with(['breeds' => function($q) use ($section_id){
$q->where('group_section_id', $section_id);
}])->get();
So, add a where filter on the relationship. But the "contains" doesn't work. | Your question is not much clear, look you want to filter and get related models, if so try like this.
$system_breeds = SystemsGroup::find($group_id)->breeds()->where('group_section_id',$section_id)->get(); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "laravel, laravel 5, eloquent, eloquent relationship"
} |
Search doesn't say how many results there are anymore
Before, there was something that said how many search results there are, like this:
> 
I'm trying to get the x and y coordinates of a specific window relative to the screen (e.g. If the window's position on the screen is (100, 300) then I should retrieve an x-coordinate of 100 and a y-coordinate of 300). How can I achieve this so that I can assign the coordinates to some variables?
int x = /*Get x-coordinate*/;
int y = /*Get y-coordinate*/; | RECT rect;
GetWindowRect(window, &rect);
int x = rect.left;
int y = rect.top; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, window, screen, coordinates"
} |
Convergence with indicator functions
I'm a bit confused when I'm trying to solve some exercise using conceps like pointwise convergence, a.e. convergence and $L_\infty$ convergence with indicator functions. For example, we consider $f_n (x)=\mathcal{X}_{[n,n+1]}(x)$ where $n\in\mathbb{N}$ and $x\in (0,\infty)$. It seems pretty obvius that $f_n\not\longrightarrow 0$, but here is my first dobut. If $n$ is large enough, in such a way that $x\notin [n,n+1]$, then $f_n (x)=0 \;\forall x\in (0,\infty)$, so $f_n=0$ pointwise. I know this can't be correct, but I need a second explanation. On the other hand, $f_n\longrightarrow 0$ a.e., but now $f_n=1$ if $x\in[n,n+1]$ and $\mu ([n,n+1])\neq 0$. Finally, why $||f_n||_\infty=1$? | Pointwise convergence means you look at some fixed $x\in(0,\infty)$ and you ask whether $f_n(x)\to 0$. You do this for each and every $x$ in your domain separately.
In this example it is certainly true that $f_n\to 0$ everywhere, because for any fixed $x\in(0,\infty)$ there's $n_0\in\mathbb{N}$ large enough such that $f_n(x)=0$ for all $n\geq n_0$. You say "If n is large enough, in such a way that $x\notin [n,n+1]$..." but this sentence is meaningless: which $x$ are you referring to? For any fixed $x$ we can find $n$ that is large enough, but we can't find $n$ that is large enough for all $x$.
(Since $f_n\to 0$ pointwise then in particular $f_n\to 0$ a.e. -- after all, it converges everywhere).
Regarding $L_\infty$, this is simply because the norm of each and every element of the sequence $f_n$ is $1$. Therefore you get a constant sequence which certainly converges to $1$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, functional analysis, analysis, lebesgue measure"
} |
How to print a div on a click of a button?
I'm using printThis by Jason day and on its config page it shows that you can trigger the plugin using:
$('selector').printThis();
Now when I do that I have noticed that this trigger is showing print box on Page load instead of clicking on a button.
How do I use this plugin and trigger it on a button instead of a default page load?
Usage: < | So in order to do that you need to add some listener for the `click` event of your button.
Assume this is your HTML:
<button id="myButton">Button</button>
<div id="myPrintableContent">
Some content to print
</div>
And this is your javascript code:
$(document).ready(function() {
$('#myButton').on('click', function () {
$('#myPrintableContent').printThis();
});
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "javascript, jquery, printthis"
} |
If a credit card won't read when swiped, does wrapping it in plastic actually help and if so, why?
I've on occasion seen when a cashier has trouble getting a credit card to read, will wrap it in a thin plastic grocery bag, and try swiping it again. Much to my surprise, it seemed to work.
Since the card uses a magnetic strip, I can't see how the plastic would help. Is there any reason it should, or is this a case where it worked, but not because of the plastic? | The best explanation I have seen for this is that the plastic bag increases the distance between the read head and the magnetic strip. As the magnetic strip is used, small particles break off and become embedded elsewhere on the stripe. These have very little magnetic force, but enough that they throw off today's more sensitive readers, even though they're embedded in a larger area of stronger magnetism.
By increasing the distance between the read head and the mag stripe, even though it's just the thickness of the plastic bag, the smaller "noisy" bits impart a smaller field on the sensor than the larger areas of magnetic material surrounding them. It increases the signal to noise ratio by placing a low pass filter between the strip and the read head.
In other words, it's similar to putting on earmuffs so you can only hear the bass line of a piece of music, muffling the midrange, and almost muting the high range frequencies. | stackexchange-physics | {
"answer_score": 23,
"question_score": 11,
"tags": "electromagnetism"
} |
How do I install a jump duct?
Our master bedroom is considerably warmer than the living/dining/kitchen area of our house, and we've been setting the thermostat quite lower than we'd like in order for the bedroom to get cool enough at night to sleep in. Upon exiting the bedroom in the morning, we've practically got to bundle up due to how cold the rest of the house is.
One suggestion we got was to install a return vent above the door, which we don't want to do because of the loss of privacy. Another suggestion was to install a jump duct in the ceiling inside and outside of the bedroom, which appeals to both my wife and me.
What is the correct way and what are the materials required to install a jump duct so as to maximize air circulation while not leaking any cold air into the attic? | Go to any big box store and get some 6" flexible insulated duct (this pic shows black sheathing on the outside, but it's often made of shiny reflective mylar):
!flexible duct
And a couple of 6" boots, one for each end:
!boot
Use aluminum HVAC tape or a large band clamp or zip tie to connect the inner sleeve of the duct to the boots, then use another layer of tape to seal up the insulated layer and prevent it from sliding around. Cut holes in the ceiling to match the rectangular boot opening, keeping one long edge of each hole flush to a ceiling joist. Then take your duct assembly up into the attic and insert the boots into each hole. You can just leave the flexible duct lying on top of the ceiling joists. Back downstairs, use small nails (with heads, not finish nails) to nail through the inside of the boot opening into the side of the adjacent ceiling joist. Then install a couple of register grilles and you're done! | stackexchange-diy | {
"answer_score": 8,
"question_score": 8,
"tags": "air conditioning, hvac, ductwork, temperature"
} |
Need to determine how php files are being rendered in a LAMP configuration (CGI, FastCGI, or mod-php)
How do I determine how our php files are being rendered in a simple LAMP configuration?
phpinfo shows:
-- Configure Command --
--enable-force-cgi-redirect
--enable-fastcgi
-- Server API --
CGI/FastCGI
-- cgi-fcgi --
Directive Local Value Master Value
cgi.check_shebang_line 1 1
cgi.fix_pathinfo 1 1
cgi.force_redirect 1 1
cgi.nph 0 0
cgi.redirect_status_env no value no value
cgi.rfc2616_headers 0 0
fastcgi.logging 1 1 | The phpinfo should really give you all the infomration you require regarding your current PHP implementation. It provides you with the PHP interpreter running, it's configuration directives, as well as letting you know whether you're running in mod_php or a cgi based ( in your case cgi based via CGI/FastCGI ).
What sort of additional information are you currently looking to get ? | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 1,
"tags": "php, fastcgi, cgi, mod php"
} |
in Vb6 and c# how do I have multiple of a string
Is there a single command that replicates a string into multiples of that string or character. Sql has replicate which can replicate a space for instance into many:
replicate(' ', 10000) -- will make 10k spaces.
Is there a similiar command in vb6 and c#? | To repeat an actual string, not just one character _(code is the same for C# and VB.Net)_ :
//Repeat "asd" 100 times
String.Join("", Enumerable.Repeat("asd", 100).ToArray()) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "c#, vb6"
} |
How to use R Random forests to reduce attributes having no discrete classes?
I want to use Random forests for attribute reduction. One problem I have in my data is that I don't have discrete class - only continuous, which indicates how example differs from 'normal'. This class attribute is a kind of distance from zero to infinity. Is there any way to use Random forest for such data? | That should be no problem -- RF will just switch to regression mode. Use `randomForest` function from the `randomForest` package.
To get object similarity with `proximity=TRUE` argument, like:
randomForest(Sepal.Length~.,data=iris,proximity=TRUE)$proximity
To get node-purity (Gini-index like) attribute importance:
randomForest(Sepal.Length~.,data=iris)$importance[,"IncNodePurity"]
To get mean MSE increase (accuracy-decrease like) attribute importance:
randomForest(Sepal.Length~.,data=iris,importance=TRUE)$importance[,"%IncMSE"] | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "r, statistics, machine learning, feature selection, random forest"
} |
How to select multiple dates in flutter
I want to select multiple dates from date picker (not range). Actually in my app I have added a workshop that will be hosted on multiple days, like 1 June, 7 June, 9 June. So i want to add add multiple dates. Is there a option to select multiple dates in date picker? | Try to refer **`table_calendar`** package and **`daterangepicker`** use **`syncfusion_flutter_datepicker`** package for that hope its help to you. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "flutter, datepicker"
} |
Codecademy help, Javascript
Despite my best efforts, I can't seem to get this question correct and I keep getting errors. Seeing as the Codecademy forums are a bit slow, I figured I would post here.
This is the question I'm working on: <
Here is the code I have input:
// Write your function below.
// Don't forget to call your function!
var sleepCheck = function(numHours)
{
if (sleepCheck >= 8); {
return "You're getting plenty of sleep! Maybe even too much!";
}
else {
return "Get some more shut eye!";
}
};
console.log(sleepCheck(10));
console.log(sleepCheck(5));
console.log(sleepCheck(8));
**Thank you to everybody who answered for your input, my issue has been taken care of.** | if (sleepCheck >= 8); {
Change that to
if (numHours >= 8) { | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -3,
"tags": "javascript"
} |
Error in mule start up due to long properties file
I am facing one weird issue while running mule application. We have multiple entries in mule-app.properties (220 lines ). When I try to run the application, it fails with `file or extension too` error.
()
An example of its use:
stopBackBackgroundTaskBlock = [^
{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskId];
backgroundTaskId = UIBackgroundTaskInvalid;
} copy];
How can I convert this code to Swift? | Try
var stopBackBackgroundTaskBlock:()->() = {
UIApplication.sharedApplication().endBackgroundTask(backgroundTaskId)
backgroundTaskId = UIBackgroundTaskInvalid
}
When you want to execute this block
stopBackBackgroundTaskBlock() | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -3,
"tags": "swift"
} |
Is a Galois group of a number field faithfully represented by its action on the set prime ideals of the ring of integers?
Is a Galois group $G$ of a number field $K$ faithfully represented by its action on the set prime ideals of the ring of integers $O_K$?
This is true in some cases, like $Z[i]$. (Where we can see the group by its action on $(2 + i)$ and $(2 -i)$). I am wondering if it is true in general, or in some general class of cases.
In the monogenic case my best guess would be to find some integer $a$ so that $O_K = Z[a]$, and then try to find some prime $p \in Z$ which splits completely in $K$ into $(p, l(a))$ (for some linear $l$ by Kummer's theorem) and then analyze the action of $G$ on these ideals. Alternatively, one could try to lift the action of $G$ on the set of Galois conjugates $a_i$ to some ideals $(x + a_i)$, where $x$ is some integer that makes these ideals distinct somehow.
I'm not really sure what to do. Thanks for your help. | The answer is yes. One way to see this is to note that there is a prime $p$ of $\mathbb{Q}$ which splits completely in $K$ (this is proved by analytic methods involving Dedekind zeta functions, and the Chebotarev Density Theorem implies the density of primes which split completely in $K$ is exactly $1/[K:\mathbb{Q}]$.) But the Galois group acts transitively on the primes of $K$ lying above $p$. There are exactly $[K:\mathbb{Q}]$ such primes, hence the action is faithful on the primes above $p$. This can even be generalized to Galois extensions of any number field, and the proof is the same. | stackexchange-math | {
"answer_score": 3,
"question_score": 2,
"tags": "algebraic number theory, galois theory"
} |
How to setup local Ubuntu server that provides security updates to ubuntu desktop systems?
I want to setup local Ubuntu server that download and provide security updates from internet as per requirement of Ubuntu desktop systems connected in local area network. How can I setup such server ? | You could use Ubuntu Server with landscape, which is a control panel to deploy updates and install packages for remote Ubuntu systems. | stackexchange-askubuntu | {
"answer_score": 1,
"question_score": 1,
"tags": "server, updates, apt mirror"
} |
How can I make my loop start a new line every output?
This is what I've got so far. The problem is at the bottom where I'm writing to a file. The data is basically a bunch of arrays I'm pulling values from and I want to write each array to a line, skip a line, and write the next array. I tried adding \n after the %s but it ends up writing everything to the file in a vertical column.
for i in frange(2.0, 7.5, 0.5):
filename = str('pH')+str(i)+str('_calcpka.dat')
readFile(array_pf, filename) ##goes through files and takes data I need
df = []
for i in array_pf: ##does some math and puts into new array..
x = 1-i
df.append(x)
titration_curves = open('titration_curves.dat', 'w') ##writes to file
for i in df:
titration_curves.write("%s " % i) | It looks like `df` is just an array of values, not an array of arrays. What you need to do is get your input into an array of arrays, where every inner array corresponds to one line in the file. Then you do something like:
for df in dfs:
for i in df:
titration_curves.write("%s " % i)
titration_curves.write("\n") | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "python, loops, output"
} |
Color differences between cocoa and photoshop
I'm having some trouble with colors in interface builder and cocoa.
I build out my interface in photoshop, and when I copy the RGB values from photoshop and set my UI elements in interface builder, or through code, the colors are not even close. I've messed around with setting color profiles in photoshop but can't seem to find one that makes a difference (maybe I'm just using them wrong)
Can anyone lend a hand as to how to set photoshop to more accurately depict the colors used by cocoa? This is what I mean:
!enter image description here
I created a box in interface builder and set its RGB to 50, 100, 150, then took a screenshot of it and pasted it into photoshop. Then I created another box in photoshop and set its rgb value to 50, 100, 150. If I sample the IB color, it's RGB comes out to 63, 120, 163. | In Photoshop _colour settings_ choose a _working space_ of
> ColorSync RGB - Generic RGB Profile
Create a new Ps document, in the 'new' dialogue box open up the 'Advanced' tab, for _Color Profile_ :
> Generic RGB Profile
In the Ps _View menu_ make sure you don't have "Proof Colors" enabled.
You should be good to go. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 7,
"tags": "cocoa, macos, colors, photoshop"
} |
Am I a UI designer?
I'm familiar with making mobile apps interface, but only "images". I don't make any code, just images. And the developers need to deal with the other stuff.
Can I say that I'm a UI designer? Or to say this do I need to develop the interfaces in code? | A UI designer is involved in the interface of an app or site. You do not need to know code, but it is recommended to know it, as it will help the design process go smoother and quicker. Some designs may look good, but not function well according to the developer. | stackexchange-graphicdesign | {
"answer_score": 2,
"question_score": 1,
"tags": "interface design"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.