INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Let $S$ be a semigroup that satisfies the property $\forall a \in S, aS=S \wedge Sa=S$. Show that $S$ is a group.
Let $S$ be a semigroup that satisfies the property \begin{align*} \forall a \in S, \quad aS=S \wedge Sa=S. \end{align*}
> I want to show that $S$ is a group, ie, that $S$ satisfies
>
>> (1) $\exists e \in S \quad \forall a \in S : \quad ea=ae=a$;
>>
>> (2) $\forall a \in S \quad \exists b \in S : \quad ab=ba=e$.
However, I can only show that
(1') $\exists e \in S \quad \forall a \in S : \quad ea=a$;
(2') $\forall a \in S \quad \exists b \in S : \quad ba=e$.
With what I've shown, is it possible to state that $S$ is a group?
|
Take $a$ in $S$. We have $e\in S$ so that $ae=a$ (Because $aS=S$).
Now take $b\in S$. we have $s\in S$ so that $b=sa$ (Because $Sa=S$). Therefore $be=(sa)e=s(ae)=sa=b$. So $e$ is a right identity.
Let $a$ be as above,we have $e'\in S$ so that $ea=a$ (Because $Sa=S$).
Now take $b\in S$. we have $s'\in S$ so that $b=as'$ (Because $aS=S$). Therefore $e'b=e'(as')=(ea)s'=as'=b$. So $e'$ is left identity.
Now notice $e=e'e$ because $e'$ is left identity and $e'e=e'$ because $e$ is right identity. So $e=e'e=e'$ and $e$ is identity.
Take $b\in S$, we have $c$ so .that $bc=e$ and $d$ so that $db=e$ because $bS=S$ and $Sb=s$.
Now notice $c=ec=(db)c=d(bc)=de=d$ and so $c=d$ is the inverse of $b$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "group theory, semigroups"
}
|
Java: What is the property of a JOptionPane object that prevents clicks below itself?
I have created my own JOptionPane using a JDialog, but I can't seem to replicate the behavior of a typical JOptionPane that disallows the user from clicking anywhere but the JOptionPane window.
What property of JOptionPane do I need to replicate with a JDialog so that I can mimic this behavior? (I am aware that JOptionPanes are simply specialized JDialogs, as you can see if look at the JOptionPane class source code).
|
It is nothing more than a **_modal_** JDialog and it's the modality that gives it this property. You cannot replicate this directly without creating and using a modal JDialog as far as I know. You must be sure that the JDialog is set to refer to the correct parent window (often a JFrame) and that its ModalityType is set correctly.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "java, swing, modal dialog, joptionpane, jdialog"
}
|
Is it possible to read a script value?
I'm new in python. I have a question can I read a script value with python.
import requests
from bs4 import BeautifulSoup
import json
url='
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
print(soup.find_all('script')[9]["cp30"])
|
You're going to have to parse the javascript yourself. For this particular value, the simple script below works. For other values such as arrays or objects, parsing will be not as simple.
import requests
from bs4 import BeautifulSoup
import json
url = '
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
for e in soup.find_all('script'):
if not e.string: continue
for line in e.string.splitlines():
if 'cp30' in line:
_, value = line.split(':')
value = json.loads(value)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, python, python 3.x, beautifulsoup"
}
|
Prove $K(\mathbb{Z}^n,2) = B\mathbb{T}^n$
I want to proof statement $K(\mathbb{Z}^n,2) = B\mathbb{T}^n$, how can I do that? I need to use Chern classes or something like that? Hope for your help.
|
Let $X$ be a topological space, a map $f:X\rightarrow B\mathbb{T}^n$ defines a $\mathbb{T}^n$-bundle over $X$, defined by $1$-cocycle $c\in H^1(X,\mathbb{T}^n)=H^2(X,\mathbb{Z})$. This follow from the exact sequence $0\rightarrow \mathbb{Z}^n\rightarrow\mathbb{R}^n\rightarrow \mathbb{T}^n\rightarrow 1$; since $\mathbb{R}^n$ is contractible, the long exact sequence in cohomology gives $H^n(X,\mathbb{T^n})=H^{n+1}(X,\mathbb{Z}^n)$.
Since $K(\mathbb{Z}^n,2)$ represents the $2$-singular cohomology with coefficients in $\mathbb{Z}^n$; that is the set of homotopy classes of maps $[X,K(\mathbb{Z}^n,2)]=H^2(X,\mathbb{Z}^n)$ we deduce that $B\mathbb{T}^n=K(\mathbb{Z}^n,2)$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "algebraic topology, classifying spaces"
}
|
Is it proper to speak of non-existent objects?
I hear a lot of people say things like "The set of all sets does not exist". But this seems to be improper to say. I think one should really say that "There does not exist a set of all sets". Anyway, what I am really asking is, are there any philosophers who think that talk of non-existent objects is merely a language game? And if so, can anyone direct me to such a paper? I am only using the set theory example merely as one example. I could just as well have used "unicorns", "Santa Claus", or "Harry Potter".
|
Speaking of non-existent objects has been a major source of confusion. Bertrand Russell caught this language bug and developed his famous theory of description. Basically, it says:
1. A name that does not have a corresponding object is called nonsense. It is not OK to speak nonsense.
2. If an object is spoken of in the form of "the so-and-so," that object is mentioned by description, where "the so-and-so" can be interpreted as "the x that satisfies ϕ(x)."
"The so-and-so does not exist" means "for all the x's, ϕ(x) is false." It is OK to speak of non-existent object by means of description.
See Why are propositions about Hamlet false while propositions about Louis XIX meaningless?
|
stackexchange-philosophy
|
{
"answer_score": 5,
"question_score": 6,
"tags": "reference request"
}
|
How to set MySQLdb Connection timeout to infinity in python
I am doing some task on database after every 10 hours . I have connected to database only one time at the start of the script. after 10 hours database connection gets timeout. I can use other method here but i want to know that how to set Connection timeout to infinity . After 10 hours i am getting an error which is given below .
**Code:**
import MySQLdb,time
db = MySQLdb.connect("hostname", "user", "password", "db_name")
while True:
db.commit() # to refresh database
cursor = db.cursor()
cursor.execute("some query here")
db.commit()
cursor.close()
time.sleep(36000)# Wait for 10 hours
**Error**
> OperationalError: (2006, 'MySQL server has gone away')
|
The problem is the connection is closed from the db server side, what you have to do is;
* Changing the timeout of mysql Or more usefull
* Just reconnect to the db again in your loop
If you use linux you can use cron to launch your script every X sec, if you use windows use the scheduling task service to launch the script when you desire.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, mysql"
}
|
How to add a HtmlPrefix to Views Using MVC Actions?
I have the following action to call the Multiple partial Views in a Single page.
public ActionResult AddDetail(string Key)
{
var viewData = new ViewDataDictionary(ViewData)
{
TemplateInfo = new System.Web.Mvc.TemplateInfo
{
HtmlFieldPrefix = string.Format("{0}", key)
}
};
return View(key);
}
[View]
@model Customer
@Html.TextBoxFor(model=>model.Name)
The above code gives me the html rendered as
<input type="text" name="Name"/>
But, I wants to have
<input type="text" name="Customer.Name" />
If I pass the `AddDetail("Customer")` action.
I don't know how to get the `ViewContext` and append the `Prefix` to the Views.
Could someone please help me to add a prefix?
|
Try this :)
public ActionResult AddDetail(string Key)
{
ViewData.TemplateInfo.HtmlFieldPrefix = string.Format("{0}", key)
return View(key);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, asp.net mvc 3, razor"
}
|
SQL Select Certain Value First
SELECT AssetValue
FROM Assets
WHERE (AssetType = 'Country')
Very simple Select Statement, but it outputs
Afghanistan
Albania
Algeria
....
How do I make United States and Canada appear on the top of this? Is this possible with SQL or do I need to do something in my ASP code? My PK is a INT Identity.
|
SELECT AssetValue
FROM Assets
WHERE (AssetType = 'Country')
ORDER BY CASE AssetValue
WHEN 'US' THEN 1
WHEN 'Canada' THEN 2 ELSE 3 END, AssetValue
|
stackexchange-stackoverflow
|
{
"answer_score": 23,
"question_score": 6,
"tags": "sql, sql server, sql server 2005, select"
}
|
Powershell extract string start with
I have a txt file with following content:
testdemo | 5 | 4563456| OMNI | retailomni
testRetail | 142 | 3453456345| testRetai111l | test
testtesttest | 44 | 4564356| apl | APL
I need to select whole string, that starts from "testdemo". How this can be done in PS?
$operator = "testdemo"
$operatorcontent = Get-Content operators.txt | "Need to get whole string, starts from $operator"
|
You can use `Select-String` cmdlet.
Get-Content operators.txt | Select-String -Pattern "testdemo"
More about `Select-String` \--> `Get-Help Select-String -Online`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "powershell"
}
|
ubuntu-application-switcher
After following this guideline my Ubuntu application switcher would look like this. It seemed like there are 2 application switchers getting overlapped. Anybody has any idea on this, please help me
|
It seems like you have two independent application switchers running in parallel, so you may want to disable/uninstall one, or re-assign keyboard shortcuts.
To change shortcuts for the default switcher, you can use the Unity Tweak Tool (`sudo apt install unity-tweak-tool`). After opening it, click on "Switcher" and adjust "Window switching shortcuts".
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "macbuntu"
}
|
Check if value is in array PHP (easy?)
I think I have a very easy question, but I am stuck anyway. I want to check if the value is in an array, and if it is, i want to change the variable value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, $test)){
$admin_is_menu = "true";
}
echo $admin_is_menu;
In the code above, it should output the echo `"true"`, since `"about"` is in the array. But is unfortunally does not work.
What am I doing wrong?
|
Try `array_column` to get all array value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, array_column($test,'alias'))){
$admin_is_menu = "true";
}
echo $admin_is_menu;
DEMO
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, arrays"
}
|
Why does Snape weaken Harry's protection against legilimency?
In _Deathly Hallows_ we learn Snape was in love with Lily, so he risked his life becoming a double agent in order to protect Harry.
But in _Order of the Phoenix_ , instead of strengthening Harry's protection against legilimency, he weakens it, granting Voldemort access to Harry's mind.
Then, why did he risk Harry's life, if he was risking his own life to protect him?
|
This quote explains it:
> “ **Snape made it worse** , my scar always hurt worse after lessons with him —” Harry remembered Ron’s thoughts on the subject and plunged on. “How do you know he wasn ’t trying to **soften me up for Voldemort, make it easier for him to get inside my** —”
>
> “I trust Severus Snape,” said Dumbledore simply. “But I forgot — another old man’s mistake — that some wounds run too deep for the healing. **I thought Professor Snape could overcome his feelings about your father — I was wrong**.”
>
> — _Order of the Phoenix_ , chapter 37 ( _The lost prophecy_ ), emphasis mine
Then:
1. Snape hates Harry because he is James' son, but also wants to protect him because he is Lily's son.
2. Snape decides to protect him, risking his life.
3. However, he didn't control well his hate, which made him weaken Harry's protection.
I find it somewhat nonsense, but seems the canon answer.
|
stackexchange-scifi
|
{
"answer_score": 26,
"question_score": 26,
"tags": "harry potter, severus snape"
}
|
Add variable inside a variable?
> **Possible Duplicate:**
> Which is the best method to perform string concatination in PHP?
I tried to add a variable and string to another variable like this:
finalData += $ajaxData + 'some text';
To no avail. The result is nothing. Any advice? Thanks
**EDIT: I made a major mistake! I forgot I was working with Jquery! It was a long day guys sorry! :)**
Mods please delete question.
|
string concatenation in php is done with a `.` so you need to do:
$finalData .= $ajaxData . 'some text';
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery"
}
|
Get Folder names into txt file in C#
I'm trying to write folder names into a txt file. So far I'm here;
string yol = Application.StartupPath + "\\isimler.txt";
System.IO.StreamWriter zzz = new System.IO.StreamWriter(yol);
string[] lines = Directory.GetDirectories(@"C:\test");
zzz.WriteLine(lines);
zzz.Close();
How can i write folder names to txt file?
|
Using `Directory.GetDirectories` to get all the folder name in specified directory, then traverse it and write to .txt file. The code snippet as following:
string yol = "isimler.txt";
System.IO.StreamWriter zzz = new System.IO.StreamWriter(yol);
string[] lines = Directory.GetDirectories(@"C:\");
foreach(string name in lines)
zzz.WriteLine(name);
zzz.Close();
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -6,
"tags": "c#"
}
|
Keyboard Events
I need to listen for keyboard events from a **specific** keyboard device & know which key is pressed in a (C#) WPF application. Ideally, this shouldn't be window dependant and work so long as the application has focus.
unfortunately I can't think of / find any way to do this.
any ideas?
D.R
**Edit:** I've been looking into the OpenTK.Input library, which has a nice interface for keys... Does anybody know how to get a KeyboardDevice without creating a `GameWindow`
**Info:** Just by the way, this is for a barcode scanner which emulates a keyboard... who's bright idea was that, eh?
|
Managed to find this tutorial on msdn. along with a Sample Scanner object which comes with the POS.Net SDK
I haven't really had the time to pick apart how it works yet to give a proper overview, but it seems I should be able to write a custom service object abstraction for any "keyboard wedge" HID device.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "c#, wpf, input, keyboard events"
}
|
Choosing $12$ donuts from $20$ kinds of donuts
> original question: A donut shop offers $20$ kinds of donuts. Assuming that there are at least a dozen of each kind as you enter the shop, in how many ways can you select a dozen donuts?
The correct answer is: ${}^{31}C_{19}$
I think we can assume that there are $20$ boxes and $12$ balls so that there are $19$ lines and It means choosing $19$ or $12$ from $31$. Is what I think correct?
In addition, I wonder the original question said 'assuming at least a dozen of each kind as you enter the shop'.
|
You are actually asked to find the cardinality of the set:$$\left\\{(a_1,\dots, a_{20})\in\mathbb Z_{\geq0}^{20}\,\middle|\, \sum_{i=1}^{20}a_i=12\right\\}$$ Here $a_i$ stands for the number of selected donuts that are of kind $i\in\\{1,\dots,20\\}$.
This can be done by application of stars and bars) and indeed leads to outcome $\binom{12+19}{19}=\binom{31}{19}$.
It seems that your "lines" agree with "bars" and your "balls" with "stars", and that your thinking about this is correct.
If there would be less than a dozen donuts of some kind, e.g. there are $10$ of kind $5$ then extra condition $a_5\leq10$ would arise (making things more complex).
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "combinatorics, combinations"
}
|
Symfony 2 Form Errors
i want to have a simple
{{ form_errors(form) }}
call in twig for all my validation errors.
But this is not working. Only when i call a field specifically i get the validation message back, but only for this field.
Is it possible to return all my validation messages in one simple {{ form_errors(form) }} call ?
example of my entity validation :
/**
* @var string
*
* @ORM\Column(name="pdb_domain_account", type="string", length=255, nullable=false)
* @Assert\NotBlank(
* message = "The field name cannot be empty")
* @Assert\Regex("/^[A-z]+$/",
* message = "Only letters are allowed for the relation name.")
*/
private $pdbDomainAccount;
this is working for one field :
{{ form_errors(form.pdbDomainAccount) }}
|
You need to make sure that your form types are setting `error-bubbling` to `true`, so they pass the errors to the parent form, and then you can use `{{ form_errors(form) }}`
_From Symfony2 doc:_
> If true, any errors for this field will be passed to the parent field or form. For example, if set to true on a normal field, any errors for that field will be attached to the main form, not to the specific field.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, oop, symfony, twig"
}
|
Do UK citizens have a right to legal advice?
As a British citizen: If I can't afford to pay a solicitor to get legal advice, am I entitled to free legal advice from the government?
|
It depends on the circumstances, see here.
> You’ll usually need to show that:
>
> * your case is eligible for legal aid
>
> * the problem is serious
>
> * you can’t afford to pay for legal costs
>
>
|
stackexchange-law
|
{
"answer_score": 6,
"question_score": 6,
"tags": "united kingdom, human rights"
}
|
MvvmCross binding to multiple properties on android control using swiss syntax
What is the correct syntax for binding to multiple properties on an Android element?
I tried something like this `local:MvxBind="{ Value StartTime, Text StartTimeText}"`
where properties StartTime and StartTime text are defined in the ViewModel but this does not work. Value and Text are properties of this custom control.
The ViewModel may look like this:
public class ViewModel
{
public DateTime StartTime{get;set;}
public string StartTimeText {get;set;}
}
I found this related question, but cannot find the correct Swiss syntax for multiple bindings. Any one done multiple bindings on an element?
TIA.
|
Syntax I was looking for is:
> local:MvxBind="Value StartTime; Text StartTimeText"
Don't forget the space after the ";". Without it you won't get the first binding.
|
stackexchange-stackoverflow
|
{
"answer_score": 25,
"question_score": 13,
"tags": "android, binding, mvvmcross"
}
|
How often do local elections take place in England?
Local elections are coming up in England. When I look up Wokingham Borough local election results, it lists results from 2015, 2014, 2012, 2011, 2010, 2008, 2007, 2006, 2004, 2003, and 2002. That seems very often. How often are local elections and what duration are local politicians elected for?
|
Councillors in the UK have four year terms. However, those terms don't necessarily all start at the same time.
For some councils (like the one in the question), one third of the seats are elected at a time, with there being elections in May in three years out of every four.
Some councils are elected in halves, with elections for half the seats every 2 years.
And finally, some councils are elected all at once, with a single election for all seats every four years.
The list of local elections for 2016 shows examples of all three systems.
(As for _why_ there is this mix of systems: I think that would be a very good question in itself! There doesn't appear to be much of a pattern.)
|
stackexchange-politics
|
{
"answer_score": 4,
"question_score": 3,
"tags": "election, united kingdom, local government"
}
|
WPF Image Border
I have this Image:
!ArrowImage
I want the image to have a border If I do:
<Border BorderThickness="1" BorderBrush="Black" HorizontalAlignment="Right" Width="22" VerticalAlignment="Center">
<Image Source="/<AppName>;component/Images/Background/Achtergrond_Arrow.png" HorizontalAlignment="Right" Width="22" >
<Image.Effect>
<DropShadowEffect Color="#FF868686" Direction="0" ShadowDepth="0" BlurRadius="10" />
</Image.Effect>
</Image>
</Border>
it gives a Square border, not following the arrow itself.
!Square Image
Does anybody have any idea on how to fix this??
|
Don't use an image but draw the border and triangle yourself. You can use a `Path`, a `Line` and other basic geometric shapes for this.
This post may give you a starting point. Or a Petzold blog post can give you further assistance.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "wpf, image, border"
}
|
Python treating digit and float as same index in list
I am trying to find index value of list from below code.
a = [4.5, 6 , "hi" , 6.0]
for b in a:
if type(b)==float:
print(a.index(float(b))+0, b , id(b))
else:
print(a.index(b)+0 , b , id(b))
what I found is for value "6" and "6.0" is taking same index position from the output. How do I get different index value for each value in list.
|
The list.index function is not written to discriminate between types. If you want this, you'll have to write your own function. Using enumeration in your loop will give the real index.
a = [4.5, 6 , "hi" , 6.0]
for idx, b in enumerate(a):
if type(b)==float:
print(idx, b , id(b))
else:
print(idx , b , id(b))
You can wrap this code in a function to create a new type-sensitive index function which only returns `idx`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x, list, indexing"
}
|
How do you prove that $5(7^n)+3(11^n)-8$ is divisible by $3$ for all natural numbers $n$?
How do you prove that $5(7^n)+3(11^n)-8$ is divisible by $3$ for all natural numbers $n$? I have been trying to figure this out and kept reaching dead ends. I would be grateful for some help
|
If you are unfamiliar with modulo arithmetic:
* Since $7^n=(6+1)^n = 1^n + *\cdot 1^{n-1}6^1 + \cdots + *\cdot 1\cdot 6^{n-1} + * \cdot 6^n$, (where it's not important which numbers are in the positions marked by an asterisk), you can see that $7^n = 3k_1 + 1$ for some $k_1\in\mathbb N$
* Similarly, you can show that $11^k = (12-1)^n = 3k_2 + (-1)^n$ for some $k_2\in\mathbb N$, but in this case, that doesn't even matter, because $3\cdot 11^n$ is _always_ divisible by $3$.
You also have $8 = 3\cdot 2 + 2$, so you have
$$\begin{align}5\cdot 7^n + 3\cdot 11^n - 8 &= 5\cdot (3k_1 + 1) + 3\cdot 11^n - 3\cdot 2 - 2 \\\&= 3\cdot(5k_1 + 11^n - 2) + 5 - 2 \\\&= 3\cdot(5k_1 + 11^n - 2) + 3 \\\&= 3\cdot (5k_1 + 11^n - 2 + 1)\end{align}$$ which is clearly a multiple of $3$.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": -1,
"tags": "number theory"
}
|
How do i use the jQuery.parseJSON properly
I have set of values coming from server side where iam trying to generate JSON and use it in my code
here is the statement now the problem is it is working perfectly if the value is fine with out single quotes and double quotes.
var stds = jQuery.parseJSON('<?php echo json_encode($this->emps); ?>');
CASE 1:
ABC:"E" DTSM
VCD:"E" DMST
CASE 2:
*****
ABC:E DTSM
VCD:E DMST
How can i still generate the JSON with case 1. iam getting JS error "exception thrown and not caught". This is due to malformed JSON string
|
Because JSON is already a valid fragment of JavaScript, you could simply write
var stds = <?php echo json_encode( $this->emps ); ?>;
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "jquery, jquery selectors"
}
|
Of Gold and Silver
Gold makes me.
Silver is my enemy.
Who am I?
* * *
Hint:
> This riddle is based on a saying
|
> Speech is silver, but silence is golden.
So we have
> Silence
|
stackexchange-puzzling
|
{
"answer_score": 9,
"question_score": 3,
"tags": "riddle"
}
|
What is the issue with Canadian tax regime?
One of my cousins lives in Toronto, Canada. Her husband is an accountant who works in a private company. Last year, he was offered a promotion which he denied. According to him, he would have to pay more taxes, and as a result, his net income would decrease.
I don't have any means to talk to this person to ask about this problem. So, can you shed some light on this?
My younger brother is working in Canada. He said the employer is cutting $600 of his $2500 salary on the pretext of tax.
Can you explain?
|
> According to him, he would have to pay more taxes, and as a result, his net income would decrease.
Your cousin's accountant husband has an incomplete understanding of Canada's taxation rules.
When your income reaches into the next tax bracket, it's not the _entire_ income that is taxed at the higher rate. It's only the _portion_ of the income that is above the previous tax bracket.
See 8.2.4 Tax brackets and rates for complete information and examples.
|
stackexchange-expatriates
|
{
"answer_score": 6,
"question_score": 1,
"tags": "canada, taxes"
}
|
Mysterious error in this C++ pointer program in visual studio
I have a written code for finding missing elements below.
#include <iostream>
int main() {
int arr[7] = { 1,3,5,7,9,11,13 };
int max{ arr[0] }, min{ arr[0] };
for (int i = 0; i < 7; i++) {
if (max < arr[i])
max = arr[i];
if (min > arr[i])
min = arr[i];
}
int* ptr = new int[max];
for (int j = 0; j < 7; j++)
ptr[arr[j]] = 1;
for (int k = min; k < max; k++)
if (ptr[k] == 0)
std::cout << k << " ";
delete[] ptr;
return 0;
}
However this gives me an mysterious error about heap corruption like this :
enter image description here
I don't see any problem here. Anyone see it ? Please tell me.
|
`max` is `13`.
So `ptr`'s length is also `13`.
int* ptr = new int[max];
for (int j = 0; j < 7; j++)
ptr[arr[j]] = 1;
this is accessing `ptr[13]`, which is out of bounds.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "c++, pointers"
}
|
Matchstick Puzzles
### Puzzle #1:
There is a matchstick:
**|**
Add 2 more matchsticks to make the number, 11.
### Puzzle #2:
There is a palace made out of 11 matchsticks:

