INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to check if my Queue (Service Broker) is enable or not?
rarely, for reasons that have not yet identified, my queue is disabled, when this happend, I enable again with this query:
ALTER QUEUE [MyQueue] WITH STATUS = ON;
but, i want to know when the queue is disabled, such as an event (T-SQL), or check each "x" time if queue is enabled. | Look into `sys.service_queues`:
select is_receive_enabled
from sys.service_queues
where name = N'MyQueue';
Your queue gets disabled by the poison message handling mechanism.aspx). When this happens an event is fired which can be captured via Event Notification, see Service Broker Application Queue Disable Event. | stackexchange-stackoverflow | {
"answer_score": 21,
"question_score": 11,
"tags": "sql, sql server 2008, service broker"
} |
Is there a way to override LaTeX's errors about double subscripts and superscripts?
Minor point about LaTeX that bothers me. When one writes
a^b^c, a_b_c
or
a'^b
in math mode, LaTeX gives an error message complaining about multiple super/subscripts. This is particularly annoying after replacing a string containing a super/subscript or when using the apostrophe, `'`.
Is there a way to override the error and have LaTeX simply output
a^{bc} a_{bc} {a'}^b
and so on? | The following is what you wish
\catcode`\^ = 13 \def^#1{\sp{#1}{}}
\catcode`\_ = 13 \def_#1{\sb{#1}{}} | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 5,
"tags": "latex, tex, mathematical expressions"
} |
What type of database is a data.frame?
I was wondering what type of database is a data.frame. If we take a look at this answer at Quora, we have a good guide of what type of databases there are. Roughly speaking, we have relational databases (which I guess is not the case of a Data.Frame) and noSQL databases (columnar, Key-value, Document Store and Graph).
So, my question is: What kind of database is a data.frame? | A data frame is a relation. Each row is a tuple, each column is an attribute. See:
<
however it is strictly ordered, so I imagine DB theory purists would insist there is also a hidden attribute that defines the ordering that R uses. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "database, r"
} |
Fourier Transform of Poisson Equation
While trying to solve the Poisson Equation by using Green's Function I have to Fourier transform the equation i.e
$$-\nabla^{2}\phi(r)=\rho(r).$$
In the book after Fourier transform, the solution is written as $$k^{2}\phi(k)=\rho(k).$$
I can understand the expression in the right hand side, but why there is $k^{2}$ in the left hand side? | It's easiest to see if you start with the definition of the inverse fourier transform
$$ f(\mathbf x) = \int d\mathbf k \, \hat f(\mathbf k) e^{i \mathbf k \cdot \mathbf x} $$
and take a laplacian of both sides
$$ \nabla^2 f(\mathbf x) = \nabla^2 \int d\mathbf k \, \hat f(\mathbf k) e^{i \mathbf k \cdot \mathbf x} = \int d\mathbf k\, \hat f(\mathbf k) \nabla^2 e^{i \mathbf k \cdot \mathbf x} = \int d\mathbf k \, [ -k^2 \hat f(\mathbf k) ] e^{i \mathbf k \cdot \mathbf x}$$
So we say $$ \mathcal{F} \left[ \nabla^2 f(\mathbf x) \right] = -k^2 \hat f(\mathbf k)$$
_Note: depending on your field and book, your mileage may vary when it comes to factors of $2\pi$ or signs_ | stackexchange-math | {
"answer_score": 12,
"question_score": 5,
"tags": "partial differential equations, fourier analysis"
} |
How to add the source packages on launchpad to my PPA?
I have a working project on launchpad, with generation of packages for three version of Ubuntu distribution and all is fine there. However, I cannot find the option to tell launchpad to put the source package on my PPA for people to download. I would like my users to be able to do:
$ apt-get source my-package
And get the source package that they can compile on their own machine if they want to.
Is it possible to make the source package available from my PPA?
Just in case, here is my project: < | Just point your package users to add PPA with source option:
sudo add-apt-repository -s ppa:pierre-barbierdereuille/ppa
instead of binary builds only:
sudo add-apt-repository ppa:pierre-barbierdereuille/ppa
**Reference:** `man add-apt-repository`
> **-s** , **\--enable-source** Allow downloading of the source packages from the repository | stackexchange-askubuntu | {
"answer_score": 3,
"question_score": 3,
"tags": "apt, package management, ppa, source packages"
} |
Scala Option - Getting rid of if (opt.isDefined) {}
My code is becoming littered with the following code pattern:
val opt = somethingReturningAnOpt
if (opt.isDefinedAt) {
val actualThingIWant = opt.get
}
Is there some way to simplify this? (it seems needlessly complex and a code smell). Ideally it would be something like:
if (Some(actualThingIWant) = somethingReturningAnOpt) {
doSomethingWith(actualThingIWant)
}
Is anything like that possible? | Maybe something like this:
somethingReturningAnOpt match {
case Some(actualThingIWant) => doSomethingWith(actualThingIWant)
case None =>
}
or as pst suggests:
somethingReturningAnOpt.foreach { actualThingIWant =>
doSomethingWith(actualThingIWant)
}
// or...
for (actualThingIWant <- somethingReturningAnOpt) {
doSomethingWith(actualThingIWant)
} | stackexchange-stackoverflow | {
"answer_score": 38,
"question_score": 31,
"tags": "scala, scala option"
} |
How to create a caller/callee graph?
I want to display a 'flow' chart of a process showing time spent in children relative to the parent. For example, say that I have MethodA which calls MethodB and MethodC. 30% of the time relative to MethodA in MethodB and 70% in MethodC. I want to display something like this: !enter image description here
I know this is a sort of vague question, so to narrow the scope, I don't know what kind of chart this might be. What kind of Libraries might provide the capability to display this type of chart? | I've used `Graph#` for same purpose - but this is a WPF library. Good news for you is that it uses `QuickGraph` (< library internally and you can google around that library to see whether there is any code for it to be used as part of winforms. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, winforms, charts"
} |
How can I add a ResourceDictionary defined in a subfolder to App.xaml?
All of the code samples I've found so far reference a Resource Dictionary that's not in a project subfolder (the dictionary is at the root of the project). I have mine in a subfolder, and I can't figure out how to get WPF to find it. This doesn't work...
<Application.Resources>
<ResourceDictionary Source="/Skins/Black/GlossyButtons.xaml"/>
</Application.Resources>
The ASP.Net tilde syntax doesn't seem to work either.
Is this the best way to include a ResourceDictionary in your app so that WPF can find resources? My goal in this particular case is to apply a style defined in GlossyButtons.xaml to all of the buttons in my app. | Discovered the problem - WPF couldn't find an assembly referenced in GlossyButtons.xaml, but didn't show the actual error (that there was a problem with the .xaml) until I had compiled and executed several times. The error displayed (at first) was that GlossyButtons.xaml couldn't be located.
That was a little confusing. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 8,
"tags": "wpf, xaml, resourcedictionary, app.xaml"
} |
Find Index of DataRowView in DataView
Is there a way to get the index of a selected `DataRowView` in a `DataRow`?
I current have the following code
private long GetSelectedIndex(DataView dataView, string searchString)
{
long selectedIndex = 0;
foreach(DataRowView dataRow in dataView)
{
if(dataRow.Row.ItemArray.Contains(searchString)
{
//Do Something.... I've tried everything to get the index out of the dataRow
}
}
return selectedIndex;
} | Maybe try
int index = dataView.Table.Rows.IndexOf(dataRow.Row) | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "c#, dataview, datarowview"
} |
mysql query to php array and display the array
$query2 = "SELECT * FROM `Listing` WHERE listingid = '{$myID}'";
if(!($result2 = @ mysql_query($query2,$connection)))
echo "query failed<br>";
$result_array = array();
while($row2 = mysql_fetch_assoc($result2))
{
$result_array[] = $row2;
}
foreach ($result_array as $key => $val) {
echo "$key = $val\n";
}
Listing (Table) has 7 fields.
I get a bunch of "0 = Array"
How do I store mysql query results into php array and display them? I want to have it as array first so i can sort them. | You are actually storing them. The code you have listed is storing them in array of arrays to see them you can modify the `for` with:
foreach ($result_array as $key => $val) {
echo "$key = " . print_r($val, true) . "\n";
}
$val is actually an array containing all the fields of a row. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql"
} |
Some weird propositions in probability
I have met some weird statements in probability that I am not sure whether they are true or false. For all event space A:
$A\subset\Omega$ and $\Omega\subset A$ ($\Omega$ is the sample space).
This is really weird, because that would mean $A=\Omega$. In my opinion, it must be
$A\subset\Omega$ and $\emptyset\subset A$ ($\emptyset$ represents impossible events) | Your second conclusion, $\emptyset \subset A \subset \Omega$, is correct. Every set has the empty set as a subset, and every event is a subset of the sample space.
If you found this in a textbook, try looking up its errata online. You can usually find them for free on the textbook's website. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "probability"
} |
graph in console visual c++ real time
I want to make graph from the result of the sensors, I read the sensors from arduino board. I use console application program in VC++ 2010.
But after I search in the google, it seems imposible to make graph from the console application.
Is there any library or other application to do it? | You _can_ make graphs in a console program, but they have to be using ASCII instead of, well, graphical. Something like this:
Y
^
| *
| * *
| * *
| * * *
+-------> X
A B C
If you want a "proper" graphical application, you have to use another project-type when creating the project.
Unfortunately if you have the Express version of Visual Studio you can't really make a GUI application easily, you have to make a WIN32 project and handle the GUI much yourself. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "c++, graph, console application, real time"
} |
PHP check in Array from MYSQL
I want to search in a array from mysql if one dates from a columns is the current date. For exemple i have this dates in array:
2013-09-03,2013-09-04,2013-09-06,2013-09-05,2013-09-07
and the current date: 2013-09-03 so i try this:
$dates = unserialize($row['dates']);
$currentDate = date("Y-m-d");
$array = array($dates);
if (in_array($currentDate, $array)) {
echo "IS HERE !";
}
but with out luck. | You said `var_dump($row["dates"])` results in:
array(1) { [0]=> string(54) "2013-09-03,2013-09-04,2013-09-06,2013-09-05,2013-09-07" }
Meaning `$row["dates"][0]` contains your string with all dates.
You can do this to test:"
$currentDate = date("Y-m-d");
$date_array = explode(',', $row["dates"][0]); // Create an array with all your dates
if (in_array($currentDate, $date_array)) {
echo "IS HERE !";
}
You can also do this:
// Because $row["dates"][0] is a string with dates, you can simply search the date as string.
if(strpos($row["dates"][0], $currentDate) !== FALSE){
echo "IS HERE !";
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, arrays"
} |
Adding an Image programmatically between an UIImage and UILabel
I have an `UIImage` above which I am supposed to add another `UIImage` programmatically, above which there will be an `UILabel`. I successfully added the Image but it overlaps the Label.
If 1. BG image 2.Image to be added programmatically 3. Label,
then the sequence I want is, 1 2 3
and what I get is
1 3 2
2 overlaps my Label. I have tried Send to Back, Bring to Front and `bringSubviewToFront`. It did not work. | What you should do is add the particular images in that sequence itself, i.e. in the ViewWillAppear or the ViewDidLoad method use the method `self.view addSubview:BGimage` . Then add the next image on the previous one like `BGimage addSubview:image2` . Similarly add the UILabel on the Image 2 like `Image2 addSubview:Label`
This will put your images and the label in the particular sequence you want :) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone, objective c, ios"
} |
Newbie: C# List returns back System.Collections.Generic.List
Seems this would be pretty simple:
class Program
{
static void Main()
{
List<string> lst = new List<string>();
lst.Add("String 1");
lst.Add("String 2");
foreach (string item in lst)
{
Console.WriteLine(lst);
}
Console.ReadLine();
}
}
However it returns:
System.Collections.Generic.List`1[System.String] | Try this instead:
foreach (string item in lst)
{
Console.WriteLine(item);
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "c#, list, collections, foreach"
} |
UILabels text disappears when animating
I have this code:
- (void)my_button_tapped
{
if (my_button.tag == 0)
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
my_label.frame = CGRectMake(450, 455, 200, 20);
[UIView commitAnimations];
[my_button setBackgroundImage:[UIImage imageNamed:@"check.png"] forState:UIControlStateNormal];
my_button.tag = 1;
}
else
{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
my_label.frame = CGRectMake(450, 455, 0, 20);
[UIView commitAnimations];
[my_button setBackgroundImage:nil forState:UIControlStateNormal];
my_button.tag = 0;
}
}
When I tap my_button first time the label is expanded into 200px width, when I press the button again the label decreases to 0px width but immediately at button press the text disappears. What's wrong? | The problem is that the button knows that at the end of the animation the text won't be able to be displayed (due to the width) and so it hides the text label. To get the effect you want you probably want to use a `CGAffineTransform` scale to compress it to zero width. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "objective c"
} |
WM_PAINT and DX12
**Hi!**
Could someone anwser my question, please? My program has one thread for the window's message loop and another for D3D12 rendering. Everything is fine, but the question is what window proc. should do with WM_PAINT? Currently the app has such fragment of code:
case WM_PAINT:
return 0;
Is there any better/more efficient way, or that is OK? | Typically a Win32 render loop will have a trivial paint for those cases where the rendering isn't started or is halted for some reason (so you at least can't see 'junk' behind your window).
{
case WM_PAINT:
{
PAINTSTRUCT ps;
(void)BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
break;
...
}
return DefWindowProc(hWnd, message, wParam, lParam); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "windows, winapi, visual c++, directx 12"
} |
Bitwise-operator standard for different sized variables
int8 a = <some value>;
int16 b = <some value>;
a |= b;
* What is the defined behaviour for this example?
* Will `a` be threaded as a 16-bit integer?
* Will `b` drop the 8 most significant bits?
* Will both of them use the register size and drop all most significant bits it cannot assign?
* Is it undefined behaviour? | As on most common systems† (all I've ever used), both `int8_t` and `int16_t` have lower conversion rank than `int`, both operands will be promoted to the latter.
Then, the `operator |=` operates on those two (commonly 32 bit) `int`s and in the last step, the resulting `int` is converted to `int8_t`. If the result does not fit into `int8_t`, `a`'s value is implementation defined. Usually, it just drops the extra bits.
* * *
† Actually, that holds on all systems as `int` is at least 16 bit and `long` at least 32 bit, so neither of the types you use can have a rank greater than `int`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, bitwise operators"
} |
Change of intended date of arrival
I was recently issued with a U.K. Standard visitor's visa. It's valid for 6 months and multi-entry. When I applied, my intended travel dates were in December. However with new family developments I am unable to travel in December. My purpose for traveling to the U.K. hasn't changed, nor has the duration, the only thing that has changed is the date. Would I have problems entering the U.K on a changed date that is still within my visa validity? | Since you journey is still within your visa validity period, another entry date will not be an issue. You can enter and leave the country between two dates printed on your visa - "valid from" and "valid until".
And entry date is not printed on the visa anyway so no one would even know that your planned arrival date had changed. | stackexchange-travel | {
"answer_score": 2,
"question_score": 3,
"tags": "uk"
} |
how to disable <select> based on user selection in another <select>
i have two `<select>`, named **category** and **category_sport**
i want `<select name='category_sport'>` disable , if i click `<option>sport</option>` in `<select name='category'>` , i want enable `<select name='category_sport'>`
Anyone have an idea how ?
function disable()
{
document.getElementById("katOl").disabled=true;
}
function enable()
{
document.getElementById("katOl").disabled=false;
}
the script above is used in `<option>` ex:
<select name='category'>
<option value="1" onclick='enable()' >sport</option>
</select>
<select id='katOl' name='category_sport'>
<option value="1">Football</option>
</select>
but isn't work | try something like this
javascript
function check(val)
{
if(val == '1'){
document.getElementById("katOl").disabled=true;
}else{
document.getElementById("katOl").disabled=false;
}
}
html
<select name='category' onchange="check(this.value)">
<option value="" >SELECT</option>
<option value="1" >sport</option>
</select> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, jquery, html"
} |
Adding new item to pageCollection's object
i am working with an pageCollectionin silverlight ,i have some remove and addition work in to the pagedviewcollection's object
i was able to remove from collection as below
_pageCollection.RemoveAt(_index);
but i am not able add an item to the pageCollection .how to add an item to the _pageCollection. i feel it should be dealt with below code
_pageCollection.AddNew();
but i amnot able to get how to proceed? | If you use a PagedCollectionView you have to set a source IEnumerable. If you add it to this collection it will work (assuming that your PCV is working with a list of Products which have an id).
myPagedCollectionView = new PagedCollectionView(myCollection);
myCollection.Add(new Product(){Id=5});
If you work with AddNew you have to do it like this :
var obj = (Product)myPagedCollectionView.AddNew();
obj.Id = 5;
Hope this is what you needed. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "silverlight, pagination"
} |
Why is this an invalid operand?
I have the following ASM file generated by a compiler I'm writing:
; This code has been generated by the 7Basic
; compiler <
; Uninitialized data
SECTION .bss
v_0 resb 4
v_4 resb 4
v_8 resb 4
; Code
SECTION .text
push 1
pop eax
mov v_0, eax
push 2
pop eax
mov v_4, eax
mov eax, v_0
push eax
mov eax, v_4
push eax
pop ebx
pop eax
imul eax,ebx
push eax
pop eax
mov v_8, eax
When I try to compile it, I get the following errors:
> test.asm:16: error: invalid combination of opcode and operands
> test.asm:19: error: invalid combination of opcode and operands
> test.asm:29: error: invalid combination of opcode and operands
This really doesn't make sense because according to the NASM docs, I'm allowed to:
> MOV mem_offs, reg_eax 386
Why can't I perform this operation? | You need square brackets to dereference the pointers:
mov [v_0], eax | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "assembly, nasm, opcode, operand"
} |
How to add a raw itinerary with Leaflet?
I using leaflet. With it I'm displaying two different map : one is with open street map, the other is from ign geoportal.
How to add a raw itinerary with Leaflet ?
I expect this itinerary to be displayed on both map.
Thanks | If you have two maps you should add the itineray to each map
var map1 = L.map('map1', {
center: [51.505, -0.09],
zoom: 13
}),
map2 = L.map('map2', {
center: [51.505, -0.09],
zoom: 13
}),
latlngs = 'Your latlngs array',
itinerary = L.polyline(latlngs, {color: 'red'});
map1.addLayer(itinerary);
map2.addLayer(itinerary);
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "leaflet"
} |
Проблема с форматированием текста из файла
Я извлекаю текст из файла, где есть строки в тегах `<b>` и `<i>` и вставляю его в приложение, но в итоге текст получается в исходном формате (с этими тегами, без жирного шрифта и курсива).
Как исправить?
`label.setText(SplitLineFile.split_line('lessons.txt')[number] )`
:
def __init__(self):
super().__init__()
self.label = QLabel("""
x18
<br>x19<br>
<b>Hello <i>World</i></b>""")
self.label.setTextFormat(Qt.RichText) # <---- попробуйте закомментировать
self.layout = QGridLayout(self)
self.layout.addWidget(self.label)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
\/[\d]*\-(.*)$ $1/$
This looks good with a testing tool, but this still doesn't work on my wordpress site.
My htaccess:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# BEGIN - Custom Redirects
RedirectMatch 301 /heute(.*) /$1
RewriteRule ^(.*)\/[\d]*\-(.*)$ $1/$2
# END - Custom Redirects
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress | Not sure if this will work with every URL you have, but this whould give you a base to work off of. Note that this sepcifically checks for 5 digit IDs. If you want this to be more flexible, simply change `{5}` to a different quatifier like `*`. Also note that this might match URLs you don't want to redirect.
> * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
Your rule:
RewriteEngine on
RedirectMatch 301 ^(.*)\/[\d]{5}\-(.*)$ $1/$2
Or a more precise variant to avoid unwanted redirects:
RewriteEngine on
RedirectMatch 301 ^(.*example\.com\/.+)(?:\/[\d]{5})\-(.*)$ $1/$2
Since you mentioned that you're new to regex, here are some tools that will help you get started:
Online Regex building/testing tool: regex101.com
Online .htaccess rewrite testing tool: htaccess.madewithlove.be | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 0,
"tags": "redirect"
} |
What is the rotor speed of an EC135/H135 helicopter?
I need the Eurocopter EC135's rotor speed to estimate its natural frequencies. I checked the helicopter TCDS but I only find there percentage values. For example for the P1 variant: 104% Max and 95% Min. This is percentage of what? In other helicopters I normally get concrete values in RPM. | The main rotor speed (100%) of the EC-135 is 395 RPM. | stackexchange-aviation | {
"answer_score": 4,
"question_score": 4,
"tags": "helicopter"
} |
Properties in my code behind all go null when Wizard control's next button is clicked,
I have a wizard control, and I have this code
protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
if (Wizard1.ActiveStepIndex == 0)
{
if (firstName != null && lastName != null)
{
Wizard1.ActiveStepIndex = 1;
}
else
{
e.Cancel = true;
}
}
}
when the code gets to firstName and lastName they are both null, I have populated them in a previous method above, they are not empty until this event fires. My searching has only let me to something about causes validation, is this the culprit? | Properties will be lost on postback unless you store them in a ViewState or Session or Database.
e.g. ViewState
public string Firstname{
get {
return ViewState["Firstname"] == null ?String.Empty :(string)ViewState["Firstname"];
}
set { ViewState["Firstname"] = value; }
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c#, asp.net, webforms, formwizard"
} |
Select for a substring in array in DB2
I have the following Car's table in DB2:
id reference
1 31943149-blue
2 40213982-red
3 93713946-blue
...
Then I need to find all entries which reference ending is inside a dynamic list of colors. How could I do that? In fact, the dynamic list of colors should be found from another query to another table, so I guess than an UNION or INNER JOIN could be better in terms of performance.
Thanks in advance | You can join the two tables, using `LIKE` in the `ON` condition.
SELECT car.*
FROM car
JOIN colors ON car.reference LIKE ('%-' CONCAT colors.color) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql, database, db2"
} |
General Question: Balance Among Three People
Just thinking about this scenario. If three friends go out for a trip, A spent $45, B $35, and C $10, is there a general formula to figure out that C needs to transfer $15 to C and $5 to B to make it balance?
Thanks | There is a similar question on the math part of stackexchange. It appears to be an NP-problem. So there is no smart way to solve the problem in generel. You can write code that can do it for three persons, but there are no generel formula as you ask for.
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "excel, powerbi, dax"
} |
File System indexing
I am creating an application were I need to scan a directory hive to find a certain file.
I also want to better understand how indexing works.
Can anyone point me to any resource preferably in C# that shows how I can create a basic index for file system searching? | So, it sounds like you need a library for doing searches.
Lucene is a java search library, which has been ported to C#. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, .net"
} |
What are the good ways to maintain the bicycle while raining season?
I have a bicycle. I ride it everyday because it was my primary vehicle. When I was going to campus or another places, I used it. Currently, the raining season is on my country. I would like to keep my bicycle healthy, for example case, preventing a bicycle chains from the corrosion. Also, another use cases which can be happened while raining season.
Any good suggestion for that cases? | Use fenders with good coverage! They will keep most of the dirty spray water off your bike. You'll be surprised how much less oiling your chain needs with proper fenders.
_Proper fenders_ means:
* a front fender with a mud flap that reaches within a few centimeters of the road
* a rear fender that starts some centimeters below the chain stays, so that water dripping off does not end up on the chain | stackexchange-bicycles | {
"answer_score": 5,
"question_score": 4,
"tags": "preventative maintenance, rain, corrosion"
} |
setting up the equation of area between two polar curves
I have to find the area inside $r=2\cos x$ and outside $r=1.$ Can someone please check if I set up my equation correctly? I did:
$$2\left(\frac12\int\limits_0^\pi 2\cos^2 x\ dx-\frac12\int\limits_{-\pi/3}^{\pi/3} 1^2\ dx\right)$$ I have a gut feeling that my bounds for the second part are incorrect but that's were the radio lines hit on the graph. | Indeed, two polar curves intersect themselves at:
$$2\cos(t)=1\to t=\pi/3$$ Note that i consider the symmetric which rules the whole story so, $$0\leq t\leq\pi/3$$and so $$A=2\times\left(\frac{1}2\int_0^{\pi/3}(4\cos^2(t)-1)dt\right)$$
!enter image description here | stackexchange-math | {
"answer_score": 4,
"question_score": 0,
"tags": "calculus, integration, graphing functions, area"
} |
Laravel 5.5 - Eloquent - Retrieve "microseconds" from MySQL table with "datetime(6)" field
I've a problem to retrieve `datetime(6)` field from MySQL 5.7 table. If I run it directly from mysql client, it works:
mysql> SELECT arrival from table1 limit 1;
+----------------------------+
| arrival |
+----------------------------+
| 2016-06-22 16:52:06.260000 |
+----------------------------+
1 row in set (0.00 sec)
mysql>
but getting the field from Laravel using Eloquent, the microsecond are not reported:
class Table1Model extends Model
{
protected $table = 'table1';
}
class Table1Controller extends Controller
{
public function index()
{
$data = Table1Model::first()->arrival;
dd($data);
}
}
// the output is: "2016-06-22 16:52:06"
Is this an Eloquent problem? How get the microsecond?
Thank you. | Thanks @apokryfos , true... this is a bug.
I found a simple workaround using `RAW` query:
class Table1Model extends Model
{
protected $table = 'table1';
}
class Table1Controller extends Controller
{
public function index()
{
$query = Table1Model::select(
DB::raw(
CONVERT(CAST(arrival AS DATETIME(3)), CHAR)
)
);
$data = $query->get();
dd($data);
}
}
// the output is: "2016-06-22 16:52:06.260" | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, eloquent, laravel 5.5"
} |
WPF ListBox send SelectedItem value to the viewmodel
Inside MainWindow there is listbox filled with some data. These data is loaded from viewmodel, so I dont have any codebehind.
**MainWindow.xaml**
<ListBox Name="listBoxData"
DataContext="{Binding Source={StaticResource MainWindowViewModelDataSource}}"
ItemTemplate="{DynamicResource BookTemplate}"
ItemsSource="{Binding Books}" />
How can I know which book is selected inside listbox (using `ICommand`) and send it's property (`int Id` for example) to `viewmodel` for further processing? | Simply bind `SelectedItem` to some property (say _SelectedBook_ ) in your ViewModel, no need to have _ICommand_ for this.
<ListBox Name="listBoxData"
ItemTemplate="{DynamicResource BookTemplate}"
ItemsSource="{Binding Books}"
SelectedItem="{Binding SelectedBook}" />
You can get Id for the book by simply accessing ViewModel property:
int selectedBookId = SelectedBook.Id; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "c#, .net, wpf"
} |
Finding roots of $A_1 \cos\left(k_1 \theta +\phi_1\right) + A_2 \cos\left(k_2 \theta +\phi_2\right)= 0$
I'm trying to find the roots of this equation $$ A_1 \cos\left(k_1 \theta +\phi_1\right) + A_2 \cos\left(k_2 \theta +\phi_2\right) = 0 $$
I've found many solutions for special cases when the phase shift, frequency or amplitude are the same, but is there a set of closed form roots in the general case?
**EDIT** My specific case of interest is $k_1 = 1$, $k_2 = 2$ but also interested in where general solutions are possible | In general, you need numerical methods. Even when$$A_1=A_2=1,\,\phi_1=\phi_2=0,\,k_1=1,\,k_2\in\Bbb N,$$the above is equivalent to solving arbitrarily high-degree polynomials in $\cos\theta$. In particular, radical solutions are unavailable for even $k_2\ge6$.
Edit: the recently requested special case $k_1=1,\,k_2=2$ is tractable: with $z:=\exp i\theta$ we want to solve$$0=A_1(e^{i\phi_1}z+e^{-i\phi_1}/z)/2+A_2(e^{i\phi_2}z^2+e^{-i\phi_2}/z^2)/2,$$which simplifies to a quartic in $z$, which we can solve. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "trigonometry, roots"
} |
how to display a string as a block of text in html
I have a JavaScript function that returns a string. I want to write this string to an html page, but in a block-of-text format where I can specify the width. I'm currently using a read-only `textarea`, but I'm sure there's a much better way. How would I do this?
Example:
String returned from javascript function:
`The dog was lazy in the sun.`
On the html page:
The dog was
lazy in the
sun.
**Edit:**
Sorry, I wasn't being clear enough. This javascript function could return any string, I don't know what it could return. So inside my html, I would do the following:
<script type="text/javascript" />
document.write(functionCall());
</script>
but I would like to format this like in the example above. Unfortunately, wrapping this in `<div>` tags with the `width` attribute doesn't work. | var text, width, container;
width = "200px"; // set this to whatever you like
text = some_function();
// you can create a <div id="text-container"></div> in your
// HTML wherever you want the text to show up, or you can
// the JavaScript just create it at the bottom of the page
container = document.getElementById("text-container");
if(!container) {
container = document.createElement("div");
container.id = "text-container";
document.body.appendChild(container);
}
container.style.width=width;
container.innerHTML = text; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "javascript, html"
} |
Python: generate a list containing lists from several lists
I have the following lists:
[1,2,3]
[1]
[1,2,3,4]
From the above, I would like to generate a list containing:
[[1,1,1],[1,1,2],[1,1,3],[1,1,4],
[2,1,1], [2,1,2], [2,1,3], [2,1,4],
[3,1,2], [3,1,3],[3,1,4]]
What is this process called?
Generate a factorial of python lists?
Is there a built-in library that does this? | Using `itertools.product`:
>>> import itertools
>>> [list(xs) for xs in itertools.product([1,2,3], [1], [1,2,3,4])]
[[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]] | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "python"
} |
apache.commons.logging.log performance without debug logging code guard
apache.coomons.logging.Log.Log2JLogger provides code guards such as `log.IsDebugEnabled()`. However, one can just go ahead and call `log.debug(message)` and we do not see these messages if debug level is not configured.
From a performance perspective, especially considering we want to leave these debug messages for production debugging, would it be considered best practice to call these code guards before attempting to log?
For example, would this be considered best practice?
if log.isDebugEnabled()
log.debug("trouble brewing...");
Or does calling
log.debug("I'll slow you down...");
already do this for us? | If the cost of creating your parameter to the logging method is high, then you should call the guard method first. In the example you gave, there is no point since a static String has no performance cost and as you correctly surmise, the logging framework makes the check anyway before deciding whether to log.
But consider the following;
logger.debug(myObject.someMethod());
In this case, the `myObject.someMethod()` will be called _prior_ to the logger receiving the return value from it. If that method performs lengthy operations, then you will suffer the performance penalty whether the logger is enabled for debug or not. In this case, you **would** want to use the `isDebugEnabled()` prior to making that call. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, log4j"
} |
SharePoint Link Sharing
In the SharePoint Admin center it is possible to set the default for link sharing of a site to "People with Existing Access".
For some sites, we would like to not only enable this setting as the default, but also hide the other options, so that "People with Existing Access" is the only way to share.

num target prot opt source destination
1 ACCEPT tcp -- 0.0.0.0/0 192.168.0.1 tcp dpt:80
The output from the command I'm looking for would be something like:
1 -A INPUT -i eth0 -p tcp --dport 80 -d 192.168.0.1 -j ACCEPT
I seem to remember that it was just another option passed into the standard `iptables -L` command, but I could be wrong. Does anyone know of a command to accomplish this? | It's super simple: `iptables -S` gives you exactly what you ask for. | stackexchange-unix | {
"answer_score": 10,
"question_score": 8,
"tags": "iptables"
} |
Для чего комбинируют эти команды git fetch , git reset --hard origin/master?
Есть много примеров где используются команды
git fetch
git reset --hard origin/master
Для чего комбинируют эти команды ?
Если есть ссылки буду рад посмотреть. | `git fetch` притягивает все ветки из внешнего репозитория. Внешний репо еще называют `upstream` и чаще всего проекция на апстрим называется `origin`. Заметьте, хоть локальная ветка `master` и повторяет апстрим ветку `origin/master`, это не одно и то же. `git fetch` не обновляет локальный `master`, она обновляет только `origin/*` ветки, в том числе и `origin/master`. Обновление текущей ветки в основном делается при помощи `git pull`. Хозяйке на заметку:
`git pull` в мастере равносилен (почти)
git fetch
git merge origin/master
Далее по `git reset --hard origin/master`. Пока вы не сделали `git push`, все ваши коммиты сидят в ветке `master`. А `origin/master` по прежнему чиста от последних незапушенных изменений. Поэтому команда `git reset --hard origin/master` говорит гиту `приведи пожалуйста файловую структуру и историю коммитов моей ветки к тому состоянию, в котором сейчас находится ветка origin/master`. | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "git"
} |
Xcode 11 scenekit editor bug
I am getting this weird graphical issue with xcode scenekit editor when ever I select an object. Is there a way to fix it?
 macos version: 10.15.3 (19D76) | This is due to a bug in the Metal GPU driver. As a workaround you can hide the grid or selection outline in the "Display options" menu (second icon from the right in the toolbar at the bottom of the view). | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "xcode, scenekit"
} |
Prove the derivative of the function $f:U\rightarrow\mathbb{R}$, where $U$ is an open subset of $\mathbb{R}^n$, is zero at a local minimum.
Say we have a function $f:U\rightarrow\mathbb{R}$ where $U$ is an open subset of $\mathbb{R}^n$. Prove if f has a local minimum at $c \in U$ and $f$ is differentiable at $c$, then $f'(c) = 0$.
Outline of my attempt: Since $c$ is a local minimum there is an $\epsilon > 0$ such that $f(c+h) - f(c) \geq 0$ for all $h$ and $|h| < \epsilon$. Therefore the limit as $h \rightarrow 0$ of $\frac{f(c+h) - f(c)}{\|h\|}$ is $0$ and thus the derivative is $0$. However, this doesn't feel correct to me. One concern I had was, can I say the above limit approaches $0$? | We see by the first principles, that $f'(c)=\lim_{h\rightarrow0^+}\frac{f(c+he_i)-f(c)}{h}\leq 0$, and $f'(c)=\lim_{h\rightarrow0^-}\frac{f(c+he_i)-f(c)}{h}\ge 0$, thus $f'(c)=0$.
Here $e_i=(0,0,...,1,...,0)$ with $1$ in the $i$-th position.
We see this holds for all directions $e_i$, so $f$ is totally differentiable (or **differentiable** ) and $f'(c)=0$. | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "real analysis, limits"
} |
Text alignment in html
how to align text to right or left without using paragraph tag in HTML
Is there any other tag to do alignment? | Any **block container** with `style="text-align: left"` will do. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, alignment"
} |
Problem calling Google Chart API from C# App
I want to generate a QR Code in a Job or Winforms app.
My api call is straightforward:
When I call it from the browser its fine.
When I call it using the following code, I get a timeout error:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;
request.ContentType = "image/png";
HttpWebResponse imgresponse = (HttpWebResponse)request.GetResponse();
System.Drawing.Image img = System.Drawing.Image.FromStream(imgresponse.GetResponseStream());
When I turn on Fiddler to debug the request, it works. I assume that I need to set some header on the request. I've tried a few but no success.. | Don't really understand why, but using this code works:
byte[] fileBytes = null;
WebClient client = new WebClient();
fileBytes = client.DownloadData(url);
MemoryStream theMemStream = new MemoryStream();
theMemStream.Write(fileBytes, 0, fileBytes.Length);
System.Drawing.Image img2 = System.Drawing.Image.FromStream(theMemStream); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c#, google visualization"
} |
Simulator For Blackberry for Windows PC?
Is there any single software that can be used to test the website designed for all blackberry mobile devices. In Blackberry website, they have given different simulators for each phone, we would like to know if there is any one software that an be used to test all the blackberry devices? | <
Just click on "Download a device simulator" and you should be good to go! | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mobile, blackberry simulator"
} |
What does $p^\alpha\| n$ mean?
What does $p^\alpha\| n$ mean ? I saw this in Euler totient function, $$\varphi(n)=\prod_{p^\alpha\| n}p^\alpha(p-1).$$ | It means that $p^{\alpha}\mid n$ but $p^{\alpha+1}\nmid n$.
For example. $2^2\mid 12$ but $2^3\nmid 12$. Hence $2^2\|12$ | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "elementary number theory, notation, divisibility"
} |
Finding maximum index of a row of array in MATLAB
I want to get the index of a specific row in a 2-D array. I have a 15*15 array (Q), and I want to get index of the maximum number of 2nd row. I wrote this code, but an error occurred:
y=Q(2,:);
x=max(y)
??? Subscript indices must either be real positive integers or logicals. | You are getting the maximum _value_ of the second row, but you want the _index_ of the maximum value. Here's how to get the index:
[~, index] = max(y) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "arrays, matlab, indexing"
} |
Complex Analysis Roots Problem
I have some problem on finding roots and showing that they exist under certain conditions:
**Problem:** Prove that $e^z+z^3$ has no root in $\\{z:|z|<3/4\\}$ and has three roots in $\\{z:|z|<2\\}.$
I am preparing for my finals for complex analysis, and this is one of the review problems, but I cannot seem to solve it and its frustrating as I am stuck on this chapter complex roots and residues. I would appreciate if someone could show me how to solve this. | **Hint:** For the first part, consider the possible values of $|e^z|$ and $|z^3|$ in that disk. For the second part, use Rouche's Theorem. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "complex analysis"
} |
Cocos2d-x Sprite Inheritance class Error
I'm making a spacewar game.
I finished adding enemies, shooting bullets, detecting collisions.
The next step is adding HP for each object.
I created class which inherits Sprite
class Target : public cocos2d::Sprite
{
public:
int hp = -1;
};
I checked whether HP changes well or not by adding 3 code lines below.
Target *target = new Target();
target->hp = 1;
CCLog("hp: %d", target->hp);
result:
hp: 1
The problem is, after returning Sprite by this line,
target = (Target*)Sprite::createWithSpriteFrameName("enemy1.png");
CCLog("hp: %d", target->hp);
the result is
hp: -33686019
In addition, I'm not able to change the HP variable. When I change it, the debugger stops at "target->hp = 1;". | You're doing it wrong. First - you can't initialise int in .h file. Second - don't use new directly - it'll easily cause memory leaks if not handled properly, instead use cocos2d-x pattern.
I'll do it like this:
.h file:
#ifndef __Sample__Target__
#define __Sample__Target__
#include "cocos2d.h"
USING_NS_CC;
class Target : public Sprite
{
public:
static Target* create(const std::string& filename);
int hp;
};
#endif
.cpp file:
#include "Target.h"
Target* Target::create(const std::string& filename) {
auto ret = new (std::nothrow) Target;
if(ret && ret->initWithFile(filename)) {
ret->autorelease();
ret->hp = 1; //declare here or in init
return ret;
}
CC_SAFE_RELEASE(ret);
return nullptr;
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "cocos2d x"
} |
Half-Life: Was launching the rocket optional?
I just played through Half-Life for the first time. I launched some rocket for no apparent reason (never really explained) then realized I had to backtrack and go down a ladder in the previous courtyard. So my question is, couldn't I have just gone down that ladder without launching the rocket? And what was the point of the rocket, besides having those blue exploding things that killed me over and over? | The rocket's mission is to deliver a satellite that will close the portal to Xen. This happens all thanks to your launch.
You can't continue the game without launching it. The next part of the map is locked untill you launch and then backtrack. | stackexchange-gaming | {
"answer_score": 8,
"question_score": 3,
"tags": "half life"
} |
Angle between two lines in term of absolute angles
How to find a general equation for an angle between two lines as a function of absolute angles of the two lines? As shown in the figure, i would like to find a general equation to represent angle between the two lines (i.e. $\theta$) in term of absolute angles (i.e. $\phi_1$ and $\phi_2$) which are known in this problem.
See figure here
!angle between two lines.
What is the general equation for $\theta$ which is valid for all values of $\phi_1$ and $\phi_2$? | In general, the angle between two lines is either $|\phi_2 - \phi_1|$ or $180^\circ - |\phi_2-\phi_1|$. Both will work since they add up to $180^\circ$. If you want to know which one is the acute angle (seems to be what you're asking), then it depends on the specific angles
$$ \theta = \begin{cases} \phi_2 - \phi_1 & \text{if}\quad 180^\circ \ge \phi_2 \ge \phi_1 \ge 0^\circ \\\ 180^\circ - (\phi_2 - \phi_1) & \text{if}\quad 360^\circ \ge \phi_2 \ge 180^\circ \ge \phi_1 \ge 0^\circ \\\ \phi_2 - \phi_1 & \textrm{if}\quad 360^\circ \ge \phi_2 \ge \phi_1 \ge 180^\circ \end{cases} $$
For your figure, the acute angle is $\theta = 180^\circ - (\phi_2-\phi_1)$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "geometry"
} |
NodeJS + Soket.IO чат и sql injection
При отправке сообщения делается sql запрос
connection.query('INSERT INTO `'+config.db_prefix+'_chat`(`user_id`, `msg`) VALUES ("'+user_id+'", "'+msg.message+'")', function (err, result) {
if (err) throw err;
//тут рассылка клиентам в чате
});
И если в сообщении содержатся такие символы как `/` и другими спец символами то процесс nodejs крашится и пишет ошибку sql синтаксиса как лучше реализовать "экранирование" без потери этих символов? | Не надо подставлять переменные непосредственно в текст запроса. Функции `query` можно передать массив подставляемых в запрос переменных. В самом тексте запроса переменные надо обозначить вопросительными знаками. Примерно так:
connection.query('INSERT INTO `'+config.db_prefix+'_chat`(`user_id`, `msg`) VALUES (?,?)',
[user_id,msg.message] , function (err, result) {
...
}); | stackexchange-ru_stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "sql, node.js"
} |
Scope CSS to module only in Angular 5 to prevent bleeding into other parts of app
How do I scope CSS to only a module in Angular? When I load a module lazily, and have ViewEncapsulation.None in that module, the CSS bleeds into other parts of my app. Any idea how to prevent that, or keep that CSS only for that module in Angular 5? | There is no such think as module CSS scope.
The default `ViewEncapsulation.Emulated` does that per component. With `ViewEncapsulation.None` you disable that. There are no other ways provided by Angular.
You can add a CSS class or attribute to every component in a module and add that class or attribute to every selector in that module to limit the CSS to components of that module. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 1,
"tags": "css, angular, angular2viewencapsulation"
} |
Greenfoot Can I create an actor instance in constructors?
I'm using the Greenfoot program to create a game, but cannot instantiate anything in a constructor. For some reason, nothing is made when I write `getWorld().addObject()` in the constructor.
I can create objects in the `act()` method, though. | Since Greenfoot only allows you to add objects from a world object, the other actors you are calling don't exist yet. This means there are no constructors to call `getworld()` on. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "java, greenfoot"
} |
What was the original rhyming scheme of "Do not shun me..."?
The poem _Do Not Shun Me..._ starts as follows:
> Do not shun me, my lord, nor recoil
> Because callouses all my hands cover;
> For such sis the badget of a hard toil,
> And will not defile you, no never.
> 'Tis a medal of suffering and working,
> And no plague-spot will meet thy inspection;
> Then give me thy hand, without shirking,
> Since mine is not stained by infection.
> Ah, uncover thy head with more zeal,
> When I bow to the ground thus responding,
> _Thy_ head I'll not pluck off, nor steal,
> And with mine, Sir, thou'lt not be absconding.
In the English at least, more or less every other sentence ends in a rhyme ("recoil... toil", "working... shirking", "inspection... infection", "zeal... steal" and "responding... absconding"). Was this also the case in the original language? | Yes, it's the same ABAB pattern.
Original on wikisource:
> Не цурайся мяне, панічок,
>
> Што далонь пакрываюць мазолі;
>
> Мазоль — працавітых значок,
>
> Не заразе цябе ён ніколі. | stackexchange-literature | {
"answer_score": 4,
"question_score": 2,
"tags": "poetry, belarusian language, like water like fire, francisak bahusevic"
} |
Interrupt busy loop in Node.js
I have a simple busy loop in my Node.js code that has turned out to take several seconds to complete. During this time I need to perform some I/O operations, which currently are queued and all executed after the loop instead of "parallel" with the loop. I know that Node doesn't do parallel execution, so I'm looking for some way to interrupt the loop to allow Node to do other stuff.
I have tried implementing the loop with async, but that resulted in exceeding the call stack ( _i_ easily goes up to 2,000,000).
while(i < length){
if(something) sendWebSocketMessage();
//Do stuff with i
i++;
}
Any ideas? | A solution could be to write your loop like this:
(function step(){
doSomething();
if (length--) setImmediate(step);
})();
This way other events coming in between would be handled. If your loop is long because of a big number of iterations (vs because of long steps), you could have a partial looping in place of `doSomething()`.
If you want to slow down your loop, in order to let more time to other tasks, you could also use `setTimeout` with a non null timeout:
(function step(){
doSomething();
if (length--) setTimeout(step, 5);
})(); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "javascript, node.js, asynchronous, synchronous"
} |
django queryset for many-to-many field
I have the following Django 1.2 models:
class Category(models.Model):
name = models.CharField(max_length=255)
class Article(models.Model):
title = models.CharField(max_length=10, unique=True)
categories = models.ManyToManyField(Category)
class Preference(models.Model):
title = models.CharField(max_length=10, unique=True)
categories = models.ManyToManyField(Category)
How can I perform a query that will give me all Article objects that are associated with any of the same categories that a given Preference object is related with?
e.g. If I have a Preference object that is related to categories "fish", "cats" and "dogs", I want a list of all Articles that are associated with any of "fish", "cats" or "dogs". | Try:
preference = Preference.objects.get(**conditions)
Article.objects.filter(categories__in = preference.categories.all()) | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 15,
"tags": "django, django queryset"
} |
Hyphenation usage in US English
I am writing my Ph.D. Thesis in US English and have two questions on hyphenating.
1. Would it be _re-entry_ or _reentry_?
2. Would it be _(re)training_ or _(re-)training_? Or would it be _retraining_ at all times? In my study, people might get retraining but not always. Therefore, I sometimes use parentheses.
Is there a general rule (in US English) for using these hyphenations?
Thank you all in advance.
Cheers,
Roy | Write these without the hyphen.
The venerable _Chicago Manual of Style_ (13th ed) has this entry in Table 6-1 for the _re-_ :
* reedit, reunify, redigitalize, reexamine
At the top of the table, chief exceptions are listed. The last of these exceptions is:
> A few compounds in which the last letter of the prefix is the same as the first letter of the word following.
Concerning the same last letter of the prefix and first letter following, the table says:
> Newly-invented compounds of the last type tend to be treated in hyphenated style when they first appear and then to be closed up when they have become more familiar.... In addition to familiarity, appearance also influences the retention of hyphens, and it is never wrong to keep a hyphen so as to avoid misleading or puzzling forms (e.g., _non-native, aniti-intellectual_ ). | stackexchange-english | {
"answer_score": 0,
"question_score": 1,
"tags": "orthography, hyphenation"
} |
Two pages with almost identical scroll events has different performance
I Have two pages first our blog home page and second our news website home page,
The blog has an annoying lag in chrome when you scroll down our up.
But almost the same code works great in our news website. You can find both pages below:
news website
blog
The Problem is: i used chrome developer tools rendering panel to see FPS, Repaint areas, animation tweaks, but i could not find the problem causing lag on blog page.
any ideas on how to find the problem? | Try to remove the slick-slider on top in the devtools. Seems to increase performance a lot! Maybe you can optimize from there. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -4,
"tags": "javascript, html, css, performance"
} |
a nice alternative in countdown timer - putting "0" in front of single digit
I've been building countdown timer and I was wondering if I can replace this code:
if( daysLeft< 10){
daysLeft = "0" + daysLeft;
}
if( hoursLeft< 10){
hoursLeft = "0" + hoursLeft;
}
if( minutesLeft< 10){
minutesLeft = "0" + minutesLeft;
}
if( secondsLeft< 10){
secondsLeft = "0" + secondsLeft;
}
with something more appropriate (nicer). Fiddle: < Thanks! | Creat a function to do this:
function addLeadingZero(i) {
if(i < 10)
return "0" + i;
return i;
}
And then use it like this:
var x = 5;
var result = addLeadingZero(x); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "jquery, html, css"
} |
Comparison of empirical distributions in ciruclar/polar coordinates
I have 4 sets of 24 measurements of a polar variable (univariate). I want to use a statistical test, like the Kolmogorov-Smirnov test, to test whether said sets differ significantly from each other.
My questions:
* Is the K-S test suitable for this type of data?
* Is the K-S test suitable for sets of this size?
* If yes to the above, how is the K-S test defined mathematically for polar distributions?
* If no to the above, which test is suitable, is there an existing implementation in R or python, or a mathematical description so I can implement it myself?
Thank you in advance! | After searching, I found that the Watson test is needed in this case. | stackexchange-stats | {
"answer_score": 0,
"question_score": 0,
"tags": "kolmogorov smirnov test, circular statistics, empirical cumulative distr fn"
} |
Initial Value of an Enum
I have a class with a property which is an enum
The enum is
/// <summary>
/// All available delivery actions
/// </summary>
public enum EnumDeliveryAction
{
/// <summary>
/// Tasks with email delivery action will be emailed
/// </summary>
Email,
/// <summary>
/// Tasks with SharePoint delivery action
/// </summary>
SharePoint
}
When I create an instance of this class, NOWHERE in the code, do I specify the value of the enum field, but it seems to default to the first item in the enumlist, and not a null value, is this how enums work? How is it possible to ensure that the enum gets some kind of null value if it is not set, I don't want it defaulting to the first value in the enum. | Default value for `enum` types is `0` (which is by default, the first element in the enumeration). Fields of a class will be initialized to the default value.
If you need to represent an _unknown_ value in the enum, you can add an element `Unknown` with value 0. Alternatively, you could declare the field as `Nullable<MyEnum>` (`MyEnum?`). | stackexchange-stackoverflow | {
"answer_score": 114,
"question_score": 68,
"tags": "c#, enums"
} |
SAS data step - dynamic select field from table
I have little problem with one case. Please look at table HAVE. And WANT. My process: get value from VAR, divide by 12, round up to the nearest whole number and put in WANT table, in RES field value from FIELD&"result of the action". How I can do that? My final table has thousand records, and these fields hundred - by two kind.
DATA HAVE;
infile DATALINES dsd missover;
input ID VAR FIELD1 FIELD2 FIELD3 FIELD4;
CARDS;
1, 10, 1, 6, 5, 6
2, 20, 1, 6, 8, 8
3, 30, 5, 8, 12, 7
4, 40, 5, 9, 5, 6
5, 50, 8, 10, 12, 8
;run;
DATA WANT;
infile DATALINES dsd missover;
input ID RES;
CARDS;
1, 1
2, 6
3, 12
4, 6
5, 8
;run;
THANK YOU!! | Looks like you want to use an ARRAY statement. This will allow you reference a variable by an index into the array.
data want;
set have ;
array f field1-field4;
index=ciel(var/12);
if 1 <= index <= dim(f) then res=f[index];
run; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sas, datastep"
} |
How do exceptions work in C++?
ebool keep_trying= true;
do {
char fname[80]; // std::string is better
cout Image "Please enter the file name: ";
cin Image fname;
try {
A= read_matrix_file(fname);
...
keep_trying= false;
} catch (cannot_open_file& e) {
cout Image "Could not open the file. Try another one!\n";
} catch (...)
cout Image "Something is fishy here. Try another file!\n";
}
} while (keep_trying);
This code is from Discovering modern c++. I don't understand what "A" in the try-block stand for and "e"(cannot_open_file& e) in the next catch-block | That appears to be an incomplete code snippet. You can assume that 'A' is of whatever type that read_matrix_file() returns. And 'e' is a reference to a cannot_open_file type, which should be defined somewhere else in the code. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "c++, c++11, exception"
} |
Преобразование строки в нижний регистр
Подскажите функцию, которая преобразует строку в нижний регистр. | Вроде такой функции нет, можно пройти по всем символам строки, и к ним применить tolower(). Или вместо tolower() использовать добавить вычесть:
char A;
... //initialization
A = A - 'A' + 'a'; // tolower;
A = tolower(A); // tolower from ctype.h | stackexchange-ru_stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "c, c++"
} |
Array of children present in node of firebase realtime database in android studio
I am unable to think of a possible logic to get my desired output in Java, Android Studio. Can anyone please help me with any possible outcome? My desired output is of a String array containing as follows:
Strs[0]="neet"
Strs[1]="jee mains"
I want to get a String array of a node from the firebase realtime database when the children of the nodes vary. I am hereby attaching the image from the database for clear understanding:
;
DatabaseReference courceRef = database.getReference().child("Cources");
List<String> cources = ArrayList<String>();
courceRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
cources.clear();
for(DataSnapshot snap:dataSnapshot.getChildren()){
cources.add(snap.getKey());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
}); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "java, android, firebase, firebase realtime database"
} |
MongoDB - Change primary shard only for a certain database
I have a sharded MongoDB cluster running 3 different Databases. Currently all 3 databases has the same shard configured as their primary shard (shard000) Is it possible to change the primary shard for one of these databases to something other than shard000?
Just to make things clear, I have no intention of retiring shard000 any time soon, I just want to remove some of the non shared collections load off it.
Thanks, Meny | Yes you can with a single command:
db.adminCommand({ movePrimary : "YourDBName", to : "shard001" })
then is important to flush configuration on all mongos (suppose all than the one that did the move, but better be safe):
db.adminCommand({flushRouterConfig: 1})
If your databases are small you can do it on-the-fly, else you better plan for a downtime only for this database during the move process.
Useful link: < | stackexchange-dba | {
"answer_score": 2,
"question_score": 0,
"tags": "mongodb, sharding"
} |
How to delete a google tag manager container?
I can not find how to delete a container, I did not find the delete button when I access the container settings,can anyone help with this ? | Go to the admin section for your container, open "Container setting" and click in the menu with the three little dots on the right. If you have the necessary permissions (guaranteed if you created the container yourself) there will be a delete option.
 resulting in `my_model.h5`, I can load the model as
from keras import load_model
model = load_model("my_model.h5")
Loading a new dataset on which I simply want to **apply** my NN (not train or validate), how do I do that? As far as I understand, for each sample I feed in, I should be able to get out a score between 0 and 1 quantifying the NN's confidence in that sample being signal-like. How do I get those numbers, e.g. in the form `{sample1: score, sample2: score,...}`?
Any help much appreciated! | This is it:
results = model.predict(inputData)
The `inputData` must have the same number of dimensions that you training data had, and the shapes must be compatible.
As it's standard, the samples are in the first dimension.
for res in results:
#res is the score for a sample | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "machine learning, neural network, keras"
} |
R legend pch mix of character and numeric
Is it possible to use a mix of character and number as plotting symbols in R legend?
plot(x=c(2,4,8),y=c(5,4,2),pch=16)
points(x=c(3,5),y=c(2,4),pch="+")
legend(7,4.5,pch=c("+",16),legend=c("A","B")) #This is the problem | My first thought is to plot the legend twice, once to print the character symbols and once to print the numeric ones:
plot(x=c(2,4,8),y=c(5,4,2),pch=16)
points(x=c(3,5),y=c(2,4),pch="+")
legend(7,4.5,pch=c(NA,16),legend=c("A","B")) # NA means don't plot pt. character
legend(7,4.5,pch=c("+",NA),legend=c("A","B"))
**NOTE:** Oddly, this works in R's native graphical device (on Windows) and in `pdf()`, but not in `bmp()` or `png()` devices ...
!enter image description here | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 19,
"tags": "r"
} |
Creating random character unique URLS
How do I generate random 12 character char for URL of a page for the record in the database like how youtube does it with 11 characters <
I want it to be unique for each entry in the database and consist of letters of upper and lower case, numbers and maybe (if not bad for security) even special characters. | Function:
function generateRandomString($length = 12) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
Then call it:
$randomString = generateRandomString();
Slightly adapted from Stephen Watkins' solution here | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, random, unique"
} |
In x = 1, are both x and 1 objects?
In `x = 1`, are both `x` and `1` objects? Because `print(1)` and `x = 1; print(x)` will result in the same output.
Even the syntax of `print` function is:
> print( ***objects** , sep=' ', end='\n', file=sys.stdout, flush=False) | Names in Python are not objects. Using a name in an expression automatically evaluates to the object _referred to_ by the name. It is not possible to interact with the name itself in any way, such as passing it around or calling a method on it.
>>> x = 1
>>> type(1) # pass number to function...
<class 'int'> # ...and receive the number!
>>> type(x) # pass name to function...
<class 'int'> # ...but receive the target!
Note that technically, `1` is also not an object but a _literal_ of an object. Only the object can be passed around – it does not reveal whether it originates from a literal `1` or, for example, a mathematical expression such as `2 - 1`. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 4,
"tags": "python, object, assignment operator"
} |
Which is the function that initializes the content of the "$scripts" variable used in html.tlp.php?
The template file html.tpl.php has access to the `$scripts` variable, which is not initialized in template_preprocess_html(). I have also looked at template_preprocess(), and template_process(), but neither of those functions initialize `$scripts`. | The `$scripts` variable is initialized in `template_process_html()`, which uses the following code.
$variables['css'] = drupal_add_css();
$variables['styles'] = drupal_get_css();
$variables['scripts'] = drupal_get_js(); | stackexchange-drupal | {
"answer_score": 2,
"question_score": -1,
"tags": "7, theming"
} |
For loop from integer to decimal. How can it reach the decimal?
Is there a way to have a for loop like this where the loop hits the 60.1875? If I start the range at .1875 it will work but I can't do that in this case.
for a from 1 to 60.1875
next a
Edit: This code needs to test options for running a print job on different size papers. We prefer to test whole numbers but we always need to test the outer limit of the press as well which is 60.1875. | You need the Step keyword, or the loop will jump in steps of 1 only and will ignore non-integer values.
for example:
Dim start As Decimal = 1
Dim finish As Decimal = 60.1875
For i=start to finish Step 0.0005
If i = Int(i) Or i=start or i=finish Then
'... do whatever
End If
Next
Added the check for integers and outer bounds, but tbh this is cacked; there are better ways to do it! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "asp.net, vb.net"
} |
Reverse of array_search() that looks for the key instead of the value
PHP's `array_search()` does this:
> Searches the array for a given **value** and returns the corresponding **key** if successful
I would like a function that does the exact opposite, that is, searches the array for a given **key** and returns the corresponding **value** if successful.
Is this available at all in PHP 5? If not, what solution would you suggest? | You can just use square bracket syntax, as follows:
$arr = array("key" => "value");
$v = $arr["key"]; // returns "value" | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 7,
"tags": "php, arrays, function"
} |
How to know which COM component is called by a certain PIA?
I got a PIA installed on my box, it is **Microsoft.mshtml**. If I understandd it correctly, these PIA is provided by Microsoft to ease our life of COM interop. But I want to know which COM component is actually wrapped/called by this PIA. Because I am having a UnauthorizedAccessException, I want to locate the actual COM component and use _dcomcnfg.exe_ to grant it proper permission. I hope this is the right direction.
Thanks! | It is c:\windows\system32\mshtml.dll. I seriously doubt that dcomcnfg.exe is going to solve your problem, this is an in-process COM server. You might get more insight by using Sysinternals' ProcMon utility to see exactly which registry or file access is generating the exception. Look for error code 5.
You only need the PIA when you expose types from that COM server in your own public classes. Not that common. PIAs are history with the terrific "Embed Interop Types" option in VS2010. Nicknamed the "no pia" option. You avoid the PIA with Project + Add Reference, Browse tab, select c:\windows\system32\mshtml.tlb. The .dll in earlier versions of Windows. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": ".net, com, interop"
} |
Prove there exists no uniform distribution on a countable and infinite set.
Can anyone help me with this problem, I can't figure out how to solve it...
> Let $X$ be a random variable which can take an infinite and countable set of values. Prove that $X$ cannot be uniformly distributed among these values.
Thanks! | Let $X$ be a random variable which assumes values in a countable infinite set $Q$. We can prove there is no uniform distribution on $Q$.
Assume there exists such a uniform distribution, that is, there exists $a \geq 0$ such that $P(X=q) = a$ for every $q \in Q$.
Observe that, since $Q$ is countable, by countable additivity of $P$,
$1 = P(X \in Q) = \sum_{q \in Q}{P(X = q)} = \sum_{q \in Q}{a}$
Observe that if $a=0$, $\sum_{q \in Q}{a}=0$. Similarly, if $a>0$, $\sum_{q \in Q}{a} = \infty$. Contradiction. | stackexchange-math | {
"answer_score": 15,
"question_score": 13,
"tags": "statistics, uniform distribution"
} |
Incomplete elliptic integral of the second kind with negative parameter
Abramowitz & Stegun 17.4.18 gives the following formula for $E(u, -m)$:
$$ E(u,-m) = (1+m)^{1/2} \\{E(u(1+m)^{1/2},m(m+1)^{-1}) - m(1+m)^{-1/2} \mathrm{sn}(u(1+m)^{1/2}, m(1+m)^{-1})\; \mathrm{cd}(u(1+m)^{1/2}, m(1+m)^{-1}) \\}. $$
However, a quick Mathematica test does not seem to verify this relationship:
u = RandomReal[]; m = RandomReal[]; a = u Sqrt[1 + m]; b = m / (m + 1);
Sqrt[1 + m] (EllipticE[a, b] - m / Sqrt[1 + m] JacobiSN[a, b] JacobiCD[a, b])
EllipticE[u, -m]
>>> 0.136459
>>> 0.214315 + 0. I
Does anyone know the correct equation, or have I made an error somewhere? | Try
test[u_,m_] := Module[{s, a, b}, s = Sqrt[1 + m]; a = u s; b = m/(1 + m);
{ s EllipticE[JacobiAmplitude[a, b], b] -
m / s JacobiSN[a, b] JacobiCD[a, b],
EllipticE[JacobiAmplitude[u, -m], -m] }]; | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "mathematica, elliptic functions, elliptic integrals"
} |
How could i use r to add data to a table?
I am looking for an approach.
We have a historical table with the consumption per week of a list of items (19.000 item).
We want to predict the consumption for the next n weeks.
We are thinking on use R to do that prediction.
Our prediction expert recomend to use R, by using croston function from the forecast package.
I want to create a script to execute the prediction on each item and save the prediction on a table of mysql.
How could i do this? Could any one help me on the approach?
Regards | This is a lot more programming related question than question about statistical methods.
You can use RODBC library to connect your R session with MySQL dbms.
Is your R in the same machine as dbms? Do you have an system ODBC DSN defined?
Steps:
1) First R session gets data into data.frame in memory by executing SQL query.
2) Next your prediction algorithm loops this data N times.
3) Each loop writes a set of rows into a temporary table inside MySQL dbms.
4) When loop is finished, you can use R to write rows from the temp table into a production table via SQL.
5) Your predictions are ready to be used in other processes. | stackexchange-stats | {
"answer_score": 0,
"question_score": 0,
"tags": "r, forecasting, tables, database, crostons method"
} |
How to add a sentence to the enter entry and before return instruction of all the functions of my project . Thanks
I want to print some useful message after entering or returning functions by adding the following sentence.
printf("enter %s\n", __FUNCTION__);
Add the following sentence before return instruction.
printf("exit %s\n", __FUNCTION__);
My OS is ubuntu. I think vim can do this work. Editing before return instruction is easy. However, to the first case, finding the first line of every function is not easy . Can gcc do this work during the precompiled period ? Can any one help me . Thanks very much. | You are considering an editor-based approach.
You could also consider a compiler based approach. You could extend GCC using your MELT extension which would add a pass. This pass would just have to add some extra Gimple into the GCC internal representations. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, function, gcc, vim"
} |
Track Network send / receive data
Suppose a website is loaded completely. Website is in HTTP version and has contact form. When we submit form, ajax is used to send the data. Page is neither refreshed. I want to track what data the website send from my browser to its server. | There are two applications that immediately spring to mind that will enable you to monitor and also change http(s) traffic that travels through your browser.
* **Fiddler2**
* **Burp Suite**
In simple terms, they allow you to set up what is effectively a "man in the middle" style attack by way of a local proxy.
To quote the Burp Suite home page "An intercepting Proxy, which lets you inspect and modify traffic between your browser and the target application."
Both applications are quite mature and have great documentation on their respective sites.
There is also a really good playlist on Youtube by the developer of Fiddler2 that is well worth the time in checking out. The user name is Teleriklnc and the playlist is "Fiddler Web Debugging Proxy". (sorry no links, have reached my quota)
Further general reading on the topic - at the OWASP website. Hope this helps. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "networking"
} |
Using JMeter to generate parts of message flows
I am looking into whether I can use `JMeter` for load testing of a server.
I read that I can set it up as proxy to "record" a flow but I am not sure on the following.
Assume that I record a flow for 1 user which is like the following:
HTTP-1 req <data>
HTTP-1 reply
HTTP-2 req <data>
HTTP-2 reply
HTTP-3 req <data>
HTTP-3 reply
Now in the `data` which is an `XML` fragment there is an item that is unique for each user e.g. `<user-id>AAA1</user-id>`
**Question:** Once the flow has been "recorded" and I want to simulate e.g. 50 concurrent users against my real server, is it possible each "user" to send the `data` with a _separate/different_ `user-id`? E.g. for first _user_ it will be `AAA1` as in the test case. For second _user_ it will be `AAA2` etc? | JMeter can do this.
To send a different user-id:
* Use a CSV Data Set config, in it declare userId as a var , set sharing to all threads
* For each HTTP-N req , Use HTTP Sampler with Post Body mode, and use userId as a var : ${userId} in XML body
Depending on wether you use or not HTTP Session add a Cookie Manager | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, http, web applications, jmeter, load testing"
} |
Substitute a regex pattern using awk
I am trying to write a regex expression to replace one or more '+' symbols present in a file with a space. I tried the following:
echo This++++this+++is+not++done | awk '{ sub(/\++/, " "); print }'
This this+++is+not++done
Expected:
This this is not done
Any ideas why this did not work? | Use `gsub` which does global substitution:
echo This++++this+++is+not++done | awk '{gsub(/\++/," ");}1'
`sub` function replaces only 1st match, to replace all matches use `gsub`. | stackexchange-stackoverflow | {
"answer_score": 43,
"question_score": 26,
"tags": "regex, linux, awk"
} |
Float <i> to the right of <div> in html
I want to align this `<i>` to the right side in my `<div>`. This is my html code:
<div class="container-fluid p-1 bg-primary text-white d-flex align-items-center justify-content-center">
<h2>Heading</h2>
<span class="badge rounded-pill bg-success ms-3">Welcome</span>
<i class="fas fa-question-circle" style="float: right;"></i>
</div>
The above code is not working. What can I do to fix this? | Change HTML This Way
<link href=" rel="stylesheet"/>
<link href=" rel="stylesheet"/>
<div class="container-fluid p-1 bg-primary text-white d-flex align-items-center justify-content-between">
<div class="justify-content-center d-flex flex-fill align-items-center">
<h2>Heading</h2>
<div>
<span class="badge rounded-pill bg-success">Welcome</span>
</div>
</div>
<div>
<i class="fas fa-question-circle"></i>
</div>
</div> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html, bootstrap 5"
} |
nQSError: 14025 No fact table exists at the requested level of detail post migration to 11g from version 10
the analysis was working on version 10, after migration to version 11, it started giving error
[nQSError: 14025] No fact table exists at the requested level of detail | 11g is more strict that 10g was in terms of a conformed data model. These types of errors almost always stem from something in the BMM being set up incorrectly, so I would start there. There are several things it could be.
Check your levels on the LTS being used. Set any levels to total for things you want the LTS to work with, but that it does not join to. This will force OBIEE to ignore that item in the join criteria, since there is no join. Set these levels on the column as well.
If you have levels set to detail, make sure the physical join actually exists.
Run a consistency check, and look for any warnings where it says no physical join, or logical tables source joins table at incorrect grain (I can't remember the exact wording, but you will know it when you see it). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "obiee"
} |
Firefox error rendering an SVG image to HTML5 canvas with drawImage
I am trying to convert an external svg icon to a base64 png using a canvas. It is working in all browsers except Firefox, which throws an error "NS_ERROR_NOT_AVAILABLE".
var img = new Image();
img.src = "icon.svg";
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
};
Can anyone help me on this please? Thanks in advance. | Firefox does not support drawing SVG images to canvas unless the svg file has width/height attributes on the root `<svg>` element and those width/height attributes are not percentages. This is a longstanding bug.
You will need to edit the icon.svg file so it meets the above criteria. | stackexchange-stackoverflow | {
"answer_score": 56,
"question_score": 22,
"tags": "javascript, firefox, svg, html5 canvas, base64"
} |
return an undefined value with forge.prefs
I try to use the module PREFS but I don't know why it returns me an undefined value
function getId() {
var id=0;
forge.prefs.get("user_id", function(value){
id=value;
forge.logging.info("entry id " +id);
});
return id;
};
OUTPUT : when I call this method it returns me 0 !!! and the log with "entry id 37"
I don't know why the value of id do not change after call this method. | i found the solution from Patrick Rudolph `forge.prefs.get()` is probably an asynchronous function call, which means that its callback is executed somewhat delayed. In your example load_my_car() is executed before the two callbacks are fired, so the variables are still undefined.
You have to make sure that the callbacks are fired before calling load_my_car(), try this:
forge.prefs.get('offset_val' function(offset1){
forge.prefs.get('id', function(val){
load_my_car(val,offset1);
});
})
; If you really don't want to have two nested forge.prefs.get() you'd need to check which callback finishes first and then only call load_my_car() after the second finished. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ios5, preferences, trigger.io"
} |
Transitioning from AWS WorkMail to different mail server, but keeping AWS SES
We are currently using AWS WorkMail for the email addresses of our team members, and we are using AWS SES to send automated emails from an EC2 instance.
Due to different reasons we want to move the email addresses of our team members to a different email service (not hosted on AWS). However, we want to continue to send emails from noreply@... using AWS SES.
What would be the best approach for this? I was thinking of the following:
* Setting the MX DNS-Entry to our new email server
* Setting the TXT DNS-Entry from `v=spf1 include:amazonses.com ~all` to `v=spf1 include:amazonses.com include:ournewserver.com ~all`
* Sending emails using SMTP on the new server
Would that be a good approach? Is there anything else I have to do or anything else I have to keep in mind when doing those changes?
Thanks a lot in advance! | From my perspective this looks fine, I would recommend that you do it in a staged approach:
* Lower TTL records on all records
* Add the SPF record first as it should be non-breaking
* Update MX records/SMTP.
Lowering the TTLs will make for a quicker rollback. Try to seperate all steps with a gap longer than the TTL so that you can be more determined over how to rollback the particular step. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "amazon web services, email, smtp, amazon ses, amazon workmail"
} |
Prevent sorting with for-in loop in Javascript
I have the following JSON array sorted by type (rather than ID).
var response = {"5":"Contacts","2":"Messages","3":"Profiles","1":"Schools","4":"Statistics"};
for (var key in response) {
alert(key + ' ' + response[key]);
}
I am wanting the order to stay as is however what is happening is that it is sorting it by ID so that it produces "1 Schools" first. How do I prevent a for-in loop from sorting by key?
I realize that no sorting order is guaranteed with a for-in loop, so how do I get around this? I need to access both the key and type. Is there a different type of array and/or loop that I should be using instead?
Also, just for further clarification and in case it makes a difference, my actual code has the JSON array coming from an AJAX request from PHP using json_encode. | You do not have an array, you have an object. Key ordering in an object is not guaranteed in javascript. If you want a sorted collection, you should use an actual array:
var response = [{"key":"5", "value":"Contacts"},{"key":"2", "value":"Messages"},{"key":"3", "value":"Profiles"},{"key":"1", "value":"Schools"},{"key":"4", "value":"Statistics"}];
for (var i =0; i < response.length; i++) {
alert(response[i].key + ' ' + response[i].value);
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, json"
} |
At which point in the universe history will inflation prevent galaxies feeding from intergalactic matter?
It's my understanding that galaxies formed from accretion of intergalactic matter around supermassive black holes. As the universe expands the amount of matter entering a galaxy decreases, until at some point this process stops or becomes negligible.
At which point in the past or the future will matter accretion from the intergalactic medium cease? How is this point in time shifted by the filamentous organization of baryonic intergalactic matter? | Although galaxies are moving apart from one another faster and faster, it is only at the largest scales where the average energy density of matter is smaller than the dark energy density. Clusters and superclusters of galaxies are unlikely to dissolve because they are more energy-dense than dark energy, and they will only become more dense as they collapse from their own self-gravity. | stackexchange-physics | {
"answer_score": 0,
"question_score": 1,
"tags": "cosmology, gravity, cosmological inflation, galaxies"
} |
Please install kpsewhich and put it on path - error using LATEX with Xournalpp snap
In Xournal++ I want to use `Tools` -> `Add/Edit Tex` But I get
> Could not find kpsewhich in PATH; please install kpsewhich and put it on path.
I checked, it is installed
$ whereis kpsewhich
kpsewhich: /usr/bin/kpsewhich /usr/share/man/man1/kpsewhich.1.gz
But on
$ PATH=$PATH:/usr/bin/kpsewhich:/usr/share/man/man1/kpsewhich.1.gz
$ xournalpp
I still get the error message above.
**UPDATES:**
I checked `echo $PATH` and `/usr/bin` is already on the path. | I was having the same issue as you. I was using the snap package of xournalpp.
First remove the snap package. `sudo snap remove xournalpp`
After removing that package and installing it from the _bleeding edge_ PPA repository, latex worked just fine.
sudo add-apt-repository ppa:andreasbutti/xournalpp-master
sudo apt update
sudo apt install xournalpp
If you want to stick to the latest stable version, you can instead use the _stable releases_ PPA.
sudo add-apt-repository ppa:apandada1/xournalpp-stable
sudo apt update
sudo apt install xournalpp | stackexchange-askubuntu | {
"answer_score": 3,
"question_score": 1,
"tags": "command line"
} |
Is a meromorphic function satisfying $f(2z)=\frac{f(z)}{1+f(z)^2}$ constant?
Let $f(z)$ be a holomorphic function on the unit disk satisfying $f(0)=0$ and $$f(2z)=\frac{f(z)}{1+f(z)^2}.$$
Extend it to a meromorphic function on the entire complex plane using this recursion. Must $f(z)$ be constant? I think so, but I can't prove it.
Substituting $g(z)=1/f(z)$ and rearranging yields
$$g(2z)=g(z)+\frac{1}{g(z)},$$
which seems useful, but I'm not sure how to proceed after that. | Write $f(z)=z^kg(z)$ with $k>0$, $g$ holomorhic, $g(0)\ne0$. Then $$2^kg(2z)=\frac{g(z)}{1+z^{2k}g(z)^2}$$ which gives a contradiction if we let $z=0$. | stackexchange-math | {
"answer_score": 7,
"question_score": 6,
"tags": "complex analysis"
} |
Bash - kill process when other process dies
My bash script looks something like this:
#!/bin/bash
java -jar my_app.jar &
python -m my_module
How do I kill the python process when the java process dies? | Like this maybe:
#!/bin/bash
{ java -jar my_app.jar ; pkill -f my_module; } &
python -m my_module
You may want to further limit the selection of your Python process to be killed with additional switches. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "bash, process"
} |
SwiftUI Image in ZStack not aligning to bottom of screen
I have this code
struct ContentView: View {
var body: some View {
ZStack(alignment:.bottom) {
Image("login-devices-mobile")
.resizable()
.scaledToFit()
}.padding(0.0).background(Image("login-background").aspectRatio(contentMode: ContentMode.fill))
}
}
which I am trying to display an image on the bottom of the screen. However when I run the preview. It still shows in the middle.
 {
Image("login-devices-mobile")
.resizable()
.scaledToFit()
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) // << here !!
.background(Image("login-background").aspectRatio(contentMode: ContentMode.fill)) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "swift, swiftui"
} |
Postgres Join Query for a table referencing itself
I have a table badges with the following schemas
create table badges (
id, serial primary key,
title, text not null,
next_badge_id: int references badges,
.
.
)
Given table as:
id | title | next_badge_id
----+------------------+---------------
1 | Bronze Partner | 2
2 | Silver partner | 3
3 | Gold partner | 4
4 | Diamond partner | 5
5 | Platinum partner |
How do I write a query to return this:
id | title | next_badge
----+------------------+---------------
1 | Bronze Partner | Silver partner
2 | Silver partner | Gold partner
3 | Gold partner | Diamond partner
4 | Diamond partner | Platinum partner
5 | Platinum partner | | You can use `left join` query
Sample data and query structure: dbfiddle
select
b1.id,
b1.title,
b2.title as next_badge
from
badges b1
left join badges b2 on b1.next_badge_id = b2.id | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "sql, postgresql, join"
} |
Positivity conditions for $N^\dagger N$ where $N$ is a linear map
Let $N: \mathcal{A} \rightarrow \mathcal{B}$ be a positive linear map between two Hilbert spaces, $\mathcal{A}$ and $\mathcal{B}$. Define the adjoint map $N^\dagger$ as the linear map which satisfies for any $x\in \mathcal{A}$ and $y\in\mathcal{B}$
$$\langle y, N(x)\rangle = \langle N^\dagger(y), x\rangle$$
Under what conditions is the map $N^\dagger N$ a strictly positive map? That is, when do we have the condition below for any $x$?
$$\langle x, N^\dagger N x\rangle > 0$$ | As Theo Bendit suggests, we have $N^\dagger N > 0$ if and only if $N$ is injective.
If $N$ is injective then for $x \ne 0$ we have $Nx \ne 0$ so $$\langle x, N^\dagger Nx\rangle = \langle Nx,Nx\rangle = \|Nx\|^2 > 0$$
Conversely, if $N^\dagger N > 0$, then for $x \ne 0$ we have $$\|Nx\|^2 = \langle Nx,Nx\rangle = \langle x, N^\dagger Nx\rangle > 0$$ so $Nx \ne 0$. It follows that $N$ is injective. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "linear algebra, adjoint operators"
} |
How Do I Access the Payload of a Fetch Response
I'm sending a fetch request to a Google Script and want to know how to get the payload of the response.
Client-side Code:
fetch(url, {
method: 'POST',
body: JSON.stringify({ type: 'proposal' }),
headers: {
'Content-Type': 'text/plain;charset=utf-8',
}
}).then( (response) => {
console.log("success:", response);
}).catch(err => {
console.log("Error:" + err);
});
And on the server side (GAS) I have this:
function doPost(e) {
return ContentService.createTextOutput('It works!'); // Please add this.
}
The code successfully sends the fetch request and by looking at the Payload via Firefox Dev Tools I get the expected response ('It Works!').
However, in my log I'm getting the response object. How do I get access to the actual payload (the ContentService TextOutput returned by the script). | Take a look at the "Using Fetch" docs on MDN: <
The response from `fetch` is a response object, which includes a number of methods that you can call in order to get the parsed response. Each of them returns a promise, and you'll need to call the right one based on the type of data in the response.
For example:
fetch('/url', {
method: 'POST'
...
}).then(res => res.text())
.then(text => {
...here is the text response
})
Or if your response is JSON:
fetch('/url', {
method: 'POST',
...
}).then(res => res.json())
.then(json => {
...here is the JSON response
}) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, google apps script"
} |
Subsets and Splits