INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to include html files properly
I'm trying to include a css file using this code :
HTML code:
<html ng-app="a">
<head>
<cssA></cssA>
</head>
<body><script src="app.js"></script></body>
</html>
AngularJS
(function () {
'use strict';
var app = angular.module('a', []),
app
.directive("cssA", function () {
return {
restrict: 'E',
templateUrl: "multiple-css.html"
};
});
}());
multiple-css.html
<link rel="stylesheet" href="
<link rel="stylesheet" href="https:/maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
How do I please include that html file ? | Directive names are normalized.
In HTML they should be spinal-case:
<html ng-app="a">
<head>
<css-a></css-a>
</head>
<body><script src="app.js"></script></body>
</html>
In JS, they are camel-case:
app.directive("cssA", function () {
return {
restrict: 'E',
templateUrl: "multiple-css.html"
};
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angularjs"
} |
Zend MVC, views/actions scheduling
I'm using Zend MVC and I'm looking for a way to schedule the views and actions but I don't know where to begin. The idea is to get a file like an XML file where I can define all the views of the website, to define the possible actions from a view and defines the transition.
Do you know where I can find some info (tuto) on this topic ?
Regards, Ced. | Is schedule the right word or did you mean something like **define the views and actions** , as in an application/website skeleton?
If that's the case you want the project profile '.zfproject.xml'. This file is automatically updated when you use the Zend Framework CLI tool. Read about it:
1. Using the CLI Tool;
2. Using Zend_Tool On The Command Line. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, zend framework, model view controller"
} |
Find $\int\limits_{0}^{2\pi} \frac{1}{5-3\cos(x)} \,\,dx$
I have to find $$\int_0^{2\pi} \frac{1}{5-3\cos(x)} \,\,dx$$
I tried to do it by substitution $t = \tan(\frac{x}{2})$
Then we have that $$\cos(x) = \frac{1-t^2}{1+t^2} \quad dx = \frac{2\,dt}{1+t^2}$$ but then also limits of integration are changing so we have $$\int\limits_{t(0)}^{t(2\pi)} \frac{1}{5 - \frac{1-t^2}{1+t^2}} \cdot \frac{2dt}{1+t^2} = \int\limits_0^0 \frac{1}{5 - \frac{1-t^2}{1+t^2}} \cdot \frac{2\,dt}{1+t^2} = 0$$ I figured out that it is not correct because $\tan(\frac{\pi}{2})$ is not defined and $t(\pi) = \tan(\frac{\pi}{2})$ and $\pi \in [0, 2\pi]$. How can I "repair" that and do it right? | Since the function you integrate is periodic you can change the limits and take the same integral from $-\pi$ to $\pi$. After the substitution you'll end up with an integral from -infinity to +infinity. If you want to stick to the original limits you have to break your integral to two parts. | stackexchange-math | {
"answer_score": 3,
"question_score": 8,
"tags": "calculus, real analysis, integration, definite integrals"
} |
Do I need to restart Camunda process engine when I design new process in BPMN Tools
My Camunda process engine has been running, at this time, I'd like to design a new process.
Do I need to restart Camunda process engine when I have finished new process in BPMN Tools? | Well, that depends how you use your engine. If it is a shared engine, just deploy the new processes and you will see that the engine will hold the old and new versions. If it is an embedded version, you could try to deploy resources via the REST api, but probably it is easiest to just restart and let the engine scan for new models. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "process, bpmn, camunda"
} |
Keyframes won't respond to 'Cycles' f-curve modifier
I'm making some material tests with Mapping nodes, but the Y scale of one of the Mapping nodes won't respond to the Cycles modifier. The other values do respond to modifiers but these won't:
$. Pick $r<2$ such that $K\subset D_r(0)$. By the maximum principle, $$ \max_{z\in K}|P_n(z)-P_m(z)|\le \sup_{z\in D_r(0)}|P_n(z)-P_m(z)|=\max_{z\in\partial D_r(0)}|P_n(z)-P_m(z)|\to 0 $$ when $n,m\to\infty$ by your initial assumption. Can you see how to complete the argument? | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "complex analysis"
} |
Characterization of two-step 2x2 stochastic matrices
Show that:
> A 2 x 2 stochastic matrix is two-step transition matrix of a Markov chain if and only if the sum of its principal diagonal terms is greater than or equal to $1$. | Encode the Markov matrix $\begin{pmatrix}1-a & a\\\ b & 1-b\end{pmatrix}$ by the couple $(a,b)$ with $a$ and $b$ between $0$ and $1$. The square of this matrix is encoded by the couple $$ (a(2-a-b),b(2-a-b)), $$ hence the question is to determine for which $a$ and $b$ between $0$ and $1$, there exists $x$ and $y$ between $0$ and $1$ such that $$ a=x(2-x-y),\qquad b=y(2-x-y). $$ If $x$ and $y$ exist, their sum $s$ solves $s(2-s)=a+b$ hence $(s-1)^2=1-a-b$, in particular $$ a+b\le1. $$ Assume this condition holds. Then $s=1\pm\sqrt{1-a-b}$, hence $$ x=a/(2-s)=a/(1\mp\sqrt{1-a-b}), $$ and $$y=b/(2-s)=b/(1\mp\sqrt{1-a-b}). $$ Since $1+\sqrt{1-a-b}$ is between $1$ and $2$, at least the choice $+$ in $\mp$ yields solutions $x$ and $y$ between $0$ and $1$.
Finally the Markov matrix $\begin{pmatrix}1-a & a\\\ b & 1-b\end{pmatrix}$ is the square of a Markov matrix if and only if $$ a+b\le1. $$ | stackexchange-math | {
"answer_score": 6,
"question_score": 4,
"tags": "stochastic processes"
} |
Ruby Koans about_methods line 123 object loop
Each time I add in the correct code, it gives me the same error due to AboutMethods:0x00000101841a28 number changing each time. It's like its stuck and I don't know how to get out this loop. It worked once, then I went on to the next step, but then it triggered an error after that.
I must not be inputting the correct line of code given from the console?
def test_calling_private_methods_with_an_explicit_receiver
exception = assert_raise(NoMethodError) do
self.my_private_method
end
assert_match "private method `my_private_method' called for #<AboutMethods:0x000001008debf8>", exception.message
end
The AboutMethods:0x000001008debf8 changes each time, not sure how to approach this problem? | `AboutMethods:0x...` is the output of the `inspect` method, which usually (and in this case) includes the class name (`AboutMethods`) and the object id (`0x...`). The object id is related to the objects location in memory, so it will change every time.
In my experience, there is very little value to checking the string from an exception (it's brittle). However, if you feel the need, use a regex:
` assert_match /private method `my_private_method' called for \#\<AboutMethods:.*/ ` | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 4,
"tags": "ruby"
} |
SAS: PROC EXPORT adds a "_" in the Excel sheet name but the _ is not there in SAS?
I have the following SAS code that exports to an .xls-file. (NB: I need the OLD 1997-2003 format).
I specify the sheet name to be: 'PB Organization'
but when the file is created the sheet name is 'PB_Organization'
An "_" has been added. What is happening?
PS: The file contains the right columns and rows, it is just the sheet name that is wrong.
%let Path_Org = "\\Folder\CurrentMonth - PB Organization";
proc export data=pb_org2
outfile = &Path_Org
dbms=xls replace;
sheet = 'PB Organization';
run; | from SAS docs:
**_SHEET=sheet-name_**
_identifies a particular spreadsheet in an Excel workbook. Use the SHEET= option only when you want to import an entire spreadsheet. **If the EXPORT procedure sheet-name contains special characters (such as space) SAS converts it to an underscore**._
The space is converted to an underscore. "Employee Information" becomes "Employee_Information"
see also here < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "sas, export to excel, excel 2003"
} |
How can I adjust my third vector position?
How can I adjust my third vector position? I want the vector to start from the origin (0,0) and point to the (4,-7) position, which is the green one in the picture. How to design it? Attach my code as below, thank you
import numpy as np
import matplotlib.pyplot as plt
V = np.array([[1,1],[-2,2],[4,-7]])
origin= [0], [0]
plt.quiver( *origin, V[:,0], V[:,1], color=['r','b','g'], scale=21)
plt.show()