> Just add 2 matchstick to create an X before the I (XI -> 11 in roman numeration)
2)
> Your image is wrong, there are many more matchstick in your picture (or the proportion are kinda bad), so i made a new one by myself and i moved the roof horizontally in the center. In the image, there are 8 small squares and 3 big one, made by 4 small squares (sorry for my bad art, i'm a programmer, not an artist C:) 
> In the image below, there are 2 big squares and one small square in the middle by moving the 2 on the top right and the 2 on the bottom left: 
Preposition-b | Verb - Hitpael - Infinitive construct | third person masculine singular
Strong's Hebrew 2603: To bend, stoop in kindness to an inferior, to favor, bestow, to implore
In < only 2 out of 28 translations use the phrase "for his life". It is not in the original Hebrew subordinate clause. In this case, ESV is more faithful to the original than NIV. By hindsight, we knew that they didn't kill Joseph.
|
stackexchange-hermeneutics
|
{
"answer_score": 0,
"question_score": 1,
"tags": "genesis, niv"
}
|
Password protect directory in AWS EC2 running Apache/Linux
As the title says, I have an AWS EC2 instance with Apache. It's a Linux server. I want to password protect one directory. I was following this answer: <
htaccess:
AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /var/www/admin/.htpasswd
Require valid-user
Created a proper .htpasswd file, but wondering if there's another step.
However, it's not working (i.e., directory isn't protected). I restarted my server and that didn't help. Wondering if I need to change something in my config file.
If I look at the contents of the directory where I placed my .htaccess file, using terminal `ls`, the .htaccess file isn't visible. I uploaded it using SFTP and see it using my FTP application, but maybe it's not actually there. Same thing for my .htpasswd file.
|
Dumb mistake.
Needed to add this to my server config file:
<Directory /var/www/html/MYPROTECTEDDIRECTORY>
AllowOverride All
</Directory>
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "linux, apache, .htaccess, amazon web services, amazon ec2"
}
|
which is the best practice to write keys in any language?
which is the best practice?:
if(1){
demo();
}
Or
if(1)
{
demo();
}
And parentesis:
if(1)
Or
if( 1 )
And that one way is better than another?. There are some standard about it?
|
Your answer will depend on the type of the language you are using, and the type of the program you are writing. Some will be better than others in some situations and others will worse that others in other situations. The best way really, is to use them in different programs and/or languages and learn for yourself which is the best for you. Everyone's answer have their up's and down's, but it is up to you to decide. I hope this helps you!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -5,
"tags": "optimization, ident"
}
|
capture authorization code programmatically in OAuth 2.0
In a standard OAuth auth code Grant flow, user is redirected to authorization server page where he provides consent to allow the requesting app to perform some actions on his behalf, after which a browser redirects the user to a redirect URI with auth code. Application then exchanges this code with authorization server to get an Access token..
Consider a scenario where user has already given consent or consent is somehow implicit (i.e., user is not required to interact with the authorization server consent page).. in this case, is it acceptable to use an http client with redirection disabled as the user agent instead of browser and capture the `Location` header of the redirection response from the authorization server ?
|
Yes, this is fine, as long as the request is done over HTTPS. From a security perspective there's no difference between having your browser do it and having a different application do it.
|
stackexchange-security
|
{
"answer_score": 0,
"question_score": 0,
"tags": "authentication, authorization, oauth2"
}
|
Enabling Territory Reports in Territory Management 2.0
We have enabled Territory Management 2.0 in our Salesforce org. However, we cannot find the Territory Reports as described here:
How do we add/enable these reports?
|
As it turns out, Salesforce does not include standard, out of the box Territory reports with Territory Management 2.0. They only include Territory reports for the original territory management feature.
One must custom build their own Territory Reports using Salesforce reporting features.
|
stackexchange-salesforce
|
{
"answer_score": 1,
"question_score": 1,
"tags": "reporting, record type, territory management, territory"
}
|
Is constraint layout more flexible in locating views in Android Studio?
Both constraint and relative view groups support relative positioning of a view wrt other. Relative layout provides 4 different attributes : layout_toRightOf / toLeftOf / toTopOf / toBottomOf , and Constraint provides many combinations of format " layout_constraintTop_toTopOf "
BUT can’t we place the views at any position just using the 4 attributes of Relative layout ? In what way is Constraint layout more responsive ?
|
According to Google Developers ConstraintLayout has better performance than RelativeLayout. In addition (as you've mentioned) it's more advanced than RelativeLayout and allows you to build your Layout more precisely with all these additional constraints options. What's more, if you set the view A's width or height to `match_constraint` (0dp), and set its end constraint to start of view B, the A's width or height can be dynamically scaled when B's visibility is gone.
Any view inside ConstraintLayout requires only two constraints for X and Y axis e.g. `layout_constraintTop_toTopOf` and `layout_constraintStart_toStartOf`.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, android studio, android relativelayout, android constraintlayout"
}
|
Azure data factory not loading
I am not able to open Azure data factory in any browser, it just keep loading from past 1 hour. I have tried refreshing and using other browser, is there any specific reason why it happens? All other services on azure portal is working fine.
Browsers which I have tried:
* Mozilla Firefox 65.0.2
* Internet explorer 9
* Microsoft Edge 42
* Opera Latest
For all of the above browsers all services are fine but when I click on "Author & Monitor", it opens up a new tab and keep loading.
+", "");
System.out.println(replaceBeforeSide);
//Desired result = "TH";
|
Converting my comment to answer so that solution is easy to find for future visitors.
You could use a simple regex with a capture group:
replaceBeforeSide = test.replaceAll(".+?(TH|TV)", "$1");
or even shorter:
replaceBeforeSide = test.replaceAll(".+?(T[HV])", "$1");
Using `.+?`, we are matching 1+ of any character (non-greedy) before matching `(TH|TV)` that we capture in group #1.
In replacement we just put `$1` back so that only string before `(TH|TV)` is removed.
We could also use a lookahead and avoid capture group:
replaceBeforeSide = test.replaceAll(".+?(?=T[HV])", "");
If you want to match ignore case then use inline modifier `(?i)`:
replaceBeforeSide = test.replaceAll("(?i).+?(?=T[HV])", "");
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, regex, string, syntax"
}
|
How to modify activation email content in Open edX Platform?
Someone has previously asked a question regarding the location of the activation email .txt file for the profile activation email that is sent out when a user registers on an Open edX platform.
I have located these files and made changes. Further, I have manually compiled the assets and restarted the lms, cms, and workers. My problem is that the old email is still sent when a user registers on the platform.
Can anyone help me understand what I need to do to make these changes happen? I've been working on this for a while and, to me, this seems like a straight forward problem. But I don't really understand what is happening, so am having trouble getting the desired output.
|
With latest platform release you just need to change the content in following files:
1. lms/templates/emails/activation_email_subject.txt
2. lms/templates/emails/activation_email.txt
Nothing else needed, tested locally.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "edx, openedx"
}
|
Absolute values of a closed set's elements
> Let $A \subset \mathbb{R}^n$ be a closed set. Is the set $\\{|x| : x \in A \\} \subset \mathbb{R} $ closed?
Based on my intuition, I strongly believe that the above set is closed, but I couldn't give a precise proof. Can anyone help me?
Thanks!
|
It is closed.
Given $y=\lim y_n, y_n\in\\{|x|:x\in A\\}$ we have to show that $y\in\\{|x|:x\in A\\}$.
For each $y_n$ there is at least one $x_n\in A$ such that $|x_n|=y_n$. So consider a sequence $x_n$ with this property.
$\\{x_n\\}$ is bounded (why?) so there exists a subsequence $x_{n_k}$ such that $x_{n_k}\rightarrow x$ for some $x\in\mathbb{R}^n$ (Bolzano–Weierstrass theorem).
We know $x\in A$ because $A$ is closed. Moreover, $|x|=\lim |x_{n_k}|=\lim y_{n_k}=y$, so $y\in\\{|x|:x\in A\\}$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, absolute value"
}
|
NVCC ptas=-v output
a I compiled my program with "nvcc -ccbin=icpc source/* -Iinclude -arch=sm_35 --ptxas-options=-v ". Output is below:
ptxas info : 0 bytes gmem
ptxas info : 0 bytes gmem
ptxas info : 450 bytes gmem
ptxas info : Compiling entry function '_Z21process_full_instancePiPViS1_S_' for 'sm_35'
ptxas info : Function properties for _Z21process_full_instancePiPViS1_S_
408 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info : Used 174 registers, 9748 bytes smem, 352 bytes cmem[0]
I think gmem refers to global memory, but why the first line and third line have different values (0 vs 450) for geme?
smem is shared memory, how about cmem?
Is the memory usage for a block or a SM (stream processor)? Blocks are dynamically assigned to SM. Can we infer how many blocks will concurrently run on a SM?
My GPU is K20.
|
> smem is shared memory, how about cmem?
* **cmem** stands for constant memory
* **gmem** stands for global memory
* **smem** stands for shared memory
* **lmem** stands for local memory
* **stack frame** is part of local memory
* **spill loads** and **store** use part of the stack frame
> Is the memory usage for a block or a SM (stream processor)?
No, the number of registers is per thread while the shared memory is per block.
> Can we infer how many blocks will concurrently run on a SM?
No. Since you can't determine the number of threads per block you cannot calculate the resources each block requires.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "cuda"
}
|
Oracle view and grant question
How can I use grant and creation of a view to allow a user to have read only access to certain columns in a table but also be allowed to update only one of the columns?
Can you specify a specific column only for update on a grant?
|
So let's say we have a table T with col1...col5 and the user U, he should not see col5 () view needed) and should update col3 (no view needed):
CREATE VIEW V AS SELECT col1, col2, col3, col4 FROM T;
GRANT SELECT, UPDATE (col3) ON V TO U;
see <
EDIT: corrected a mistake...
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "oracle, view, sql grant"
}
|
Adding Scala to `PATH` in Zsh
I have downloaded Scala to `~/bin` for easy access on my machine; but I seem to have some difficulty adding it to the `PATH`.
On my MacBook I simply added the following to `~/.profile` and everything just worked:
SCALA_HOME=$HOME/bin/scala-2.11.7
PATH=$PATH:$SCALA_HOME/bin
On my Linux box however, I've tried putting the same code in both `~/.profile` and `~/.zshrc`, and it still doesn't correctly display `/home/coffee/bin/scala-2.11.7/bin/scala` when running `which scala`.
`source .zshrc` doesn't work at all, and `source .profile` only works until I re-open the console (I put the code into both just in case).
So what am I doing wrong here, and how do I get it to work?
|
The fact that `PATH` is not sourced from `~/.profile` has 2 very good reasons behind it:
1. Only login shells source `~/.profile`. So that's not expected to be sourced in a normal terminal. If you're unable to get it to work in a login shell that's because
2. Zsh sources `~/.zprofile`, not `~/.profile`.
The fact that the changes are lost after sourcing `~/.profile` is expected, since what is sourced affects only the current shell; that's why `~/.profile` / `~/.zprofile` are sourced each time the shell starts.
The fact that it works when sourcing `~/.profile` and not when sourcing `~/.zshrc` is apparently unexplainable.
My guess is that an `export` / `source` is messing with `PATH` later / you're just running the wrong commands in `~/.zshrc`.
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": -2,
"tags": "command line, environment variables, zsh"
}
|
רָעָ֔ה in Jeremiah 29:11 - what part of speech?
In this fragment of Jeremiah 29:11 (plans of shalom and not evil):
מַחְשְׁבֹ֤ות שָׁלֹום֙ וְלֹ֣א לְרָעָ֔ה
I've got Bible Works (v6) parsing לְרָעָ֔ה as an adjective (with leading particle preposition).
On the other hand, it seems to align with TWOT 2191c (listed as parent noun of verb).
What is the part of speech for רָעָ֔ה in Jeremiah 29:11?
|
Noun, feminine, secondary form of רעע, meaning a disaster, defeat, social disorder. See also II Kings 21:12 Jeremiah 17:17, Psalms 91:10.
I would translate here (Jeremiah 29:11) as "Intents of peace and not for evil", adding an explicit translation of the ל in לרעה.
Can also mean evil or an evil deed. Compare Genesis 39:9, I Samuel 25:21, II Samuel 3:39.
Might be better if you used a standard Hebrew dictionary like the Even Shoshan.
|
stackexchange-hermeneutics
|
{
"answer_score": 3,
"question_score": 2,
"tags": "hebrew, grammar"
}
|
Spring annotations basic question
As far as I understand, main purpose of dependency injection is to have all dependencies separated declaratively, so that we can easily review and change the dependency structure easily...right?
Then by using dependency annotations spread through out the code, aren't we just going back to non-centralized system (similar to simple new operator), which is harder to tweak?
|
`@Autowired`/`@Inject` annotations usually declare dependencies on interfaces rather than on concrete classes (as in the case of `new`), thus you still can control which implementations should be injected by controlling which beans are declared in the context. Also, these dependencies can be overriden manually.
`@Component`-family annotations can be controlled as well, since you can exclude particular classes from component scanning.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "spring, annotations"
}
|
Looking for a book about magic shadows
I remember reading a book that was about a boy learning to control his shadow, everyone had their own shadow and his was particularly weak. I recall early on he had to fight someone much stronger with a dragon shadow, but that's about it. Anyone know what this book is called? I've been looking for years, and all my attempts have turned up empty. I believe he may have been attending some sort of school, I think the fight with the dragon shadow was some sort of coming of age test. If I remember anything else I'll place it here.
|
It could be the Seventh Τower series by Garth Nix.
!enter image description here
It's fairly vague, though in the first book the protagonist has an encounter with a dragon shadow servant.
|
stackexchange-scifi
|
{
"answer_score": 9,
"question_score": 5,
"tags": "story identification, books"
}
|
What type of cable is this?
What type of cable is this? I found it in the wall without any junction box just taped off at the end with electrical tape.
Thanks!
!enter image description here
|
It's a data cable.
Probably CAT5 or CAT5E grade. (it will be written on the blue jacket every metre.)
These cables are used for ethernet (between computers and routers) and for connecting telephones, and home automation equipment, intercoms, thermostats etc. I'm guessing there used to be a phone jack there.
|
stackexchange-diy
|
{
"answer_score": 4,
"question_score": 1,
"tags": "electrical, cables"
}
|
What parts of the raw e-mail can be changed for the DKIM to stay valid?
Subj:
**Which parts of a raw e-mail message can be changed by a forwarding mail server for its DKIM signature to stay valid?**
Or, alternatively:
**What parts of the letter are signed by DKIM (and thus cannot be changed)?**
For the purpose of the question, I assume that the entire message has been signed by the sending server (no `l=` parameter).
I'm interested in a general answer because I didn't find a clear one at either Wikipedia article or DKIM FAQ.
|
Studying RFC 6376, and ultimately, its section 3.7. Computing the Message Hashes, I conclude:
> DKIM signature covers the message's body and the headers listed in the `h=` field.
So, all other headers can be added/edited so long as they don't clash with those covered by the signature.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "email, dkim"
}
|
Unable to set GOPATH in elementary os loki
**Input :**
echo "GOPATH=/home/chawat/Programming/GoWorkspace" >> ~/.bashrc
echo "export GOPATH" >> ~/.bashrc
echo "PATH=\$PATH:\$GOPATH/bin" >> ~/.bashrc
source ~/.bashrc
**Output:**
bash: /home/chawat/.bashrc: line 171: syntax error near unexpected token `newline'
bash: /home/chawat/.bashrc: line 171: `esacGOPATH=/home/chawat/Programming/GoWorkspace'
plz help me whats wrong?
|
It sounds like `.bashrc` was not terminated by a newline before you ran those commands. Look at the end of the file in a text editor and make sure that `GOPATH=/home/chawat/Programming/GoWorkspace` starts on a line of its own.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "bash, go, elementary os"
}
|
JQuery Mobile Apply custom theme to autodividers
Is there any way to add attributes to programmatically created autodividers?
I'm generating the autodividers using the code below:
$("#classList").listview({
autodividers:true,
autodividersSelector: function ( li ) {
var hi = li.text().split(" ");
return hi[0];
}
}).listview("refresh").trigger('create');
And I want to set the data-divider-theme to b. I tried doing this after the dividers were created using the following commands in console:
$(".ui-li-divider").attr('data-divider-theme', 'b');
$("#classList").listview('refresh');
but the dividers didn't change in appearance. Is there any code I should add into the creation of the autodividers or after the creation of the autodividers to change this attribute?
Thanks!
|
You can set the **dividerTheme** option:
$("#classList").listview({
autodividers:true,
dividerTheme: "b",
autodividersSelector: function ( li ) {
var hi = li.text().split(" ");
return hi[0];
}
}).listview("refresh").trigger('create');
or just add the class `ui-bar-b` to the dividers
$(".ui-li-divider").removeClass("ui-bar-a").addClass("ui-bar-b");
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery, css, listview, jquery mobile"
}
|
Is the sixed field of a DS record protocol?
Can some tell me what the layout is of DS record for DNSsec. A specialy the naming
If you look at this DS record:
231.72.212.in-addr.arpa. 3600 IN DS 45767 8 2 93f383a81ff2c124bdd395f51e58b88317cb8852facd93d3f6f30efdd2afa5b8
fieldsnames :
1. Hostname
2. ttl
3. ?? how is IN called
4. Record type in this case DS
5. keytag
6. Algorithm
7. Digest Type
8. Digest Field
I am not sure of my self about field 6 is this protocol or NOT
|
OKe i found finaly the correct RFC : <
I updated the exampel accordenly
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "layout, dnssec"
}
|
How to allow user to login only from the office?
I have a web application that has simple user/pass authorisation. The client wants to allow his employees to use it only from the office.
What are the best ways to do it?
* Create the allowed IP list and see if user's IP match it?
* Activate/deactivate users records in DB when they come and when they leave the office (add this work for a manager)?
* Maybe configure browser to send some specific data to the server (User-agent)?
* Something else?
_Web app is written on PHP, PostgreSQL_
|
I found an easy way to see if the user has logged in to the web-app from the office computer:
Manually add some string to browser's config parameter 'user-agent' and check `$_SERVER['HTTP_USER_AGENT']` if it contains it.
For example 'Mozilla/5.0 (Windows NT 6.1; rv:27.0) Gecko/20100101 Firefox/27.0 OFFICE'
Of course it's absolutely unsafe, but it can be suitable for a client.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "php, ip, authorization"
}
|
How do I use the pen tool to draw an open line?
In Photoshop, how does one create the below single-line zig zag effect, per the instructions? Every time I have completed a work path, it will join one end to the other, so the stroke I apply after making it into a selection will always be of a looped shape. (N.B. The grey line above the jagged one is the bottom edge of a rectangle that was created in the previous step. The zig zag line appears to be on its own)
Thanks very much for any help.
!enter image description here
|
There's a trick... it's not an open path. It's a closed path with 3 sides outside the canvas.
!path
By making 3 sides fall off the canvas, their edges aren't seen, the path is closed and you can then apply layer styles to it.
|
stackexchange-graphicdesign
|
{
"answer_score": 7,
"question_score": 4,
"tags": "adobe photoshop, pen tool"
}
|
Create a Pandas Dataframe from two lists: column 1 is first list, column 2 is second list which is a nested list
I am attempting to use two different lists to create a Pandas dataframe. The first list is to be the first column and the second list is the other column. The second list is nested and I want the first column to repeat values for as many values are in the nested item in the second column.
For example, the two lists:
`list1 = ['first', 'second', 'third']`
`list2 = [['a', 'b', 'c', 'd'], ['e', 'f'], ['g']]`
Would return the output
column1 column2
0 first b
1 first c
2 first d
3 second e
4 second f
5 third g
I have tried using `dict(zip(list1, list2)` and then using `pd.from_dict()` but it is not yielding the results I need.
Anyone have any suggestions?
|
try `zip` followed by `explode`:
df = pd.DataFrame(list(zip(list1,list2)), columns=[1,2]).explode(2).reset_index(drop=True).add_prefix('column')
* * *
**df:**
column1 column2
0 first a
1 first b
2 first c
3 first d
4 second e
5 second f
6 third g
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, pandas, list, nested lists"
}
|
Rules ignored when restore quality profile in SonarQube
I saw many posts with this question, but I didn't find the answer so I ask. I upgraded Sonarqube from 4.5 to 5.6 and it works fine, but the quality profiles are empty. I tried to restore one with the backup/restore option but the rules are ignored: image. Can you help me?
|
It sounds like you started up your new instance without the code analyzers.
Unfortunately, installing the analyzers now won't restore your profile customizations. You allude to having backup profile files, so you may be able to get them back that way, but you should be aware that you'll lose some rule customizations.
Assuming you backed up your database before the upgrade like the docs tell you to, your best bet is to restore your DB backup to the pre-upgrade state, install the missing code analyzers, _then_ run the database upgrade.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "sonarqube, profile"
}
|
Поворот вектора относительно второго

