INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Find the $a$ to make the sum of series equal to zero,$\sum_{n=0}^{\infty }\frac{1}{3n^2+3n-a}=0$
Find all values of $a$ which make the sum of series $\sum_{n=0}^{\infty }\frac{1}{3n^2+3n-a}=0$ | Starting from the representation
$$\pi \cot \pi z = \lim_{N\to\infty} \sum_{n=-N}^N \frac{1}{z-n},$$
we obtain
\begin{align} \pi \tan \pi z &= -\pi \cot \pi\left(z-\tfrac{1}{2}\right)\\\ &= \lim_{N\to\infty} \sum_{n=-N}^N \frac{1}{n+\frac{1}{2}-z}\\\ &= \lim_{N\to\infty} \left(\frac{1}{N+\frac{1}{2}-z} + \sum_{n=0}^{N-1} \frac{2z}{\left(n+\frac{1}{2}\right)^2-z^2}\right)\\\ &= 2z \sum_{n=0}^\infty \frac{1}{\left(n+\frac{1}{2}\right)^2-z^2} \end{align}
and
$$\frac{\pi \tan \pi z}{6z} = \sum_{n=0}^\infty \frac{1}{3n^2+3n - 3\left(z^2-\frac{1}{4}\right)}.$$
It should not be hard to find the values of $a$ from that. | stackexchange-math | {
"answer_score": 7,
"question_score": 4,
"tags": "sequences and series"
} |
Replace all hyphens with no spaces before or after it with spaces
I have a table that has a column with probably a few thousand occurrences of a phrase with dashes instead of spaces. For example:
my-name-is-jack
I need to find these occurrences and swap the dash with a space. However, there are other phrases with dashes that have spaces before and/or after them that should not be changed. For example:
stackoverflow - a cool site for developers
How would I do something like this?
*I'm assuming I would do it with Regex, however I've never seen Regex used in Mysql. I'd appreciate any help I can get.
Thanks! | The usual solution is to replace the "substring that should not be touched" with a substring that cannot occur in your data, make the actual replacement, then undo the temporary replacement:
SELECT test, REPLACE(REPLACE(REPLACE(test, ' - ', '^^^'), '-', ' '), '^^^', ' - ') AS result
FROM (
SELECT 'my-name-is-jack - stackoverflow' AS test
) AS tests
-- returns "my name is jack - stackoverflow" | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "mysql, sql, regex, string"
} |
Why does my cat meow at me when I Iaugh?
This is quite a funny and also adorable trait that our seven year old cat has developed over the last year.
Every time I laugh loudly, when friends are over or watching something on TV, the cat rushes from whichever room he's at and looks me in the eyes and starts meowing loud. If I continue he even tries to climb on me.
He doesn't do it with anyone else in the house, just me. I feel like he's more attached to me in general and probably assumes something bad is happening to me and wants to help.
I'm wondering what could be causing his (adorable and funny) reaction. | Cats are very interesting because naturally they are almost never vocal with other cats. Cats almost never meow at each other at all, instead they use body language and more subtle cues to communicate. However, they have learned that humans communicate via loud vocalization, so many cats will mimic their people by "talking" to us in "our own language." In general, cats meow because they know that people prefer to communicate that way.
So what is your cat doing specifically? Here is one theory, although you will likely never know for sure. I would suspect that your cat has noticed that when you laugh, other people laugh too. Cats have noses that are sensitive enough to smell human hormones and emotions, so he has likely noticed that when people laugh together, it makes you happier. My suspicion is that your feline friend is trying to be a good friend and "laugh" with you to be social and make you happy.
It sure is cute :) | stackexchange-pets | {
"answer_score": 8,
"question_score": 4,
"tags": "cats, behavior"
} |
Create drag-able panels in Flex like its in netvibes.com
I want to create a news application for my website.
My question is how should i create drag-able panels/canvas inside another panel/canvas.
What i exactly intend to do can be seen on netvibes.com . The website has different panels of every news group, and this panel could be moved from one place to other, but in a well defined manner. And the other panel take over the place of dragged panel.
Is there any component in flex, which can help me make something like that.
If i was unable to make my question clear, plz let me know, i will try to make it more clear.
Regards Zeeshan | A TileList with drag and drop enabled should be able to accomplish something like that. Or, use a Spark List with a custom layout that you create.
It might be a bit tricky getting the list elements to drag and drop based on clicking the title, but it should be doable. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "apache flex, flex3"
} |
When was the last time that the Cabinet Secretary was a Privy Counsellor?
Simon Case, the British Cabinet Secretary (most senior civil servant) was appointed to the Privy Council on 13 September 2022.
Has it ever happened before that a serving cabinet secretary was a member of the privy council? If so, when was the last time? | The last time this was the case was in 1972, when Sir Burke Trend - then Cabinet Secretary for Ted Heath - became a Privy Counsellor. His appointment was published in the London Gazette on May 23rd, 1972, and he remained Cabinet Secretary until 1973. | stackexchange-politics | {
"answer_score": 8,
"question_score": 2,
"tags": "united kingdom, civil service"
} |
Magento custom option with radio buttons on the same row
I've created a simple product with custom option for size (with radio buttons) instead of a configurable product. My problem is that radio buttons are displayed on different rows.
see here
I want my radio buttons to look more like this
What code should I edit? thank you in advance! | add `float:left;` to stylesheet for `li`:
.product-options ul.options-list li {
/*... yor style here ...*/
float:left;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "magento, radio button"
} |
What does :/ mean in Ruby?
Very basic question here - We are asked to translate the following to the new format, so
"hello".send(:reverse)
becomes
"hello".reverse
What does the `:/` mean in the following?
10.send(:/, 3)
=> 3 | That is a method like `Fixnum#/`. `Object#send` method takes it first argument as method name, which can be either a _symbol_ or _string_.
So you are doing division operation by using `10.send(:/, 3)`, which is nothing but `10/3` (which is a syntactic sugar of `10./(3)`). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "ruby"
} |
sqlite3 index table in python
I have created this table in python 2.7 . I use it to store unique pairs name and value. In some queries I search for names and in others I search for values. Lets say that SELECT queries are 50-50. Is there any way to create a table that will be double index (one index on names and another for values) so my program will seek faster the data ?
Here is the database and table creation:
import sqlite3
#-------------------------db creation ---------------------------------------#
db1 = sqlite3.connect('/my_db.db')
cursor = db1.cursor()
cursor.execute("DROP TABLE IF EXISTS my_table")
sql = '''CREATE TABLE my_table (
name TEXT DEFAULT NULL,
value INT
);'''
cursor.execute(sql)
sql = ("CREATE INDEX index_my_table ON my_table (name);")
cursor.execute(sql)
Or is there any other faster struct for faster value seek ? | You can create another index...
sql = ("CREATE INDEX index_my_table2 ON my_table (value);")
cursor.execute(sql) | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 3,
"tags": "python, sqlite, indexing"
} |
setting number of integers for unlimited argumments
I'm not quite sure what I'm doing here but I need to be able to get an unlimited number of integers to be provided as arguments
so far I have
for sum in $@; do
sum=$(($1 + $2 + $3))
done
echo $sum
output is `5`
and my understanding is that it's taking the positional parameters here but How would I get it to do as many as I would be able to put in?
but when i try and add more numbers `1 2 3 4 `
nothing happens, it just says at `5`
I need to be able to allow for it to loop through an unlimited amount of integers | When you do `for sum in $@` what's happening is that the variable `$sum` is being set to each value in turn.
You can see this with a simple test
for lp in $@
do
echo $lp
done
If you run this with "10 20 30 40" as parameters then you'll see it output each value in turn.
So what you need is a loop with a temporary variable and a sum of the values
sum=0
for lp in $@
do
sum=$(( sum + lp ))
done
echo $sum | stackexchange-unix | {
"answer_score": 2,
"question_score": 0,
"tags": "bash, shell script, scripting, for"
} |
Automatic versioning of web site projects in Team City
At my current client we have some legacy ASP.Net web site projects. I am in the process of introducing automatic versioning for our builds and was wondering of how to best do this with web site projects in Team City?
I am currently using Team City's %build.number% variable (set through project build template) as the authoritative version number for a build. For any .NET project that produces assemblies it's hassle-free to use "AssemblyInfo Patcher" Build Feature in Team City but this does not work for web site projects since they do not produce assemblies.
So, any suggestions? I am already using Powershell and psake in my builds so creating scripts that use %build.number% is not a problem, it is more a question of how to inject this into the web site project in a "nice" manner. | I attempted several solutions but ended up with using the version number of a dependent assembly that gets set by Team City during the build. I added a class to the assembly and it looks something like this:
public class VersionUtils
{
private readonly ILog _logger;
public VersionUtils()
{
_logger = LogManager.GetLogger("VersionLogger");
}
public string GetWebAppVerison()
{
string version = "unknown version";
var assembly = Assembly.GetAssembly(typeof(VersionUtils));
try
{
version = assembly.GetName().Version.ToString();
}
catch(Exception ex)
{
_logger.Warn("Could not find or read version number from " + assembly.GetName(), ex);
}
return version;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "continuous integration, teamcity, versioning, web site project"
} |
Triangle in Circle Problems

* * *
In Fig.2 given that EC & ED are tangents to the semicircle
Prove that EO is perpendicular to AB.
(I found this problem on twitter and was able to solve it through co-ordinate geometry but the steps were too long and complex. There should be an elegant solution) | Fig. 1 is just related to the classical Simson line, whose existence depends on angle chasing.
About Fig. 2, the hint I give you is to consider the intersection of $AC$ and $BD$.
This point $Q$ is collinear with $E$ and $O$ _and_ it lies on the circle through $C,O,D$.
.
* Use a web server other than IIS.
* Use unique IP addresses for each SSL-enabled web site. | stackexchange-serverfault | {
"answer_score": 5,
"question_score": 2,
"tags": "windows server 2008 r2, iis, iis 7, windows"
} |
Check if parent class exists in jQuery and set different var
A website has category descriptions. This descriptions are to long and I made them shorter with jQuery. The wordcount max default value is 7 words
var maxWords = 7;
When the parent css class **expanded** exists
<div class="below expanded">
the var maxWords has to be 20;
var maxWords = 20;
To realise this, I added in my jQuery function this:
if($(this).closest(".below").hasClass(".expanded")) {
{
var maxWords = 7;
} else {
var maxWords = 20;
}
But this did not work.
I made a JSFiddle for you to see the full jQuery Code. The category2 description needs 20 words instead of 7.
To JSFiddle: <
Thank you very much. | just modify code like this:-
var maxWords = 20;
//check with ! and remove . from expanded
if(!$(this).closest(".below").hasClass("expanded")) {
maxWords = 7;
}
Working snippet:- < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "javascript, jquery"
} |
Dimension of nullspace
I can understand the dimension of column space of matrix is the no. of independent column vectors But why is the dimension of nullspace = no. of free variables? | > For an $m \times n$ matrix, $A$, the Rank-Nullity theorem says that: $$ \text{column rank}(A) + \text{nullity}(A) = n.$$ where $\text{nullity}(A)$ is the dimension of the null space of $A$.
When you find the reduced row echelon form of a matrix, the max number of independent columns (i.e. the column rank) is the number of pivot columns (columns containing a leading one for some row). Notice now that free variables correspond to the columns without pivots. So the number of free variables is $n - \text{column rank}(A)$.
So \begin{align*} \text{nullity}(A) &= n - \text{column rank}(A) \\\ &= \text{number of free variables}. \end{align*} | stackexchange-math | {
"answer_score": 5,
"question_score": 1,
"tags": "linear algebra, matrices"
} |
Highlight Rows in an excel document
Is there a way to highlight/fill the cells in row x a given colour from a visual basic application? I can read and write to cells but can't find syntax to format cells or entire rows if possible.
Edit: code for Read/Write
Dim APP As New Excel.Application
Dim worksheet As Excel.Worksheet
Dim workbook As Excel.Workbook
workbook = APP.Workbooks.Open(InputFile)
worksheet = workbook.Worksheets(1)
Read:
Arr(i, 0) = worksheet.Cells(rowcount, 14).value
Write:
worksheet.Cells(row, Col).value = Arr(i, 2) | Yeah you can. Use code like:
`Range("A1").Interior.Color = RGB(255, 0, 0)`
You can set range like.. `Range("A1:A10")`
For all cells in row(1):
`Rows(1).Interior.Color = RGB(255, 0, 0)`
@Edit
Also possible to set colors via _ColorIndex_ for example:
`Range("A1").Interior.ColorIndex = 37` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "vb.net, windows, excel, forms"
} |
Mailkit unexpected disconnection from server when downloading headers from Yahoo Mail
I am trying to fetch IMAP headers from **Yahoo Mail**. It works fine when I try to grab the first 100 headers but it disconnects when I try to get the headers of all 32,000+ emails. I get an exception saying that "The IMAP server has unexpectedly disconnected".
I tried using **Gmail** to grab up to 19,000 headers and it works fine.
Any ideas or is there any limitations? I have included the protocol log here: < | Upgrade your MailKit. The problem is probably that your list of UIDs is too long causing your IMAP server to disconnect.
The latest version of MailKit will break apart the list of UIDs into multiple duplicate commands with smaller subsets of the UIDs in order to avoid creating a command-line that is too long for the IMAP server to handle. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "imap, mailkit"
} |
how to store the object into array and then displays all the objects in the create button elements?
This is my code so far:
var cars=["BMW","MERCEDEZ"];
var arr = [];
for (var j=0; j<= 1; j++){
for (var x=0; x <= 5; x++) {
arr ={
index: a,
name: arr[j] + (x+(5*j)),
price: (x+(5*j))
};
}
}
I want to display all the objects from `arr[]` in the create button elements:
btnShow = document.createElement("input");
btnShow.setAttribute("type", "button");
How do I do this? | you need to add elements to the array not set different object instad of the array
replace
arr = {
index: a,
name: cars[x+(5*j)],
price: cars[x+(5*j)]
};
with
arr.push({
index: a,
name: cars[x+(5*j)],
price: cars[x+(5*j)]
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, arrays, object"
} |
Confusing "override a private method"
I have two question on this code
public class Override {
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
Override po = new Derived();
po.f();
}
}
class Derived extends Override {
public void f() {
System.out.println("public f()");
}
}
/*
* Output: private f()
*/// :~
1) How is function f is visible on the reference of Override po;
2) Why is output "private f()" | 1. The `main` method is inside class `Override`, so ofcourse it can see the private members of class `Override`.
2. You are **not** overriding method `f` in class `Derived`, there is no polymorphism. The type of the variable `po` is `Override`, so it will take method `f` from class `Override`.
Note that method `f` in class `Override` is not visible at all in class `Derived`. The method `f` in class `Derived` is a different method, that doesn't have anything to do with the method `f` in the superclass. | stackexchange-stackoverflow | {
"answer_score": 24,
"question_score": 13,
"tags": "java, overriding, private"
} |
TIdTCPClient to SSL
When I connect to 80 port, plain text web site using TIdTCPClient component, all works fine, data is received without a problem, but, when I connect to 443 port, SSL web site, data **not always** came.
Maybe something with my receive data block ? Need advice.
while not Terminated do
begin
SetLength(data, 0);
ws.IOHandler.ReadBytes(data, -1);
if Length(data) = 0 then
break;
// processing_my(data);
end;
Thanks | Opening the connection to an other port to have it secure is not enough. To connect to anything SSL, you'll need an IOHandler that supports it, such as TIdSSLIOHandlerSocketOpenSSL | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "delphi, delphi xe3"
} |
Table with lot of fields , or table with 1 to 1 relation for search performance
I have a master table with about 100 fields .
In my application there are lot of search queries involve lot of these fields and other child/lookup tables fields.
In database concept as I know it's advised to separate fields according to their logical groups.But in my case this will generate about 10 tables with one to one relation (ie: using lot of join queries when searching).
So I am afraid that this database design slows down search performance .
Any advice ? | No, do not separate the columns into multiple tables unless there is some very clear and specific benefit to doing so. There is none in your case, nor in the great majority of cases. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "mysql, database, database design"
} |
Windows Phone GetUserStoreForApplication exception when clossing aplication
I had done a small application. I am interested to save some data when user click back and close the Applicaiton.
This is classic application even Application will be closed.
private void Application_Closing
{
objSaveData = null;
}
....
public class objSaveData
{
~objSaveData
{
try
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
}
catch
{
}
}
}
The Emulator returns me an error. How can I solve this problem? | It's really simple:
private void Application_Closing
{
//objSaveData = null; // no use
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
... use it to save something
}
public class objSaveData
{
// destructors are called in an unpredictable fashion, usually too late.
// ~objSaveData
// {
// try
// {
// IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
// }
// empty catch blocks hide errors, don't do this
// catch
// {
// }
// }
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, debugging, windows phone 8"
} |
Why can't I add a trendline to a chart in Excel 2007?
I created a really simple chart based on 2 columns (date and numeric value).
I click on the chart, go to Chart Tools/Layout. The Trendline drop down is greyed out.
What am I missing? | 1. Just select the chart you want to add/activate a trendline then
2. click "INSERT" tab just after "home" office tab then
3. click the drop down arrow of "Area" chart type, then
4. select "Area" instead of "Stacked area" | stackexchange-superuser | {
"answer_score": 3,
"question_score": 3,
"tags": "microsoft excel 2007, charts"
} |
How to change the site title font style in wordpress theme Bizberg Consulting Dark
hello guys av been trying to change the font family/ font style of this WordPress theme **Bizberg Consulting Dark** for days now, I have looked for this on all the theme editor files but could not find the solution when I inspected the theme on chrome the front family is currently on
.primary_header_2 h3, .bizberg_header_wrapper h3 {
font-family: Dancing Script;
}
I also tried changing this using the additional CSS option on WordPress but any input I give it doesn't work, but when I try
.primary_header_2 h3, .bizberg_header_wrapper h3 {
display: none;}
The whole of the site title disappears showing that this id is the correct id for this change but when I try to input another type of font-family it doesn't work I have looked for this on all the theme editor files but could not find the solution | in your additional css option in wordpress after the css you should input !important and this will overide all functions the theme is playinging initially eg
.header_site_title {
font-family: Times New Roman !important;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "css, wordpress, webfonts"
} |
Lebesgue integral, Cavalieri's principle
Merry Christmas,
Can you prove my answer:
Let $B_r^n (p):=\\{x\in\mathbb R^n \mid |x-p|\le r\\}$ be the Ball with radius $r\in\mathbb R_{+}$ and origin $p\in\mathbb R$ and dimension $n\in\mathbb N$.
Evaluate $\lambda_3(B_1^3(0)\cap(B_r^2(0)\times\mathbb R))$, when $r\in (0,1)$
Answer: I evalute the internal term: $$B_1^3(0)\cap(B_r^2(0)\times\mathbb R) =\\{(x,y,z)\in\mathbb R^3\mid x^2+y^2+z^2\le 1;x,y,z\in (-1,0)\cup (0,1)\\}$$
And with the Principle of Cavalieri, I get following integral:
$$\int_{-1}^1 \int_{-1}^1 \int_{-\sqrt{1-x^2-z^2}}^{\sqrt{1-x^2-z^2}} \, dy \, dx \, dz=\frac{4}{3}\pi$$
Do you agree? | The fact that the region is within $B_r^2(0)\times\mathbb R$ says $x^2+y^2\le r^2$; the fact that it is within $B_1^3(0)$ says $x^2+y^2+z^2\le 1$. Your condition that $x,y,z\in (-1,0)\cup (0,1)$ fails to say that $x^2+y^2+z^2\le 1$. It is also not at all clear why you excluded $0$.
Your bounds of integration, in $$ \int_{-1}^1 \int_{-1}^1 \cdots\cdots \, dx \, dz $$ fail to constrain the pair $(x,z)$ to the region it should be in.
You could write $$ \iiint_{B_1^3(0)\cap(B_r^2(0)\times\mathbb R} 1 \, d(x,y,z) = \int_0^{2\pi} \int_0^r \int_{-\sqrt{1-s^2}}^{\sqrt{1-s^2}} 1 \, dz \,(s\,ds) \,d\theta. $$ Alternatively, you could use spherical coordinates.
In Cartesian coordinates, one can write $$ \int_{-r}^r \left( \int_{-\sqrt{r^2-x^2}}^{\sqrt{r^2-x^2}} \left( \int_{\sqrt{1-x^2-y^2}}^{\sqrt{1-x^2-y^2}} 1\,dz \right) \,dy \right) \, dx. $$ | stackexchange-math | {
"answer_score": 2,
"question_score": 3,
"tags": "real analysis, measure theory, lebesgue integral"
} |
Linq Order list within a list based on parent Id
Having a list of items I need to sort/order items within that list based on outter list's id
public class Venue
{
public int Id { get; set; }
public string Code { get; set; }
public IEnumerable<Machines> Machines { get; set; }
}
public class Machine
{
public string Name { get; set; }
}
Suppose I have a list of 3 venues and I want to sort only Venue's Machines where Venue.Id = 1; Having a list of venues, I want to always sort by Venue Code, THEN sort machines by Name of Venue with Id = 1;
I tried this but doesn't work correctly:
query = query.OrderBy(x => x.Code).ThenBy(y => y.Machines.OrderBy(q => q.Name).Where(x => y.Id == 1)) | If you want to sort a property of an object which is an `IEnumerable<T>` you need to select a new:
query = query
.Select(v => new Venue
{
Id = v.Id,
Code = v.Code,
Machines = v.Id == 1 ? v.Machines.OrderBy(m => m.Name) : v.Machines
})
.OrderBy(v => v.Code); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, linq"
} |
How can you make a Discord's bot commands not case sensitive?
So I have a Discord bot running discord.py which replies Hello! to anyone saying Hello while the bot is running. The code looks like
if message.content == "Hello":
await message.channel.send('Hello!')
It works, but only if the message is in the exact same case as the original message. I would like it so that if someone said hello, then it would also return Hello! Is this possible, or do I just have to encode every single case of the Hello string? | Simply convert the message content to lowercase, then compare it against lowercase commands. This way no matter how the input was capitalized the bot sees the same result of "hello".
if message.content.lower() == "hello":
await message.channel.send('Hello!') | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, discord, discord.py"
} |
Derivatives of trace of complicated function
When $A$, $B$ and $C$ are positive semi-definite and hermitian symmetric matrices, what is the derivative and second derivatives of $f(x) = tr(x^2 A (xB + C)^{-1})$, for $x>0$ ? | * Consider $f(x) = x^2 A ( x B + C )^{-1}$. Then we have $$ f(x) (x B + C) = x^2 A $$ Differentiating on both sides yields $$ f(x) B + \frac{df}{dx}(x) (x B + C) = 2 x A $$ So we get $$ \frac{df}{dx}(x) = 2 x A (x B + C)^{-1} - x^2 A (x B + C)^{-1} B (x B + C)^{-1} $$
* The trace function is linear. So its derivative is itself.
* Next you combine these derivatives to get the composite function. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "matrices, derivatives, inverse, trace"
} |
How to find indices of NA values in one matrix and remove these indices from another matrix in R?
I have 2 matrix (8760,318).
A = 1 2 3 4
5 6 7 8
9 0 1 11
1 8 3 7
B = NA NA NA NA
NA NA NA NA
1 3 5 7
2 4 6 8
I would like to find the indices of NA values in Matrix B and remove values corresponding to these indices in Matrix A and Matrix B. In the end I would like to have
A = 9 0 1 11
1 8 3 7
B = 1 3 5 7
2 4 6 8
I also would like to protect matrix form (x,318). All methods I have tried so far, broke the matrix form and gave me a vector with 1 row. | For A (lil bit hacky, maybe i will edit)
A[!is.na(B)[,1],]
For B
na.omit(B) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "r, matrix, na"
} |
Possess full down payment at loan application or settlement?
So, we just sent in an offer on a house stating how much we will pay in cash (down payment). I understand that this is transfered to the seller (along with the loan amount) at settlement. However, our next step is to apply for the loan, though we have been pre-approved. Currently, we don't have the exact amount of the down payment in our accounts, however, we will by settlement due to 4 more paychecks coming in.
Does it matter to the lender at the time of loan application, whether the full amount of the down payment is in our possession? | The definite answer is "maybe." A bank can demand that you have all funds readily available X number of days prior to a closing. On the other hand, if you have steady income, and today's shortfall is minimal, a bank may ignore it, and trust that you'll appear at the closing with the proper funds.
This is really a question for the bank. I'm sure members can produce anecdotes supporting an answer that goes either way.
From where I sit, as a Realtor, I'd expect a client to be pre-qualified for the amount they intend to borrow, and have access to funds for the downpayment. If the downpayment wasn't handy, I'd be sure the P&S bought them enough time to get it together and get the funding.
Last - it sounds like you are leaving yourself with no liquidity at all. That's a dangerous path, in my opinion. | stackexchange-money | {
"answer_score": 9,
"question_score": 3,
"tags": "mortgage, down payment"
} |
Given ten letters : K,K,K,S,S,S,S,S,S,S. Find number of ways to arrange given ten letters such that no K should be there between two S?
Given ten letters : K,K,K,S,S,S,S,S,S,S.
How many ways to arrange given ten letters such that **no** letter "K" between two letters "S", example : "KKSSSSSSSK", "KKKSSSSSSS", "SKKSSSSSSK", etc.
I am confused.
I have calculate ways to arrange 10 given letters, $$\dfrac{10!}{3!\cdot 7!}=120 \text{ ways.}$$ Now I want to calculate the complement of "to arrange given ten letters such that no "K" between two "S" ", that is "there is letter "K" between two letters "S"". If I calculate how many ways : $$8\cdot \dfrac{7!}{2!\cdot 5!}=168\text{ ways.}$$
That is impossible, negative number. $$120-168=-48\text{ ways.}$$
How to solve that combinatorics problem? Please help me :( | You don't require the rule for complements to do this. Just count the ways to arrange
* arrange KKK,S,S,S,S,S and placing remaining S one each at the ends.
* arrange KK,S,S,S,S,S,S,S and placing the remaining K at either end. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "combinatorics, combinations"
} |
Remove jQuery AJAX timestamp from query string
How can I remove the jQuery AJAX cache preventer (`_=3452345235`) when dealing with string URLs?
I am writing a global AJAX fail handler and to do this I need to know which URL failed, but everytime I check the URL of the request which failed the jQuery cache query string means all my URLs are different so I need to remove this from the string before doing any more work
So if my URL is (as a string, not `window.location`) is
/device/page/?page=2&_=23523452345
I want to solely remove the timestamp to be left with
/device/page/?page=2 | THis should work for you.
var url = '/device/page/?page=2&_=23523452345';
url = url.replace(/&?_=[0-9]*/, '');
Regards.
**UPDATE**
The first work for at the end and in the middle of the query string but not at the beginning of the query sting `?_=212115211&page=2`.
This regex works for any location of the `_` param.
url = url.replace(/&?_=[0-9]*/, '');
Thanks | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, ajax, query string"
} |
Let $A$ be $m\times n$ and $B$ be $n\times m$ matrix over real number with $m<n$.
> Let $A$ be $m\times n$ and $B$ be $n\times m$ matrix over real number with $m<n$. Then
>
> 1. $AB$ is always nonsingular.
>
> 2. $AB$ is always singular.
>
> 3. $BA$ is always nonsingular
>
> 4. $BA$ is always singular.
>
>
1. False, Since $A=0$, $B=0$ $\implies$ $AB=0$.
2. Need not be true. Let $x$ be $1\times n$ matrix. Since, $x x^T\ge 0$
3. Using the same reasoning 3 can be false.
What is the guarantee that $BA$ is always singular? If $A=x\neq 0, B=x^t.$ Then $BA$ is singular. How do I prove In general? | $BA \in \mathbb{R}^{n \times n}$,
but $rank(BA)\le \min\\{rank(A) ,rank(B) \\} \le m<n$
Hence it must be singular. | stackexchange-math | {
"answer_score": 0,
"question_score": 2,
"tags": "linear algebra, matrices"
} |
PEAR HTML Quickform - Default File Upload path
I am using PEAR HTML Quickform for various forms on my php website.
One of the issue I am having is that if a user select a file to upload (button Browse...) and submit while he forgot to fill a required field, the form is reloaded with all the info and an error message, but for the file. So he has to browse once again that same file before submitting again.
I am wondering if there was something to prevent that, in HTML Quickform or even with other work around you could think of. Basically I imagine trying to default the file path the user selected before submitting. But then again, is it possible to "default" a file field ? | Defaults for a file upload field are not possible for security reasons; this is a browser limitation. Otherwise you could pre-fill a hidden form with `/etc/passwd` or other system files and auto-submit them via javascript :)
* * *
You can only try handle the file even in the case of an form error, and modify the form to not have a file upload field anymore (and show the uploaded file).
But then you also have to clean up in case the form never gets submitted again. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, html, pear, quickform"
} |
How meaningful is the notion of now here on Earth?
Special relativity and the lack of a now moment is causing me a bit of grief.
How meaningful is the notion of now here on Earth between each of us? Does the lack of an objective now moment in any way change how we should think about our friends and family and philosophy between the relationships we form?
My friends' and families' notion of now doesn't ever line up with mine; what does this mean for their conscious perceptions? Am I getting something wrong? | Special relativity has no bearing whatsoever on your day to day activities. If you are moving relative to someone else, then yes in theory you will be time dilated in their frame of reference and they will be time dilated in yours, but the effects at everyday speeds are so utterly minuscule compared with the typical reaction time of your brain that you can ignore them completely.
As for the relativity of simultaneity, that too is dependent on speed but it is also dependent on distance, decreasing with proximity, so the effects are again absolutely negligible in day to day life.
In any event, you should not equate the effects of the relativity of simultaneity with the lack of a common local 'now'. If you are not sure what I mean by that, please post a question of physics SE. | stackexchange-philosophy | {
"answer_score": 13,
"question_score": 2,
"tags": "philosophy of science, consciousness, physics"
} |
"No quotas available" in brand new Azure subscription
We have a brand new (as in, created a couple of days ago and no resources in it yet) Azure pay-as-you-go subscription, and now when I try to provision something, I'm not allowed.
Looking at the subscription in the portal, under "Usage + quotas" the list is empty.
Did we do something wrong when signing up? How do we enable it? | Turns out there were some things I could do myself on this, and some things I had to turn to Azure Support for.
## Thing I could do myself: Enable a bunch of resource providers
It turned out the subscription did not have a single resource provider enabled. To fix, I found the Subscription blade, and clicked the "Resource Providers" menu item (toward the bottom). That opened up a list where I could register lots of stuff. This also enabled corresponding quotas on the subscription.
## Thing I couldn't do myslef: Increase e.g. VM quotas
Some of those quotas, however, I wasn't able to figure out how to turn on myself. Crucially, one of them was for provisioning VM:s (including "hidden" ones, e.g. the underlying VM:s in an AKS cluster or an App Service). Thankfully, Azure Support were really responsive and from first contact until I was able to provision stuff took less than a business day. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "azure"
} |
How to load a script on $(document).ready()
How can I load a JavaScript with this code
<script type="text/javascript" src="
after page has loaded
$(document).ready(function()
{
});
Is there another way? | Try appending the script to the head section: (Working jsFiddle)
$(document).ready(function(){
$('<script/>',{type:'text/javascript', src:'
});
EDIT: I like this syntax better.. | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 2,
"tags": "javascript, jquery"
} |
How to read this Scala declaration?
In Akka HTTP, a route is of type:
type Route = RequestContext ⇒ Future[RouteResult]
How to read this? My understanding is that Route is class which behaves like a function which accepts RequestContext type as parameter and returns a Future. Correct me if I am wrong. | > My understanding is that Route is class which behaves like a function which accepts RequestContext type as parameter and returns a Future
You're almost there. `Route` isn't a _class_ , it's a _type alias_. It doesn't create a new data structure, it allows us to write more concise code which has exactly the same meaning, but usually shorter.
`Route`, as declared, is a function which takes a `RequestContext` and returns a `Future[RouteResult]`, nothing more, nothing less. The upside is that you don't have to write:
def foo(route: RequestContext => Future[RouteResult]): Future[RouteResult]
But can do:
def foo(route: Route): Future[RouteResult] | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "scala"
} |
Jade expression to render image from url sends another request to the server
I have a jade file, where I parse the user data and construct the page. There is a place in this file where I loop through the users' images and render them to the page:
.picture-item(ng-repeat='m in userProfile.media')
img.picture(src='{{m.mediaUrl}}')
But the problem is, even though this line of code shows the image on the page, it send another request to server like below:
`
This happens on: ` page. If I go to a user's profile, let's say: ` then the code above sends a request like:
`m.mediaUrl` are user's instagram image urls.
What could be the problem here? Any ideas?
Thanks in advance. | You are running into a known issue with AngularJS client side late binding.
You can use another attribute for the `img` tag instead:
<
.picture-item(ng-repeat='m in userProfile.media')
img.picture(ngSrc='{{m.mediaUrl}}') | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angularjs, pug"
} |
How to set Xamarin.Forms Label Font Bold
In **Xamarin.Forms** I am using a **Label** and trying to set a **Font**.
The following code works:-
Label label1 = new Label();
label1.Font = Font.SystemFontOfSize(10);
However trying to specify the _Font Attributes_ such like:-
Label label1 = new Label();
label1.Font = Font.SystemFontOfSize(10, FontAttributes.Bold);
is preventing the **ContentPage** from rendering with an exception.
There is a **Font.BoldSystemFontOfSize()** , which could be used, however this is meant to be deprecated, so I am trying to now use **Font.SystemOfSize** instead.
How is it done using this? | Here's a piece of code that works in my project:
new Label {
Text = "text goes here",
Font = Font.SystemFontOfSize (NamedSize.Medium)
.WithAttributes (FontAttributes.Bold),
}
This allows you to not specify a certain font size and instead use the font size used by default for the label | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 25,
"tags": "xamarin.forms"
} |
POSIX timer : Invalid argument
I'm trying to use a POSIX timer, but my code can't run.
timer_t id_timer_;
// some code. timer_create(), etc.
void timerPeriod (unsigned long sec, unsigned long nsec)
{
struct itimerspec myperiod;
myperiod.it_interval.tv_sec = sec;
myperiod.it_interval.tv_nsec = nsec;
myperiod.it_value.tv_sec = sec;
myperiod.it_value.tv_nsec = nsec;
if (timer_settime (&id_timer_, 0, &myperiod, 0))
perror("timer_settime");
}
It returns `timer_settime: Invalid argument`, while arguments are looking good to me.
I also tried `timer_settime(id_timer_, 0, &myperiod, 0)` (without the **&** before `id_timer_`), which I think is the good way to use `timer_settime()` : segmentation fault...
Any clue ? | In ordre to create the timer, the `struct sigaction` must be properly set.
struct sigaction sa;
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = your_handler;
In my previous code, `sa_flags` was set to `0` instead of `SA_SIGINFO`.
More info on kernel.org | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c++, timer, segmentation fault, posix"
} |
Worklight Studio + WAS Liberty Profile 8.5.5 => deploy on WAS ND 8.5.5
As far as I know Worklight Studio does not support integration within IDE with WebSphere Application Server Network Deployment, and we are constrained to use WAS ND 8.5.5 for hosting of application due to corporate hosting environment restrictions.
The plan is to use: Worklight Studio + WAS Liberty Profile 8.5.5 on development machines, and then move the WAR file to corporate hosting environment with WAS ND 8.5.5.
Are there concerns if this may not work? Maybe there are other suggestions on how organize development and debugging of Workligh application (including Java Adapters). | You can see in the IBM Worklight System Requirements website that WAS ND 8.5.5 is supported when it comes to Production environment. It is indeed not supported in Worklight Studio.
As for concerns, as there are current customers in production (live) in very large scales who use WAS ND with Worklight, things seem to be OK.
Related question:
* How to integrate Workligt Studio 6 with WAS ND 8.5.5 in RAD 9 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ibm mobilefirst, worklight studio, websphere liberty"
} |
How to update or write to a file system on Hadoop?
So I am working with a file systems on Hadoop, and I need to make some update to that file system by using path. In this file system, I have different txt format files. I can get to those files by using path. Below I think i can read a text file on Hadoop by using BufferedReader, but untested yet.
fs = FileSystem.get(URI.create(path), conf);
Path pt = new Path(out + "/" + name + ".txt");
BufferedReader each_br = new BufferedReader(new InputStreamReader(fs.open(pt)));
I want to write to a particular file by using the path. I couldn't figure that out. Any ideas how?
Thanks, | You already have the reading down, and the writing is just as simple.
fs = FileSystem.get(URI.create(path), conf);
FSDataOutputStream out = fs.create(new Path("myOutFile"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
That will get you the standard java BufferedWriter. From that you should be able to do anything you want. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "java, hadoop, overwrite"
} |
Migrating code sign certs for android
I have a code cert that is going to expire soon and have recently acquired a new cert from the same provider. I need to transition my android app from the older cert to the new cert. However because the certs are different android requires a full uninstall (deleting app data which I would prefer to avoid).
Due to my client specification I'm unable to use a self signed cert.
Is there a way to transfer without losing the local app data?
I am aware at `adt -migrate` exists but when I use it I get the following error
Migration certificate can only be applied to desktop native installers with native extensions. Target: apk | > Is there a way to transfer without losing the local app data?
No, other than by backing up the data, uninstalling the old app, installing the new app, and restoring the data. If your app does not already have a full backup mechanism, then you are in a world of hurt, if you cannot get the CA to extend the certificate (per flx's answer).
> Due to my client specification I'm unable to use a self signed cert.
That does not change the fact that you need a signing key that will live long enough for the lifetime of the app. And, since certificate authorities do go out of business, so your client should buy a suitably-long certificate now, rather than assuming that an extension can be obtained at any point in the future.
Or, your client should come to its senses and use a self-signed certificate. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "android, actionscript 3, air, flash builder, code signing"
} |
How do you calculate all the values in a column in SQLite (Android) into a new variable for textview?
My database takes in a bill (name, date due, amount of bill) and adds them to a row. So now I populate 5 rows with dummy bills at varying amounts. What I'm trying to do is combine the total of all bills entered into a textview.
So if I row1 bill is $50.00 and row2 bill is $25.00, how can I add them both and connect the total ($75.00) to a textview that will update itself each time a new bill is added or an old bill is subtracted?
Thanks in advance! | You should use a simple `SELECT SUM(ammount) FROM table` on your table, and make that update every time a new row is added. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sqlite, variables, textview"
} |
How to count exactly a word in string in python3?
So I want to count exactly the number of appearances of "100" in python. My example code:
a = " I love 1000 and 100 dollars."
b = a.count("100")
print(b)
The result is 2 but I just want it is 1.
2
[Finished in 0.1s]
Is there any basic tip for that? I'm just a beginner learn python. | If you want to count substrings within the string, the Regular Expression module, `re`, would be useful:
import re
len(re.findall(r'\b100\b', a)) # prints 1
`len` returning the count of how many occurrences `re.findall()` finds, i.e. `1`.
Replace the `100` with the specific substring you wish to count:
b = len(re.findall(r'\bI love\b', a))
>>> b
1
technique borrowed from this answer Find substring in string but only if whole words? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "python, count"
} |
Solr Sunspot -- How to make 2 strings like "Co." and "Company" appear identical?
I have many records that contain abbreviations in a column of names. I might have the record "ABC Brewing Co.", and I want solr to interpret this as being identical to a search for "ABC Brewing Company". Any ideas on how this might be accomplished? | You should look into using the SynonymFilterFactory at index or query time to accomplish this. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "solr, sunspot, sunspot rails, sunspot solr"
} |
How does WindowsPhone10 tell its platform in cordova-plugin-device
I know I can recognize Windows Phone 7 as "WinCE" and Windows Phone 8 as "Win32NT" in cordova-plugin-device with command:
platform === 'WinCE' || platform === 'Win32NT'
but how about Windows Phone 10?
We don't have success on offline storage and I would like to know if there is a miss on this line.
I would like to ask, what is the alternative on that if for WP10? | > does the WP10 platform fall through these ifs or does it need its own?
I just tested it on windows phone 10 and the output of `device.platform` is `windows`: .
Look at Cocoa OpenGL app in C (found using google to search the web) for ideas how to get an OpenGL context. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "macos, cocoa, opengl"
} |
Solving of algebra of the picture
i saw this picture over social network
!enter image description here
put into equation that will be:
Given:
A=rabit
B=Dog
C=Cat
A+C=10
A+B=20
C+B=24
solve A+B+C = ?
some programming logic? what is your answer? | I do not see any programming logic in this, its just Math.
B + C = 24 -A-C = -20
Adding these two,
B-A = 4
Now taking the 1st equation,
A+B = 10 -A+B = 4
Adding both again
2B= 14
**B = 7 Then, A = 3 ( from A+B = 10) and C = 17kgs (from B + C = 24)** | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -4,
"tags": "math"
} |
Report - Periodic
How to design a periodic report in SSRS. I need just logical steps. report looks like below.
Period 1 - 1/1/2014 - 1/15/2014
Origin Destination # of loads Average Billable Average Expenses Average Profit
a b 2 100 50 50
c d 3 300 50 250 | \-- First create a report with two parameter startdate and enddate and then create a Dataset with Query like (change logic according to requirement)... Map the parameter value at DataSet Property
SELECT Origin,Destination,loads,Average(Billable),Average(Expenses),Average(Profit)
FROM Table1
WHERE DateCol BETWEEN @startdate and @enddate
Group by Origin,Destination,loads | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "tsql, reporting services"
} |
Force classes to implement one of a set of methods
Let's say I need a group of classes to implement **all of methods** X, Y and Z to work properly. In that case, I can let them implement a common interface to force that.
Now, my case is a bit different - my classes need to implement **at least one of** X, Y and Z, not necessarily all of them. Interfaces can't help me here. The closest thing I can think of is a common parent - it can check the existence of X, Y or Z in its construcor.
I'd rather avoid inheritance here, because I may need to implement this "interface" in a class that already has a parent. So - is there another elegant way to do this?
(I am working in PHP, but if a general OOP solution exists, it may serve to a broader audience.) | > I'd rather avoid inheritance here, because I may need to implement this "interface" in a class that already has a parent. So - is there another elegant way to do this?
If I understood you correctly, you can solve that issue through Traits:
trait DefaultImpl
{
public function x()
{
echo "Default implementation of x()\n";
}
public function y()
{
echo "Default implementation of y()\n";
}
public function z()
{
echo "Default implementation of z()\n";
}
}
class XImpl
{
use DefaultImpl;
public function x()
{
echo "Custom implementation of X\n";
}
}
$x = new XImpl();
$x->x();
$x->y();
$x->z();
It's not a very good solution from design point of view. But it's better than unnecessary inheritance. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, oop, maintainability, defensive programming"
} |
¿Es "eventualmente" una traducción válida de "eventually"?
Cada vez más oigo y leo frases como:
> No me gustan las patatas, pero sé que **eventualmente** me acabarán gustando.
Para mí esto es un falso amigo de la palabra _eventually_ , que quiere decir _finalmente, al final, con el tiempo_.....
Miré la definición en la RAE y me lo confirma:
> **eventualmente**
>
> 1. adv. Incierta o casualmente.
>
Lo que me hace pensar, por ejemplo, en la palabra _eventual_ y los contratos eventuales.
Pero me pregunto: ¿acaso hay alguna acepción que me pasa desapercibida? ¿Es erróneo usarla como traducción de _eventually_ o puede haber casos en que sí sea válida? | De acuerdo con el Diccionario panhispánico de dudas, No debe utilizarse con el significado de 'al final o finalmente', es decir, no es equivalente con _eventually_
Cito de la referencia:
> No debe utilizarse con el significado de ‘al final o finalmente’, calco censurable del inglés eventually: «Tal vez por eso Castro terminó eventualmente desterrando al Che de Cuba» (DAméricas [EE. UU.] 15.4.97).
Nótese que la oración es un ejemplo de un mal uso de la palabra **eventualmente**
Referencia | stackexchange-spanish | {
"answer_score": 6,
"question_score": 3,
"tags": "traducción, uso de palabras"
} |
How does WF hosted as WCF in IIS 6 resume after delay?
Does a WF hosted as WCF (.NET 3.5) in IIS 6 resume after a delay activity when persisted to SqlWorkflowPersistenceService ? And if so, which kind of thread is being used (one from the ASP.NET worker threads or a background thread from IIS ?) | .NET code never uses "a thread from IIS 6". It's always an ASP.NET worker thread.
In IIS 7 the two are the same. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, wcf, iis 6, workflow foundation"
} |
Searching files based on extension using os.path
I was wondering how to search for files based on their extension. If you were to search for py or txt or some other extension, the user would input it and then it would search for it. I'm not allowed to use glob nor os.walk
This is the method I have. If necessary, I'll post the whole code.
The user first inputs a directory which is in another method after that, they would say
E txt or E .txt (both works) and it would return the files based on what extension you used. I'm not sure what's wrong with my code though. | In your code,
for file in directory
is definitely wrong, as directory is a string with the path in it. it should be something like
for file in os.listdir(directory):
to get a list of files in the directory | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, os.path"
} |
Creating lists using yield in Ruby and Python
I'm trying to come up with an elegant way of creating a list from a function that yields values in both Python and Ruby.
In Python:
def foo(x):
for i in range(x):
if bar(i): yield i
result = list(foo(100))
In Ruby:
def foo(x)
x.times {|i| yield i if bar(i)}
end
result = []
foo(100) {|x| result << x}
Although I love working in both languages, I've always been a bit bothered by the Ruby version having to initialize the list and then fill it. Python's `yield` results in simple iteration, which is great. Ruby's `yield` invokes a block, which is also great, but when I just want to fill a list, it feels kinda clunky.
Is there a more elegant Ruby way?
**UPDATE** Reworked the example to show that the number of values yielded from the function isn't necessarily equal to x. | So, for your new example, try this:
def foo(x)
(0..x).select { |i| bar(i) }
end
Basically, unless you're writing an iterator of your own, you don't need `yield` very often in Ruby. You'll probably do a lot better if you stop trying to write Python idioms using Ruby syntax. | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 3,
"tags": "python, ruby, list, yield"
} |
iOS MDCTextField placeholder text not floating when used in MDCTextInputControllerUnderline
The placeholder is not floating above the textfield, any ideas?:
<
@IBOutlet weak var text: MDCTextField!
override func viewDidLoad() {
super.viewDidLoad()
var textFieldController = MDCTextInputControllerUnderline(textInput: text)
text.placeholder = "TEST"
} | It seems as if you aren't retaining your underline controller. Make it a property (var or let outside a method.) That should keep it around so it can do the work instead of leaving the text field to revert to unstyled defaults. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 2,
"tags": "material components ios"
} |
Twitter Streaming API, how to update user timeline
Please forgive this question if its a bit dumb, but I am new to php and slightly lost.
I am trying to write a little twitter client, where the user's timeline updates come from the Twitter Streaming API (it is not complete but for the sake of design it will do).
The process would be:
User signs up-> I add him to the list of users to track in the Stream -> If I see a message for the user I publish it on his timeline. (The stream listening would happen on the server).
How do I go about doing something like this in php ? It seems a socket server is the way to go (< but then people tend to say its a bit of hack....
Thanks a lot | there is a php class that handels all this for you. see, < Hope this helps. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, api, twitter"
} |
jQuery animation delay not working
I am animating a div when a user hovers over and just wanted a bit of a delay on it but it doesn't seem to add the delay in, is there something i'm doing wrong?
$(".carousel-desc").mouseenter(function () {
$(this).delay(1000).animate({ 'height': '180px' }, { queue: false, duration: 600 });
});
$(".carousel-desc").mouseleave(function () {
$(this).delay(1000).animate({ 'height': '40px' }, { queue: false, duration: 600 });
});
Thanks, J. | I think the problem is `queue: false;` Usally your animation get queued, but you let the animate-function animate immediately.
Maybe this will do what you propably need:
$("#element").mouseEnter(function(){
$("#element").clearQueue();
//other stuff
}
for your stuff:
$(".carousel-desc").mouseenter(function () {
$(this).clearQueue();
$(this).delay(1000).animate({ 'height': '180px' }, { duration: 600 });
});
$(".carousel-desc").mouseleave(function () {
$(this).clearQueue();
$(this).delay(1000).animate({ 'height': '40px' }, { duration: 600 });
}); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "jquery, jquery animate"
} |
Inverting the transformation $u=4xy, v=x^2/y$
I'm trying to invert the transformation $u=4xy, v=x^2/y$. In order to isolate $x$ I did $uv=4x^3$ so $$x=(\frac{uv}{4})^{1/3}$$ and then I substituted this expression into $u=4xy$ to obtain $$y=\frac{u}{4x}=\frac{u^{2/3}}{v^{1/3}4^{2/3}}$$. However, I'm not sure if this is the simplest way I can expression $x,y$ in terms of $u,v$. | Hint: cube $y$, then take the cube root again. It'll look neater that way. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "algebra precalculus, transformation"
} |
Check what image is displayed in an ImageView?
So I know you can set the images of a ImageView like the following (assuming bun_picture is an ImageView):
bun_picture.setImageResource(R.drawable.rawbun);
but is there any way to check what image an ImageView is currently displaying? Something like (NOTE: .getImageResource doesn't exist, I'm just using it to get across what I want to do):
if(bun_picture.getImageResource() == R.drawable.rawbun) == true){
do something}
Obviously that doesn't work, but is there some equivalent I can use?
Thanks | Unless you have called `mutate()` on either of the drawables, you can check if two drawables represent the same image by comparing their `ConstantState` fields.
ConstantState mine = bun_picture.getConstantState();
ConstantState other = ContextCompat.getDrawable(context, R.drawable.rawbun).getConstantState();
if (mine.equals(other)) {
// they are the same
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "java, android, image, android imageview"
} |
How can I express this in another way?
I want to express the following sentence in another way.
> The first algorithm was applied to obtain the norm solution by gradually decreasing the value of X.
Can anyone give me some help? Thank you. | > The first algorithm was applied **over** a gradually decreasing value of X to obtain the norm solution
_Over_ is a good word to use when talking about ranges. | stackexchange-english | {
"answer_score": 1,
"question_score": 1,
"tags": "american english, speech"
} |
Form won't submit return false;
My simple form won't submit after the input and textarea have been filled. edited for readability.
$(function () {
$("#contactform").submit(function () {
$(":input").not("[type=submit]").removeClass('error').each(function () {
if ($.trim($(this).val()).length == 0) $(this).addClass('error');
});
if($(document).hasClass("error")){
return false;
}
});
});
<form id="contactform" action="success.php" method="post">
<input type="text" id="name" placeholder="name" autofocus >
<input type="text" placeholder="email" >
<textarea placeholder="message" ></textarea>
<input type="submit">
</input>
</form> | You should check to see if there are any errors before returning false
$(function () {
$("#contactform").submit(function () {
$(":input").not("[type=submit]").removeClass('error').each(function () {
if ($.trim($(this).val()).length == 0) $(this).addClass('error');
});
// if there is anything with a class of error inside the form
// can also use $(this).find('.error') - it's the same thing
if($('.error',this).length){
// then return false
return false;
}
});
});
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -5,
"tags": "jquery, html"
} |
Get percentage per level
I've created a level system based on posts.
Level 1 = 1-25 posts
Level 2 = 26-50 posts
Level 3 = 51-250 posts, etc...
I also wanted to show a progress bar
Normally you would so something like this:
$author_posts = 15;
$progress = ($author_posts * 100) / 25; //(level 1)
The progress percentage is then `60%`.
But what should I use if user reached `level 3` already?
if( $author_posts >= '250' ) {
$progress = '100';
} elseif( $author_posts < '51' ) {
$progress = '0';
} else {
$progress = // what should I use here?
}
<div class="progress-bar" style="width:<?php echo esc_attr( $progress ); ?>%;"></div> | Your included `if` block implies that a user is at 0% progress until they hit the lower boundary for that level. Can we then assume that none of the previous posts beneath that boundary count as a percentage once it is breached? This means only posts 51 to 250 count as percentage points, giving a range of 200 posts (inclusive). So 1 post = 0.5%.
If so
$progress = round( ( ( $author_posts - 51 ) / 200 ) * 100 )
> 51 posts = 0%
>
> 52 posts = 1% (rounded up)
>
> 200 posts = 75%
A reusable version of this formula could look like
$progress = round( ( ( $author_posts - $lower ) / ( ( $upper - $lower ) + 1 ) ) * 100 )
Where `$upper` and `$lower` boundaries are re-defined within each level. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, progress bar, percentage"
} |
Code markup in Apple Notes app
I am currently running macOS Sierra (10.12.6) and was wondering if there is an easy way to format code (like there is for Title, Heading, etc.) in Apple's Notes app?
I'm open to any workarounds to achieve this. I would like to have syntax highlighting as you would see in a text editor (like Atom or Sublime). | Notes in macOS High Sierra includes a Monospaced format.
> In addition to the existing format types such as Title, Heading and Body, there is a new format named ‘Monospaced’. This format is a variation of the Body format but with a monospaced font family.
>
> ;
imageView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.CENTER);
GlideApp.with(this)
.load(url)
.skipMemoryCache(true)
.fitCenter()
.onlyRetrieveFromCache(true)
.into(imageView);
frameLayout.addView(imageView);
Can Someone help me with it? | You are setting `onlyRetrieveFromCache(true)` which works as below as per documentation
> If the image is found in the memory cache or in the disk cache, it will be loaded. Otherwise, if this option is set to true, the load will fail.
So, If your image at url is not found in cache glide will not load the image. make sure you are having image in cache or do not use this property. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "android, android framelayout"
} |
Javascript - Regex Does not contain some character
I try to regex for not contain some character.
I need to show /%7(.*?);/g which dose not contain "=".
I try to input ?!xx=1 and change to ?!( (. _?)=(._?) ) But it dose not work.
Please help. Thanks.
//Here is my simple regex
reg = /%7((?!xx=1).*?);/g ;
//Here is my string
str = "%7aa; %7bb=11; %7cc=123; %7xx=1; %7yy; %7zz=2;"
//I need
%7aa; and %7yy; | Instead of using a negative lookahead, try using a `^` block:
const reg = /%7([^=;]+);/g;
The `([^=;]+)` bit matches any non-`=`, the condition you're looking for, and non-`;`, the character at the end of your regex.
I left the capture group in since your question's regex also contains it.
const reg = /%7([^=;]+);/g;
const str = "%7aa; %7bb=11; %7cc=123; %7xx=1; %7yy; %7zz=2;"
const matches = str.match(reg);
console.log(matches); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "javascript, regex"
} |
Is it Variation? Counting elements
Lets assume that we have a element, which can have value from 1 till n. (let's set it on 20 to make it easier) And we have the Set, that consists of object, which consists of three elements $\langle e_1, e_2, e_3 \rangle$.
We have also one rule regarding to objects in the set: $e_1 \geq e_2 \geq e_3$ \- example of good objects: $\langle n, n, n\rangle$, $\langle n, n-1, n-1\rangle$, $\langle 20, 19, 18\rangle$, $\langle 3, 2, 1\rangle$, $\langle 3, 3, 3\rangle$, $\langle 3, 2, 2\rangle$.
\- example of bad objects: $\langle n, n+1, n\rangle$, $\langle 2, 3, 2\rangle$, $\langle 3, 2, 4\rangle$.
Now the question: How to count the amount of all good objects, which pass to this Set (they don't violate the rule ) ? Can you give me any hints?
I can solve this with brute force method. But probably there is a short way. | If the first number is $k$, and the second number is $j$, where $j \leq k$ then the last number has $j$ choices.
So the number of favorable cases is $$\sum_{k=1}^n \sum_{j=1}^k j = \sum_{k=1}^n \frac{k(k+1)}{2} = \frac{n(n+1)(n+2)}{6}$$
In general, if you have elements from $1$ to $n$ and want to choose an $m$ element set with the ordering you want the answer is $$\binom{n+m-1}{m}$$ which can be seen by induction on $m$ or by a combinatorial argument as proved here. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "combinatorics"
} |
In languages where you have a choice, is it better to put the main function/method/code at the top or bottom?
When you're writing a program that consists of a small bit of main logic that calls a bunch of supporting functions, you can choose either put the main logic at the top of the file or the bottom (Let's assume the language allows either.) Which is better? Should I put my main logic at the beginning of the file or the end, after all the supporting functions? Is there a significant difference in utility/readability/understandability between the two? | I guess its just a matter of preference. Personally I like to have it at the top, so that as soon as you open the code you can see exactly what its doing and then go to the definitions of the methods from there. I think it makes more sense then opening a file and seeing a bunch of random methods and then scrolling to the bottom to see them actually being called.
As I said, its all preference though. Either:
function myMain(){
methodOne();
methodTwo();
methodThree();
}
function methodOne(){
//code here
}
function methodTwo(){
//code here
}
function methodThree(){
//code here
}
Or:
function methodOne(){
//code here
}
function methodTwo(){
//code here
}
function methodThree(){
//code here
}
function myMain(){
methodOne();
methodTwo();
methodThree();
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "language agnostic, main method"
} |
How can I multiply 2 separate rand values within one argument in Ruby?
I would like to multiply 2 separate random numbers within an argument, to match the following (for example):
> rand(1..6) + rand(1..6)
>
> =>9 (result could be anything between 2-12)
I am in early stages of learning Ruby, so forgive me, but how do I achieve the same with multiplication? For example, the following will only multiply the same random number twice:
> 2 * rand(1..6)
>
> =>2 (will only produce 2,4,6,etc)
Which is what you would expect. But how do I alter that statement to signify 2 separate rand calculations within that range (giving me a possible value between 2 and 12)? Thank you.
EDIT: Solved by using @var **.times** the rand, then doing an element **.push**. This allows me also to display both results individually, as well as doing **.sum** to make the total. | 2.times.sum { rand(1..6) }
or
(1..2).sum { rand(1..6) } | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "ruby, random, calculation"
} |
Eloquent ORM: Select as excerpt
I'd like to perform the following select statement using Eloquent ORM:
SELECT LEFT(title, 200) AS excerpt FROM table WHERE id = 1;
The important part is the `LEFT(...) AS excerpt`. Is there some sort of function (left() doesn't exist) which allows such selections? If not, how do I go about implementing it? | I came up with a solution. If there's a neater way of doing this, please let me know, otherwise I'll stay with the following piece of code:
Post::select(DB::raw('LEFT(title, 200) AS excerpt'))->get();
`Post` is the name of an Eloquent model. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, select, orm, eloquent"
} |
C# stack frames, curly brackets and performance
Do curly brackets always imply a stack frame. Example 1:
{
int b;
}
Obviously a stack frame will be created. So then example 2:
<some code>
{
int a;
<some more code>
}
<yet more code>
I'd assume there will be a stack frame to reflect the scope of `a`.
Example 3:
for (i=0; i<10; i++)
{
<single statement of code>
}
Is a stack frame created for the scope of `i`?
Example 4:
And is it more efficient code-wise to use:
for (i=0; i<10; i++)
<single statement of code>
In generally, my question is does the compiler always create a stack frame when curly braces are used, or does it use intelligence and only create them when required?
[If my knowledge of stack frames seems a bit simplistic, I'm going back 30 years to my degrees, so apologies for that] | When I write this:
int x = 4;
int y = 3;
Console.WriteLine(x + y);
Console.WriteLine(x);
Or this:
int x = 4;
{
int y = 3;
Console.WriteLine(x + y);
}
Console.WriteLine(x);
I still get this in the IL:
.maxstack 2
.locals init (
[0] int32 x,
[1] int32 y
)
There's not an extra stack frame. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, scope, compiler optimization, stack frame"
} |
Android root commands not working in application
I was experimenting with some shell commands on a rooted Nexus 7 tablet and I found that only the commands that seem like they wouldn't need root privilege are being executed.
For example, if I call:
Process process = Runtime.getRuntime().exec("su -c mkdir /sdcard/test");
the directory is created. But if I call:
Process process = Runtime.getRuntime().exec("su -c mkdir /system/test");
Nothing happens.
(I have tried all sorts of commands, and tried all sorts of different syntax in case something was off, but only commands that I wouldn't need root access for get executed)
When I try to execute this command, I get the popup from SuperUser and grant my application root privilege but is there something else that I am missing? I have looked all around and as far as I can tell this should work.
Thanks. | 1. You must quote the argument to `mkdir`, otherwise `su` will assume that `/system/test` is a user name and fail to run.
`Process process = Runtime.getRuntime().exec("su -c \"mkdir /path/to/test\"");`
2. Some areas of the filesystem, such as `/system`, are read only due to the way the filesystem is organized/mounted. Root access won't change that, your command will still fail.
To verify whether what you're trying to do is possible, install a terminal emulator on the device and run the command by hand first. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, shell, command, root"
} |
Select lines based on lines above them
I have a list of items, from which I want to select the names of active items:
item {
status: "Active"
properties {
key_a: value
}
id: 42
name: "Foo"
}
item {
status: "Disabled"
properties {
key_b: value
}
id: 12
name: "Bar"
}
item {
status: "Active"
id: 2
name: "Baz"
}
I know that I can extract the names using capture groups with `pcregrep`:
$ cat list.txt | pcregrep -o1 -i '^ name: "(.*)"'
Foo
Bar
Baz
Using an OR expression, I can also get a list of repeated status values and names:
$ cat list.txt | pcregrep -o2 -i '^ (status|name): "(.*)"'
Active
Foo
Disabled
Bar
Active
Baz
Finally, I need to filter the names in the list based on their preceding lines. How can I do this?
The final output should be:
Foo
Baz | Since most of the heavy lifting has already been done by `pcregrep`, you can now pass on it' s o/p to this short `sed` snippet :
sed -ne 'N;s/^Active\n//p'
which makes `sed` to look at 2 lines at a time, rather than the default of 1. The `N` command sticks the next line to the pattern space by separating with a newline `\n`. Now, only if sed was able to remove the Active first line in the pattern space, is the remaining pattern space going to be printed. This is a conditional print. Otw nothing and `-n` shall ensure no autoprinting of the pattern space. HTH. | stackexchange-unix | {
"answer_score": 1,
"question_score": 0,
"tags": "text processing, grep, pcregrep"
} |
jest - how to check if a word is a english word
I am using Jest to test for a function, which generate a english word.
I tried below but not working. Just want to check if the word is combined by english characters
it("generate a english word", () => {
const word = "APPLE";
expect(word).toMatch('/^[A-Za-z]*$/');
});
What's wrong with it? | This test
expect(word).toMatch('/^[A-Za-z]*$/');
tries to match the **string** `'/^[A-Za-z]*$/'`. You want to pass it as a regular expression instead
expect(word).toMatch(/^[A-Za-z]*$/);
The lack of quotation marks in the second case makes all the difference.
Here is the link to the documentation < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, reactjs, jestjs"
} |
/bin/login not working when run on console as root user
when login command is executed it doesn't accepts root login , here the log of my console is copied once see it and helps me. But succeeds using another user ( sai ) .
root@sai:~# login
sai login: root
Login incorrect
sai login: sai
Password:
Last login: Thu Jan 5 11:25:38 IST 2017 on pts/28
Welcome to Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-103-generic x86_64)
########* Documentation:
inet addr:192.168.2.198 Bcast:192.168.2.255 Mask:255.255.255.0
inet addr:127.0.0.1 Mask:255.0.0.0
inet addr:172.16.201.1 Bcast:172.16.201.255 Mask:255.255.255.0
inet addr:192.168.206.1 Bcast:192.168.206.255 Mask:255.255.255.0
391 packages can be updated.
50 updates are security updates.
sai@sai:~$
anyone please explain what's happening here ? | configure login source file in busybox source as to take rules from file with name `<service-name>` and compile, then write the configuration or rules in file `/etc/pam.d/<service_name>`. I added configuration settings to that file. Then it is Working Fine.
refer this link < for more information.
Thanks for the comments. | stackexchange-askubuntu | {
"answer_score": -1,
"question_score": -1,
"tags": "login, root, pam"
} |
Can Space Eagles be earned?
In Angry Birds: Space, can you earn Space Eagles without purchasing them? The Game Center achievement reads like you have to purchase them, and there are other achievements tied to the Space Eagle. I'm wondering if you have to purchase them to complete the other achievements tied to the Space Eagle. | Yes: So far I've earnt 6 space eagles (in batches of three each time) through gameplay/3 star levels.
I've currently completed up to 2-11 and they did seem to come at major points: first unlocked golden egg/ 10 worlds and after the first boss fight. | stackexchange-gaming | {
"answer_score": 7,
"question_score": 10,
"tags": "angry birds space"
} |
Laravel query two table
Hello just a question from a newbie i just to query this two and i want the second table to be inside the array of the other table.
the table looks like this
bulletin
|d : 1"|
|content: "test"|
|id : 2|
|content: "test2"|
images
|id : 1|
|bulletin_id: 1|
|upload_name: 1.jpg|
|id : 2|
|bulletin_id: 1|
|upload_name: 2.jpg|
|id : 3|
|bulletin_id: 2|
|upload_name: 3.jpg|
|id : 4|
|bulletin_id: 2|
|upload_name: 2.jpg|
my query looks like this
$bulletin = DB::table('bulletin')
->select('bulletin.id','content','upload_name')
->join('images', 'images.bulletin_id', '=', 'bulletin.id')
->get();
is it possible to get this data look like this
array
(
id:1,
content:test,
upload_name:array
(
1.jpg,
2.jpg
)
) | First define your models.
php artisan make:model Bulletin
php artisan make:model Image
**App\Bulletin.php**
protected $table = 'bulletin';
Then the relationship:
**App\Bulletin.php**
use Image;
//
public function upload_name()
{
return $this->hasMany(Image::class);
}
So now you can query your objects:
**app\Http\Controllers\BulletinController.php**
public function index()
{
$bulletins = Bulletin::with('upload_name')->get();
return $bulletins;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "laravel, model view controller"
} |
jsfiddle is blank
> **Possible Duplicate:**
> not seeing code on jsfiddle, only result
I have this weird issue where on multiple browsers, the coding (HTML, JS, CSS) does not show. The result of it does and it does work. But I don't have the coding if I go to for example
<
<
I am not simply going to the page and deleting the coding.
Any idea on what has happened?
Thx | Reloading your cache should fix the issue. Let me know if that helps.
Also you can report your issue here. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "jsfiddle"
} |
How to implement a median split of an ArrayList
I am trying to return an ArrayList of values above the median of a column. For example I have a list of objects like:
List<ObjectX> where
Object X has a value v such that v=25.
Object X has a value v such that v=15.
Object X has a value v such that v=5.
Object X has a value v such that v=35.
My attempt:
public static ArrayList<ObjectX> medianSplit(ArrayList<ObjectX> data,boolean lowerHaf){
Collections.sort(data);
return data.subset(0,data.size()/2);
}
This is not a school project, and I able to use any code, my attempt was based off another SO post. | This seems to work using subList
public static void main(String args[]) throws IOException {
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(232);
list.add(4);
list.add(89);
list.add(77);
list.add(12);
list.add(19);
List<Integer> lowerHalf = medianSplit(list);
System.out.println("list: " + lowerHalf);
}
public static List<Integer> medianSplit(List<Integer> data) {
Collections.sort(data);
return data.subList(0, data.size() / 2);
}
Output:
list: [2, 4, 12]
BUILD SUCCESSFUL (total time: 0 seconds) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "java, arraylist"
} |
Batch File to open a custom Directory
I'm trying to create a batch file that asks the user for a directory, and opens that directory. But, it keeps opening "My Documents" instead! Here's my Code:
`@echo off set /p DIR= "Enter a Directory: " %SystemRoot%\explorer.exe "%DIR%"` | Try doing
@echo off
set "dir="
set /p "DIR=Enter a Directory: "
if defined DIR start "" "%DIR%" | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "batch file"
} |
Display results of a query before query itself
I have this query:
<?php
echo $grand_total; // info on top of page
$getinfo = mysql_query("SELECT * FROM sales");
while($rows = mysql_fetch_assoc($getinfo)){
$price = $rows['price']; // I want this to be display on top of my page before this query
$quantity = $rows['quantity']; // I want this to be display on top of my page before this query
$total = $price * $quantity;
$grand_total += $total;
}
?>
I want to display the result of this query on the top of my page. Thanks in advance :)
!enter image description here | Using Javascript will likely work.
<div id="grandtotal">0.00</div>
<?php
$getinfo = mysql_query("SELECT * FROM sales");
while($rows = mysql_fetch_assoc($getinfo)){
$price = $rows['price']; // I want this to be display on top of my page before this query
$quantity = $rows['quantity']; // I want this to be display on top of my page before this query
$total = $price * $quantity;
$grand_total += $total;
}
?>
<script>
// I am using jQuery here. Traditional js will work
$('#grandtotal').html('<?php echo $grand_total; ?>');
</script> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -7,
"tags": "php, mysql"
} |
How do I add time from a database in Rails?
I am fairly new to rails, and attempting to add an amount of time to a datetime in the database. The time and time unit both are returned from the database.
So the data is...
start: 11/1/2015 10:45:00
duration: 75
unit: "minutes"
I want to add the 75 minutes to the start. I know I can do this if I know them already by saying start + 75.minutes, but how do I do this when both the duration and the unit are variables? | Use `send` method:
start + duration.send(unit) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "datetime, ruby on rails 4"
} |
Call stack of x86 saving a single byte
I'm currently learning x86 assembly with "Guide to assembly language in Linux" and on page 241 there is written that only 16 bit words or 32 bit words are saved onto the stack, but is this true? I mean in C a char array consists of single bytes and those are saved onto the stack as C consists of functions which use the call stack, right? So what am i getting wrong? | Even bytes are padded with zeros and converted to 16 bit or 32 bit words before being pushed.
Consider the stack as pile of plates of particular size (16 or 32). Is there a way you can push half the size plate .. No ? Even if you want to push the half the size, you would pad it to make the full size plate and then push it. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "c, assembly, stack, x86, callstack"
} |
Is it an acceptable idea that I write HTML codes into JS codes?
Every website has some static codes which always are constant. For example header, footer, advertising box and ...!
Well I want to write all those static HTML codes into JS file, and as you know it will be catch. So loading will be faster. I mean Why user should download my fixed HTML codes all the time? I think I can catch them by that trick I mentioned.
However I don't have a lot of experience in this field. So will not I faced with some problems later if I do that? | Mixing up view (HTML) and business logic (JS) is an anti-pattern as it violates Separation of Concerns. That said, it depends most on which kind of code you are mixing within the view: is it strictly related to that view's rendering?
If though your motivation is _loading will be faster_ I think you are doing it wrong. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -1,
"tags": "javascript, html, performance"
} |
How strong CodeIgniter is comparing to Zend Framework? especially for developing a hotels directory portal
When I decided to start using php framework, I have gone for CodeIgniter because of I didn't have much learning time, I had strict project dead-line. I actually wanted Zend Framework so much. I'm happy with CI so far... But I'm about to start a big hotels directory project like kayak.com . My project will not have so big db of course, but structure will be similar.
Now I worry if I make mistake to start such project with CI :-S Would it be pain in ass at the project development process. I'm not sure how strong and reliable CI is for such projects :/
I appreciate advices so much!! thanks!! | Both have there pros and cons, ZF is a much stricter framework the CI, in that CI themselves say that you need not use models (which is a bad habit to get into). Zend has far greater supporting libraries, the authentication libraries for CI are pretty poor to be honest, while zends authentication is pretty, it comes with an ACL library as part of its core. My choice would be Zend.
====In response to your comment=====
I would think that if you have used CI then you have some knowledge about MVC even if you CI has put you in a habit of using it badly. Zend has amazing documentation and support so any stumbling blocks you may reach in the convertion from CI to Zend would easily be solved. It may cause a few sleepless nights, but surely that is small price to pay for adding another feather to your cap? | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "zend framework, codeigniter, portal"
} |
Openpyxl: listing all defined names of a workbook
I am trying to read in all the data contained in named ranges in a xlsx workbook across multiple sheets, but for the purposes of this exercise, I don't know what the names of any named ranges will be ahead of time.
I can access `wb.defined_names` but this returns a DefinedNameList; if I try to iterate over it I don't seem to be able to access any of the data underneath.
**How can I access the names of named ranges and the corresponding cell references as a list of strings?**
Context: Up until now I have been achieving this with xlwings, but am having issues with xlwings opening a wb whilst I have other wb tabs open. Switching to openpyxl seems like a good possible solution if I can fix this issue | [dn for dn in wb.defined_names.definedName] | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 3,
"tags": "python, openpyxl"
} |
$a>0$, & let $x$ be a real number. Prove that if $\{r_n \}$ is decreasing rational sequence with limit $x$, then $a^x=\cdots$
Let $a>0$, and let $x$ be a real number. Prove that if $\\{r_{n} \\}$ is any decreasing rational sequence with limit $x$, then $a^x = \lim_{n \rightarrow \infty} a^{r_n}$
Where in the book $a^x$ is defined as $\lim_{n \rightarrow \infty} a^{s_n}$ where $ \\{ s_n \\}$ is an increasing sequence. | Note that $\\{-r_n\\}$ is an increasing sequence of rationals that converges to $-x$
Using the definition of your book, we know that: $$lim_{n\rightarrow\infty}a^{-r_n}=a^{-x}>0$$
Since the limit is positive, thus: $$lim_{n\rightarrow\infty}a^{r_n}=a^{x}$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "real analysis"
} |
How to get a Type.Name that includes generic parameters?
`new List<int>().GetType().Name` is List`1. How do I get a name more like `List<int>` ( **not** `List<T>`)? | One way would be using `new List<int>().GetType().ToString()`, which returns `System.Collections.Generic.List`1[System.Int32]`.
Or you could write yourself a small helper method along the lines of:
string GetShortName(Type type)
{
string result = type.Name;
if (type.IsGenericType)
{
// remove genric indication (e.g. `1)
result = result.Substring(0, result.LastIndexOf('`'));
result = string.Format(
"{0}<{1}>",
result,
string.Join(", ",
type.GetGenericArguments().Select(t => GetShortName(t))));
}
return result;
}
which outputs strings like:
List<Int32>
List<T>
Dictionary<List<Double>, Int32>
Tuple<T1, T2, T3, T4>
Note that for nested types, this would return only the innermost name. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": ".net, reflection"
} |
How can PCI-E 4x network card support 10GB/s speed?
This card <
Manufacturer claim this is 10GB/s card:
* 10 Gigabit throughput with 100-meter UTP cable
* PCI Express rev. 2.0 Specification x4 interface
Now wikipedia say, that 4x PCI-E slot revision 2 supports max 2.0 GB/s bandwidth. So how is this card supposed to work? Is the wikipedia wrong? Or manufacturer lying? Or is there some black magic I am not aware of?
<
 is 16 gigabits per second (Gb/s). Hence the PCIe x4 slot can easily support 10 gigabit with, in theory, 6Gb/s spare. | stackexchange-superuser | {
"answer_score": 2,
"question_score": 0,
"tags": "networking, pci express"
} |
C# XMLReader ReadString how to read everything include nested xml in an element?
My xml file with sample data as following
<FRUIT>
<HTML><B>1.</B> Apple</HTML>
<HTML><B>2.</B> Banana</HTML>
</FRUIT>
and my code
XmlReader xmlr = XmlReader.Create(myxmlfile);
while (xmlr.Read())
{
if ((xmlr.IsStartElement()) && (xmlr.Name == "HTML"))
{
// this will return blank string!
html = xmlr.ReadString();
}
}
I need to get the full string of `<B>1.</B> Apple`
How could I read everything inside HTML element with ReadString()? | If the structure is fixed and you know the elements before then you can do this:
List<string> bananas = new List<>string();
string contents = string.Empty;
xmlr.ReadToFollowing("HTML");
do
{
contents = xmlr.ReadInnerXML();
if(!string.IsNullOrEmpty(contents))
{
bananas.Add(contents);
}
}while(!string.IsNullOrEmpty(contents))
Also read XMLReader on MSDN.aspx) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, xml, xml parsing, xmlreader"
} |
File no longer available when trying to edit in vim via <()
When working with mercurial, I frequently do things like
vim <(hg cat -r 42 somefile)
However, if I try this with a file larger than several hundred lines, I get a Read Error in vim, and only the first couple of hundred lines are included. If I use gvim instead of vim, I get an error like
E211: FIle "/proc/3546/fd/63" no longer available
Isn't this supposed to work? I don't know if it's relevant, but I've tried both in bash and zsh, with the same result, and I also tried
cat <(hg cat -r 42 somefile)
which prints the entire file as I would expect. | Those are pipes, not regular files. It goes away when `vim` closes the file descriptor. You could do:
hg cat -r 42 somefile | vim -
(there `vim` is told it may not be a regular file so behaves accordingly. Use `vim -R -` or `view -` if you don't want `vim` to complain that the data has not been saved on exit).
Or with `zsh`, using a temporary file:
vim =(hg cat -r 42 somefile) | stackexchange-unix | {
"answer_score": 2,
"question_score": 2,
"tags": "shell, vim"
} |
Integration by parts, any help?
How may I calculate Integration by parts for the following multivariable function?
$$I_n(x)=\int_{a}^{x} (x-t)^{n}f(t)dt$$ | I can write out the formula for you, I guess, assuming that $F' =f$ exists: $$ \int_a^x (x-t)^n f(t)dt = \int_a^x (x-t)^n dF(t)t = [(x-t)^n F(t)]_a^x + \int_a^x n(x-t)^{n-1} F(t) dt $$ so that $$ \int_a^x (x-t)^n f(t)dt = -(x-a)^n F(a) + \int_a^x n(x-t)^{n-1} F(t) dt $$ Is that what you are looking for? Does $f$ have any other properties, like those of a CDF, for example? | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "calculus"
} |
How can I block user interactions with the background views while modal transitions popup shows in swiftUI?
I want to block tapping views in background of my modal transition popup. How can I achieve this in swiftUI? (my example modal transition < | You can add `.disabled(Bool)` in your background view with a @State Boolean variable. As-
struct HomePageSwiftUIView: View {
@State private var isModalShowing: Bool = false
var body: some View {
VStack() {
// Your background view
}
.disabled(isModalShowing)
VStack() {
// Your background view
}
.disabled(isModalShowing)
VStack() {
// Your popup view (Dont add it)
}
}
}
While clicking alert button just set `isModalShowing = true` and also `isModalShowing = false` when alert dismissed. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios, swift"
} |
AWVERIFY not propergating
Yesterday at about 3pm, I setup awverify records for two website I want to transfer from one Azure account to another. By the end of the day Azure still wasn't allowing me to add my domains, so I took a gamble and re-pointed the domain and www sub-domain to the new IP. This morning of course my sites were down and Azure still won't accept my domains. I've had to point the domain and www sub-domain back to the old IP.
Obviously I'm expecting the response that the awverify CNAME hasn't propagated, but my DNS, and others I checked online, changed within an hour. Why would Azure take 18 hours and counting?
I'm quite sure I've set it up correctly... !Azure error requesting AWVERIFY CNAME
!DNS lookup for AWVERIFY showing the correct CNAME
!DNS control panel | I found the answer, though I can't find this documented elsewhere. The cause of the issue is that I was migrating from one Azure account to another. It seems that Azure will not allow two website (even in different accounts) to use the same host names.
Once I deleted the host names from the old account, I was able to add them to the new account.
I can see why this would be the case, but it should be documented somewhere as I can't be the first person to run in to this. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "azure, dns, azure web app service"
} |
jquery : alternate row colour in table except cell with class to keep background colour
I am new to jquery. I have this in my code:
$("tbody tr:odd ").addClass("alt");
with css:
tbody tr.alt td {
background-color: #e6EEEE;
}
I have a cell in table with
<td class="coloron">
Right now, the every other row command is over riding my class="coloron".
How can I maintain my cell unique colour while having every other row colouring? | Define the styles so that your unique color is defined **later** in the stylesheet, like this:
tbody tr.alt td {
background-color: #e6EEEE;
}
tbody tr td.coloron {
background-color: #FFFFFF;
}
If a row has multiple classes, given the same level of specificity in the style rule, the one defined last in the CSS wins. You can see it working here. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "jquery, css, css specificity"
} |
Disabling version suffix/extension in autoconf or makefile
Currently large library i am compiling on Linux outputs shared library as:
libxxx1.1.so.0.0.0
Problem arises when i try to load it in java's System.loadLibrary(..);
What can i do to make compiled so be simple libxxxx.so? | I believe you want the `libtool` `-avoid-version` flag... assuming you are using `libtool` for this. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, linux, makefile, shared, autoconf"
} |
How to split list of words into 2d array of letters?
What would be right syntax to create a 2d array `letter[x][y]` with all the letters of `String words`? x = ordinal of word and y = ordinal of letter of the word-x i.e. `letter[1][2]` would be 3rd letter of "Eraser" which is "a"
This is what I tried:
String words = "Pencil Eraser Scissors";
String[] separate = words.split(" ");
String[][] letters = separate.split(""); | String[][] letters = separate.split("");
That wouldn't compile since arrays don't have a `split` method.
I would use a 2D char array to accomplish this.
String words = "Pencil Eraser Scissors";
String[] wordsSplitted = words.split(" ");
char[][] lettersByWord = new char[wordsSplitted.length][];
for(int i = 0; i < lettersByWord.length; i++){
lettersByWord[i] = wordsSplitted[i].toCharArray();
}
System.out.print(Arrays.deepToString(lettersByWord));
Prints:
[[P, e, n, c, i, l], [E, r, a, s, e, r], [S, c, i, s, s, o, r, s]] | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "java, arrays, string, 2d"
} |
"As though" PLUS "if"
Is it grammatically correct to use "as if/though" in the same sentence with an if-clause? For example, "He wanted to explain himself. As if/though IF they knew the truth, they would forgive him." If not, is there any way to go about it? Could you just omit the second "if" and say: "As if they knew the truth, they would forgive him," implying that that's what he hoped for, but they probably wouldn't. Or maybe replacing "as if" with "like" would work? "Like if the knew the truth. . ." | Nothing wrong with:
> He wanted to explain himself. As though if they knew the truth, they would forgive him.
Your alternative:
> He wanted to explain himself. As if if they knew the truth, they would forgive him.
is a little more problematic. I'm not sure the phrase "as if" used in this way is grammatically correct, though it is certainly colloquial. Other than that the phrase is as grammatically valid as the other one, but is very hard to parse and _sounds_ strange, requiring a re-read to understand. | stackexchange-english | {
"answer_score": 2,
"question_score": 1,
"tags": "grammar, grammaticality"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.