origin = np.array([[0,0] for _ in range(3)])
plt.quiver(origin[:,0], origin[:,1], V[:,0], V[:,1],
color=['r','b','g'], scale=21)
plt.show()
note that the `scale` will shorten the vectors; this way they will not point at the vectors you have given, but in their direction and scaled down. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, matplotlib"
} |
Save web part configuration for a certain web part page
How can I save the configuration of a web part for a certain web part page in SharePoint? | From the UI you can export the web part. Edit the page, click the drop-down on the web part, and select Export. This allows you to save the web part's XML configuration so it can be uploaded elsewhere.
You can also programmatically export the web part using the SPLimitedWebPartManager.ExportWebPart() method.
For those web parts that do not allow an export, enumerate the web part properties programmatically. Here is a complete list of all web part members. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "sharepoint, web parts, webpartpage"
} |
use csv parameters in jmeter httprequest path
I want to use CSV Data Set Config to modify the path of a HTTP Request.
* My CSV file:
120,120
121,121
* My CSV variable names: `paraa, parab`.
* My http request path: `/my/path/with/?{paraa}/?{parab}/`.
I tried and I failed.
Is there anyway to work this around? | Seems that you incorrectly refer jmeter variables.
Try
/my/path/with/${paraa}/${parab}/
instead,
where `${paraa}, ${parab}` refer corresponding values extracted in CSV Data Set Config:
!enter image description here | stackexchange-stackoverflow | {
"answer_score": 19,
"question_score": 4,
"tags": "jmeter, load testing"
} |
How to dynamically call scopes with 'OR' clause from an array
I have an array, and I'd like to call scopes with `OR` clause:
cars = ['bmw', 'audi', 'toyota']
class Car < AR
scope :from_bmw, -> { where(type: 'bmw') }
scope :from_audi, -> { where(type: 'audi') }
scope :from_toyota, -> { where(type: 'toyota') }
end
I'd like to achieve something like this:
Car.from_bmw.or(Car.from_audi).or(Car.from_toyota)
My `cars` array can change; in case: `cars = ['toyota', 'audi']`, my method should produce:
Car.from_toyota.or(Car.from_audi)
I have something like the following:
def generate(cars)
scopes = cars.map {|f| "from_#{f} "}
scopes.each do |s|
# HOW TO I ITERATE OVER HERE AND CALL EACH SCOPE???
end
end
I don't want to pass type as an argument to scope, there's a reason behind it. | def generate(cars)
return Car.none if cars.blank?
scopes = cars.map {|f| "from_#{f} "}
scope = Car.send(scopes.shift)
scopes.each do |s|
scope = scope.or(Car.send(s))
end
scope
end | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, rails activerecord"
} |
Can people steal my icons?
I've got some icons, nicely displayed in a row in my house:
!enter image description here
If I have guests over, will they be able to pick them up and take them? | As long as the icon's in your house, it's safe.
The Glitch Strategy Wiki seems to have my back:
> Using the Place verb will place the icon on the ground. The icon is safe when placed in your house. When placed elsewhere, anyone can pick it up.
Together we just tested this, and no, I can't take your icons. I _can_ take your butterfly milker (among other things left on the ground) but I can't access your storage cabinets, or disassemble your machines or the still. | stackexchange-gaming | {
"answer_score": 8,
"question_score": 7,
"tags": "glitch"
} |
Rendering itemviews in marionetteJS
Recently I have been fiddling around with JS frameworks. Being new to BackboneJS I'm running stuck on the most simplest of things. The rendering of an itemView.
I made a Plunker here. I'm sure it's something stupidly simple, but I can't seem to find the problem. The console shows no errors for me. | you have just one small error, in your in index.html you have this
<div id="#content"> // you dont need the # there
remove it and it will work
<div id="content"> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, model view controller, marionette"
} |
Will inline speed up void a(string b) { cout << b; }
For an assignment, we're supposed to write two methods for handling outputs. One for outputting strings, and one for integers.
Basically we have two methods calling another method:
void TheClass::displayString(string str){ cout << str; }
void TheClass::displayNumber(int n) { cout << n; }
Will inline speed things up by saving some overhead by not calling yet another function or will it create more in regards to namespaces and such for cout?
inline void TheClass::displayString(string str) { cout << str; }
inline void TheClass::displayNumber(int n) { cout << n; } | Namespaces don't have anything to do with it.
You probably won't see any benefit here for one simple reason: the function is so small that I'd expect the compiler to be inlining it _anyway_.
Remember, the keyword `inline` is a _hint_ not a directive, and usually you can just let your toolchain decide when to inline. It's good at that. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 1,
"tags": "c++, performance, methods, inline, overhead"
} |
numpy.concatencate two same size row vector to matrix
a=np.random.uniform(0,1,10)
b=np.random.uniform(0,1,10)
a=np.concatenate(a,b, axis=0)
I am refresh `a` to be `(2x10)` matrix. But what I got was just an `(1x20)` array.
The example works well.
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
np.concatenate((a, b), axis=0)
gives
array([[1, 2],
[3, 4],
[5, 6]])
Why? And what can I do to change this?
Thank you and the editor. | One way to solve this (I'm sure there are many alternatives) is to create `a` and `b` as 2-dimensional arrays, with dimensions 1x10, rather than simply making them 1-dimensional arrays. You can do this by passing a tuple as the `size` argument to `np.random.uniform`:
a = np.random.uniform(0, 1, (1, 10))
b = np.random.uniform(0, 1, (1, 10))
result = np.concatenate((a, b), axis=0) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "python, numpy"
} |
How do I change the selector so that the website shows login instead of signup using selenium python and chromedriver?
enter image description here REGISTER LOGIN The code i wrote in python
driver.find_element_by_xpath("//div[@id='sectionContainer']//div[@id='login_section_btn']")
#driver.execute_script("arguments[0].setAttribute('class','active_section_btn')", element)
Error message that i am getting is:
> Unable to locate element: {"method":"xpath","selector":"//div[@id='sectionContainer']//div[@id='login_section_btn']"} ( | driver = webdriver.Chrome()
driver.get("
WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.XPATH, "// div[@id='sectionContainer']//div[@id='login_section_btn']"))
).click()
you should use explicit wait for waiting till the element is loaded properly. THe second error element not interactable may be bacause the button is disabled or something unless we have access to website or have screen shot its hard to tell. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "python, selenium, xpath, selenium chromedriver"
} |
How to create tooltips as bubble boxes in Qt?
I have trying implementing tooltips as bubble boxes in qt, without any luck. Even tried placing a css file in qt having code to mainpulate tooltips, but of no use. Any methods to create tooltips as bubble boxes in qt widgets? | You can use `QBalloonTip` which is an internal class defined in :
* Qt 5:
`QtDir/Src/qtbase/src/widgets/util/qsystemtrayicon_p.h`
* Qt 4:
`QtDir/src/gui/utils/util/qsystemtrayicon_p.h`
`QBalloonTip` inherits `QWidget` and it is implemented in `qsystemtrayicon.cpp` at the same directory. It has the following method to show a balloon tip:
void QBalloonTip::balloon(const QPoint& pos, int msecs, bool showArrow)
You can modify the source code of this class to have your desired balloon tip. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "qt"
} |
How to construct sequences by induction?
if $(u_{n})_{n\in\mathbb{N}}$ is an arbitrary sequence of reals. How do I start to construct, by induction, two real sequences $(a_{n})$ and $(b_{n})$ such that these criteria hold:
* $(a_{n})$ is increasing
* $(b_{n})$ is decreasing
* for all n$\in \mathbb{N}, a_{n} < b_{n}$
* the sequence $(b_{n} - a_{n})$ converges to 0.
* $u_{n} \notin [a_{n}, b_{n}]$ | Take an arbitrary initial interval $a_0<b_0$. If this interval contains $u_0$, trim it on one side by keeping one of $\left[\dfrac{u_0+b_0}2,b_0\right]$ or $\left[a_0,\dfrac{a_0+u_0}2\right]$.
Shrink this interval, for instance with $a_1=\dfrac{2a_0+b_0}3,b_1=\dfrac{a_0+2b_0}3$. If the new interval contains $u_1$, trim it on one side by keeping one of $\left[\dfrac{u_1+b_1}2,b_1\right]$ or $\left[a_1,\dfrac{a_1+u_1}2\right]$.
And so on.
You can easily check that those intervals are non-empty, nested, do not contain the respective $u_n$ and their size converges to $0$. | stackexchange-math | {
"answer_score": 1,
"question_score": 4,
"tags": "real analysis, induction"
} |
Keyboard does not dismiss interactively
On an iOS app, I have the following view structure:
UIViewController > UIView > UIScrollView > UITextView
The UIScrollView has the "Dismiss Interactively" setting. When I tap on the UITextView, the keyboard pops-up properly. However I now try to gradually dismiss the keyboard by slowly swiping my finger down, but nothing happens.
Did I forget anything in my configuration ?
Example project | Issue was linked to the fact that the scrollView contents were shorter than the screen size. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, objective c, uiscrollview, keyboard"
} |
How to disable .removeClass()
I have a problem with `jquery-2.1.4.js`.
I have added a `layerslider` to my website, but this script changed div classes. I tried to change this script for lower versions, but it still not working.
So... I have classes like:
<a href="#" class="col-md-3 col-sm-6"><p><img src="...pomoc.jpg" alt=""></p></a>
When I added `jQuery` script to my website, result is
<a href="#"><p><img src="...pomoc.jpg" alt=""></p></a>
This is an example, but half of website gets distorted.
Is it possible to delete a `removeClass` function from this script or add some code so It doesn't change/alter classes on DOM elements. | In the jQuery script, modify the line that could be like this:
$('SELECTOR-HERE').removeClass('col-md-3 col-sm-6');
or
$('SELECTOR-HERE').removeClass('col-*');
or something similar.. (just search ".removeClass(" in the .js file)
* * *
With this:
$('SELECTOR-HERE').not('.escape-removeClass').removeClass('col-md-3 col-sm-6');
And edit your HTML as follow:
<a href="#" class="col-md-3 col-sm-6 escape-removeClass">
<p>
<img src="...pomoc.jpg" alt="">
</p>
</a>
* * *
If you want a more accurate answer, let me see the jQuery code | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, html, css, removeclass"
} |
jquery on not working properly
I have the following jquery code
$(".delete").on('click', function (e){
e.preventDefault();
var id = $(this).prop('id');
console.log('Delete button id: '+id);
var formWrapper = $(".form-wrapper:nth-child("+id+")");
console.log(formWrapper);
formWrapper.remove();
});
the delete .delete is on a button inside a form
<button class="btn btn-danger delete">-<button>
and the button is loaded on the paged ynamically after the page has loaded. So I used the on function to attach the click event on it. But it won't work and the function is never called. Isn't on supposed to work not only for elements that are on the page during load but for those that get loaded afterwards? | You are saying that the particular button is getting loaded to the DOM dynamically, so in this context you have to use **`event-delegation`** to make your code working.
Normally your code will register event for the element with the class `.delete` immediately after the `DOM` loaded. Actually we dont have any elements with that identity at that time, So this context is opt for `event-delegation`.
I actually dont know the exact dom structure of yours, so that i have used document to delegate the click event, But you should prefer some static parent of that element to implement it,
Try,
$(document).on("click",".delete", function (e){ | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "javascript, jquery"
} |
Question about indirect object?
> Grammar is driving me crazy.
What would _crazy_ be in this sentence? Is it an indirect object? | No, not an indirect object (nor a modifier), but an **objective predicative complement**. **Me** is the direct object of the verb _driving_ , and the adjective _crazy_ is describing a property that is ascribed of _me_. | stackexchange-english | {
"answer_score": 1,
"question_score": 1,
"tags": "indirect objects"
} |
¿Cómo puedo seleccionar solo un checkbox de dos y evitar que el seleccionado se desmarque al dar click en la misma?
Me gustaría saber la solución con javascript (si es posible) en marcar solo un checkbox de dos o mas y evitar que al dar clic en el seleccionado se desmarque. ¿Me podrían ayudar?. | Puedes usar una función que se ejecute cada vez que hay un cambio en alguno de los checkbox. Cuando se encuentre seleccionado el checkbox y se quiera deseleccionar entrara en la condición if y volverá a seleccionar el checkbox mediante la propiedad checked.
function verifica_seleccion(check){
if(!check.checked){
check.checked=1;
}
}
Cada elemento checkbox tiene asignada la funcion verifica_seleccion(this) en su propiedad onchange para asegurarse que una vez seleccionado, así se mantenga.
<form name="f1">
<input type="checkbox" id="check1" name="check1" onchange="verifica_seleccion(this)" value="Check1">Check1
<input type="checkbox" id="check2" name="check2" onchange="verifica_seleccion(this)" value="Check2" >Check2
<input type="checkbox" id="check3" name="check3" onchange="verifica_seleccion(this)" value="Check3" >Check3
<input type="submit" value="Enviar">
</form> | stackexchange-es_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, checkbox, input"
} |
How increase a sprites speed without ending up spiraling instead of circling
Hey so i have a sprite class, and i am making it turn 360 degrees a second, while increasing speed at the same time. However I end up spiraling and not staying on the original circle formed by the continuous turning of 360 degrees per second.
**How can i fix this? The sprite needs to go faster and stay on the same path.**
here's the code:
box.Accelerate(10*Window.GetFrameTime());
box.Turn(360.0*Window.GetFrameTime()); | If you want to make a sprite go in a circle, put that in the code. For example,
float time = Window.GetFrameTime();
angle += speed * (time - lastTime);
lastTime = time;
float x = sinf(angle), y = cosf(angle);
box.SetPos(50*x + center.x, 50*y + center.y);
box.Turn(angle + QUARTER_TURN); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, performance, path"
} |
JavaScript For/Loop comparison issue
In my opinion, this JavaScript should work, but it will not work! The loop is never run (it is skipped altogether).
FYI totalPages = 15
for (var i = 1; i >= totalPages; i++) {
pagingOptions += '<option value="' + i + '">' + i + '</option> ';
}
If I change it like this, it works:
for (var i = 1; i < totalPages; i++) {
pagingOptions += '<option value="' + i + '">' + i + '</option> ';
}
What is the problem? The JavaScript will only run the loop if the comparison is "i < totalPages"? Why would this be the case? | The semantics of the `for` loop:
for (expression1; expression2; expression3) {
// ...
}
AFTER: // statements
are:
1. evaluate `expression1`
2. evaluate `expression2` and check to see if it's `truthy`. If not, skip subsequent code (here, to "AFTER")
3. evaluate the statement (usually a block statement) associated with the `for` statement
4. evaluate `expression3`
5. go to step 2
Thus, the middle expression should evaluate to `true` when iteration of the loop body should continue. As soon as it's `false` -- even if it's `false` on the very first try -- the loop finishes.
Another way to think of it is that it's like:
expression1;
while (expression2) {
// statements
expression3;
} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "javascript"
} |
Change user slug in Buddypress
I am creating a site with Buddypress. Everything is going good so far but default member slug for buddypress is `domain.com/members/abc`. I want that it as `domain.com/abc` like facebook and twitter. Any one can help me for that..... | Place the following code in your theme's functions.php file:
add_filter( 'bp_core_enable_root_profiles', '__return_true' );
I hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users, buddypress, slug"
} |
how to stop while loop running for storing data in vector
i am using while loop for storing integer data in a vector like this :
vector<int> a;
int data=1;
cout<<"Enter data (Press Ctrl+Z to end)";
while(data)
{
cin>>data;
if(data)
a.push_back(data);
}
this loop goes infinite the reason i found out after tacing is that when i enter `Ctrl+Z (eof)` to read in `data` it does not take that value and because last value is still there in `data` the loop runs again
Enter data (Press Ctrl+Z to end)23 //data=23
56 //data=56
45 //data=45
^Z // still data=45
i don't want to use condition with a specific number to end the loop like `Enter -1 to end` and user to specify the number of items to store in vector in advance. Is there any other way i can end the loop by using `Ctrl+Z` or any other string like `done, finish etc..` | while(cin >> data){
a.push_back(data);
}
Note that the EOF is usually set by using Ctrl+D, not Ctrl+Z (which will instead let your program sleep). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, loops, vector, stl"
} |
Power BI Embedded Analytics Client API: "FailedToValidateDataRole" when calling visual.AddDataField()
I am attempting to add data to a blank Visual using Power BI Embedded Analytics Client API. The visual is type "card".
I am calling `visual.AddDataField("Fields", ...)` in my JavaScript code
This produces the following error:
FailedToValidateErrorRole Screen shot
Is _**Fields**_ the correct first parameter here? This is the name of the field when using PowerBI itself:
Power BI card example screen shot | After looking here: <
I added the following line to my source code:
let capabilties = await this.visual.getCapabilities();
Then I was able to see what the data role was that it was expecting which was actually _**Values**_
Once I used this it worked. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "powerbi"
} |
Comparing a DATETIME2 column to a DATETIME2 field does not return expected results
When tracking down a deadlock and I noticed that when I looks for records that occurred this morning that nothing is returned. However, if I looks for records that occurred **before** `1/1/1900`, then records with a time **after** `6/30/2020 15:00` are returned. This is using SQL Server Azure PaaS.
`[timestamp_utc]` is a `DateTime2`