{
var tRad = Atan2(target.y, target.x);
var aRad = Atan2(axis.y, axis.x);
var rad = tRad+aRad;
return new Vector2(Cos(rad), Sin(rad))*target.GetDistance();
}
Можно как-то проще?
|
Вот так можно довернуть `target` на угол заданный `axis`:
private Vector2 GetRotationVector (Vector2 target, Vector2 axis)
{
axis /= axis.GetDistance(); // Normalize
return new Vector2(target.x * axis.x - target.y * axis.y, target.x * axis.y + target.y * axis.x);
}
1. Если вы знаете комплексные числа, то при произведении двух чисел их аргументы складываются, а модули умножаются. Сперва мы получаем число с единичным модулем, затем умножаем на него `target`. В итоге `target` повернётся на нужный угол, но не изменит свой модуль.
2. Если вы не знаете комплексные числа, то смотрите тригонометрические формулы для суммы углов.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "математика, векторы"
}
|
TaskbarItemInfo.ProgressValue not updating
As shown in the screenshot, my `ProgressBar1.Value` updates properly, but not my `TaskbarItemInfo.ProgressValue`:
!enter image description here
This is the code I am using to update both:
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Set the Value porperty when progress changed.
this.ProgressBar1.Value = (double)e.ProgressPercentage;
this.TaskbarItemInfo.ProgressState = TaskbarItemProgressState.Normal;
this.TaskbarItemInfo.ProgressValue = e.ProgressPercentage / 100;
}
How can I make my `TaskbarItemInfo` update properly?
|
this.TaskbarItemInfo.ProgressValue = e.ProgressPercentage / 100;
It looks to me that you are dividing an int with another int therefore the result will be an int when a double is expected.
Simply try to suffix 100 with a "d" (making it a double) :
this.TaskbarItemInfo.ProgressValue = e.ProgressPercentage / 100d;
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 2,
"tags": "c#, wpf, taskbar"
}
|
At what stage does SignalR automatically reconnect
I am just starting to learn/embrace SignalR.
I have this in my JavaScript page:
$.connection.hub.start().done(function () {
//Some Code
}).fail(function () {
//Some Code
});
A connection is attempted to SignalR The connection fails Does it automatically try to reconnect until a connection is made or does it have to at least make a connection 1st before it tries to reconnect (whenever connection is lost).
Do I have to put a reattempt to connect in my .Fail function?
|
Here is documentation around SignalR javascript clients. There is a section there called connection lifetime events. When a reconnect is happening SignalR raises an event, you can handle that event in your code. There are 7 connection events. In order for this to happen you need to make one successful connection. If the connection fails then you can add code as part of the fail function to retry
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, signalr"
}
|
Why a finite dimensional algebra always has a smallest submodule having semisimple quotient
$A$ is a finite-dimensional algebra (possible without unit, the corresponding field is $\mathbb{F}$), I want to prove that A has a smallest submodule having semisimple quotient. What I have got is that if $M$ and $N$ are submodules of $A$ (as an $A$-module) such that $A/M$ and $A/N$ are semisimple $A$-modules, then $A/M\cap N$ is a semisimple $A$-module.
So to prove the original proposition, all I need to do is to prove that there are at most finite submodules of $A$ having semisimple quotient. If I prove this, I can finish my job by using the result above and by induction. But I don't know how to prove this.
Any help or hint will be appreciated. Thanks in advance.
|
You can take advantage of the fact that submodules are also $\mathbb{F}$-vector spaces and as such have a well defined dimension. No matter how many submodules there are, there are only finitely many possibilities for their dimension.
Let $k$ be the smallest dimension such that a submodule $M$ with $A/M$ semi-simple exists.
If there are somehow $M_1, M_2$ (and perhaps finitely or infinitely many others) of dimension $k$ and with semi-simple quotient, we can use your result to get a contradiction. So we conclude that $M$ is the only dimension $k$ submodule with semi-simple quotient.
This solves your problem for a not-so-elegant definition of smallest. In order to get to the better definition ($M$ is contained in every $N$ such that $A/N$ is semi-simple) we can - again! - apply your result!
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 4,
"tags": "abstract algebra, group theory, finite groups, modules"
}
|
In Gin Rummy, what happens when one knocks but the opponent has a lower or equal deadwood?
In Gin Rummy, what happens when one knocks but the opponent has a lower or equal deadwood?
E.g. I knock placing everything but a 6. My opponent was able to place everything but a 4.
So, my opponent had a lesser amount of points she couldn't place than I, but I knocked.
What does one do regarding points when this happens?
Does she get the difference, or does no-one get points?
Or does she get points like she would if she had successfully gotten a Gin?
|
Your opponent **Undercut** you and scores usually 25 points plus the difference between your score and theirs (+2 in your case). Actually, unless you **knockout** on gin (zero points), if your opponent ties your score you are undercut. From pagat.com:
> If the knocker did not go gin, and the counts are equal, or the knocker's count is greater than that of the opponent, the knocker has been undercut. In this case the knocker's opponent scores the difference between the counts plus a 10 point bonus.
|
stackexchange-boardgames
|
{
"answer_score": 7,
"question_score": 5,
"tags": "scoring, gin rummy"
}
|
Function not found: group_concat
I'm interesting in execute a query using the "group_concat" BigQuery function. When I execute the query directly in the BigQuery interface, the query ends successfully, but when I try to execute that query via Node js, the bellow error appeared:
errors:
[ { domain: 'global',
reason: 'invalidQuery',
message: 'Function not found: group_concat at [4:3]',
locationType: 'other',
location: 'query' } ]
The code is not the problem since it executes a simple query without any problem.
My query:
SELECT
st_hub_session_id,
num_requests,
group_concat( group.code, '|' ) as Codes
FROM
table.name
GROUP BY
st_hub_session_id,
group_concat
LIMIT
1000
Where could be the problem?
|
Use `STRING_AGG` in standard SQL instead of the legacy `GROUP_CONCAT`. You can use standard SQL through the UI by unchecking "Use legacy SQL" under "Show Options" or else putting `#standardSQL` at the top of your query. See also Enabling Standard SQL.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 8,
"tags": "google bigquery, google api nodejs client"
}
|
What is the difference in meaning and usage between "gather" and "collect"?
I was wondering what the actual difference between these two expressions is, since I recently read about "collecting mushrooms" but also about "gathering berries". Is there even any?
|
There is a large overlap for the usual senses (avoiding say the sense 'I gather you're going out with Jim). But not, as is ever the situation, a complete overlap.
I'd say that 'collect' has more of an 'into a nice, complete, well-arranged set' connotation, from the noun 'collection' which is often used for stamps, tea-cards, postcards, teapots ...
'Gather' has more the 'into a pile in a basket' flavour. I'd use it for both berries and mushrooms (unless I were collecting specimens).
|
stackexchange-english
|
{
"answer_score": 8,
"question_score": 6,
"tags": "word choice, differences"
}
|
Thread BLOCK issue in java
I have thread BLOCK issue. Please help me. In my class, i have two objects. One is for for synchronizing threads and the other is for doing actual business operations.
Here is my Class
Class A{
Object lock = new Object();
B b = new B();
public addSomething(){
synchronized(lock){
b.doThis();
}
}
}
I have a single instance of class A that is 'a' and from multiple threads accessing the method a.addSomething(). I am encountering thread BLOCK issue for this.
|
The problem probably is in `b.doThis()`. If it isn't well-behaved (it takes a very long time to execute or may never finish) all other threads that call `addSomething` will be blocked.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, multithreading, synchronization, block"
}
|
jQuery: Image in tooptip
I have table with products. What I want to do is display product photo in tooptip, after user hover over table row. Each row is one product. Let suppose that I have photos id in rows coded as row identifier.
<table>
<tr id="prod-37">
</tr>
<tr id="prod-38">
</tr>
</table>
I want jQuery function that will be product id aware. Link to photo is : /img/products/${id}.jpg
|
You could use <
There is an example of image and tooltip:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "jquery, tooltip"
}
|
twitter-bootstrap multiple '.container's
Is it good practice to use multiple `.container` and `.container-fluid`s? (not nested)
I'd like to create some segments of my page with `max-width` and some without any.
|
You can use any number of '.containers' and '.container-fluid''s in a page. Beware when you are using nested '.container' since its having fixed widths at breakpoints. The examples in the bootstrap site itself have used multiple containers. So you can use..
This is well answered here: Multiple and/or nested Bootstrap containers?
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "html, css, twitter bootstrap"
}
|
Android lollipop listview ending effect change color
How can i put and have this effect (the color of ending effects) that used in Android 5?
Which code should I use, and what's this name?
 = days, and the constraint $Y/250 + X/200 \le20$ is the constraint that Dean has 20 days to plant.
In your solution $x$ and $y$ represent days, so $x+y\le 20$ is the constraint that Dean has 20 days to plant.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "word problem, operations research"
}
|
Unity load files from outside of resources folder
In unity is it possible to load a resource that is out side of the resources folder. I want the user to be able to set a textAsset variable from a file outside of the Assets directory entirely.
|
You can't load `TextAsset` from an external path(path not in the Unity game). In fact, you can't even load it from a path in the project itself which is not the Resources path which is then loaded with the `Resources` API.
One option you have is to use the AssetBundle. Add the `TextAsset` to the Assetbundle then you can load the Assetbundle from any path and extract the `TextAsset` from it.
If you just want to load any file outside the Unity path, you can do this **without** `TextAsset`. Just use any of the `System.IO` API such as `File.ReadAllText` an `File.ReadAllBytes`. This should be able to load your file.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c#, unity3d"
}
|
In ∆ ABC, the altitude AD and the median BM are equal in length and they intersect inside ∆ ABC. If ABC is not an equilateral triangle, ∠MBC is
I have got no clue on how to proceed with the question as nothing is given except Median of one side =altitude of another moreover they also removed the possibility of equilateral triangle.
|
\tag{$\because$ AD=BM}$$ $$\fbox{$\therefore\angle\text{MBC}=30^o$}$$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "geometry, contest math, euclidean geometry, triangles, angle"
}
|
How to display a button based on object id and div id
I'm trying to display a button on a div, which will only show if the id of the div is within the JSON object. I've figured out a solution, but I think it's very poor as it is hardcoded. I'm fairly new to angular so if anyone could propose an alternate solution (to this and the coloring of the element itself on click as it has the same hardcoded issue) I would really appreciate it
The provided stackblitz is a simplified version of the problem
<
|
I think you looking for this: (the rest looks fine for me, maybe someone will offer a better way...)
<div #yourDiv id="1" style="height: 100px;" [ngClass]="{'colored': color === 1}">
<button id="abc" (click)="color = 1">WE WANT MORE BUTTONS HERE</button>
<button *ngIf="hasReminder(yourDiv.id)">HiddenButton</button>
</div>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, html, angular"
}
|
What do I need to learn as prerequisites for logic programming in miniKanren or Prolog?
I'm interested in logic programming for AI. Can I just learn logic programming without any math knowledge? If I couldn't, what do I need to learn?
|
Prolog is generally used for defining and solving logical formulas as the language is rooted in first-order logic. As _noncom_ mentions, one must understand first-order logic, specifically resolution and inference (ie backward chaining).
Pathfinding and graph traversals are common in the study of Artificial Intelligence and hence, one should have a solid grasp on graph theory and some knowledge of commonly used search algorithms {BFS, DFS, Iterative Deepening DFS, A*, etc} 1.
Ivan Bratko's **Prolog Programming for Artificial Intelligence** is a good place to begin reading 2. It is divided into two distinct sections; the first outlining the syntax and structure of the Prolog language and the second section outlining specific concepts related to the study of AI. The majority of the necessary mathematical background is discussed throughout the book.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "reference request, logic"
}
|
Is Django has something like "database middleware"?
Django has middleware to achieve do somthing when request and response. Is Django has "database middleware" to achieve do somthing when write data and read data.
For example,some old database does not support to utf8mb4 , so it can't support all of emoji. If Django has "database middleware" I will encode data when it is being saved , And decode when it is being reading.
|
You can overwrite model methods specially save method to achieve this.
Example from docs from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def save(self, *args, **kwargs):
# your intended modification
do_something()
super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
do_something_else()
Also check pre_save and post_save Model signals.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "python, django, database, middleware, django middleware"
}
|
Error in maven package/test commands due to external package
In eclipse I created a maven project, and then added the reference of another java-library-project (not created through maven).
When I am trying to run commands mvn test and/or mvn package; there are error occurred as the java-library (non-maven) project's package is not found as following:
**[ERROR] D:\testmaven\src\main\java\com\ezx\testmaven\testapp.java:[9,2] error: cannot find symbol [ERROR] symbol: class TestJavaAapp [ERROR] location: class testapp**
I am not really what I have to do to fix this issue, do I need to create local-repository for java-library-project(non-maven project) to package through maven? Also note this java-library-project(non-maven project) jar file is already deployed at server, so allI want to create a new maven-project jar file to deploy at server. Please help.
Thanks
|
If you compile/test your project with maven, you need to specify the dependencies to other libraries in the POM file. It is not enough to add a reference in the eclipse build path.
If you have a local library that is not in the maven repository, you can add this library to your local repository with the following mvn command:
mvn install:install-file -Dfile=<path-to-your-jarfile> -DgroupId=<your-groupid> -DartifactId=<your-artifactid> -Dversion=<your-version> -Dpackaging=jar
After this you can add the dependency in the pom.xml
<dependencies>
<dependency>
<groupId>your-groupid</groupId>
<artifactId>your-artifactid</artifactId>
<version>your-version</version>
</dependency>
</dependencies>
Now you should be able to compile and test your project with maven.
Hope that helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, maven"
}
|
Terraform if statement with true or false
I need to prepare if statement. I am wondering what is the best solution for this?
locals {
prod_ingress_certyficate = "${prod_ingress_certyficate == "true" ? var.prod_cert : var.test_cert}"
}
Is it the correct way? If the variable is true then user prod_cert and if false then use test_cert.
|
You can't reference `prod_ingress_certyficate` before it is defined. But, you could create a variable called `prod_ingress_certyficate` which then you use in `locals` in your condition:
variable "prod_cert" {
default = "prod_cert"
}
variable "test_cert" {
default = "test_cert"
}
variable "prod_ingress_certyficate" {
default = true
}
locals {
prod_ingress_certyficate = var.prod_ingress_certyficate == true ? var.prod_cert : var.test_cert
}
output "test" {
value = local.prod_ingress_certyficate
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "terraform"
}
|
Looking for a short story about a girl who can go anywhere without causing suspicion?
I remember reading a short story about a girl with an interesting superpower. She can go anywhere (e.g. any secure facility) without causing suspicion - the people around always take it for granted that she belongs there.
I tried a few Google searches to find the story, but I've had absolutely no results. Does anyone know what this is?
|
It is the short story "Access" by Andy Weir, the author of the comic _Casey and Andy_ and the novel _The Martian_. You can read the full text online on Andy Weir's creative writings website.
The girl describes her power like this:
> “As far as I can tell, everywhere I go, everyone thinks I’m _supposed_ to be there.”
|
stackexchange-scifi
|
{
"answer_score": 16,
"question_score": 19,
"tags": "story identification, short stories"
}
|
How to insert JavaScript pipe in TypoScript TYPO3 code
Is it possible to insert pipe `|` (from JavaScript code) into TypoScript? When I insert that code:
page.jsFooterInline {
10 = TEXT
10.dataWrap (
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? ' : ' + 'stats.g.doubleclick.net/dc.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
)
}
TYPO3 treat the pipe element as `wrap` and cut all of code behind the pipe.
Thanks for any help
|
You can insert inline javascript in typoscript template this way:
page.jsFooterInline {
10 = TEXT
10.value (
var _gaq = _gaq || [];
)
}
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 1,
"tags": "javascript, typo3, typoscript"
}
|
What is the value of $x$ if $x^x = x$?
What is the value of $x$ if $$x^x = x?$$ Can somebody show step by step please. Thanks!
|
Given:$\;\;$$x^{x} = x\;,\;$
Taking the logarithms on both the sides of equation we get
$ x\times\log (|x|) = \log (|x|)$
$ \therefore \;\: (x - 1)\times\log (|x|) = 0$
For the above equation to be true
Either $\;\;$$x-1 = 0\;\;$ or $ \;\;$$\log (|x|) =0$
Therefore $\;\;$$x = 1\;\;$ or $\;\;$$|x| = 1$.
Hence, the solution is $\;\;$$x = 1\;\;$ or $\;\;$$x = -1$.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 1,
"tags": "calculus, logarithms"
}
|
exec "tail -f xxx" with rust
I want to exec `tail -f a` with rust, but there is no output when I run following code:
fn main() {
// "a" is a text file and some characters have been written to it
let child = Command::new("tail").args(&["-f", "a"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn().expect("failed tail command");
let mut s = String::new();
child.stdout.expect("error of stdout")
.read_to_string(&mut s).expect("error of read all");
println!("{}", s);
}
When I append a new line to file `a` I just get `tail: a: file truncated`.
|
`read_to_string` reads until EOF, which will never be hit since `tail` outputs continuously and never ends. Change your program to read and print a line at a time.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "rust, command, tail"
}
|
Rendering MathJax in bootstrap popover
I'm trying to render mathematics in a dynamically-created bootstrap popover using Mathjax. I have created a jsfiddle at <
If you click the "Click to run Mathjax", the static div renders correctly, however if you click the "click to create popover, the popover is created and opened with the math written as latex. I would assume that clicking the Mathjax button again should rerender all mathematics on the page, in that the code: ` MathJax.Hub.Queue(["Typeset",MathJax.Hub]); ` should do this. (See MathJax Docs for this.)
I've seen some other people have trouble with this, but it appears mainly because they try to render the math before showing the popover.
|
The problem is that the backslashes are all doubled. Note that your popover shows `\\[\\frac{3}{4}\\]` rather than `\[\frac{3}{4}\]`. You do not need to double the backslashes in the `data-content` attribute, since that is not a JavaScript string. You will also want to do the `MathJax.Hub.Queue(["Typeset",MathJax.Hub])` command after creating the popover, since the data for it is not in the page until the popover is created.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "twitter bootstrap 3, mathjax"
}
|
PHP Sort array by field?
> **Possible Duplicate:**
> how to sort a multidemensional array by an inner key
> How to sort an array of arrays in php?
How can I sort an array like: `$array[$i]['title'];`
Array structure might be like:
array[0] (
'id' => 321,
'title' => 'Some Title',
'slug' => 'some-title',
'author' => 'Some Author',
'author_slug' => 'some-author'
);
array[1] (
'id' => 123,
'title' => 'Another Title',
'slug' => 'another-title',
'author' => 'Another Author',
'author_slug' => 'another-author'
);
So data is displayed in **ASC order** based off the **title field** in the array?
|
Use `usort` which is built explicitly for this purpose.
function cmp($a, $b)
{
return strcmp($a["title"], $b["title"]);
}
usort($array, "cmp");
|
stackexchange-stackoverflow
|
{
"answer_score": 146,
"question_score": 59,
"tags": "php, arrays, sorting"
}
|
TWebBrowesr Insert HTML code into body after navigate a local file
I use `TWebBrowser` in Delphi 10.x, I want to navigate to local file like `index.html` that will load some html/js/css, it is working and loaded successfully. Now I wanted to add to the body some html text, but it is not working, nothing happened (without raising errors).
//Navigate to local file
WebBrowser.Navigate(f);
//Writing a string to body
with WebBrowser.Document as IHTMLDocument2 do
begin
WebBody := body;
WebBody.insertAdjacentHTML('BeforeEnd', MyHTML);
end;
If i do not Navigate to a local file but write a whole HTML as string to it,
Navigate('about:blank', '', '', '', 'X-UA-Compatible: IE=edge,chrome=1');
...//write a initial html like above
then adding text by WebBody.insertAdjacentHTML, it is work fine.
How can I navigate local file then add some text to body (let assume it is chat app).
|
I found the solution depend on @whosrdaddy comment above but not using OnDocumentComplete.
I should wait browser to complete the navigating/processing it
procedure WaitComplete;
begin
with WebBrowser do
while Busy or (ReadyState <> READYSTATE_COMPLETE) do
begin
Vcl.Forms.Application.ProcessMessages;
end;
end;
WebBrowser.Navigate(f);
WaitComplete;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "delphi, webbrowser control, twebbrowser"
}
|
Disallow input if it matches predefined values
I would like to disallow certain input into an html input field.
Manually type in a value in a "Select" / Drop-down HTML list? this question covers how to recommend values while letting the user type.
I would like to let the user type and 'blacklist' certain values if they matches one of my predefined values and show a warning.
What is the easiest way to achieve this?
|
function myFunction(e) {
const val = e.value;
const blacklist = ["12345678", "qwerty"];
if (blacklist.indexOf(val) >= 0) alert("Blacklist");
}
<p>A function is triggered when the user releases a key in the input field.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction(this)">
You need to play with `keyup` event and provide a blacklist. You can do whatever you want with `val`, you could check if it's one of blacklist values(example above) or if it matches a RegExp pattern.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html"
}
|
Why do some factions refuse to trade?
Some factions really like me and a trade route is possible but they still and repeatedly refuse to trade with me – and other factions are neutral towards me but happily agree to a trade agreement. Can anybody explain the game mechanics the AI uses to determine if they accept or decline an offered trade agreement?
|
Possibly the most important factor that the AI uses is an unfortunate one: game difficulty. If the difficulty is above normal, the AI will only trade with you on the most favorable terms, and will deny trade relations for no particular reason. If you are playing on a harder difficulty, this might be your problem.
|
stackexchange-gaming
|
{
"answer_score": 0,
"question_score": 2,
"tags": "rome 2 total war"
}
|
Wordpress role is empty
happy Xmas and a happy New Year to all!
I'm trying to get the Wordpress role for a logged user but I'm getting an empty array. Notice that the user seems to be logged, as the first conditional doesn't get trigged. Do somebody guess what could be happening?
if ( is_user_logged_in() )
{
$user = new WP_User( $user_ID );
if (!empty( $user->roles ))
{
if(is_array($user->roles))
{
foreach ($user->roles as $role)
echo $role;
}
else
{
echo "Not array";
}
}
else
{
echo "Is empty";
}
}
else
{
echo "Not logged";
}
|
It could be that the $user_ID you're passing into WP_User() is not set. Depending on the context this may or may not be set. You might be able to obtain it by inserting in the line above:
global $user_ID;
That would definitely be the case if you're calling this from inside a function.
or to be sure, you could try:
$user_ID = get_current_user_id();
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "wordpress, roles"
}
|
Simplifying quartic complex function in terms of $\cos nx$
$$z= \cos(x)+i\sin(x)\\\ 3z^4 -z^3+2z^2-z+3$$ How would you simplify this in terms of $\cos(nx)$?
|
Hint:
since $z=0$ is not a solution we can divide by $z^2$ and we have:
$$ 3\left(z^2+\dfrac{1}{z^2}\right)-\left(z+\dfrac{1}{z}\right)+2=0 $$ than: $z=\cos x+i\sin x \Rightarrow z+\dfrac{1}{z}=2\cos x$ and $z^2+\dfrac{1}{z^2}=2\cos 2x$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "polynomials, complex numbers"
}
|
How to use hbm2ddl tool with Maven?
I would like to use the Hibernate3 plugin for Maven (developed by Codehaus) but according to the last release date (2009-01-21), it seems that it's not actively supported. I need to use the hbm2ddl tool provided by Hibernate. What do you think?
Where the hbm2ddl tool is provided? I guess this is not the Hibernate3 Maven plugin that includes it, but it is included in the hibernate dependencies?
Thanks
|
Probably you've found the old plugin's site that ends with 2.2 version. Check this site out: <
As you can see, there's 3.0 version released 2 months ago. We use it in our project with Hibernate 3.5 and it works pretty well, doing what it is supposed to do.
Hibernate doesn't need to be provided to the plugin (at least directly), because under the cover this stuff uses Hibernate3 Ant Tasks (from `hibernate-tools` artifact) with Maven AntRun Plugin. So the plugin has a dependency on Hibernate (3.3.2.GA version) itself. As I said however, we use it with Hibernate 3.5 without any problem so far.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "maven, maven 3, hbm2ddl, hibernate tools"
}
|
Grails form tag ID property for css
When you use grails form tag how can you have an id selector in the rendered HTML form tag?
If you use
<g:form action="register" controller="registration" id="registrationform"/>
it renders the form post URL as the `/registration/register/registrationform`.
Is there a way to provide a property that renders ?
|
Easiest way is
<g:form action="register" controller="registration" name="registrationForm" />
The name attribute will be used to render the id attribute
You could also use the URL parameter and pass in a map for your action and controller.
<g:form url="[action:'register', controller:'registration']" id="registrationForm" />
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 6,
"tags": "grails, gsp"
}
|
How to remove backslash from string in Python?
I need to remove backslash (`'\'`) from string in Python.
`str2 = str1.replace('\', '') ` isn`t working.
How can i do it?
|
This is due to \ being the escape sequence character in python so you have to do \\\
str2 = str1.replace('\\', '')
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "python, backslash"
}
|
How to merge 2 binarybyte array in java
I have 2 byte array like this:
byte a[i]=1;
byte b[i]=0;
I want to merge it so that the output result becomes "10". I try to use arraycopy and make new output
byte[] output=a.length+b.length;
but it still doesn't work like my expectation. Anybody knows how to solve it?
|
Try this
byte[] first = {1,2,4,56,6};
byte[] second = {4,5,7,9,2};
byte[] merged = new byte[first.length+second.length];
System.arraycopy(first,0,merged,0,first.length);
System.arraycopy(second,0,merged,first.length,second.length);
for(int i=0; i<merged.length;i++)
{
System.out.println(merged[i]);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "java, arrays"
}
|
Yii2 filter data in controller
I'm new to YII framework, I want to filter my data on the frontend using product, month and year dropdown. Here is what I have in my controller
<?php
public function actionProducts()
{
$sql = "SELECT product, cost, supplier, month, year
FROM products
WHERE year = :year
GROUP BY product, month, year";
$product = Data::findBySql($sql, [':year' => 2022])->asArray()->all();
$response = ['data' => $product];
header('Content-Type: application/json');
return json_encode($response, JSON_NUMERIC_CHECK);
?>
How do I approach this?
|
First, make your query parameter part of the function definition:
<?php
public function actionProducts($product, $month, $year)
{
$sql = "SELECT product, cost, supplier, month, year
FROM products
WHERE year = :year AND month=:month AND year=:year
GROUP BY product, month, year";
$product = Data::findBySql($sql, [
':year' => $year, ':month'=>$month, ':product'=>$product
])->asArray()->all();
Second, JSON responses are fully supported by Yii including array conversion:
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ['data' => $product];
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, filter, yii2, dropdown"
}
|
How to stop Network Manager from continually prompting for wireless password
How can I stop NetworkManager from continuously asking for the wireless password when trying to reconnect after the connection is temporarily dropped?
Unlike this post, this happens for me without suspending. My wireless `WPA2` connection might drop a couple times, and NetworkManager will automatically reconnect. However, eventually NetworkManager will start prompting for the password, which is already filled in. Clicking `Show password` confirms it's already the correct password, and clicking `Connect` without changing anything also successfully connects.
Why is it doing this, and how do I stop it?
|
Try restarting the network manager:
sudo service network-manager restart
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 13,
"tags": "networking, wireless, network manager, wpa2"
}
|
Construction of lines through a given point, cutting two given circles in congruent chords
> Given a point $P$ and two circles $\Gamma$ and $\Gamma'$ with centers $O$ and $O'$. I'm searching for a method to construct lines passing through $P$ and defining on each circle chords of same length.
A geometer professor made the following drawing to illustrate the problem.
^2} \quad \quad (1)$$ and $$R = \sqrt{R_1^2-(\frac{w}{2})^2}\quad \quad (2)$$ Let $OP=d$, $O'P=D$,and $OO'=L$.
Let $PS$ the height of $\triangle POO'$ relative to side $OO'$, and let's call $PS=H$ and $O'S=\delta$ for short. We have:
$$\delta = \frac{D^2-d^2+L^2}{2L} \quad \quad (3)$$
and
$$H^2 = D^2 - \delta^2 \quad \quad (4)$$
The value of $w$, so that P is a point of the secant lines that does not cross the segment $OO'$, can be found solving equations (1), (2), (3), (4) e (5).
$$\frac{LR}{R-r} -\delta = \sqrt{(\frac{HL} {R-r})^2-R^2} \quad \quad (5)$$
That value of $w$ makes the two secant lines relative to $\Gamma$ and $\Gamma '$ be also tangent lines of $\Lambda$ and $\Lambda '$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 4,
"tags": "geometry, euclidean geometry"
}
|
Why is $\sum\limits_{k=0}^{n}(-1)^k\binom{n}{k}^2=(-1)^{n/2}\binom{n}{n/2}$ if $n$ is even?
> Why is $\displaystyle\sum\limits_{k=0}^{n}(-1)^k\binom{n}{k}^2=(-1)^{n/2}\binom{n}{n/2}$ if $n$ is even ?
The case if $n$ is odd, is clear, since $\displaystyle(-1)^k\binom{n}{k}+(-1)^{n-k}\binom{n}{n-k}=0$ (we have $(n+1)/2$ such pairs.)
but if $n$ is even we have no symmetry, I tried to consider the odd and even terms separately but with no success.
Do you have an idea ? Thanks in advance.
|
$$\sum_k (-1)^k{n\choose k}^2= \sum_k (-1)^k{n\choose k}{n\choose n-k}$$ is the coefficient of $x^n$ in $$(1-x)^n(1+x)^n=\sum_k{(-1)^k{n\choose k}}x^k\cdot \sum_k{{n\choose k}}x^k.$$ As $(1-x)^n(1+x)^n=(1-x^2)^n$, the claim follows (and we additionally see that $\sum_k (-1)^k{n\choose k}^2=0$ if $n$ is odd).
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "combinatorics, summation, binomial coefficients, binomial theorem"
}
|
A system of three linear equations
## Problem
If the linear system $$ \begin{align*} ax+by&=k\\\ cx+dy&=l\\\ ex+fy&=m \end{align*} $$ is consistent, why at least one equation can be discarded from the system without altering the solution set? (Anton Elementary Linear Algebra 9th edition, Exercise Set 1.1, problem 13)
## My Attempt
If the linear system is consistent, then it has at least one solution (exactly one solution or infinitely many solutions). If each of the linear equations in the system correspond to lines $l_1$, $l_2$, and $l_3$, then:
* If we have infinitely many solutions, then the three lines are coincident. Two of the lines are coincident so the third line can be discarded without altering the solution set.
* If we have exactly one solution, then the three lines intersect in exactly one point. Two of the lines intersect in one point so the third line can be discarded without altering the solution set.
|
Your attempt is correct. (Just be careful about the geometric interpretation of equations as lines; as long as you have clearly defined how you are converting an algebra problem into a geometry problem and back, nobody can question you.)
Another [algebraic] approach is to show that two of the equations are sufficient to solve for $x$ and $y$ in terms of the coefficients (you can use matrices, the standard substitution method, or whatever else to do this). As you have assumed nothing about the actual coefficients, you can choose any two of the given equations and you will always be able to find the solution. This method requires some special handling of the infinite solutions or no solutions cases, but does not require geometry.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 3,
"tags": "linear algebra"
}
|
Does Oracle Database have open issue list?
I am carrying out some study of bugs in Databases, so I have to dig into those bugs reported by the users of databases. As we know, MySQL, MariaDB, PostgreSQL have ether open bug repository or open mailing list to track. HOWEVER, Oracle DB does not have such kind of thing.
Is that right ?
Thank you.
|
Oracle is not open-source, so no, they don't have a public bug tracker. If you have a support contract, you can see some bugs on Oracle Support, fixed and some not, but there are also unpublished bugs, not visible to the public.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "oracle"
}
|
An integration-via-summation formula
For symbolic transformation of integrals and series I occasionally use this formula: $$\int_0^1f(x)\,dx=-\sum_{n=1}^\infty\sum_{m=1}^{2^n-1}\frac{(-1)^m}{2^n}f\left(\frac m{2^n}\right)\tag{$\diamond$}$$ I believe it holds for all piecewise-smooth functions $f$ of bounded variation defined on $(0,1).$ Is it correct? I also think this condition might be too tight and can be relaxed. Could you please suggest a wider natural class of functions for which $(\diamond)$ holds? Is there a known name for this formula? Could you provide some reference for it?
|
In this paper by A.A. Ruffa, this formula is shown to derive from the method of exhaustion of the ancient Greeks which was used to find "the area of a shape by inscribing inside it a sequence of polygons whose areas converge to the area of the containing shape".
Accordingly the author call it the generalized metthod of exhaustion. Two proofs of the formula are given and the case of an infinite boundary for the integral is discussed. Several decompositions of elementary functions are also given.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 8,
"tags": "calculus, integration, sequences and series, definite integrals, summation"
}
|
Сортировка списка в kotlin
Не совсем понимаю как выполнить сортировку:
У меня есть список из элементов, которые имеют два свойства: **" fileName"** (который является строкой) и **" checkFile**" (который является булевым). С помощью checkFile файлы в списке сортируются на правильные(которые прошли проверку) и неправильные.
**Мне нужно отсортировать список так, чтобы при сортировке файлы, которые не прошли проверку были всегда сверху, а после них правильные**
_Как возможно прописать условие?_
|
В kotlin есть возможность сортировать коллекции по любому заданному вами принципу с помощью метода `sortBy()`, который принимает на вход лямбду.
Вот пример для вашей ситуации:
fun main() {
val list = listOf(3, 2, 1).withIndex()
println(list.sortedBy { it.value })
println(list.sortedBy { it.index })
}
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "kotlin, list, список"
}
|
imagemagick "convert" command different outputs
I am trying to convert a 8 page pdf to 8 separate pbm files, using imagemagick. When I do `convert test.pdf test.jpg`, 8 jpg files (test-0.jpg, test-1.jpg ..) are created, but when I use the command `convert test.pdf test.pbm` only 1 pbm file (test.pbm) is created. What should I do?
|
convert test.pdf out-%0d.pbm
This will give you out-0.pbm out-1.pbm... I don't know why imagemagick does this automatically for jpg but not for pbm.. If you want to pad the number to be 000-999 then add a "3" in front of the d.
Example:
convert test.pdf out-%03d.pbm
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "image, imagemagick"
}
|
Computing a fourth moment $E[Z^4] $
Suppose that $\epsilon_1,\ldots,\epsilon_n$ is a sequence of independent random variables, each taking the values $1,-1$ both with probability $1/2$. If $\alpha_1,\ldots,\alpha_n$ is a sequence of real numbers, define a random variable $Z$ and $\sigma\ge 0$ by,
$$Z = \sum_{k=1}^n\epsilon_k\alpha_k,\ \sigma^2 = \sum_{k=1}^n\alpha_k^2$$ so that $Z$ has mean zero and variance $\sigma^2$.
How can we show that
$$E[Z^4] \le 3\sigma^4$$
|
Let $b_k=a_k\epsilon_k$. When you expand out $$ Z^4=\left(\sum b_k\right)^4, $$ you get terms like $$ b_i^4,\quad b_i^2b_j^2,\quad b_i^3b_j,\quad b_i^2b_jb_k,\quad b_ib_jb_kb_\ell, $$ where $i,j,k,\ell$ are distinct indices. The expectations of each of these (using the fact that the variables are independent with zero mean) are equal to $$ a_i^4,\quad a_i^2a_j^2,\quad 0,\quad 0,\quad0. $$ Therefore, $$ E[Z^4] = \sum_ia_i^4+3\sum_{i\neq j}a_i^2a_J^2\le 3\sum_{i,j}a_i^2a_j^2= 3(\sigma^2)^2 $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "probability, integration, probability theory, inequality"
}
|
Posting JSON from hidden form field
I am intercepting a form post using jQuery. With the form fields I am creating a JSON object which is stored in a hidden form field. The value that is passed in to the form field is similar to the following:
{"Status" : "Closed", "Location" : "Glasgow", "Date" : "2012-02-15"}
But if I echo the object from the $_POST variable:
echo $_POST['JSON'];
It output's the following:
{\"Status\" : \"Closed\", \"Location\" : \"Glasgow\", \"Date\" : \"2012-02-15\"}
I have tried running this through _stripslashes()_ and _urldecode()_ but I have had no joy. I understand that I could just replace the back slashes with a replace function but thats a bit too much of a hack.
Has anyone came across this malfored JSON across post before?
**Note:** This is on the back end of a Wordpress site. I am unsure if that would cause this effect.
|
Looks like you server has magic_qoutes_gpc 'on'. (
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "php, jquery, forms, post"
}
|
Android - How to make a background pattern combining bitmaps?
I know how to make a background pattern repeating a bitmap. I also saw a way to combine two bitmaps using Canvas. But I want to make a repeating bitmap in combination with a gradient drawable to make a background. I have a .png file that it's partially transparent and I want to repeat it along with a gradient drawable (normal gradient XML).
This is the PNG: <
Is there a way to do this?
Thanks in advance.
|
You can use an XML bitmap to create a tile pattern:
<bitmap xmlns:android="
android:src="@drawable/my_png"
android:tileMode="repeat" />
Then you should be able to use this as part of a LayerList drawable that also includes your gradient. Then use the layer list as the background drawable.
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 4,
"tags": "android, background, drawable"
}
|
How to truly make a navigation bar 100% width
I'm working on my personal website and when I originally designed it (< it had two horizontal bars that where supposed to extend 100% of the total width of the website, but when I wrote the code I could not get the page to display properly (please see what I mean - www.gaspyweb.com). What am I doing wrong here? What can I do to get the Navigation and the footer bar to display like in the design that I made?
|
The `<body>` tag of your page has an 8px margin. Once you remove that margin your header and footer bars should extend to 100% of the page. Just to keep it simple add code like this:
html, body {margin: 0; padding: 0;}
The easiest way to figure this out is to use a tool like Firebug to check your elements of your page. It will quickly show you where your CSS issue is.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, css"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.