WHERE CAST(timestamp_utc AS datetime2) > '2019-03-25 10:20:00'
 x^n + \sum_{n=0}^{\infty}n x^n$
= $x^2\sum_{n=0}^{\infty}n(n-1) x^{n-2}+x \sum_{n=0}^{\infty}n x^{n-1} =x^2(\frac{1}{1-x})'' + x(\frac{1}{1-x})'$
But anyway I continute gets me a wrong answer so I wonder if there's some mistake here?
The answer should be $ -\frac{x(x+1)}{(x-1)^3} $ | Your solution is mostly correct. Your lower bounds for the summation are wrong. But that is irrelevant when it comes to your argument simplification which you must not have done correctly because you will get the right answer if you continue down the path you are currently going on. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "real analysis"
} |
Altering the format of a list of strings
I have to analyze earthquake data, and before I can begin analyzing the data, I have to change the format of the way the data is listed. I have to change the format from:
14km WSW of Willow, Alaska$2.4
4km NNW of The Geysers, California$0.9
13km ESE of Coalinga, California$2.1
...
to:
["2.4, 14km WSW of Willow, Alaska", "0.9, 4km NNW of The Geysers, California",
"2.1, 13km ESE of Coalinga, California", ...]
The code that I have for the original format (omitting the url) is:
def fileToList(url):
alist = []
source = urllib2.urlopen(url)
for line in source:
items = line.strip()
alist.append(items)
return alist
I'm trying to create variables magnitude and earthquakeloc to rearrange the format of alist, but I just don't know where to start. I am very new to coding. Any suggestions would be wonderful, thank you. | hint:
>>> a = "14km WSW of Willow, Alaska$2.4"
>>> a = a.split("$") split the string on `$`
>>> a
['14km WSW of Willow, Alaska', '2.4']
>>> a = a[::-1] reverse the list
>>> a
['2.4', '14km WSW of Willow, Alaska']
>>> ",".join(a) give jon on `,`
'2.4,14km WSW of Willow, Alaska'
one liner:
>>> ",".join(a.split("$")[::-1])
'2.4,14km WSW of Willow, Alaska'
Pythonic way for your expected output:
>>> myString = """14km WSW of Willow, Alaska$2.4
... 4km NNW of The Geysers, California$0.9
... 13km ESE of Coalinga, California$2.1"""
>>> map(lambda x: ",".join(x.split("$")[::-1]), myString.strip().split("\n"))
['2.4,14km WSW of Willow, Alaska', '0.9,4km NNW of The Geysers, California', '2.1,13km ESE of Coalinga, California'] | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python"
} |
Deviation of random matrix from its expectation informs the positiveness of its second smallest eigenvalue
Let $A$ be a PSD random matrix, which has $0$ as one of its eigenvalues. The second smallest eigenvalue of the expectation of $A$ writes as $\lambda_2(\mathbb{E}(A))>0$.
Why the following statement holds?
If $\|A-\mathbb{E}(A)\|<\lambda_2(\mathbb{E}(A))$, then $\lambda_2(A)>0.$
Note that $\|\cdot\|$ denotes the operator norm. | The random-matrix connection is a bit of a red herring: Since the weight of $A$ in the statistical average can be arbitrarily small, we might as well replace $\mathbb{E}(A)$ by an arbitrary PSD matrix $B$ with $\lambda_2(B)>0$.
The statement in the OP
> If $\|A-B\|<\lambda_2(B)$, then $\lambda_2(A)>0,$
is a consequence of the "eigenvalue stability" inequality $$|\lambda_i(A)-\lambda_i(B)|\leq \|A-B\|,$$ which is proven, for example, in Tao's notes (equation 13). | stackexchange-mathoverflow_net_7z | {
"answer_score": 1,
"question_score": 2,
"tags": "linear algebra, random matrices"
} |
How to add multiple Enums to List object
I have an enum like the following:
public enum MyCategory
{
Automotive = 1,
BeautySalon = 2,
EventsEntertainment = 3,
and so on...
}
In my main class I have a property like so:
public List<MyCategory> Categories { get; set; }
My business entity can be associated to 1 or many of these at any time. I am able display this enum listing in the UI but my question is this, is it good practice to store multiple of these enums in a List<> like this and if so, what would be the best way to approach this? | You should take advantage of the `FlagsAttribute`:
[Flags]
public enum MyCategory
{
Automotive = 1,
BeautySalon = 2,
EventsEntertainment = 4,
and so on... (each next item should have a value that it 2^n)
}
And then:
MyCategory myCategory = MyCategory.Automotive ;
myCategory |= MyCategory.BeautySalon ;
Or in case you would like to assign multiple enum values at once:
MyCategory myCategory = (MyCategory.Automotive|MyCategory.BeautySalon);
I would then recommend to use the following helper method for check purposes:
public static bool ContainsMyCategory(MyCategory val, MyCategory checkedAgainst)
{
return ((val & checkedAgainst)==checkedAgainst);
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, enums"
} |
How can a flavour changing neutral current be drawn for the higgs decay to two down-type quarks?
I am trying to draw a Feynman diagram for the decay $ h \rightarrow d+\bar{s} $, but I'm struggling to create one which makes sense. So far I have this diagram:
, and also more generally how FCNC Feynman diagrams are structured? | You were already on the right track. But in your Feynman diagram you have drawn the $u$ an $\bar{s}$ as incoming particles, instead of outgoing. So your diagram actually describes the process $$h+d+\bar{s} \to \text{nothing}$$
For describing the process $$h \to d+\bar{s}$$ the Feynman diagram would look like this.
` method can be used. But I don't want to traverse through the entire XML tree right to the bottom where the to-be replaced node is stuck. In simple, I should be able to fly right to my node of interest and replace its contents. | Check out <
$.parseXML("well formed xml document").find('css selector to find element to remove').remove() | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, dom, xml parsing"
} |
Infinite loop - iteration, the function returns true
I've question. I need to make a program running in the background. The program is to collect and save data in my database.
I started to do so:
func main() {
for {
doAll()
}
}
And that retrieves data from all addresses at one time ("go" function):
func doAll() {
rows, err := MySQL.QueryRow("SELECT * FROM `settings`")
checkError(err)
defer rows.Close()
for rows.Next() {
c := make(chan bool)
var http string
err = rows.Scan(&http )
checkError(err)
go doOne(http)
<- c
}
}
And that retrieves data from one web site.
func doOne() {
// some code
c <- true
}
My question is whether iterations of the "doAll" function will be in order? | Yes the iterations of `doAll` will be in order, because the `c` channel is unbuffered. That means in your `for rows.Next()` loop, the read from `c` will wait until `doOne` writes to the channel.
You can make this code simpler by removing the channel and executing `doOne` synchronously (that is: just call it as a function). The code refactored in this way has exactly the same semantics. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "loops, go, infinite"
} |
Perl CPAN module object method not found error
I am trying to use a CPAN module: `Math::Vector::Real::Neighbors`
I see the following error message:
> Can't locate object method "box" via package "Math::Vector::Real" at /usr/local/share/perl/5.14.2/Math/Vector/Real/Neighbors.pm line 12.
So, I go into the package and see this: `my ($bottom, $top) = Math::Vector::Real->box(@_);`
Next, I go into the `Real.pm` package at: `/usr/local/share/perl/5.14.2/Math/Vector/Real.pm`
I see the box sub routine exist in it: `sub box {...`
Any idea why the error might be cropping up? | You need to add `use Math::Vector::Real` to the top of your script to get Math::Vector::Real::Neighbors to work. The following code runs as expected:
use strict;
use warnings;
use Math::Vector::Real;
use Math::Vector::Real::Neighbors;
use Math::Vector::Real::Random;
my @v = map Math::Vector::Real->random_normal(2), 0..1000;
my @nearest_ixs = Math::Vector::Real::Neighbors->neighbors(@v);
But note that it did not work without the line **use Math::Vector::Real**. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "perl, cpan"
} |
error C2825: '_Container': must be a class or namespace when followed by '::'
I added priority_queue to my code. When I do, I get this error:
error C2825: '_Container': must be a class or namespace when followed by '::'
it leads to line 218 of the queue file: C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\queue
#include "node.h"
typedef std::pair<Nodes*, unsigned int> PathDistPair;
struct PairComparator
{
bool operator()(PathDistPair i, PathDistPair j)
{
return i.first > j.first;
}
};
MinHeap;
typedef std::priority_queue<float, PathDistPair*, PairComparator> MinHeap;
in node.h:
class Node;
typedef std::vector<Node*> Nodes;
class Node
{
....
This is right up there in the "least helpful error messages" award category. I have no idea what to do about this, other than giving up and coming up with my own priority_queue. | Your priority queue typedef doesn't specify a container in which the queue will store its items.
You need to replace your `PathDistPair*` template parameter with a container type holding `PathDistPair*` to tell `priority_queue` the underlying structure you want to use.
// E.g. Using a vector.
typedef std::priority_queue<float, std::vector<PathDistPair*>, PairComparator> MinHeap; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "c++, stl, priority queue"
} |
How to convert a JSON requestBody of the RestRequest to a Map of Strings?
A type of the body is JSON Blob in a form of:
`{"key1":"val1";"key2":"val2"}`
I wanted to convert it into a `Map<String, String>`. Do I have to manually deserialize it or there's a class which can handle that? | Let me google that for you...
The class is called JSON, and the method is:
public static Object deserializeUntyped(String jsonString)
So you use it as:
Map<String, Object> myMap = (Map<String, object>)JSON.deserializeUntyped(jsonString); | stackexchange-salesforce | {
"answer_score": 1,
"question_score": 0,
"tags": "apex, webservices, apexrest"
} |
Prove that $f: \mathbb{Z}/p\mathbb{Z} \to \mathbb{Z}/p\mathbb{Z}$ is a linear map if and only if $p=3$
Let $f:F\to F$ be defined by $f(x)=x^3$ where $F=\mathbb{Z}/p\mathbb{Z}$ for some prime $p$. Prove that $f$ is linear if and only if $p=3$.
**My attempt:**
First suppose $p=3$. Then $$f(x+y)=x^3+3x^2y+3xy^2+y^3=x^3+y^3=f(x)+f(y)$$ and $$f(\lambda x) = \lambda^3 x^3 = \lambda x^3 = \lambda f(x)$$
Therefore $f$ is linear.
Now suppose $p \neq 3$. I'm not sure what to do from here, how do I do this? | If $a^3=f(a \cdot 1)=af(1)=a$ for every $a \in \Bbb F_p$, then it holds in particular for a generator $g$ of $\Bbb F_p^*$, which is a cyclic group. Think about the order of $g$, noticing that $g^2=1$. Can you take it from here?
* * *
Other idea: if $a=2$, you get $a^3 = 8 \equiv 2 = a \pmod p$. Can you take it from here? | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "linear algebra, finite fields"
} |
What is the default timeout for Task.Wait
I have created a web application that uses Task.Wait. Soon after I used it my application slowly came to a crawl about 30 days later. I never found out why but I am suspecting it is the Task.Wait method that never time out if the remote server never response. Just wanted to know if Task.Wait is executed will it wait forever it remote server never response? | Looking at the source from Reference Source, this if the code from `Task.Wait()` :
public void Wait()
{
#if DEBUG
bool waitResult =
#endif
Wait(Timeout.Infinite, default(CancellationToken));
#if DEBUG
Contract.Assert(waitResult, "expected wait to succeed");
#endif
}
So, the timeout is `Timeout.Infinite`! | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 2,
"tags": "c#"
} |
Existe-t-il un dictionnaire anglais-français de termes techniques?
Je dois parfois traduire de l'anglais au français des offres d'emplois qui sont techniques (dans le domaine logiciel), et j'aimerais pouvoir utiliser un ouvrage de référence pour confirmer certains termes. Est-ce qu'il existe un dictionnaire en ligne de termes plus techniques? | Le Grand dictionnaire terminologique de l'Office québécois de la langue française est une bonne référence pour les termes techniques de tous les domaines, mais pas toujours aussi complets que des dictionnaires spécialisés dans un domaine particulier.
Pour le cas particulier de l'informatique, le glossaire de traduc.org est très complet.
Sinon, j'ai trouvé sur Amazon.fr un dictionnaire papier de termes techniques, reste à voir ce qu'il vaut. | stackexchange-french | {
"answer_score": 7,
"question_score": 8,
"tags": "traduction, ressources, informatique, terminologie, dictionnaires"
} |
Apply conditional formatting depending on an other field's value
On the field DaysSinceRequest of an an Access' Form, I am applying a conditional formatting depending on its value in eavch record, that part is fine.
But how could I tell "Apply the conditional formatting to the field DaysSinceRequest ONLY if the field DatePartReceived is empty/null" ?
Is there a way to do this ?
PS : Just to show that I've done something before haters start down rating, here are the rules I've applied to the field DaysSinceRequest and the result in the Datasheet View
Tell if if my post is not clear enough, thanks | Just use `Expression Is` instead of `Field Value Is` and in Expression field you can use any expression, which evaluates to Boolean value. In your case you can use `IsNull` function | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "database, forms, ms access, conditional formatting, ms access 2016"
} |
Converting MySQL ANSI input to UTF-8
I've decided to switch my web app from ANSI to UTF-8. After converting the encoding of my hardcoded files in Notepad++ (which does a _conversion_ , not only changing the character set) and setting a new meta tag for UTF-8, I now need to convert my database data.
This data has been inputted on ANSI forms, but is stocked as utf8_general_ci according to phpMyAdmin. Obviously I can't just change the MySQL stocking encoding then, because it's already the right one (apparently?).
On the web pages, my accent characters (é, à, etc.) loaded from the DB appear as . | I think I found a solution from this blog:
UPDATE `ressources` SET `title` = CONVERT(CONVERT(`title` USING binary) USING utf8);
However, I get 0 rows affected on phpMyAdmin. Any idea why? | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "mysql, encoding, utf 8, ansi"
} |
Разделение строки по символам в Python
Есть переменная `s = "Hello World"`. Tребуется разделить ее на символы с сохранением пробелов и занести это все в список, т. е. имея строку нужно получить на выходе список, где каждый следующий элемент - это следующий символ строки(включая пробелы). Конечно, можно пробежаться циклом, типа
a = list()
for i in range(len("Hello World")):
a.append("Hello World"[i])
Но, может, есть какой-то более оптимальный способ, который применяют в серьезных прогах(Кроме списочных выражений)? | Можно исползовать генераторы списков
i = [c for c in "Hello world"]
print(i) | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python"
} |
Bitwise query multiples values
I want execute a query with bitwise in SQL Server.
I have a Event table with values with all combinations.
If Monday is (2^0) 1, and Sunday is (2^6) 64, I want all records with monday, wednesday and sunday, I write this query:
SELECT Distinct(DayBitwise)
FROM Assets
WHERE DayBitwise | 1 | 4 | 64 = 1 | 4 | 64
ORDER BY DayBitwise
Expected result:
1, 3, 4, 5, 6, 7, 9, 11, 12, 13, 15, 17, 19, 20, 21, 23, 25, 27, 28, 29, 31 ....
Actual result: 1,4 ,5, 64, 65, 68
Thanks. | If you want to see if all three days are present, then do:
WHERE (DayBitwise & 1 & 4 & 64) = (1 | 4 | 64)
If you want any, then:
WHERE (DayBitwise & (1 | 4 | 64)) > 0
Note: I don't recommend using bit columns for this purpose. Bit operations are not particularly efficient in SQL. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "sql, sql server, bit manipulation"
} |
For iAd, what means to be an impression?
Say I have a view that will show an iAd banner once the view is loaded/appear, does it mean that the # of times that the view appears == the # of impressions? | Yes, the iAd code calls the server (# of requests) and when it gets an answer your code displays the ad (# of impressions). | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "iphone, iad, impressions"
} |
From PHP (LAMP) to Classic ASP, how to setup a dev environment
I'm jumping into updating a Classic ASP web app coming from a PHP background and am trying to get my bearings. I'm used to just installing something like MAMP, messing the httpd.conf a bit and getting on my way.
Ideally, I would like to be able to edit this app completely locally on my **Macbook Pro** running **OS X Leopard** so that I'm not messing with my client's server too much. Now, if I need to I'm willing to install Windows 7 via Boot Camp or running it as a virtual machine. Of course my preference is to stay completely in OS X, but I have my doubts about that possibility. So, how should I go about this?
One thing to note is that once I'm done updating this ASP web app I will have to make changes to a VB(.NET) application as well, so I'd like to have to change my virtual workspace as little as possible when that time comes around. | As you say, you will need to install Windows via Boot Camp or VM (your choice).
Once in Windows, you can install Visual Studio 2010 (Express free), where you can edit your ASP Classic files, and you will have it already installed when you need to do VB.net
Do not forget to install IIS when you install Windows (you will need it to run ASP Classic) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iis, macos, asp classic, development environment"
} |
Consequence of using both filevault and cloud encryption
I am using a macbook pro with filevault turned on. I am planning to start using a zero-knowledge cloud service (sync.com) for all my files, to have a secure backup and as a way to share certain files with others. I was wondering if the two types of encryption will work alongside each other. If so, where in the process does the cloud encryption engage, and where does filevault take over? Will there be unnecessary redundancy in the two encryptions (perhaps with longer waiting times)? Just trying to picture what will happen. Thanks! | On macOS, FileVault is encryption at rest so it’s designed to protect your files when the operating system isn’t operating. Just as you can see an email or text document once you log in and your password decrypts the drive, any apps can read clear versions of your files and send them to the cloud in the clear, print them in the clear.
Having FileVault doesn’t make things slower or faster, so you can pretty much exclude that from your worries and plans about whatever cloud sharing service and program you select.
That service will be fast or slow, secure or not on its own design and merits regardless of the status of FileVault. | stackexchange-apple | {
"answer_score": 0,
"question_score": 1,
"tags": "filevault, icloud"
} |
Visual Studio Team Services - cURLUploader to scp output from Publish Build Artifacts
I want to use the use the "Publish Build Artifacts" (artifact type "server") task to zip up my build output and then `scp` the zip file using cURLUploader to my deployment host.
I can't seem to figure out how to get a path to the zip file to enter into cURLUploader. Is there a better way to zip the build output? | You can install Zip and unzip directory build task and use it to zip your build output. The Zip file will be generated in the same path as the folder you want to Zip.
> A set of Build tasks for TFS 2015 and Visual Studio Team Services that enables you to Zip and Unzip a directories. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "azure devops, azure pipelines"
} |
What happens when a SOAP fault occurs?
If there is a web service method like this:
object MyMethod()
{
..fault happens here..
return someObject;
}
I want to know what (if anything) gets returned to the client from this method. I know there will be SOAP fault XML generated, but what about **someObject**? | The fault will be treated as an exception and the exception will be throwed, in this case, the someObject will not be delivered to the client. The client will receive the exception, and you must handle it. If you handle these exception on web service level, you can still return the someObject | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "soap, error handling"
} |
How to get a transaction id from a successful payment?
I'm using PHP and the REST Paypal APIs to make simple payments. I'm able to call the `Pay` API and make a successful payment.
However, I don't know how to get the transaction id. I need to store it in order to make a refund in the case the customer complains on something. By now I'm only able to get it from my email (I get an email about the payment including the transaction id). So I read the email, take the transaction id and pass it to the web app in order to make a refund. I'd like to get such transaction id via some REST API too. | Solved using the `PaymentDetails` API:
<
I passed to `PayKey` to the function and it returned the transaction ID for that payment. The `PayKey` is returned by the `Pay` API when the payment is made. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "paypal, paypal ipn, paypal sandbox, paypal adaptive payments, paypal rest sdk"
} |
How to return the substring of a string between two strings in Ruby?
How would I return the string between two string markers of a string in Ruby?
For example I have:
* `input_string`
* `str1_markerstring`
* `str2_markerstring`
Want to do something like:
input_string.string_between_markers(str1_markerstring, str2_markerString)
Example text:
s
# => "Charges for the period 2012-01-28 00:00:00 to 2012-02-27 23:59:59:<br>\nAny Network Cap remaining: $366.550<br>International Cap remaining: $0.000"
str1_markerstring
# => "Charges for the period"
str2_markerstring
# => "Any Network Cap"
s[/#{str1_markerstring}(.*?)#{str2_markerstring}/, 1]
# => nil # IE DIDN'T WORK IN THIS CASE
Using Ruby 1.9.3. | input_string = "blahblahblahSTARTfoofoofooENDwowowowowo"
str1_markerstring = "START"
str2_markerstring = "END"
input_string[/#{str1_markerstring}(.*?)#{str2_markerstring}/m, 1]
#=> "foofoofoo"
or to put it in a method:
class String
def string_between_markers marker1, marker2
self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1]
end
end
"blahblahblahSTARTfoofoofooENDwowowowowo".string_between_markers("START", "END")
#=> "foofoofoo" | stackexchange-stackoverflow | {
"answer_score": 98,
"question_score": 49,
"tags": "ruby, regex"
} |
Template strings in ES2015
What is the meaning of "passed array is frozen" in the context of template strings in ES2015?
Source: < | It doesn't mean any special in the context of template strings. It just means that the array is frozen. From the docs:
> An object is frozen if and only if it is not extensible, all its properties are non-configurable, and all its data properties (that is, properties which are not accessor properties with getter or setter components) are non-writable.
So the array of strings that is getting passed into the tag function is essentially **immutable**. This is supposed to allow engines to store it as a constant and repeatedly pass the same array object every time the tagged template literal is evaluated. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "javascript, ecmascript 6, template strings"
} |
How to convert a clojure keyword into a string?
In my application I need to convert clojure keyword eg. :var_name into a string "var_name". Any ideas how that could be done? | user=> (doc name)
-------------------------
clojure.core/name
([x])
Returns the name String of a string, symbol or keyword.
nil
user=> (name :var_name)
"var_name" | stackexchange-stackoverflow | {
"answer_score": 182,
"question_score": 112,
"tags": "clojure"
} |
$P(A \cup B) = 1 - P (A' \cap B')$
$P(A \cup B) = 1 - P (A' \cap B')$
Conceptually I'm fine. I drew a Venn Diagram and I understand the problem. I think I turned the right side into the left side correctly, but if someone could verify I'd appreciate it. I expanded $P (A' \cap B')$ into $P(A')*P(B')$.
$P(A')= 1-P(A)$. Then, use the same logic for $P(B')$. Then, $$1 - P (A' \cap B')$$ $$=1-[(1-P(A))*(1-P(B))]$$ $$=1-[1-P(B)-P(A)+P(A)P(B)]$$ $$=P(A)+P(B)-P(A)P(B)$$ $$=P(A \cup B)$$
How do we feel about this? | **Note:** $$ P(A \cap B) \color{red}{\neq} P(A) \cdot P(B) $$ for example take the uniform density on $[0,1]$ and $A = [0,2/3], B = [0,1/3]$. We have $$ P(A \cap B) = P([0,1/3]) = 1 / 3, P(A) \cdot P(B) = (2 / 3) \cdot (1 / 3) = 2 / 9 $$ so your proof unfortunately is not valid.
**Hint:** $$ P(C) = 1 - P(C') \text{ and by De Morgan's laws } (A \cup B)' = A' \cap B' $$ | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "probability"
} |
how to run NSThread when app goes to background
I need to control the volume of device when app is in background so for this i use following code
- (void)applicationDidEnterBackground:(UIApplication *)application
{
back=1;
NSLog(@"Enter in the back");
float v=1.0f;
[NSThread detachNewThreadSelector:@selector(changeCounter) toTarget:self withObject:_viewController];
}
changeCounter has infinite loop.But when i run the code and send the app to back.loop runs only for one time? | You need to request a background task from the UIApplication using `beginBackgroundTaskWithExpirationHandler`. There are examples in the Application Programming Guide (See the Completing a Finite-Length Task in the Background section). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "iphone, nsthread"
} |
PHP how to simulate SIGPIPE?
My environment: Ubuntu 18.04 LTS PHP 7.2.2 ZTS no-debug
I have a big application where sometimes `Broken pipe` error is happening. I want to handle it but for this I need to simulate this error for development. How can I do that ?
I have tried:
posix_kill(posix_getpid(), SIGPIPE);
while(1) {
sleep(5);
}
Also:
sudo kill -13 pid
But script keep working.
Expected result:
Thread 1 "php" received signal SIGPIPE, Broken pipe.
and script should get stopped. | **signal_example.php:**
pcntl_async_signals(true);
pcntl_signal(SIGPIPE, function (int $signo) {
echo 'Process ' . posix_getpid() . ' "php" received signal SIGPIPE, Broken pipe.';
exit;
});
while (1) {
sleep(1);
}
kill -13 990:
artemev@Vitaly-PC:~/project/example$ php signal_example.php
Process 990 "php" received signal SIGPIPE, Broken pipe. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, sigpipe"
} |
How to generate a number in C# which re start from 1 on every new date
How to generate a number in C# which start from 1 on every new date.For Example if number ended on 90 on 15 june it should be start from 1 again on 16 june. Working on a clinic Software and their requirement is that their Patient token number should start from 1 on every new day.Please Help me. It gets a number for me but i want to start it from 1 on new day
SqlCommand cm = new SqlCommand(
"select TOP 1 token_m from token ORDER BY token_m DESC;",
con);
con.Open();
SqlDataReader dr1 = cm.ExecuteReader();
while (dr1.Read())
{
token_m = (Int32.Parse(dr1[0].ToString().Trim()) + 1);
} | I do not really understand what you want, but if you need to replace values from DB with dynamically generated ids, you should store the last number and the last assignment date, then on each assignment update date and check if it is new day.
private static DateTime _lastAssigned = DateTime.Min;
private static int _lastId = 1;
...
while (dr1.Read())
{
DateTime now = DateTime.Now;
if (now.Day > _lastAssigned.Day ||
now.Month > _lastAssigned.Month ||
now.Year > _lastAssigned.Year)
_lastId = 1;
txt_id.Text = _lastId.ToString();
_lastId++;
_lastAssignment = now;
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "c#"
} |
JSのプロパティ入出力時にアクセスメソッドを動かしたい
JavaScript
ES5
C#
get/set
JavaScript
getRight()
right
getRigth
ES5
ES6 or TypeScript
var common = {};
(function () {
var _ = common;
//Rect(top,left,height,width)
_.Rect = function (top, left, height, width) {
if (!(this instanceof common.Rect)) {
return new common.Rect(top, left, height, width);
}
this.top = top;
this.left = left;
this.height = height;
this.width = width;
};
_.Rect.prototype.getRight = function() {
return this.left + this.width;
};
_.Rect.prototype.getBottom = function() {
return this.top + this.height;
};
}());
var rect1 = common.Rect(1,1,1,1);
| Object.defineProperty get
var common = {};
(function () {
var _ = common;
//Rect(top,left,height,width)
_.Rect = function (top, left, height, width) {
if (!(this instanceof common.Rect)) {
return new common.Rect(top, left, height, width);
}
this.top = top;
this.left = left;
this.height = height;
this.width = width;
Object.defineProperty(this, "right", { get: function () { return this.left + this.width; } });
Object.defineProperty(this, "bottom", { get: this.getBottom });
};
_.Rect.prototype.getRight = function() {
return this.left + this.width;
};
_.Rect.prototype.getBottom = function() {
return this.top + this.height;
};
}());
var rect1 = common.Rect(1,2,3,4);
console.log(rect1.right);
console.log(rect1.bottom); | stackexchange-ja_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript"
} |
why my navigation item / bar disappear from my storyboard in Xcode 9
I have some issue in the storyboard in my navigation bar/item. the navigation bar/item appear if I run the app. but in my storyboard it seems disappear, as we can see in the document outline, the navigation bar/item is actually available, but I don't know why it doesn't show up in my storyboard. it makes me worried.
I have tried to quit the Xcode and simulator but it still disappear in my storyboard. here is the screenshot
 \to \mathbb{R} $ , $f_n(x)=\dfrac{x^n}{n+x^n}$
I actually computed that: \begin{align} f_{n} \to f(x) \end{align} \begin{align} f(x)= \begin{cases} 0 & 0\leq x \leq 1 \\\ 1 & x>1 \end{cases} \end{align} , so I wanna take $Sup$ from $|f_n(x) - f(x)|$ ,so if the value of that tends to $0$ then I can conclude that $f_{n}$ tends to $f$ uniformly convergence, but I guess the $ Sup$ does not tend to $0$. I have problem computing the above $Sup$.
\begin{align*} |f_n(x) - f(x) | = \begin{cases} \dfrac{x^n}{n+x^n} & 0 \leq x \leq 1 \\\ \dfrac{n}{n+x^n} & x>1 \end{cases} \end{align*} I wonder how to take $Sup$ from $|f_n(x)-f(x) |$ ? | $f_n(n^{1/n})-f(n^{1/n})=\frac 1 2 -1$ so the supremum does not tend to $0$.
Note that $|f_n(x)-f(x)|$ decreasing in $[1,\infty)$ and increasing in $[0,1]$. So finding the supremum is quite easy. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "analysis"
} |
delphi xe5 StrToFloat failure changing ThousandSeparator to ','
What am I doing wrong here? I simply want to convert a formatted string to a double and using the TFormatSettings passed in as a parameter to StrToFloat. I get the following exception:
'3,332.1' is not a valid floating point value.
The thousand separator and decimal separator are the expected values (',' and '.') in TFormatSettings.
procedure TForm2.Button1Click(Sender: TObject);
var
FS: TFormatSettings;
S: String;
V: double;
begin
FS:= TFormatSettings.Create;
codesite.Send('ThousandSeparator', FS.ThousandSeparator); //correct ','
codesite.Send('DecimalSeparator', FS.DecimalSeparator); //correct '.'
S := '3,332.1';
try
V := StrToFloat(S, FS);
except on E: Exception do
ShowMessage(e.Message);
end;
CodeSite.Send('S', S);
CodeSite.Send('V', V);
end; | What you are doing here is correct, but you stumbled in what it seems a bug(if not a bug at least a not very consistent behaviour) of the TextToFloat(it seems that it ignores ThousandSeparator) internal function of Delphi SysUtils unit(take a look at the Q92265 to follow resolution ) ...
As a workaround you can try removing the group separator, in this way :
StringReplace('3,332.1', ',', '', [rfReplaceAll]) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 7,
"tags": "delphi, delphi xe5"
} |
Objective C - NSDateFormatter returns nil?
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.sss"];
self.date = [dateFormatter dateFromString:dateString];
the code works fine with this string
* "2007-06-10 06:31:54.935"
but doesn't work with this one (it returns nil if the time is set to 0):
* "2007-06-10 00:00:00.000" | Try using `@"yyyy-MM-dd HH:mm:ss.SSS"` (uppercase S for the fractional seconds).
See Date Format Patterns guide. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "objective c, nsdate, nsdateformatter"
} |
How to combine multiple lists in Python
listA = ["A", "B", "C"]
listB = ["1", "2", "3"]
listC = ["!", "@", "#"]
If I have these lists, how would I get a new list of
[("A", "1", "!"), ("B", "2", "@"), ("!", "@", "#")] | Use `zip`:
list(zip(listA,listB,listC))
[('A', '1', '!'), ('B', '2', '@'), ('C', '3', '#')] | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "python, python 3.x, list"
} |
Extract substring from this string inside Excel cell
I have this Excel cell `A2` with the contents `USD.EUR[IDEALPRO,CASH,EUR]`.
I would like to extract the substring `EUR` from the last part of the string using an Excel formula. The nearest formula I came out with is `=RIGHT(A2,4)`. However, it returns `EUR]`.
What formula can be used to extract the substring?
I am using MS Excel 2013. | If the string that you are searching is only `3 bytes` in length, then your simple formula works. But what if it changes? Try the below,
`=MID(SUBSTITUTE(F2,",","#",LEN(F2)-LEN(SUBSTITUTE(F2,",",""))),FIND("#",SUBSTITUTE(F2,",","#",LEN(F2)-LEN(SUBSTITUTE(F2,",",""))))+1,FIND("]",SUBSTITUTE(F2,",","#",LEN(F2)-LEN(SUBSTITUTE(F2,",",""))))-FIND("#",SUBSTITUTE(F2,",","#",LEN(F2)-LEN(SUBSTITUTE(F2,",",""))))-1)`
Where `F2` is your string. This formula unstrings the string between the last delimiter `","` and `"]"`. This is too complicated but it might help you. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "excel, excel formula, substring, excel 2013"
} |
Writing Django Test for Django Haystack which uses Solr as backend
I am using Django 1.4, Django-Haystack 2.0 and Solr (pysolr 2.0.15). I have to write test cases in Django for Haystack. I have written indexes for the models and defined some functions like `index_queryset`. So, now I am in a fix on how to write test cases for the same. | Well - if you are not using some special pysolr features (like proximity search) I suggest to use Simple backend in testing. You probably do not want to test how Haystack with pysolr works, because it is already tested and it is search, which is hard to predict all results and just will take long if you want to remove and build indexes often in tests.
You probably just want to test what you have written, e.g. those `index_queryset` function or maybe some `prepare_*` functions you added - test them completely separately (what is given and what they returns), just as unit tests should do - without any pysolr related stuff. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "django, solr, django haystack, pysolr"
} |
Show that some of the root of the polynomial is not real.
\begin{equation*} p(x)=a_nx^n+a_{n-1}x^{n-1}+\dots+a_3x^3+x^2+x+1. \end{equation*}
All the coefficients are real. Show that some of the roots are not real.
I don't have any idea how to do this, I only have an intuition that something is related to the coefficients of $x^2$ and $x$ and the constant 1.
Kindly help me!! | Adapting the argument from this answer by Noam Elkies.
If $p(x)$ has only real zeros, then so does its reciprocal $$ x^np(\frac1x)=x^n+x^{n-1}+x^{n-2}+\cdots+a_{n-1}x+a_n. $$ But by Vieta relations the sum of the roots of this polynomial is $-1$ and the sum of their pairwise products is $1$. Therefore the sum of the squares of the roots is $$(-1)^2-2\cdot1=-1<0\. $$ Consequently some of the roots must be non-real. | stackexchange-math | {
"answer_score": 9,
"question_score": 4,
"tags": "polynomials, roots"
} |
Getting Model property of non-associated View object
When I am in the View of a specific object, I can acces all the instances by this loop in the View:
@foreach (Reservation r in Model) { }
But How to implement the same foreach cycle with Ski Class, which is not associated with this View? | Add whatever you need access to to your model. It is common to create specific ViewModel classes that are specific to one or a few views and provide access to whatever they need. In your case it would have Reservations as well as Ski data.
Example:
public class ReservationViewModel
{
public List<Reservation> Reservations { get; set; }
public List<Ski> Skis { get; set; }
}
Now in the View you can foreach over Model.Reservations, as well as over Model.Skis. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "c#, asp.net, asp.net mvc"
} |
How to develop UIMockup in iOS sdk?
Any one have idea about UIMockup in iOS sdk? I visited Appcooker site and also This fluidui site could any one tell me how it actually works and how can I submit that app to app store?
Any help would be appreciated | You'd want to find a Mockup tool that supports exporting projects as Xcode projects. It doesn't appear that either of those products do that.
This one claims to support it, but I have no idea if it works: <
Honestly I wouldn't recommend putting too much time into this because I don't think the results would be good. If you want to turn a mockup into an app you should hire a developer. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "iphone, ios, ipad, mockup tool"
} |
How can I get the tag from a ID?
`test= (fs.readFileSync('test.txt', 'utf-8'))` Here I store the ID's and then "test" is a string and I'm trying to get the tag from the stored ID. | Assuming you have no issues getting the ID, and the "ID" is an actual user ID, you can do `Client.users.cache.get(id).tag` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, discord, discord.js"
} |
$P(Y\leq X)$ where $Y = X^2$?
Given that $X$ is continuous random variables and we know the probability density function and probability distribution of $X$.
We have a new random variable $Y = X^2$. We can easily found it's probability density function and distribution.
How I can use the above to calculate the probability $P(Y\leq X$)? | $\mathbb{P}(Y\leq X)=\mathbb{P}(X^2\leq X)=\mathbb{P}(0\leq X\leq 1)$ | stackexchange-math | {
"answer_score": 5,
"question_score": 0,
"tags": "probability"
} |
javascript closure advantages?
Whats the main purpose of **Closures** in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to understand closure and really want to know what are the main advantages of using it. | I think the best phrase to sum up the purpose of closures would be:
## Data Encapsulation
With a function closure you can store data in a separate scope, and share it only where necessary.
If you wanted to emulate `private static variables`, you could define a class inside a function, and define the `private static vars` within the closure:
(function () {
var foo;
foo = 0;
function MyClass() {
foo += 1;
}
MyClass.prototype = {
howMany: function () {
return foo;
}
};
window.MyClass = MyClass;
}()); | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 23,
"tags": "javascript, closures"
} |
HTML text and image line folding
I have the html page where textual article title is followed by an image. When the title is big enough some part of it goes to newline together with the image. But sometimes the textual title fits the page, but only without image, so the image goes to newline. How to glue the image with the last word of the title, so that image will go to the new line only with the part of text?
The current HTML markup:
<div class="title">
<a href="link to the article">Article title goes here...</a><img src="/pics/.gif"/> | Adding a non-breaking space between the img and the anchor tag should keep the browser from splitting them on separate lines. That will glue the image to the whole link, however.
To get the image glued to only the last work of the link, you can either take the last word out of the link, or put the image in, and then the same non-breaking space between the last word and the image will give you the layout you want. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "html"
} |
UI designer in eclipse CDT
I want to design a GUI for c++, i am using eclipse JUNO CDT (x64) , do you know another plugin than QT plugin ? or ares there a win64 QT version ? | I advise you to install QtSDK which includes QtCreator, designer, assistant, linguist ..etc. You can create your new Qt project with QtCreator which creates the .pro file and form files. You can design your .ui(form) files with designer and then open your project as a Makefile project in Eclipse CDT which is a better IDE than QtCreator.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "eclipse, qt, user interface, eclipse cdt"
} |
insert data in to database which is in edittext
i am new to android help me pls,i have 4 editbox and i button i want to store the contents of the all the 4 edittext when i click the save button.when click the detail button already stored edittext value in the database is to view in another activity in a list view..pls help | need to see some code to respond effectively. But just check the notepad example, it's quite straight forward and shows the main uses of a database on Android....
This is basically the code to store a new element in the DB:
public long createAppEntry(String name) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DEVICE_NAME, name);
return mDb.insert(DATABASE_TABLE_DEVICES, null, initialValues);
}
And here is how I get the values:
> private void saveState() { String s1 = contentEditText.getText().toString(); myDBAdapter.createAppEntry(1s1); }
but again, just check the Notepad app if you need more detail... | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, sqlite, button, insert, android edittext"
} |
Shut down syspro 7 processes
We have nightly backups run on our Windows Server 2012 R2 sys pro 7 server. Having the syspro processes running during backups can cause file lock issues and other errors. Does anyone know a way we could automatically shut down our syspro 7 processes prior to doing our backups and then start them up again after the backup completes? By the way we are using a C-ISAM database not SQL Server.
Thanks in advance | You could create a batch file stopping all the relevant services and use Task Scheduler to run this before your backup. Then create another batch file to start all the services up and schedule this for when the backup is complete. For your task ensure that you set it to run with elevated privileges or the services will not be stopped/started.
For example, assuming you are using the SYSPRO Communications Service, you would stop this using the following command in your batch file:`net stop SYSPROCOMMS`
Do this for each of your services you want to stop.
After you have stopped your services it would probably be worthwhile killing any runaway processes that might exist (e.g. **SYSPRO.exe** or **SYSPROSrs.exe** ). You could make use of Sysinternal's PSKILL to do this for you in your batch file.
You can check out the SYSPRO Forums for help relating to syspro. | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 0,
"tags": "backup, windows server 2012 r2, automation, batch"
} |
Reset form values
I'm wondering if there is a simple way to reset the values of a form that had already been used, using javascript. I had tried to make a function that would set the values to an "empty string" (not sure if that's what it's called in this case, but '') and then to their default values, but this didn't work. And I had tried form reset, but that seemed to delete my form. I would be okay with restoring default values except I couldn't figure out how to set the radio button to NULL or nothing.
Thanks for any suggestions. | You can use `<input type="reset" />` _[[MDN]]( , which will render a button that resets the form back to the state it was in when it was loaded.
Here's an example: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, forms"
} |
Android - Restlet
I'm trying to use this tutorial on Restlet for Android, and can't get the sample application, linked to at the bottom of my link's page to run.
There are major issues in a file called `IContactService.java`, located at `/src/org.restlet.example.android.service`, but the file has the following header, so I'm not sure how to resolve them:
/*
* This file is auto-generated. DO NOT MODIFY.
* Original file: /mnt/sda5/data/workspace/android/androidRestlet/src/org/restlet/example/android/service/IContactService.aidl
*/
Does anyone have any experience getting Restlet to work with Android? Or, are there any better frameworks / tutorials out there? | Try this REST client instead, I've used it a lot - by far the best one for Android development.
< | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "java, android, rest, frameworks"
} |
Question about univalent branch
Problem: Let the holomorphic function $f$ have a zero of order $m$ at the point $z_0$. Prove that there is an open disk centered at $z_0$ in which there is a univalent branch of $f^{1/m}$.
I suppose I can find a disk by local mapping theorem. But I don't know how to show that $f^{1/m}(z_0)=0$ is of order 1, because this implies that is injective (univalent branch).
Thanks in advance. | By Taylor's theorem $$f(z)=a_m(z-z_0)^m +a_{m+1}(z-z_0)^{m+1}+\cdots$$ in a neighbourhood of $z_0$ where $a_m\ne0$. Then $$f(z)=c^m (z-a_0)^mg(z)$$ for some $c$ where $g$ is holomorphic and $g(z_0)=1$. Then $g$ has a holomorphic $m$-th root near $z_0$. (Compose $g$ with a holomorphic branch of $w\mapsto w^{1/m}$ near $w=1$). | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "complex analysis, holomorphic functions"
} |
Should I treat every aphid infestation?
Should I treat every infestation as I catch them or is some level of aphids "tolerable" and the presence of aphids in the garden unavoidable?
In other words should I only treat the worst cases?
I'm not sure how bad it is for the plants. | Giles. Not really...there is no black and white but better a light gray. Sooner one treats aphids the better. Hard spray of water, NEEM sprayed at night as soon as you see crowds of aphids on your roses or vegetables. But if you are on your way to a well-deserved vacation and as you go out the door and catch sight of aphids, keep going to your vacation. When you get back you can take care of it or you just might have enough beneficals around that had a feast! Aphids are so normal, gotta stay on top of them but it is not life and death. | stackexchange-gardening | {
"answer_score": 5,
"question_score": 3,
"tags": "pest control, pests, pesticide, aphids"
} |
How to change the text of navigationItem.leftBarButtonItem for iPhone
How do I change the text value `navigationItem.leftBarButtonItem`?
In view A I did `self.title=@"hi"`
So when I go to B my back button has the text **@"hi"**. now I want to change it to **back**
How do I do that? | UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"blah blah blah" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem = backButton;
[backButton release];
you can use this in view A and enter any text you want | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone"
} |
Updating Magento SOAP V1 api additional attributes
Morning all! I'm attempting to target a specific product with Magento's SOAP V1 API, and change the value of one of its additional attributes. In the Magento Docs, it calls for an associative array named 'single_data'.
I've tried following a few other overflow questions, but I cannot seem to piece together an array to update one of its attributes. Has someone successfully done this that could help? Any support is much appreciated! | I've been struggling with this for a few days, but I just solved it, just in case anyone ever finds this. Within your catalog_product.update array, add the line:
`'additional_attributes' => array( 'single_data' => array('suppliersku' => $suppliersku))`
If you need to update multiple attributes, change out 'single_data' to 'multi_data' and fiddle around with the attributes inside of that | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "php, api, magento, soap, attributes"
} |
How to get the full path of the current executable file in VB?
I have created one windows application using VB. Whenever I executing the `exe`, I want to get the current directory of the `exe` file programatically.
For example,
Now, I am executing the `exe` file in `d:\myApp\test.exe`. Whenever I double click the `exe` file I want to get the path of the `exe` file like `d:\myApp\test.exe`.
Also, suppose, my `exe` is in CD or any memory stick, will it also get the path of the exe file?
I don't know is this possible or not?
Any suggestion? | Try `App.Path`. It will give you the current `exe` path. To get `exe` name you can use `App.EXEName`. Note that `App.Path` will contain the trailing `\` when in the root of a drive so any extra `\` will need to be added conditionally.
So to get full path with `exe` name try this:
App.Path & IIf(Right$(App.Path, 1) <> "\", "\", "") & App.EXEName & ".exe"
Also, It will give you CD or any memory stick's path too. | stackexchange-stackoverflow | {
"answer_score": 39,
"question_score": 16,
"tags": "vb6, path, executable path"
} |
Start time of Jewish holidays: Exactly at sunset or some other time near it?
It's my understanding that Judaism defines the start of a day as sunset. However, on one of my calendars, several Jewish holidays are indicated as starting at `sundown (approximate)`.
Does the Jewish day start exactly at sunset, or is it actually a few minutes before or after sunset? How does this apply to holidays? | The day begins at sunset, based on Bereishit 1:5 "and there was evening and morning, one day". However, doing creative work ( _melacha_ ) on a major holiday or on Shabbat is a violation of biblical law, so to be safe we add some time to both ends. Most communities (not all!) begin Shabbat or a holiday 18 minutes before sunset and end it about an hour after sunset the next day (full dark).
Your calendar is presumably trying to reflect this "fudge factor" -- the day begins at sunset, but the _observance_ of the day begins a bit before, so "approximate". This is good enough for most users of that calendar and considerably better than some calendars (which simply note the day on the next secular day). Those who are observing the day know to adjust.
For some sources about the 18-minute calculation, see this answer. | stackexchange-judaism | {
"answer_score": 3,
"question_score": 3,
"tags": "time, zemanim, chagim holidays"
} |
Google sketchup , how to display the model in iPhone/iPad?
Is there any objective-c library or workaround solution to display the skp file ? Thanks | No, you are going to need to work something with OpenES, try the unity engine. You'll be able to export in some format from sketch up to Unity. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ios, sketchup"
} |
Drupal JSON API on iPhone
I am working with an app that is querying a JSON API on a server running Drupal. I used this tutorial and have changed the code a bit to work with my program, but every request just sends me to the not authorized page that the server generates. Any ideas why? | Why not use the drupal ios sdk? < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "iphone, json, drupal"
} |
Differences in later versions of bash
In an article I was reading recently, published originally in 1996, the following code is quoted for a way in which to evaluate whether the directory $1 is stored in is writable:
if [ ! -w `dirname $1` ]
then
echo $0: I will not be able to delete $1 for you.
exit 1
fi
'Learning the Bash Shell' _O'Reilly_ \- mentions that the use of grave accents (`) is now archaic. If this is the case, what would now be the standard way of performing this task?
Many thanks,
hcaw | To do so, now we use:
if [ ! -w $(dirname $1) ]
then
echo $0: I will not be able to delete $1 for you.
exit 1
fi
that is,
` `
syntax has been replaced by
$( ) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "bash, shell, scripting"
} |
Passing user-defined Type Array as input parameter to a function
I have created a user-defined type in PostgreSQL(version 11.5).
`CREATE TYPE key_type AS (key_no character varying(50), key_nm character varying(128));`
I created below function with an input parameter of type `key_type[]` and output as `TEXT`.
`create or replace function fn_net(inp IN key_type[]) returns TEXT as........`
But I am unable to call the function, I have tried as below.
do
$$
declare
v_key key_type[];
v_res TEXT;
begin
v_key.key_no := '709R';
v_key.key_nm := 'Risk';
select * from fn_det(v_key) into v_res;
raise notice '%', v_res;
end;
$$
language plpgsql;
I get malformed array error or function does not exist error. Please help me as to how to pass the inputs correctly.
NOTE: I am able to run successfully if I specify input type as `key_type` instead of `key_type[]` but I need array type for the requirement. | Your variable assignment is wrong, you need to provide the array index to which you want to assign an element.
When you are calling a function returning a single value, you don't need a SELECT in PL/pgSQL, just assign the result:
do
$$
declare
v_key key_type[];
v_res TEXT;
begin
v_key[1] := ('709R', 'Risk'); -- first array element
v_key[2] := ('711X', 'Risk2'); -- second array element
v_res := fn_det(v_key);
raise notice '%', v_res;
end;
$$
language plpgsql; | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "postgresql, postgresql 11"
} |
How to Insert Latest Record and Inactive the other Record in MySQL
I have sample Data
ID Name val Active
1 Mohan 5 1
2 Mohan 10 1
I want to clone the record when I ran the query every time
ID Name val Active
1 Mohan 5 0
2 Mohan 10 0
3 Mohan 5 1
4 Mohan 10 1
Query
Update Table SET Active = 0 WHERE Name = 'Mohan'
INSERT INTO TABLE(ID,Name,val,Active )
SELECT ID,Name,val,1FROM TABLE WHERE Name = 'Mohan'
when I ran again this same query it is inserting 4 records I just want to insert latest Inactive records as Active (i.e. 2 Records ) | Your 2 queries may be replaced with one
INSERT INTO TABLE(ID, Name, val, Active)
SELECT ID, Name, val, 0
FROM TABLE
WHERE Name = 'Mohan'
AND Active = 1
fiddle | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql"
} |
How to determine the authorization in Joomla
After login i use need to set up redirect to custom page. How to catch this authorization in `onAfterRoute` event? | You should go to this path:
JOOMLAROOT/components/com_user/controller.php
in function register_save(), find this code:
if ( $useractivation == 1 ) {
$message = JText::_( 'REG_COMPLETE_ACTIVATE' );
} else {
$message = JText::_( 'REG_COMPLETE' );
}
after line put this code:
$this->setRedirect('/Your Custom Page Address', $message); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "joomla, authorization, joomla2.5"
} |
Upgrading to Vue 3: where to put data and methods?
!Vue 3 upgrade image from guide
I am following an upgrade guide on how to go from Vue to Vue3. It shows how to handle it if the app is structured like:
new Vue({
router,
render: h => h(App)
}).$mount("#app");
The problem is that my my app is structured like this:
new Vue({
el: '#app',
data() {
return {
// initialData
};
},
mounted() {
// mounted
},
methods: {
}
}
Where do I place the data, mounted, methods, etc to have it work with the new structure in Vue 3? | You could import `h` to render the `App` component and use your usual options :
import {createApp,h} from 'vue'
...
createApp({
data() {
return {
// initialData
};
},
mounted() {
// mounted
},
methods: {
},
render: () => h(App)
}) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "vue.js, vuejs3"
} |
Inverse of Line Graph?
**Definition:**
Let $G$ be a graph, the line graph of $G$ denoted of $L(G)$ is defined as follows:
-The vertices of $L(G)$ are the edges of $G$
-Two vertices of $L(G)$ are adjacent iff their corresponding edges in $G$ are incident G.
**Question?**
It is easy to see that if $G$ is $d$-regular graph then $L(G)$ is $(2d-2)$-regular graph. Thus we have $L(L(G))\neq G$. My question is there graph let's say $L^{-1}$, such that $L^{-1}(L(G))=G$?
Any idea will be useful! | Line graphs are not in bijection with graphs, so strictly speaking there is no inverse operation. However, it is still possible to reconstruct the original graphs (there are linear time algorithms), but the construction is not as direct as the line graph construction. So you could add more information when constructing the line graph, and use $L'(G)$ instead of $L(G)$, which gives a coloured graph where each vertex has two colors (encoding the original vertices of $G$), so that you can get an easy definition for $L'^{-1}$ with $L'^{-1}(L(G)) = G$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "combinatorics, graph theory"
} |
What was happening to Joshu Kasei at Sybil's core?
Spoilers for the latest episodes of Psycho-Pass.
* * *
During the riots, Kagari and Choe enter Sybil's core. There, Joshu Kasei forces a dominator into lethal mode to kill Choe. Then, she kind of melts down before killing Kagari as well.
> !enter image description here
Why was she melting down (her chin kind of falls down)? At first I'd have guessed it was because she was forcing the dominator, but later we see she can change their behavior with ease. | Choe attacks her with some acid just before that. It obviously didn't work quite as expected.
!enter image description here | stackexchange-anime | {
"answer_score": 5,
"question_score": 2,
"tags": "psycho pass"
} |
Is it acceptable to release object in a method of the object's class
Is it acceptable for a instance method of a class to release itself?
ie to have a method that calls:
[self release]
Assume that my code is not going to access self after calling [self release] | > Is it acceptable for a instance method of a class to release itself?
>
> ie to have a method that calls:
>
> [self release]
>
> Assume that my code is not going to access self after calling [self release]
First, I would want to have a really good reason to release myself. The only time I've done it is in a singleton that I dump to free up large chunks of memory on an iPhone. This is a rare event.
Your code is part of the class object. Hence, it is not really a problem to call [self release]. Of course, you are much safer, from an encapsulation perspective, if you call [self autorelease]. At least then, if someone up the call chain calls your methods, you don't cause an exception.
Andrew | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone, objective c"
} |
How can I make a physics body which you can put another physics body through
I want to make a `SKPhysicsBody` in swift which allows another physics body to go through it without being affected. I cannot remove the physics body because I need the gravity. Any help is appreciated. | "Physics bodies with the same `collisionBitMask` value will "pass-through" each other.".
This should answer your question. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "swift, sprite kit"
} |
Group By in SQL for column
I have a query that orders by DeliveryName
SELECT ID, CreatedAt, Identifier, Name, DeliveryName, RoundedPriceSum
FROM StarOrder
WHERE
SiteID = 1 AND --StarSite.ID 1= SE, 2 = NO
ShippingTypeID = 4 -- StarShippingType.ID 4 = STORE_PICKUP SE, 10 = STORE_PICKUP NO
and CreatedAt between '2015/01/11' and '2016/05/30'
Order BY DeliveryName DESC
I am trying to group so that each Delivery Name has a total number of rows, but having no luck. Any help would be great. | You are selecting all columns including ID (having lowest granularity or detailed data) then how can you get grouped data. Also you are not using group by clause. You need to select grouping column and summary data like sum() or avg() count() etc. to achieve this.
SELECT DeliveryName, count(*)
FROM StarOrder
WHERE SiteID = 1
AND ShippingTypeID = 4
and CreatedAt between '2015/01/11' and '2016/05/30'
group by DeliveryName
Order BY DeliveryName DESC
For example if you want to group students by class you will select **class** and **number of student**. But if you selected **class** and **name of student** then you will get row for each student. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "sql"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.