INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Using Interface builder Xcode 4
When using the interface builder, if I select a button that is in my layout, the interface builder immediately zooms into that button.
Is there any way I can stop that behaviour.
i.e. I want the interface builder to just select the button and not zoom in.
XCode 4.2 snow Leopard
Post-Script. I think the answer is "you can't". One other suggestion refers to making zoom shortcuts but that does seem to help either.
|
In response to my own question. As of 24 hours later I think the answer is "you can't".
One other suggestion found when researching in StackOverFlow refers to making zoom shortcuts but that does seem to help either.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "interface builder, xcode4.2"
}
|
Detect which View was tapped in the onSingleTapConfirmed method
I have many views (FrameLayouts) on my screen - each has a SimpleOnGestureListener set as the onTouchListener.
I'm correctly getting the onSingleTapConfirmed method being fired when I tap one of these views, but I can't work out how to determine which view was tapped?
Is there a simple way to do this from the MotionEvent?
|
> I have many views (FrameLayouts) on my screen - each has a SimpleOnGestureListener set as the onTouchListener.
Save a reference to the View in the OnTouchListener, then when a gesture callback fires you'll already know which View was touched:
public boolean onTouch(View v, MotionEvent event) {
// Remember which View was touched
mCurrent = v;
// Pass event to gesture listener, etc
}
Now use `mCurrent` in `onSingleTapConfirmed()` and any other method.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "android, view, gesture"
}
|
Would Aspose.Word handle Table of Contents (TOC)?
We're using aspose.word to create a report from a word template direct to PDF format. Now we're stuck at handling the TOC for the document. We need the TOC to be dynamic and make correct changes according to where the section is on the document.
Would aspose handle putting the correct page number to the correct category? And can anyone give a short example? The example on the aspose site wasn't helpful in this case.
We're using visual studio to make this site and it says on the aspose documentation that the setting for a TOC is set first on a regular word document then copy the field codes. So I'm approaching it this way, setting the TOC on the template itself then copying the field code to the C# code. Or am I over thinking it and all I need to do is make sure that the TOC is correct on the template itself.
|
I worked with Aspose for a bit, and as I recall, they don't really do any repagination, which is what would be necessary to properly regenerate a TOC with proper page numbers.
You may need to put an call into them. As I recall, their support was pretty easy to get in touch with. I didn't end up using their product because of some of the limitations, but for general use, it seemed pretty decent.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c#, visual studio 2008, ms word, aspose"
}
|
How to make index in "for" loop jump forward by N
I want for loop to change its pass behavior
For example, make it jump every 3rd index to another 2 positions?
for i in range(n):
if i % 3 == 0:
print('found i div by 3, jump 2 positions forward')
i = i + 2
This does not work.
It goes through every `i` in range from 0 to `n`.
|
You can use a while loop,
i = 0
while i < n:
if i % 3 == 0:
print('found i div by 3, jump 2 positions forward')
i = i + 2
continue
i = i + 1
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "python, for loop, indexing"
}
|
WSDL2OBJC for Android?
I have been using Wsdl2Objc to generate proxy's for my web services to use during IPhone dev....it works GREAT!
I now need a version similar to it, that will generate Java code, the same way.
Any ideas?
Thanks
|
There exists wsdltoksoap which can be used to interface with the ksoap2 android library.
I have been having problems with the application, however. It is getting a null pointer exception on my particular WSDL, but it has worked for others
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, iphone, wsdl2objc"
}
|
ELMAH - ErrorSignal.Raise no stack info
I am catching an exception and logging it with ELMAH.
If I do not catch the exception and let the app YSOD, ELMAH logs the full stack trace. However when I catch and use `ErrorSignal.Raise(ex)`, I do not get the stack trace.
I also tried to no avail:
ErrorSignal.FromCurrentContext().Raise(new System.ApplicationException(exception.ToString(), exception));
Whassup?
|
This'll do it:
ErrorSignal.FromCurrentContext().Raise(
new System.ApplicationException(
exception.Message + exception.StackTrace, exception));
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "elmah"
}
|
Is it possible to "split bars" in barplot with R?
I have a barplot beside = T. What I need is to split (or draw an horizontal line) at each height "marks" of each bars.
Sample matrix to plot :
> head(top.fem)
FD1 FE2 FF1
J01 2 2 10
J02 4 0 0
J03 6 2 5
J04 1 6 3
J05 10 10 2
J06 9 6 5
I simply :
barplot(top.fem,beside = T)
So, for FD1, bar 1 has a height of 2, bar 2 height of 1 and bar 3 height of 6 ect... How to split bar 1 in two, bar two in 4 and bar 3 in 6 ? The results would "look like" a stacked bar plot but it is not. Am I being clear ?
Thanx for any help !
|
You can add horizontal lines on the whole picture: if they are white, and if the background is white, they will remain unnoticed.
barplot(VADeaths, beside=TRUE, las=1)
abline(h=0:100, col="white")
barplot(
VADeaths, beside=TRUE, las=1,
add=TRUE, col=FALSE
)
!barplot
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "r"
}
|
Finding the number of items which are associated to a specified set of related items
I have a table, `Transactions`, containing this data:
+------+---------+
| id | item |
+------+---------+
| 1 | A |
| 1 | B |
| 2 | A |
| 2 | D |
| 3 | C |
| 3 | D |
| 4 | E |
| 4 | C |
| 5 | A |
| 5 | B |
| 5 | C |
+------+---------+
How would I find the number of transactions that contain a specified set of items?
For example, the number of transactions that contain items A and B is two, because only transactions 1 and 5 contain both of those items.
|
Im not sure what will be your input, but to solve your question this will do
**Sql Fiddle Demo**
This will count transactions with both items `A` and `B`
SELECT count(*)
FROM (
SELECT id, count(*)
FROM Table1
GROUP BY `id`
HAVING COUNT( CASE WHEN `item` = 'A' THEN 1 END) > 0
AND COUNT( CASE WHEN `item` = 'B' THEN 1 END) > 0
) T
**OUTPUT**
| count(*) |
|----------|
| 2 |
**NOTE**
The `count(*)` in the subquery is optional, was just add it for debug to have a visual feedaback of that subquery.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "mysql"
}
|
I'm setting a href mailto from jQuery, but I don't know how to set the target _blank
I have a hyperlink in my webpage :
<a id="contact" href="#">contact</a>
And then in jQuery I have :
$("#contact").click(function() {
document.location.href = "mailto:[email protected]";
});
When user clicks the link, it opens in the same window, how can I open mail in the other window ? I tried adding `target="_blank"` to the `<a..` but then the contact form opened in the same window and my webpage opened in another window... How can I fix it ?
|
Use `window.open` instead of `document.location.href`
$("#contact").click(function() {
win = window.open('mailto:[email protected]', '_blank');
if (win) {
//Browser has allowed it to be opened
win.focus();
} else {
//Browser has blocked it
alert('Please allow popups for this website');
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "javascript, jquery, html"
}
|
How to revert Perforce to previous stable state?
I have a project using Perforce. The scenario I am looking at is like below :
Multiple users submit their changes to Perforce repository and I would like to take a snapshot before syncing. I want to be able to revert if new release has some problems.
Basically I want to create a snapshot of current file which I can view with 'p4 have' and then revert to 'p4 have' files after syncing to head revision! How can I do that !
I tried to use 'p4 tag -l rel1 //depot/', but this command creates a label for head revision. I am looking for a way to do some command like this 'p4 label have' ! Is it possible ?
|
You need to specify that you want the label to include just the files currently in your workspace:
`p4 tag -l rel1 //depot/...#have`
Or better yet use this shortcut:
`p4 label myws` (define the label) `p4 labelsync` (labels what you currently have in your workspace)
Then you can restore with:
`p4 sync @myws`
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "perforce"
}
|
How to get the list of the fields of a Salesforce entity using Partner.wsdl
I have a C# project I'm trying to implement an automatic integration for the forms to map and send data automatically to Salesforce. For example let's say I have a form with some fields in it and I want the value of the fields that their names match the names of the fields in Lead entity be sent to salesforce and create a lead. For this I can manually create a lead using partner wsdl, But in order to be able to implement automatic mapping between Salesforce Lead entity fields and my form fields I need to fetch the name of the fields from Salesforce.
By the time I have the name of the fields of the Lead entity, I will check whether those field names exist in the form and grab the value from form fields and shape a payload and send it to salesforce.
Any idea how is it possible to get the field names of a specific Salesforce entity(Lead, Contact, Task etc) using Partner WSDL?
Thank you in advance,
|
You have to call `describeSObjects` method to get object property.
DescribeSObjectResult[] describeSObjectResults =
binding.describeSObjects(
new string[] { "account", "contact", "lead" });
Object api name will be passed in array as parameter. Please use this url to get sample code. <
Let me know if this solves your query.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, salesforce"
}
|
Specify maven dependencies for packages
Is it possible in maven project to sepecify in the dependecies, which one is applied for which java package ? If it's possible how ?
Example: I have two package:
1) org.test.compute
2) org.test.stock
And dependencies are:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.9.35</version>
</dependency>
<dependency>
<groupId>org.cloudfoundry</groupId>
<artifactId>cloudfoundry-client-lib</artifactId>
<version>1.0.0</version>
</dependency>
my goal is:
aws-java-sdk applied to org.test.compute
and org.cloudfoundry to org.test.stock
|
No, you can't. All packages of a Java application are included in the same runtime classpath, so all of the dependencies that are on the classpath are visible in all of the packages.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, maven"
}
|
Can i run objective c application on windows?
I would like to learn something about i phone development. So, first i want to know that, Can i run basic application on windows? Is there any apps or tool available for the same. I knew, We can run this on Mac/Ubuntu. But, I have installed windows 7 in my laptop.
would be grateful for help.
|
For learning purpose you can install a virtual machine install OSX and try some of the examples (which i'm guessing is not legal). But if you want to create an app to upload it to the store you **will** need a mac machine.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "iphone, objective c, ios, mobile"
}
|
Pray as if he sees you vs. Pray as if he is seeing you
When we want to write or say about something general as in the following, which sentence makes more sense over the other? And what could be the differences?
> When you pray to God, pray in a way as though he **watches/sees** you.
> When you pray to God, pray in a way as though he **is watching/seeing** you.
>
> When you pray to God, pray as if you **see** him.
> When you pray to God, pray as if you **are seeing** him.
|
_See_ is one of the sensory verbs that is generally not used in the continuous form. So in each of the following pairs the first is grammatical and the second is not:
* I see a cat. I am seeing a cat.
* I hear the phone. I am hearing the phone.
* I smelled cheese. I was smelling cheese.
Commonly, such sensory verbs are used with _can_ : _I can see a cat_ , _I could smell cheese_ , etc.
_Watch_ can take with both verb forms, with the continuous form used for actions in progress.
On this basis, your sentences read best as:
* When you pray to God, pray (in a way) as though he can see you.
* When you pray to God, pray in a way as though he is watching you.
* When you pray to God, pray as if you can see him.
* When you pray to God, pray as if you are watching him.
|
stackexchange-english
|
{
"answer_score": 1,
"question_score": 1,
"tags": "grammar, tenses"
}
|
where are meteor logs kept in local dev mode?
I know about console.log, but does meteor keep a separate internal log for various errors?
I don't see any useful response from the `check()` function.
> <
>
> to the client, it will appear only as Meteor.Error(400, "Match Failed"); the failure details will be written to the server logs but not revealed to the client.
which is what i get but no error in the server log, that i can see. perhaps just when the app is deployed to a production env the logging behavior changes? on an osx machine are there any other system level logs? I don't see anything in /var/log/
Thanks!
|
The documentation is incorrect. In v0.8.3, `check` does not log failures anywhere. This is being fixed in the next version of meteor as seen here:
> When a call to match fails in a method or subscription, log the failure on the server. (This matches the behavior described in our docs)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "logging, meteor"
}
|
Как правильно сгенерировать меню в YII?
С `YII` недавно столкнулся. в шаблоне `main.php` нужно сделать список, в который должны выгружаться все данные строк определенной таблицы. Как получить из базы данные и вывести их я в принципе уже знаю, но как правильно сгенерировать такое меню? Таки, мне кажется, есть специальный логичный и правильный вариант.
|
Есть такой виджет в Yii, называется CMenu: <
В контроллере (например Controller) создаёте публичный метод, который будет возвращать массив с наименования пунктов:
public function getMenuItems() {
$dbQuery = Menu::model()->findAll(); //Если используете ActiveRecord
$menuItems = array();
foreach($dbQuery as $item) {
$menuItems[] = array('label'=>$item->name, 'url'=>array(''));
}
return $menuItems;
}
В макете используете полученный массив в качестве параметра в виджете:
$this->widget('zii.widgets.CMenu', array(
'items'=>$this->getMenuItems(),
));
Таким методом можно вытянуть из БД и другие данные, например url'ы.
Как я понял, Вы сделали выборку по такому же принципу. Но детали не уточнили, поэтому я расписал весь процесс.
Похожий вопрос обсуждался тут: <
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "меню, php, yii"
}
|
How to create a route in express and receive a response (`Cannot GET/api/example')?
When I try to reference ` 8000/api/example` I receive the message `Cannot GET/api/example` (Not Found 404) in Postman. My goal is to receive a reply message:
{
data: 'You hit example endpoint'
}
In Postman I set in `headers Content-Type: application/json`
* * *
const express = require('express');
const app = express();
app.get('api/example', (req, res) => {
res.json({
data: 'You hit data endpoint'
});
});
const port = process.env.port || 8000;
app.listen(port, () => {
console.log(`connect on the port ${port}`);
});
|
>
> app.get('api/example', (req, res) => {
>
You are requesting `/api/example` not `api/example`. You need to specify the `/` at the start of the route.
* * *
> In Postman I set in headers `Content-Type: application/json`
You are making a GET request. There is no request body to describe the type of.
Do not confuse the `Content-Type` request header with the `Content-Type` response header or the `Accept` request header.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, node.js, express, postman"
}
|
How to combine __restrict__ with an array pointed to by a __constant__ pointer?
This will be a bit of a funky question I assume and if I need to elaborate, please say so.
The situation is as follows: I have about 2 gigs of GPU memory containing my random numbers and I need to use those in many different functions. To prevent passing around the pointers to this memory, from device function to device function (and this many times over), I put the pointers in the gpu constant memory, which is also saving me registers (for me very important). Now I know that functions can be sped up in some cases if they are explained that memory chunks pointed to by it's arguments are non-overlapping, by using the keyword `__restrict__`.
The question: how can I make sure the compiler knows that the memory chunks in global memory pointed to by the pointers in constant memory are non-overlapping (and maybe also nice to know: not ever changing after the generate randoms kernel call)?
|
I am not aware of a way to provide the compiler with heuristics on otherwise anonymous pointers.
If you can manage it, the simplest way to try and help the compiler do its job is to pass the pointers as `__restrict__` decorated kernel arguments and then force device functions inline. That will bypass the ABI and may allow the compiler to exploit the known non-aliasing condition to optimise memory access patterns. It should also help with the register footprint of your functions a bit. I'm not sure that `__restrict__` will have much effect on `__device__` functions or `__constant__` declarations, but you have noted that the compiler accepts it, so I guess it can't hurt to at least try.
I would look forward to comments from one of NVIDIA's toolchain or optimisation gurus on what might go on under the hood and what other tricks might be useful in this case.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "cuda, restrict qualifier"
}
|
Keycloak provider does not work when using Kotlin
When converting **Keycloak** sample authentication provider (Secret question authenticator) from `Java` to `Kotlin`, the **plugin does not work any more**. When deploying the `Jar` file, `log` raises odd errors such as bad signature. As far as I struggled, **the problem is Kotlin runtime libraries**. Is there a way to fix this?
|
The problem is that Kotlin has dependencies (Kotlin StdLib or AKA Kotlin runtime). Despite many documents and answers, the solution is not making a (So-called) Fat JAR by famous lines below gradle build script. The right way to resolve dependencies is to add them as WildFly (JBoss) modules using CLI or manual method.
module add --name=org.jetbrains.kotlin --dependencies=org.jetbrains --resources=<path-to-jar-file>
module add --name=org.jetrains --rsources=<path-to-jar-file>
After that, we may add then in a special JBoss file jboss-deployment-structure.xml within META-INF directory:
<jboss-deployment-structure>
<deployment>
<dependencies>
<module name="org.jetbrains.kotlin" />
</dependencies>
</deployment>
Now the jar successfully deploys and works!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, kotlin, keycloak"
}
|
Production of electricity from atmosphere
I read the electric field intesity at the surface of earth is 100v/m. Then why can't we keep two metallic sheets at different heights and produce a continuous current by connecting these two sheets via a electric cable?
|
You can, and the current would be about a micro-amp, because the atmosphere has very high resistance. So the useful power you get that way is very small.
_Check this link_.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 2,
"tags": "electric fields, voltage"
}
|
Removing unneeded information in filename using bash script
I need to remove everything before and after a name in bash script, the following are examples
test_3123_123_testone-2.cpp
abc_3123_12312_a.cpp
johnchase_4123123123_123123123_johnc-1.cpp
I would need them simply change into
testone.cpp
a.cpp
johnc.cpp
But having trouble with regex and trying to get this setup properly, any advice would be great!
|
> the text right before .cpp but ignoring any dashes(-2) if they exist behind it.
Do exactly that. Write it from the end.
* "before .cpp" -> so `.cpp` must be last
* "ignoring any dashes" \- so there is a dash(-2)
* "if they exist behind it" \- the dash is optional
* "the text" \- so match the text.
var=test_3123_123_testone-2.cpp
[[ "$var" =~ ([^_-]*)(-[0-9]+)?.cpp$ ]]
echo ${BASH_REMATCH[1]}.cpp
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "bash"
}
|
Does $\sum _{k=2} ^\infty \frac{(-1)^k}{\sqrt{k}+(-1)^k}$ converge conditionally?
Discuss the convergence of the sum:
$$\sum _{k=2} ^\infty \frac{(-1)^k}{\sqrt{k}+(-1)^k}.$$
**My answer so far:** It does not converge absolutely since
$$\left | \frac{(-1)^k}{\sqrt{k}+(-1)^k} \right | \geq \frac {1} {\sqrt{k} + 1},$$
the sum of whose terms diverges. Intuitively, I think it should converge conditionally because $ \sum \frac{(-1)^k}{\sqrt{k}}$ does, and the $(-1)^k$ in the denominator should not make a big difference. However, I am having trouble demonstrating its conditional convergence.
Evidently, the problem is that $\frac{1}{\sqrt{k}+(-1)^k}$ is not monotone. Let's call this sequence $a_n$. If we can show that
$$\sum_{k=2}^\infty |a_k - a_{k-1}| < \infty,$$
then we're done by Dirichlet's test. But this seems to be $O(1/k)$.
Any ideas?
|
**Hint:** \begin{align*} \frac{(-1)^n}{\sqrt{n}+(-1)^n} &= \frac{(-1)^n}{\sqrt{n}}\frac{1}{1+\frac{(-1)^n}{\sqrt{n}}} = \frac{(-1)^n}{\sqrt{n}}\left( 1-\frac{(-1)^n}{\sqrt{n}} + \frac{1}{n} + o\left(\frac{1}{n}\right) \right) \\\ &=\frac{(-1)^n}{\sqrt{n}} -\frac{1}{n} + \left[ \frac{(-1)^n}{n^{3/2}} + o\left(\frac{1}{n^{3/2}}\right) \right] \end{align*} The (series of the) first term converges conditionally, the second diverges, the third converges absolutely. What can you say about the sum of the three?
|
stackexchange-math
|
{
"answer_score": 8,
"question_score": 7,
"tags": "calculus, sequences and series, limits"
}
|
How to disable "Light Bulb" Quick Action "simplification" for Nullable<T>?
For several reasons we prefer `Nullable<Int32>` over `int?`. Wherever possible we prefer Types over keywords - as we do so since C#2 we have a large codebase already using that style.
I recently switched to VS2015 and got the annoying light bulbs all over my code. For `Int32` and other related non-generic types I fixed that by using this answer. For `Nullable<T>` however I cannot find the option to disable nagging.
 but it's the same infrastructure. That removes the suggestion.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 30,
"tags": "visual studio, visual studio 2015, visual studio 2017"
}
|
MySQL Regex Replace Query
I have a field with this value:
TEST:ATEST:TESTA
And I want to replace "TEST" with "NEW", I have tried this query:
UPDATE `table` SET `field` = REPLACE(`field`, 'TEST', 'NEW') WHERE `field` REGEXP 'TEST';
The result was:
NEW:ANEW:NEWA
Q: How could I do the replacement query so the result would be like this:
NEW:ATEST:TESTA
|
It is a bit of a pain, but you can do it this way:
UPDATE `table`
SET field = substr(REPLACE(concat(':', field, ':'), ':TEST:', ':NEW:'),
2, length(REPLACE(concat(':', field, ':'), ':TEST:', ':NEW:')) - 2)
WHERE concat(':', field, ':') LIKE '%:TEST:%';
I prefer `LIKE` to `REGEXP` because there is the hope of being able to use an index. That is not a possibility in this case, but there is the hope.
This is delimiting the values with colons at the beginning and the end, and only replacing fully delimited values. The trick is to then remove the additional colons.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
}
|
Please to compare two variable in php
I want to insert data in mysql table but it should not be inserted before..
I have try comparing variable it always fails.
<?PHP
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sunil_electronics";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT p_id FROM inquirycart WHERE p_id='$pid'";
$result = $conn->query($sql);
// output data of each row
$row = $result->fetch_assoc();
$id = $row['p_id'];
if ($id == $pid) {
header('Location: ' . $url . '&key1=' . $key . '&info=info');
} else {
$sql1 = "INSERT INTO inquirycart (p_id,p_name, p_image)
SELECT p_id, p_name, p_image FROM $key
WHERE p_id = '$pid'";
$result1 = $conn->query($sql1);
header('Location: ' . $url . '&key1=' . $key . '&succ=succ');
}
?>
|
If the `p_id` is not used before, the query won't return any rows. `$result->fetch_assoc()` will return `NULL`, and `$row['p_id']` will fail.
You can just check the number of rows returned.
if ($result->num_rows > 0) {
header('Location: ' . $url . '&key1=' . $key . '&info=info');
} else {
...
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql"
}
|
OSGi + Hibernate
Instead of having database actions scattered in four (osgi) bundles, all doing there slightly different things. I want to create a (simple) OSGi bundle that is responsible for all persistance issues. I feel that this is not as simple as it sounds because of the "unique classloader per bundle" thing. So what I really would appreciate is if someone knows the solution(s) to this kind of problem.
|
(If you are using Hibernate Annotations)
Save all the Entities class loaders when the Hibernate bundle is informed about an annotated class.
Then do something like this before building your SessionFactory.
ClassLoad cl = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(yourClassLoader);
factory = cfg.buildSessionFactory();
}finally {
Thread.currentThread().setContextClassLoader(cl); // restore the original class loader
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 8,
"tags": "hibernate, persistence, osgi"
}
|
How to call a popup window in C#
I have webform1,webform2. I have a submit button in webform1.When the submit is clicked, it has to perform some function then based on the result i have to show different data (let say accept/decline images) in the webform2(POPUP). When this popup is displayed user should not be allowed to make any changes to webform1.
Let me know how to achieve this.
Thanks in advance
|
Aren't you asking for a "modal" popup?
You should try with ShowModalDialog method.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, javascript, asp.net"
}
|
Measure Product Theorem: may non-$\sigma$-finiteness result unique product?
Let $i\in\\{1,2\\}$. The Measure Product Theorem states that, given the measure spaces $(X_i,\Sigma_i,\mu_i)$, there is at least one product measure $\pi$ such that $\pi(A_1\times A_2)=\mu_1(A_1)\;\mu_2(A_2)$, for $A_i\in\Sigma_i$.
It also states that if the $\mu_i$'s are $\sigma$-finite, then $\pi$ is unique.
I'd like an example of a non-$\sigma$-finite pair of measures from which, nevertheless, we only obtain one product, thus showing "if" cannot be "iff" on the paragraph above.
|
Trivial example: $X = \\{x\\}$ has one point, $\mu(\\{x\\}) = \infty$, $X_1 = X_2 = X$, and $\mu_1 = \mu_2 = \mu$. Not $\sigma$-finite, but the unique product measure is $\lambda(\\{(x,x)\\}) = \infty$.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 3,
"tags": "measure theory, examples counterexamples"
}
|
Changing text in class(class A) from another class(class B)
I declared String A in Class A and I want to send this String A to Class B(MainActivity that include inputView) for appending to inputview.
I found,
Changing text from another activity
This solution is very simple and easy.
However, android studio warned me that
"Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)".
Any better solution?
|
* Intent is the proper way to achieve data communication over Activities
> What's the best way to share data between activities?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "java, android"
}
|
Exception program not showing errors or warnings. Not displaying in console
The following code didn't show any error or warnings There is nothing displaying in console. What is the reason behind this?
public class ExceptionDemo {
public static void main( String [] args)
{
for (int i=5;i<0;i--)
{
System.out.println(10/i);
}
}
}
|
Your loop starts with `i = 5`. Then the condition `i < 0` is evaluated. As `i` is not smaller than zero, the condition evaluates to `false` and the code inside the loop is never executed.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "exception, console"
}
|
Indicating a folded state
I have an element on HTML that can be clicked, and its related content can be displayed/hidden right under it. It is common to indicate an element's folded state by `▸` (and expanded state by `▾`), but I am using triangle for something else in my UI, so I want some other way to indicate that an element is folded and is expandable. What good ways are there? Perhaps some other character/symbol, changing the color, or the background color come to my mind, but I am not sure what is good.
|
You'll want symbols that lots of people understand already. Users shouldn't have to learn anew what your symbols mean. So your first step might be to find the established conventions. So look at other sites and see what they do.
Having said that, off the top of my head I first think of plus and minus: [+] and [–]. Or you can use triangles, but make them look significantly different from your existing ones. Maybe [>] instead of filled triangles.
|
stackexchange-ux
|
{
"answer_score": 0,
"question_score": 0,
"tags": "indicator"
}
|
Update Embedded Document Mongo Field Name
I went through this link: How to rename a document field in a MongoDB?, but its not working fine for me. I've Mongo Document like below. I am using `MongoDB server version: 4.0.3`.
{
"_id" : ObjectId("5cb825e566135255e0bf38a4"),
"firstName" : "John",
"lastName" : "svc_user",
.....
.....
"status" : "A",
"effDate" : ISODate("2012-08-24T01:46:33.000Z"),
"department" : [
{
"deptName" : "KG",
....
....
},
...
....
.....
],
...
...
...
}
I executed the below query:
db.employee.update({}, {$rename:{"department.deptName":"department.departmentName"}}, false, true);
Error: cannot use the part (department of department.deptName) to traverse the element
|
In Mongo 4.2 you could run this one:
db.collection.updateMany(
{
department: { $exists: true },
"department.deptName": { $exists: true }
},
[{
$set: {
department: {
$map: {
input: "$department",
in: { departmentName: "$$this.deptName" }
}
}
}
}]
)
I assume in 4.0.3. you have to modify the field name one-by-one with a loop in JavaScript
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mongodb"
}
|
D3 plus wrapping text in circles
So I've been trying to use D3plus in order to wrap text inside circles but with no success. In my application I have a few circle/text pairs, put together into a "g" element. In my code, after I create the "g" elements and append circles and text to it I call the d3plus `d3plus.textwrap()`function like this:
d3plus.textwrap()
//selecting the first text element
.container(d3.select("#Text0"))
.draw();
However, instead of getting wrapped, the text simply disappears. The text is still visible as an element in DOM, but for some reason its size becomes 0x0. Does anyone know what is wrong here?
|
Use method `resize as true` as following code:
<!DOCTYPE html>
<meta charset="utf-8">
<script src="//d3plus.org/js/d3.js"></script>
<script src="//d3plus.org/js/d3plus.js"></script>
<style>
svg {font-family:"Helvetica","Arial",sans-serif;height: 425px;margin: 25px; width: 400px;}
.type {fill: #888;text-anchor: middle;}
.shape {fill: #eee;stroke: #ccc;}
</style>
<svg>
<circle class="shape" r="85px" cx="275px" cy="300px"></circle>
<text id="circleResize" class="wrap" y="260px" x="200px" font-size="12">
Appeared Text inside circle </text>
</svg>
<script>
d3plus.textwrap()
.container(d3.select("#circleResize"))
.resize(true)
.draw();
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "javascript, d3.js, d3plus"
}
|
Django rest framework self.objects.all() as variable
I have parent id in my model:
parent = models.ForeignKey("self", null=True)
and in serializer:
parent = serializers.PrimaryKeyRelatedField(queryset=Category.objects.all(), required=False)
It shows me selectbox with items: "Category object" as it saves all items like that. What I can do to show Category names?
And there is no None option in selectbox.
Another question: How to show Categories in select with parent=None?
|
In you model `Category`,define `__unicode__` method
class Category(models.Model):
//your fields
def __unicode__(self):
return self.name
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, django, serialization, django rest framework"
}
|
In Derby, is there a way to create a database table that has a column that defaults to the UTC timestamp?
I use Derby as a solution for whitebox testing my code. In what will become my production database, I have a column that defaults to the system timestamp in UTC. However; I cannot figure out how to do this in Derby. Is there a way to set up a column like this using Derby? I've googled for a good while now and haven't found anything useful.
|
Derby simply does not have a concept of timezones. While I was unable to solve this without complex triggers that called java methods, I found that the solution to my real problem (unit testing) was much simpler. In my unit test, I simply asserted that my returned date was off by the difference between the default timezone and UTC rather than asserting that the dates were equal (or very close).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sql, derby, utc"
}
|
Why are negative frequencies of a discrete fourier transform appear where high frequencies are supposed to be?
i am very new to this topic, please help me understand why this happens...
if i make the dft of a cos wave
cos(w*x)=0.5*(exp(i*w*x)+exp(-i*w*x))
i expect to get one peak at the "w" frequency, and the negative one "-w" should not be visible, but it appears at the far end of the spectrum where higher frequencies are supposed to be...
why? do high frequencies produce the same effect as negative ones?
if you imagine a wave with frequency equal to `3*pi/2`, that is, `(0, 3pi/2, 6pi/2, 9pi/2)`, it does seem like a wave with negative frequency `-pi/2 (0, -pi/2, -pi, -3pi/2)`
is that the reason to what is happening? please help!
|
High frequencies between the Nyquist rate (Fs/2) and the Sample rate (Fs) alias to negative frequencies, due to sampling above the Nyquist rate. And vice versa, negative frequencies alias to the top half of an FFT. "Alias" means you can't tell those frequencies apart at that sample rate, due to the fact that sampling sinewaves at either of those frequencies at that sample rate can produce absolutely identical sets of samples.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "fft, dft"
}
|
Upgrade Git 1.9.3 on Mac OS X or not?
Xcode installed Git 1.9.3 on Mac OS X 10.10.1.
When I run Heroku, the following message shows up:
> Your version of git is 1.9.3. Which has serious security vulnerabilities. More information here: <
Should I download from Git from official website and upgrade to 2.x? Will it affect Xcode's operation?
|
I am running git 2.1.2 and everything seems fine, including Xcode – I use git extensively there. I installed using homebrew, and I highly recommend using that method if you plan to upgrade.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "xcode, git, heroku, osx yosemite"
}
|
How do natural reach and the feat Snap Shot work together?
The feat Snap Shot says
> While wielding a ranged weapon with which you have Weapon Focus, **you threaten squares within 5 feet of you**. You can make attacks of opportunity with that ranged weapon. You do not provoke attacks of opportunity when making a ranged attack as an attack of opportunity.
Emphasis mine. But if a creature has a natural reach of _more_ than 5 ft., are the creature's attacks of opportunity due to the feat Snap Shot _still_ limited to _only_ the creature's adjacent squares? For example, does a storm giant that's armed with a Huge composite longbow and that possesses this feat still only threaten adjacent squares with his composite longbow or does he threaten 15 ft. out with his composite longbow?
|
## By RAW, they are still limited to only 5' from you.
This is, however, obviously insane.
A GM should simply houserule this to be the natural (or magically modified natural) reach of the creature.
Otherwise there's little (no) reason for a Large or larger (or buffed with a +reach spell) creature to ever have this feat. It's use is still dubious compared to armour spikes or quick-drawing a one-handed weapon or improved unarmed strikes, but at least the use it has (dealing bow damage with enhancements instead of smaller non-primary-weapon damage from an aoo) is preserved.
|
stackexchange-rpg
|
{
"answer_score": 4,
"question_score": 1,
"tags": "pathfinder 1e, feats, reach"
}
|
Validating Domain For AWS ACM in GoDaddy
I have requested an SSL certificate from AWS and I opted for DNS validation. Now they are asking me to add a CNAME record to validate. They have provided me the following to be used:
Name: xxx.example.com. [Host field on GoDaddy]
Value: xxx.acm-validations.aws. [Points to field on GoDaddy]
Type: CNAME
Now whenever I provide this using GoDaddy DNS interface, it throws an error saying for 'Points to' field:
> Enter either @ or a valid host name such as: `subdomain.example.tld`
Did anyone encounter this issue on GoDaddy DNS entries?
|
The `Host` field should be filled with xxx (your subdomain) and the `Points To` field with xxx.acm-validations.aws (without dot).
|
stackexchange-stackoverflow
|
{
"answer_score": 25,
"question_score": 31,
"tags": "amazon web services, validation, dns"
}
|
My react app freezes/lags on mobile devices
I created an app but it freezes on mobile devices, i don't know what is the issue.
The app on netlify : <
On computers it works very fine and it's fluid, but on mobile devices it works on landing in the page, but after 2/3 actions, it freezes.
Can someone help me please?
|
Opening your app and checking the console, you can see that it is not working fine on desktop either. There is an infinite `console.log` being called from `Planning.js`. 
The reason it may seem to be ok on a desktop is likely because desktops have more resources than phones, so you don't see as much performance drop-off from repeated console logs.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, node.js, reactjs, react hooks"
}
|
Combinations function in Java
In one of the examples in my book it creates two methods. One called combinations and one called factorial. The body on the combinations method contains the following code
private int combinations(int n, int k){
return factorial(n) / (factorial (k) * factorial (n-k));
}
In an example of actually seeing how the math works out for this formula the textbook gives the following example. With n = 5 and k = 2. It gives the following steps and says you should get 10. I'm having difficulty understating the logic.
Does ! have a special meaning in this case? How does 5! = 120 and how does !2 x !3 = 2 x 6?
C (n,k) = n!
_________
k! x (n - k)!
C (5,2) = 5!
___________
2! x !3
= 120
_________
2 x 6
= 10
|
`n!` means `factorial(n)`. It is equal to: -
n! = n * (n - 1) * (n - 2) * .... * 1
So,
5! = 5 * 4 * 3 * 2 * 1 = 120
And `!3` is rather a typo in your book. It doesn't represent a `factorial`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, math, statistics"
}
|
How to convert BarCodeKit Objective-C code into Swift?
This is Objective-C code in BarCodeKit:
NSError *error;
_barcodeObject = [[_barcodeClass alloc] initWithContent:_contentsTextField.text error:&error];
How do I convert this code to Swift?
When I tried the following in Swift, it said that I can't pass `NSError` into the function.
var error1 = NSError()
BCKCode39Co = BCKCode39Co.init(content: Content, error: NSError?)
|
Looking at the headers for BarCodeKit, I'd suggest you use the class method:
+ (instancetype)code39WithContent:(NSString *)content error:(NSError *__autoreleasing *)error;
E.g. in Swift 4.2:
do {
let barcode = try BCKCode39Code.code39(withContent: string) // or use rendition with `withModulo43` parameter
imageView.image = UIImage(barCode: barcode, options: nil)
} catch {
print(error)
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "objective c, swift"
}
|
Terminology: Data sample vs statistical sample
I am writing an eye tracking paper that involve both "samples" as used in signal theory (e.g "the sampling rate was of 50 samples per second) and statistical samples.
A reviewer is suggesting that I change the terminology to avoid confusion between the two uses of the term _sample_. What terminology change could I make to meet this request? So far, the only plausible change I could think of was:
* eye tracking samples would become "data points"
* statistical samples would remain "samples".
|
Can you use _eye tracking observations_?
This way, if you have a single study outcome, you can say things like: For our study outcome, we collected 50 _eye tracking observations_ per second per study subject for a total of 120 seconds, etc.
If you have multiple study outcomes, you can clarify that: For each outcome variable, we collected 50 _eye tracking observations_ per second per study subject for a total of 120 seconds, etc.
|
stackexchange-stats
|
{
"answer_score": 5,
"question_score": 4,
"tags": "sampling, terminology"
}
|
Getting initial content into an app on installation
I'm making an iOS app that will have updatable content, and I want to include some initial content with the app installation. Knowing content placed in the main bundle can't be modified, where should I store this initial content, and how could I get it there, short of downloading it on initial launch?
|
Content in the main bundle can't be _modified_ , but it can certainly be _copied_ to your user's documents folder and used from there. In your `-applicationDidFinishLaunching:` or similar on-startup method, you can:
1. Get the path to the desired documents folder/file
2. Check if any of your downloaded content already exists at that path
1. If not, copy your special resource from the main bundle to the documents folder
2. If so, just keep going - you already have content
3. Continue by downloading updates or whatever else your app needs from the network
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios"
}
|
PHP proper login after hash
When I search for "php proper login", all I find is how to properly hash a password. However, I remember reading that the following code is wrong because you can just add ?loggedIn=True to the URL. So what is the proper way to do this?
if($hash == $hashFromDatabase){
$loggedIn = True;
}
Then change the page accordingly to the value of $loggedIn.
|
`?loggedIn=True` would only work if you have `register_globals` enabled. Check your ini settings (I _really_ hope you don't).
You can also use `$_SESSION['loggedIn'] = True`, or even `$_SESSION['user'] = $username` so that they remain logged in for multiple requests.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "php, authentication, passwords"
}
|
Proof that $A \subseteq B \Leftrightarrow A \cup B = B$
I want to proof that:
$A \subseteq B \Leftrightarrow A \cup B = B$
At the moment I have no idea on how to start. Please give me a hint.
Thx in advance!
|
A good place to start is always with definitions. Recall the definition of $A\subseteq{B}$:
$$x\in{A}\to{x}\in{B}$$
Now recll the definition of union:
$$A\cup{B}=\\{x:x\in{A}\lor{x}\in{B}\\}$$
And finally, rewrite the predicate:
$$A\cup{B}=B\leftrightarrow\\{x:x\in{A}\lor{x}\in{B}\\}=\\{x:x\in{B}\\}$$
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "elementary set theory"
}
|
How to determine if there is a support for NVMe

According to user testimony at the post NVMe supported or not? Acer aspire 3 A315-53G, NVMe is indeed supported.
Actually in this post, the initial comment was negative, and the poster then bought a lower-performance disk, so was quite disgruntled.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ssd, pci express, nvme"
}
|
Connecting Azure Analysis service to Traffic Manager and Power BI
anyone has used a Traffic Manager above two Azure Analysis services for high availability and connect Traffic Manager to Power BI? we really need this to provide high availability but power BI doesn't seem to accept the Traffic Manager's URL we have followed this article to set things up.
Alias Server Names
thanks
|
We worked out what the issue was - you can only connect the Traffic Manager to Power BI under HTTPS , we found this article very useful thanks to @NancyXiong-MSFT
SendingUserstotheGeographicallyNearestAzureAnalysisServices
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "azure, powerbi, azure traffic manager, azure analysis services"
}
|
How do I select multiple components in the NetBeans UI builder on a Mac?
When I am building a gui in NetBeans on a Mac, sometimes I want to select multiple components and move them together, delete them together, copy them together, or whatever. In Windows I would hold down the Ctrl key. On a Mac I usually (for other applications) hold down the Command key. Neither of these works in NetBeans 7.0 on a Mac. Is there a key modifier for selections on Mac in Netbeans?
I'm not sure the name of the gui builder in Netbeans, maybe it is called a ui editor or gui editor. Just thought I'd throw that in for people searching with the term "editor".
|
When in the "customize layout" frame for the GridBags layout, Ctrl-Alt click will allow multiple selection. But this doesn't work in the main editor.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "netbeans, netbeans 7"
}
|
How does kubernetes maintain the deployment yaml internally. Where will be it stored after the first deployment
Once you deploy a pod, kubernetes monitors the pod health and if something goes wrong, new pod is created . How is this working internally. After deployment, where is kubernetes storing the deployment yaml.
|
Kubernetes uses the ETCD database as data store. The flow is like this. Kubectl command connect to API server and sends the yaml file to API server. API parses and store the information in ETCD database. Kube controller and schedule looks at the ETCD database and starts the POD. Controller maintain the number of replica defined in the yaml file.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "kubernetes"
}
|
Print multiple char variables in one line?
So I was just wondering if there was a way to print out multiple `char` variables in one line that does not add the Unicode together that a traditional print statement does.
For example:
char a ='A';
char b ='B';
char c ='C';
System.out.println(a+b+c); <--- This spits out an integer of the sum of the characters
|
System.out.println(a+""+b+""+c);
or:
System.out.printf("%c%c%c\n", a, b, c);
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 3,
"tags": "java, char"
}
|
What does the number mean in an HGVSp annotation?
Let's take the example `p.Arg452Pro` that I got from an annotated VCF file that contains an `HGVSp` column.
What does `452` mean in this case ?
Theoretically, is it possible to have the same `HGVSp` on the same gene but on a different transcript level ?
For example:
Chromosome Position Ensembl_Gene Ensembl_transcript HGVSp
4 4613173 ENSG00052342 ENST00141456 p.Arg452Pro
4 4613176 ENSG00052342 ENST00141458 p.Arg452Pro
Thank you in advance.
|
It's the position in the protein. `p.Arg452Pro` means that there is a variant that changes an **Arg** inine residue at position 452 of the protein into a **Pro** line.
And yes, it is absolutely possible to have the same HGVS p. notation on the same gene but on different transcripts. More than possible, it is quite common. Your particular example isn't actually a real variant since that position on chromosome 4 is intronic in both hg19 and hg38, but TP53:p.R175L1 is a real example of what you describe:
{
int var;
if(args.length > 0){
var = 10;
}
else{
var = 20;
}
System.out.println(var);
}
}
Here if I remove `else` part it's showing compilation error as:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The local variable var may not have been initialized
Explain how the local variable value is initialized if I use `else` part.
|
Look at it like this _what happens when the`if` condition in your code is not met?_ The reason you would be getting an error saying :
> The local variable **var** may not have been initialized
is because if the condition is `false` you really don't have `var` initialised, do you?
On the other hand `else` was serving the purpose of ensuring the initialization in the existing code for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -5,
"tags": "java"
}
|
Facebook Page Calendar Export
Is there any way of exporting upcoming events from a Facebook page into your own calendar?
For example, this page: < has two upcoming events.
If you press the "export" link below the events, it will just export your own Facebook calendar.
I want to export these upcoming events, even though the user has not marked that they will attend them, and nothing but that. I would like it to function the same way as the current Facebook "export" function does.
Is it possible through the developer API or is it do-able in an even easier way?
|
You'll have to have the correct permissions to perform this action. To get all the events created by a person/page, all you have to do is query the Graph API as follows : `
In your case the `EVENT_CREATOR_ID` is the `page_id`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "facebook, calendar, facebook page"
}
|
Препроцессор: превратить __LINE__ в строку
Навеяно этим вопросом.
Все время от времени пользуются отладочным выводом с предопределенными макросами типа
cout << __FILE__ << " line " << __LINE__ << endl;
Задумался - как написать макрос `FILELINE`, чтоб эту строчку выше заменить на
cout << FILELINE << endl;
Ну т.е. чтоб макрос раскрывался в строку, в составе которой было число, в которую раскрывается `__LINE__`. Как ни кручусь - все время или число оказывается не в кавычках, или в кавычках оказывается `"__LINE__"`.
Ну не может быть, чтоб эта задача была неразрешима. Ткните носом, о чем я не подумал?
|
Перевод ответа с английского StackOverflow:
Вам нужно сделать это в несколько этапов:
#define S1(x) #x
#define S2(x) S1(x)
#define LOCATION __FILE__ " : " S2(__LINE__)
Почему?
**_Краткий ответ_ :** Вам нужно раскрыть макрос `__LINE__`, прежде чем передавать его в `#x`.
**_Развернутый ответ:_** Во-первых, используя оператор `#` в функционально-подобном макросе, он должен сопровождаться параметром макроса, но `__LINE__` не является параметром, поэтому компилятор жалуется, что он является ошибочным оператором.
Во-вторых, `__LINE__` сам по себе является макросом и содержит номер текущей строки, его следует раскрыть до числа перед использованием его с `#`, в противном случае вы получите строку `"__LINE __"` вместо числа.
Макрос `S2 (__LINE__)` расширяет `__LINE__` до номера строки, затем мы передаем номер строки в `#x`.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 6,
"tags": "c++, c, макросы, препроцессор"
}
|
Uncaught TypeError: Cannot read properties of undefined (reading 'includes')?
I am trying to resolve this TypeError but have not been able to. Below is the code it is pointing to. I have tried assigning a var to it as some other similar posts have mentioned but no luck. ):
const emailReducer = (state, action) => {
if (action.type === 'USER_INPUT') {
return { value: action.val, isValid: action.val.includes('@') }
}
if (action.type === 'INPUT_BLUR') {
return { value: state.value, isValid: state.val.includes('@') }
}
return { value: '', isValid: false };
};
|
We can see `state.val` is undefined thus lacking the `includes` method. In your code, seems the value should be addressed as `state.value` instead.
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": -2,
"tags": "reactjs, typeerror"
}
|
How to enable a the php_soap extension from .user.ini (no acces to php.ini)
Our application is being hosted on GoDaddy (plesk). We need to enable 'php_soap' extension for our application to work. We contacted the customer support that we don't have access to `php.ini` file to do so but they told us that we can use `.user.ini` instead. We've tried doing that but `.user.ini` doesn't seem to enable `php_soap` extension when we added the line.
extension=php_soap.dll
after testing if `.user.ini` works at all by changing another setting `upload_max_filesize` and it works. But enabling the `soap` extension doesn't work
|
Apparently our client's host plan was "Shared Hosting" which was restricted by GoDaddy to not have access to the SOAP extension specifically for performance reasons. We changed the hosting plan and the problem is solved.
|
stackexchange-webmasters
|
{
"answer_score": 1,
"question_score": 2,
"tags": "web hosting, php"
}
|
take a char and print out from char to 'a' and reverse it should be recursive
this is what Ii wrote so far but it is not the correct output
def characters(char):
numb=ord(char)
while numb>ord('a'):
print chr(numb),
numb=numb-1
return
**I want the this output** :
characters('h')
g f e d c b a
|
Whenever you design a recursive function, the first thing you want to ask yourself is: how does the algorithm terminate? I.e., what's the base case? In your example, the algorithm should stop printing characters after the letter 'a' is printed, so that's your base case.
Next, you have to ask how to get to the base case from your starting case. That's pretty easy: you want to print the previous character until you reach the base case. (A character is essentially just an integer, so that means you want to subtract one from the character and print it as a string.)
Putting that all together, I got:
def print_reverse(ch):
print ch,
if ch > 'a':
print_reverse(chr(ord(ch)-1))
else:
print # New line
print_reverse('h')
(If you don't know what the Python functions `ord` and `chr` do, look them up in the interactive interpreter using `help(ord)` and `help(chr)`.)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "python, recursion, char"
}
|
Sencha touch 1.1 or 2
_I have to evaluate Sencha Touch for building native Ipad html5 based apps. I was wondering which version should I start with v1.1 or v2.0?_
I bought this book and created a simple html5 app (with Panels, proxies, MVC, toolbars) and integrated it with Java Spring and freemarker templates. All worked perfectly , the book was excellent and the onine documentation was great. This was with version v1.1.
Then Sencha announced that v2 is out with lot of improvements especially in performance. This made me think whether I should start again with 2.0 or just continue building on my prototype with v1.1 and wait till v2.0 gets more mature and has more documentation.
|
I have been working with Sencha products since Ext2. Throughout all these years I have been rewriting my code numerous time just to adapt to their freaking changing coding pattern.
From the troublesome `Class.superclass.method.call()` to the new `me.callParent()`, till the recent adoption of `initialize` & removal of `initComponent` in ST2, I would suggest you to go for the newest release since whatever in the past will not be reuse again. Learn the new coding style, don't waste time on the old structure. It won't help you much, considering our web is changing very fast and ST1 and ST2 is pretty disjoint as well.
While 1.1 is good old solid (much like Ext), v2 is much fun to work with with the auto loader.
I built two native Cordova (formerly PhoneGap) apps on iOS lately and the performance is pretty good so far.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "sencha touch, sencha touch 2"
}
|
Proof regarding lebesgue measure (from Folland's book)
**Q.** Let $\mu$ denote the Lebesgue measure on real line. If $E\in\mathcal{B}_{\mathbb{R}}$ and $\mu(E)<\infty$, then for every $\epsilon>0$ there exists a set $A$ which is a finite union of open intervals such that $$\mu((E\backslash A)\cup(A\backslash E))<\epsilon$$
**Try**
It is clear that $(E\backslash A)$ and $(A\backslash E)$ are disjoint. So,$$\mu((E\backslash A)\cup(A\backslash E))=\mu(E\backslash A)+\mu(A\backslash E)$$
But I have no idea how to proceed further.
|
You know (c.f. Lebesgue outer measure) that for every $\delta>0$ there are open intervals $I_1,I_2,\dots$ such that $E\subset\cup_{k=1}^\infty I_k$ and such that $\mu(E)+\delta\geq\sum_k\mu(I_k)$. Try $A=\cup_{k=1}^{N}I_k$ for $N$ big enough.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "real analysis, measure theory"
}
|
Which definition of "franchise" fits in this context?
Which definition of "franchise" fits best in this context?
> Despite the seemingly strong empirical support in previous studies for theories of majoritarian democracy, our analyses suggest that majorities of the American public actually have little influence over the policies our government adopts. Americans do enjoy many features central to democratic governance, such as regular elections, freedom of speech and association, and a widespread (if still contested) **franchise**. But we believe that if policymaking is dominated by powerful business organizations and a small number of affluent Americans, then America’s claims to being a democratic society are seriously threatened.
1. The right to vote?
2. The rights of citizenship?
3. The right to carry out specified commercial activities?
|
The right to vote.
_Franchise_ has that sense as a specific from of the second definition you list, but that the franchise is widespread (rather than restricted to a specific group) is both something that fits alongside the other features listed, something that has not always been enjoyed in the country in question (which would hence make it more immediately come to mind) and which is indeed still contested with laws which those opposed claim are an attempt to restrict the franchise.
|
stackexchange-english
|
{
"answer_score": 2,
"question_score": 1,
"tags": "meaning"
}
|
mongodb: how to express "schema"?
Once many teams work with the same mongodb database there needs to be some way to express what each document may contain. Otherwise the document will end be having "email", "mail", "email_addr" fields added by each team. What's the best way to represent this for the purpose of communication across teams?
|
Obviously, the best way is what the team is most comfortable with. It can be UML, whiteboard drawings, XML mappings, model code files, maybe even haiku poems :)
I personally prefer using an ODM (mongoid). It encourages you to specify all fields in the model class. Then you just need one glance at it to understand the schema.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mongodb"
}
|
Select table and replace column by value from another table
I'm trying to achieve a query on my database(MySQL).
For example:
**Table1**
id,code,name
1,1,Tom
2,1,Jerry
3,1,Peter
4,2,Charles
**Table2**
code,name
1,alpha
2,beta
3,gamma
I need to select ALL values from table 1 with the maximum code, but replacing that column (table1.code) for the max value code(table2.code) from table2.
**Desidered output**
id,code,name
4,3,Charles
For select the max value, I know this:
SELECT * FROM Table1 WHERE code = (SELECT MAX(code) FROM Table1)
How to replace?
SELECT REPLACE(Table1.code, SELECT * FROM Table1 WHERE code = (SELECT MAX(code) FROM Table1), SELECT code FROM Table2 WHERE code = (SELECT MAX(code) FROM Table2)) * FROM Table1 WHERE code = (SELECT MAX(code) FROM Table1)
I'm confused :c Thanks for reading!
|
Try this.
SELECT id,
(SELECT Max(code)
FROM table2),
name
FROM table1 A
WHERE code = (SELECT Max(code) code
FROM table1)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "mysql, sql, database, select"
}
|
onclick alert for html pages not popping up
How do i ensure that the alert popup would show up when my link is clicked?
<a href="#" onclick="alert('Test');" class="button4" style="margin-top: 10px; font-family: robotoreg;width: 100%;background:#b3c833;">Click <br /><b>Here</b> Now!</a>
The above code works however if i enter :
<a href="#" onclick="alert('Congratulations\nYou have completed the quiz!\nClick Next to play more games');" class="button4" style="margin-top: 10px; font-family: robotoreg;width: 100%;background:#b3c833;"></a>
The alert popup doesnt show up.
Any ideas why? Thanks
|
here, i use both of ur example
jsfiddle.net/9hk6kcuo/
it works. the 2nd ex not works 'cause you have ' in your js code (you 're). it split ur code into 2
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, html"
}
|
Create a table without border
I've managed to create a table:
//I create the table here and the default name is table1
XTextTable xTT = (XTextTable) UnoRuntime.queryInterface(XTextTable.class, oInt);
xTT.initialize(1, 1);
However, this create the table with a default border. I would like to create this table without it.
This property is setted by the image

borderLine.OuterLineWidth = 0
tableBorder = table.getPropertyValue("TableBorder")
tableBorder.VerticalLine = borderLine
tableBorder.HorizontalLine = borderLine
tableBorder.LeftLine = borderLine
tableBorder.RightLine = borderLine
tableBorder.TopLine = borderLine
tableBorder.BottomLine = borderLine
table.setPropertyValue("TableBorder", tableBorder)
For a related Java example, search for "TableBorder" on this page: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, openoffice.org, openoffice writer"
}
|
why does this main function does nothing?
I see this strange python function
@click.group()
def main():
pass
It is the main entrance function, but why does it do nothing?
|
If a function is decorated with `@click.group`, a `Group` is created, and can later be used to add subcommands, e.g.:
@click.group()
def main():
pass
@main.command()
def sub():
print('I am a subcommand')
The group function doesn't have to do anything itself, if you don't need additional logic or default logic without a subcommand.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, function"
}
|
Does a White Mage Arcanist need to Use Magic Device to activate a Wand of Cure Light Wounds?
I was tasked with building the third character of a 3 person party, and make that character fill in all the missing holes. The other two characters are a Hunter specializing in bows and a Sword and Board Barbarian.
I found White Mage archetype Arcanist because it allows me to spontaneously cast heal spells and still gain the battle control spells of a wizard.
Cure Light Wounds, while I can spontaneously cast it, is not part of my spell list. So, do I need to perform a Use Magic Device check on a wand of Cure Light Wounds, even though I can cast the spell?
|
**Yes** , you must make a UMD check. The relevant text is this (emphasis added):
> At 1st level, a white mage can expend 1 point from her arcane reservoir to use one of her spell slots to cast a cure spell (any spell with "cure" in its name) from the cleric spell list **as if it were on her spell list** and prepared.
It's never really on your spell list; you just get to act like it is in a certain limited circumstance. But if you're not expending that point, you don't get that benefit.
You can probably argue that expending the point should allow you to use a single charge of the wand without making a check, but strictly speaking that's a bit of a houserule, since the RAW is limited to using spell slots. Perfectly reasonable, balance-wise, but not really part of the text.
|
stackexchange-rpg
|
{
"answer_score": 5,
"question_score": 2,
"tags": "pathfinder 1e, spells, archetype"
}
|
Is there an equivalent to "awww" in English for expressing sympathy?
Just now, I was talking to someone on WeChat and he mentioned how he got caught out in the rain. I wanted to say "awww" out of sympathy as we do in English, but I don't know how to. The closest I know is (a) = "ah" or (ō) = "oh", "oops" which don't really suit the situation.
**Question** : Is there an equivalent to "awww" in English for expressing sympathy?
Searching for `awww` in YouDao suggests , such as , but I don't think this is the same as sympathy (although maybe I'm wrong). Other searches (`aww` (dict.cn) `aww` (YouDao)) don't really help.
|
There isn't one.
At least not specifically for expressing sympathy. There are other exclamations that can be used to express sympathy, like , , but none are specific to sympathy, and can be used in other situations.
This feels like a cop-out but it's true; Chinese doesn't have exact equivalents for all English exclamations, but the converse also applies. To give you two examples, there isn't a Chinese word to express disapproval, like "boo"; you might say something specific like , which means "get off the stage". There isn't an English equivalent to ; instead you might say "go team", or "USA", depending on what you're cheering.
|
stackexchange-chinese
|
{
"answer_score": 2,
"question_score": 2,
"tags": "translation, word choice"
}
|
Prove that Statements forms are tautologies
Given variable statement forms $A$ and $B$. How to prove that if $(A\land B)$ is a tautology then $A$ and $B$ are tautologies too?.
Mi approach would be a proof by contradiction, something like: If we suppose $(A \land B)$ is a tautology but $A$ and $B$ are not tautologies, then $(A \land B)$ can't be a tautology and this will contradict the hypothesis, so $A$ and $B$ are tautologies. Is this correct or near correct?
|
Your reasoning works, but it would be best to do this with more symbolic justification as to why "then $(A \land B)$ can't be a tautology.
> ...suppose [for the sake of contradiction) that $(A \land B)$ is a tautology but $A$ and $B$ are not [both] tautologies,
So $A \not\equiv T$ or $B\not\equiv T$ (or both).
> then $(A \land B)$ can't be a tautology
because...there would then be at least one truth value assignments such that $A$ is false, or $B$ is false, and hence there would be truth value assignments such that $A\land B$ is false. This means that $A \land B \not\equiv T$. That is, _it is not true that $A \land B$ is a tautology._
> and this will contradict the hypothesis, so $A$ and $B$ [must both be] tautologies.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "discrete mathematics, logic"
}
|
Is it possible to use CDI with VRaptor?
Is it possible to use CDI as dependendcy injection container for VRaptor framework?
|
Apparently not. But VRaptor 4 will support.
More info: <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "java, cdi, vraptor"
}
|
Assumption Needed when Solving Puzzle
When solving a logic puzzle, at times, one _must_ make an assumption in order for a solution to be found. For example, in this perfectly good logic puzzle, it had to be assumed that the characters knew amongst themselves who's who (i.e. the Knight knows who the Joker and Knave are, etc).
What is the technical term (a noun) which represents a necessary assumption, without which, a solution may be impossible? I have heard this term at some point (somewhere here on Puzzling.SE), but it has escaped me — if it helps, I think it was something like 'zero assumption' (90% sure it was more than one word) and it had a Wikipedia entry.
PS: I'm not entirely certain the puzzle I mentioned _requires_ any extra assumptions - it's a perfectly good logic puzzle.
|
OP: Seems that it was: **FIRST PRINCIPLE**
* * *
Could it be **Basic supposition**? I've seen it in some (really old) books about philosophy and physics, but the full phrase does not have a Wikipedia entry.
**EDIT**
Scratch, that. You are probably searching for **Tacit assumption**, also known as **Implicit assumption**
**SECOND EDIT**
Could it be **Unstated assumption** as described in the **second** paragraph on the Wikipedia link?
**THIRD EDIT** (this is getting fun)
Or maybe **First principle** a.k.a. **Foundational proposition/assumption**
**Bonus question:** How many terms for practically the same thing are there?
|
stackexchange-puzzling
|
{
"answer_score": 3,
"question_score": 8,
"tags": "logical deduction, puzzle theory"
}
|
Scala using toSet.toList vs distinct
If I want to get the unique elements of in a List I can either do a `distinct` or call `toSet.toList`. Which is more efficient and why ? Is there any other efficient way of doing this ? My understanding is that `distinct` will also maintain the order whereas `toSet.toList` won't.
scala> val mylist = List(1,2,3,3,4,4,4,5,6,6,6,6,7)
mylist: List[Int] = List(1, 2, 3, 3, 4, 4, 4, 5, 6, 6, 6, 6, 7)
scala> mylist.distinct
res11: List[Int] = List(1, 2, 3, 4, 5, 6, 7)
scala> mylist.toSet.toList
res12: List[Int] = List(5, 1, 6, 2, 7, 3, 4)
|
Taken directly from the source code found here:
/** Builds a new $coll from this $coll without any duplicate elements.
* $willNotTerminateInf
*
* @return A new $coll which contains the first occurrence of every element of this $coll.
*/
def distinct: Repr = {
val b = newBuilder
val seen = mutable.HashSet[A]()
for (x <- this) {
if (!seen(x)) {
b += x
seen += x
}
}
b.result
}
So it appears that if order preservation is important, use `distinct` otherwise, they're relatively just as expensive.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 12,
"tags": "list, scala, collections, set, distinct"
}
|
how to use dynamic paint weight for texturing object?
I have a dynamic paint with surface type set to weight, which I use to displace my object. What I want to do is to apply the texture (in cycles) to my object based on the dynamic paint weight. Just using attribute node with dp_weight going into colorRamp doesn't work.
Any answers highly appreciated.
-laurin
|
I've tried to accomplish this as well.
In the point density texture there's an option to source the values from vertex weights. Unfortunately this only seems to work with volumes, as any output that comes from it when used as a surface texture doesn't seem to correspond with the mesh weights.
There's a workaround though, but you have to set your dynamic paint to texture and bake it out, that way you can load it in to Cycles as an image sequence. If you edit the weights you have to re-bake it, so not the most elegant of solutions.
Maybe someone else has a technique that's more efficient?
edit: workaround tutorial
|
stackexchange-blender
|
{
"answer_score": 1,
"question_score": 1,
"tags": "cycles render engine, materials, weight painting, dynamic paint"
}
|
Inheritance impossible in Windows Runtime Component?
Scenario:
I have 3 classes (A,B,C) in my Windows Runtime Component project.
class A{}
public sealed class B : A {}
public sealed class C : A {}
On compiling the above code, I get the following **error** :
> "Inconsistent accessibility: base class 'A' is less accessible than class 'C'."
If I make class A public, it gives a **compile error** :
> "Exporting unsealed types is not supported. Please mark type 'MyProject.A' as sealed."
But now, if I make A as sealed, then B and C cannot inherit from it.
Considering the fact that only WinRT types are allowed for inheritance, is it anyhow possible to use custom/user-defined classes for inheritance? If not, is there any workaround to achieve the same?
|
As you've figured out by yourself, you can't expose classes that inherit from others in a Windows Runtime Component; that is true even if you try to use an abstract class as a parent class. This is a "drawback" needed to make WinRT components works with all the others languages that the WinRT framework supports. The only way to workaround this is avoiding inheritance. You can only use interfaces or object composition where you can simulate inheritance behaviors, e.g.:
public sealed class A
{
public void Method() { }
}
public sealed class B
{
A a;
public void Method()
{
// Do B stuff
// Call fake "virtual" method
a.Method();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "c#, windows, windows runtime, win universal app, winmd"
}
|
Send Cognos Burst Reporting to multiple emails
I have a few reports that need to be sent form hourly certain intervals during the day.
I know how to schedule burst jobs and they send out fine, but i am being tasked with sending that same exact thing to "CC" that persons mananagerl1 and managerl2
Lets say part of the email table looks like
Name | mgr1 | mgr2 | email | mgr1eml | mgr2email
normally i burst to email and group by name
how would i burst to all three emails without having to create 3 different reports?
|
It's been a while, but I think you can do it this way: Use a comma delimited string for your email addresses:
[email protected],[email protected],...
Set your burst property to email addresses (Report Studio > File menu > Burst Options > Burst Recipient > Type).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "cognos, cognos 10"
}
|
Unsupported depth in Opencv
I am trying to learn some basics, but I keep getting errors.
I am trying to resize a cv::Mat
Edit to clarify why I am not loading an image: I am trying to test without having access to external files.
Inside the code, though, I put `int x = M.depth();` and it read 0
cv::Mat M(2,2, CV_8UC3, cv::Scalar(0,0,255));
scale = 2;
cv::Size myImageSize;
myImageSize.height = M.rows;
myImageSize.width = M.cols;
cv::Mat ImgCopy = cvCreateImage(myImageSize, M.depth(), M.channels());
..
cv::resize(M, ImgCopy, myImageSize, 0, 0, CV_INTER_LINEAR);
I am getting an error on the line cvCreateImage
Input image depth is not supported by function (Unsupported format) in unknown functio, file... \modules\core\src\array.cpp...
I have tried with other values (CV_32F...) and I get the same error.
Please help !
|
`cvCreateImage()` is for use with the C API and returns an `IplImage*`. To initialize a `cv::Mat`, use the appropriate constructor.
cv::Mat ImgCopy(M.size(), M.type());
is the most succinct way to create and allocate memory for a new `cv::Mat`.
However, `cv::resize()` makes it even easier. You just have to declare your image
cv::Mat ImgCopy
and the arguments to `cv::resize()` allow automatic calculation of the correct dimensions and type. The last three parameters do not need to be specified because you don't change them from the defaults.
cv::resize(M, ImgCopy, myImageSize);
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "c++, opencv"
}
|
How to get the user check in information from facebook account?
< every where only this link is showing ,but using this we get only near by locations .
I want is how to get the checkin information from FB account to our application.
|
Maybe you mean this links?
Here you can see a full list: Facebook Field values
Here you can send a test messages for test a response data: Facebook Graph API Explorer
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "xcode, facebook"
}
|
Calling SQL Server database from Unix
With oracle currently there is a way to call a database through a command prompt using sqlplus. I'm wanting to know if there is a way to call a SQL Server server the same way so that I can have a shell script do it for me. Is there a way?
|
<
"FreeTDS is a set of libraries for Unix and Linux that allows your programs to natively talk to Microsoft SQL Server and Sybase databases. "
<
> fisql
>
> A complete replacement of the isql utility programs distributed by Sybase and Microsoft. > Like them, fisql uses the command "go" on a line by itself as a separator between batches.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "sql server, unix"
}
|
change rpmbuild directory to /var/lib/jenkins/rpmbuild/
I am generating an RPM package using jenkins, although SOURCE, BUILD, BUILDROOT are all stored under /var/lib/jenkins/rpmbuild/, the rpm package after generation gets redirected to /root/rpmbuild/RPMS and I get error as
error: cannot create /root/rpmbuild/RPMS/noarch: Permission denied
I tried creating /var/lib/jenkins/rpmbuild/RPMS/noarch but it failed, I checked my .rpmmacro too and there I have defined topdir as
%_topdir %(echo $HOME)/rpmbuild
and owner and group of .rpmmacro is jenkins
I want the rpm package to get stored under /var/lib/jenkins/rpmbuild/RPMS/noarch/ as the task is build by jenkins and that's the only directory that jenkins owns.
|
To answer my own question,
There is a key in spec file called `%define`, you just need to define the directory or path where you want your rpm package to save. You just need to define it for the first time if you are using same spec file for every build.
for me it was
%define _rpmdir /root/rpmbuild/RPMS/
which I changed to
%define _rpmdir /var/lib/jenkins/rpmbuild/RPMS/
and it started working
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "rpm, rpmbuild"
}
|
IF Statement to Delete Symbolic Link
I am trying to remove an error from appearing on the terminal (it annoys me as it is not one that I need to be worried about).
I have the following code which will check for a broken symbolic link, and if the link is broken it will delete the link:
find /usr/lib/libdb.so -xtype l -delete
How do I change this to a iIF statement?
if [ broken link ] then;
delete file
else
do nothing
fi
Could anyone shed any light on this for me please?
|
To follow your approach, you could try this command:
if [ "`find /usr/lib/libdb.so -type l -xtype l`" != "" ]; then
echo delete file
else
echo do nothing
fi
or, more concisely:
find /usr/lib/libdb.so -type l -xtype l -print -delete
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "shell, unix"
}
|
number format in Oracle Business Intelligence (OBIEE) Analysis
how do I set number format in Oracle Business Intelligence (OBIEE) Analysis ? I mean decimal places and use of 1000 separator. Thanks ahead.
|
In the criteria tab of your analysis:
1. Click the fact column and select "Column Properties"
2. Click on "Data Format"
3. Check "Override Default Data Format" box
4. Specify decimal places and 1000s separator
5. If you want this format to be applied to all the ocurrences of this fact column (and assuming you have the privileges) you can save this format as system-wide default by clicking "Save as default"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "business intelligence, number formatting, obiee"
}
|
What are the benefits of importing your old character in Penny Arcade Adventures: Episode 2?
In Episode 2 of the Penny Arcade Adventures XBLA/PSN game, you have the option of either making a new character or importing your old character (by accessing your end-of-game save data from Episode 1). Is there any benefit to doing so, aside from a greater sense of continuity? Do acquisitions from the first episode carry over into the second, or what?
|
From my (admittedly hazy) recollection of PAAOtRS, you keep your characters levels, the look of your customized character and, assuming you unlocked him in the first game, the support character Div.
A cursory googling seems to confirm this.
|
stackexchange-gaming
|
{
"answer_score": 5,
"question_score": 8,
"tags": "penny arcade 2"
}
|
Rails Redis Reset Counters to 0
I would like to reset the value of a REDIS counter to 0 in a Rails 4 app.
I use hincrby to increment counters
$redis.hincrby("user:likes", "key", 1)
I can't delete the key with hdel < because I need to get the key often.
GETSET is atomic and could do the job < as in the example
GETSET mycounter "0"
But since I use hashes I need to use HSET <
$redis.hset("user:likes", "key", "0")
It's not specified if hset is atomic, anyone used hset to reset redis counters to 0? If it's not a good option to reset a counter to 0, any idea how to do it?
|
It is atomic, so if you run `$redis.hset("user:likes", "key", "0")`, it doesn't affect other fields inside the "user:likes" hash besides the field: "key"
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "ruby, ruby on rails 4, redis, counter"
}
|
How to view Heap and non-heap memory usage telemetry of java
How to view Heap and non-heap memory usage telemetry of java? I need to view the graphical chart. Kindly guide me
|
Yes I can use jvisualvm or jconsole. Thanks for SimY4
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, heap memory"
}
|
Transferring Everything from One Domain to Another
I want to move from one domain to another one that is shorter and (hopefully) easier to remember, but I also want the transition to be as seamless as possible.
I'm a coder so I know about 301 redirects and I intend to use them, but is there something easier than manually adding entries in my .htaccess file?
The website is static with the exception of the blog, which is under the /blog/ directory and powered by WordPress. I want it redirected to my new domain name. File and folder structures don't change. Isn't there some kind of wildcard thing for this?
|
What type of web server is the site being hosted on? If its on Apache, you can use the RedirectMatch command
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "dns, redirect, http status code 301"
}
|
logback: FileNamePattern from application.properties
I would like to get the file name of my logback file from a property defined in the
application.properties
but I don't know if it is possible
<fileNamePattern>${user.home}/logs/>${logFileName}.%i.log.zip</fileNamePattern>
|
You can register your `application.properties` file in the `logback.xml` configuration file. logback will then recognize the properties defined in that file.
logback.xml:
<property resource="application.properties"/>
More details: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring boot, log4j, logback"
}
|
Is Possible to integrate small cocos2d-x 3.2 game inside existing IOS application using swift 3?
Hello friends is it possible to create a game using cocos2dx 3.x , Swift.If this is possible than how can i integrate my game inside my native IOS application using swift3.Please Guide me.
|
Sure, that's quite possible since cocos2d-x will work on a OpenGLES view. And also xCode understands C++. But it will be a bit tricky to add ; you need to handle all of build configurations with large cocos2d-x library etc.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, swift3, cocos2d x 3.x, xcode8.2"
}
|
Finding out when an order status has been set to completed
I'm selling virtual products in my store where my customers buy a subscription for sth. This subscription is valid for 31 days beginning with the day when the order has been completed.
How do I find out the day when the order status had been set to completed?
My Idea was to look for the "updated_at" field of an order but I'm unsure if this is the right way to determine when the order was completed.
$sales_model = Mage::getModel("sales/order");
$all_orders = $sales_model -> getCollection()
->addFieldToFilter('status', 'complete')
->addAttributeToFilter('updated_at', array(
'from' => $one_month_ago,
'to' => date('Y-m-d 24:00:00'),
'date' => true,
)
);
|
The way I would approach this, is by create a custom module the keep track of the order status using observer
See Magento order status change events
Then log (in a db) the order # and date when the order was complete and expire. This way you could easily run report on when subscription will expire
Customize Magento using Event/Observe
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "magento"
}
|
Soundcloud embedding: change in iframe source URI?
Until a few days ago, I could just take a Soundcloud link like this one:
`
… and put it into an iframe `src` like this:
`//w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/artist/song-title`
Now I’m getting an error saying “url parameter is not a valid SoundCloud URL”. The embedding options at any Soundcloud page now show a link built like this:
`
I couldn’t find any information on a recent change. Does this mean I cannot derive the embedded source from a standard Soundcloud URI? Is there no way around a server-side oEmbed call?
|
I found that removing 'api.' from the url parameter worked.
Old:
//w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/(blah blah blah)
New:
//w.soundcloud.com/player/?url=https%3A//soundcloud.com/(blah blah blah)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "soundcloud, embedding"
}
|
More elegant alternative for "value === false"?
In JavaScript, I want to compare a value for (strict) equality to `false`.
From Java / C# I am used to writing:
if (!value)
//Do Something
However, I can not use it in JavaScript as `null`, `undefined` (and others IMHO) evaluate to `false` inside an if-statement, too. (I don't want that).
Thus, I have therefore been writing the following to formulate such a check:
if (value === false)
//Do Something
Yet, this construct looks a little bit strange to me.
Are there any more elegant ways here (which lead to the same results as the `=== false` of course)?
Introducing a method `isFalse` would be an option, of course, but that's not what I am looking for as it would look even more distracting than the `=== false`.
|
Please, don't write a function `isFalse()` (a candidate for The Daily WTF), use the `===` operator even if it looks strange to you, there is no cleaner way.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, coding style, comparison, boolean"
}
|
How pull a docker image and give it a diferente name?
I need pull a docker image of tensorflow.
I know that for pull a image i have to use this commmand:
docker pull tensorflow/tensorflow:2.4.3
But i dont want my image with this name:
tensorflow/tensorflow:2.4.3
How can i change this name in the moment that i pull it ?
|
The location you pulled it from and the name are tightly coupled. So you can retag after pulling:
docker pull tensorflow/tensorflow:2.4.3
docker tag tensorflow/tensorflow:2.4.3 yourid/tensorflow:2.4.3
Otherwise, you'd need to pull the image from outside of docker and side load the image, but that's really more effort than it's worth, and losses efficiencies like skipping already pulled layers.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, docker"
}
|
How to add the same thing to every row in a column in SQL?
Im not sure why I cant find this online but I simply want to tell a query to have a new column which is the same thing for every row.
So something like this:
ID Pollo
001 True
002 False
003 True
004 False
005 True
And I wanna make it this where I add a variable called Tag and it is strictly the word "Mark" for every row:
ID Pollo Tag
001 True Mark
002 False Mark
003 True Mark
004 False Mark
005 True Mark
|
You can add a constant expression as a column in a query's select-list, and an expression can be a simple value:
SELECT ID, Pollo, 'Mark' AS Tag
FROM mytable;
Since this value is a constant, it will be the same on every row returned by the query.
You should assign the column an alias by using the `AS` keyword. This becomes the header for the column.
The data type for the column is implied by the expression. In this case, it's a varchar.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "mysql"
}
|
How to add up values from a php foreach block
My php script is getting data from an xml file. I am fetching a list of prices and echoing them in a foreach statement. The problem is I need to calculate the sum of prices outside the foreach. Here is what I've done so far. Converting to array then going array_sum is the only thing I can think of.
<?php
$data = simplexml_load_file("products.xml");
foreach ($data as $val) {
echo $val->price . "<br>";
$total[] = $val->price;
}
$sum = array_sum($total);
echo $sum;
So far, this is not returning the total. It simply returns 0, which is weird because when I vardump $total, it shows up as an array.
|
When using SimpleXML and you do
$total[] = $val->price;
this creates an array of SimpleXMLElements and not values.
A simple solution in this case is to cast the value, depending on the type of value either
$total[] = (int)$val->price;
or
$total[] = (float)$val->price;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php"
}
|
Проблема с паузой при вызове Popen
В скрипте используется сторонний файл типа *.jar Для его запуска используется файл bat, который вызывается следующим образом
from subprocess import Popen
p = Popen(gatlingdir + '\\bin\\gatling.bat -ro res', cwd = gatlingdir + '\\bin')
stdout, stderr = p.communicate()
После выполнения сторонний файл выводит: "Для продолжения нажмите любую клавишу..."
Можно ли это как-то обойти?
|
Из документации <
# Если хотите что-то послать в stdin процесса, необходимо указать stdin=PIPE:
p = Popen(gatlingdir + '\\bin\\gatling.bat -ro res', cwd = gatlingdir + '\\bin', stdin=PIPE)
Оттуда же
# Необязательный аргумент input означает данные, которые будут посланы в дочерний процесс
stdout, stderr = p.communicate(input='1')
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, python 3.x, subprocess"
}
|
What is the default pooling size of Max pooling layers in Keras?
What is the default pooling size of maxpooling layers in Keras? Pooling layers have 3 args: pool_size, strides and padding. If the pool_size is not explicitly specified, what pool_size value does Keras use by default?
For example in the following keras pooling layer, which is the pool_size?
model.add(tf.keras.layers.MaxPooling2D(strides=(2,2), padding='same'))
|
The default in Keras as it is in Tensorflow with the Keras backend is `pool_size=(2,2)`, therefore it will halve the input's `x` and `y` spatial dimensions.
Here you can see the documentation in Tensorflow where it is mentioned.
To be more specific, the `stride` and `pool_size` arguments are highly related and differ only when you change the padding type. As mentioned in the documentation:
`output_shape = math.floor((input_shape - pool_size) / strides) + 1` in the case where `input_shape >= pool_size` if the chosen padding is `valid`.
Otherwise, if chosen padding is `same`:
`output_shape = math.floor((input_shape - 1) / strides) + 1`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, keras"
}
|
Display UTF8 and ISO-8859-1 in select box HTML
**Hello, Folks!**
All my script files are utf8, the server responses are utf8, the db collation.. quite everything.
I have a JSON data that populates the options of a select box. When I fix ISO I get in trouble in UTF8, or vice versa.
**The point is:** How can select option display both ISO-8859-1 and UTF-8 special chars?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<select id="values" name="values">
<option>VALÊNCIA 18</option>
<option>BAHRAIN â€«Ø§Ù„Ø¨ØØ±ÙŠÙ†â€¬â€Ž 40</option>
</select>
</body>
</html>
|
**[SOLVED]** If any one had the same problem as me and the charset was already correct, simply do this:
1. Copy all the code inside the .html file.
2. Open notepad (or any basic text editor) and paste the code.
3. Go "File -> Save As"
4. Enter you file name "example.html" (Select "Save as type: All Files (.)")
5. Select Encoding as UTF-8
6. Hit Save and you can now delete your old .html file and the encoding should be fixed
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, json, utf 8, character encoding"
}
|
How to get the current working directory in Rust if it is a symlink
If there is a directory `/tmp/foo/bar` and a directory `/tmp/bar` which is a link to `/tmp/foo/bar` made with `ln -s /tmp/foo/bar /tmp/bar`, then if the current working directory is `/tmp/bar`, Rust's `std::env::current_dir` will return `/tmp/foo/bar` instead of `/tmp/bar`?
Is there a way to get the current working directory in Rust without resolving symbolic links?
|
As per this GitHub issue, this is not really possible.
> For UNIX Rust just calls `getcwd()` and that behavior is documented in the POSIX spec, so it will be the same on all conforming implementations.
From the linked spec:
> The pathname shall contain no components that are dot or dot-dot, or are symbolic links.
A possible workaround is to look at the `PWD` environment variable, but it's dependent on the shell to set this, and it's not a requirement that shells do so. The executable may not have been invoked from a shell, either.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "rust, directory, path, symlink, working directory"
}
|
Как соединить строковые переменные?
Пробую написать небольшой скрипт на bash и уже в самом начале проблема. Создаю две переменные и пытаюсь их соединить, но вместо этого происходит какая-то ересь, прошу помощи. Гугл ответа пока не дал.
#!/bin/bash
DIR='/test/test/test/conf/'
conf=${DIR}'nginx/test.conf'
echo $conf
В результате получаю ответ вида:
> nginx/test.conf/conf/
Как я понял символы второй строки просто перезаписывает символы первой, до тех пор, пока символы второй строки не закончатся. Но как заставить это работать как надо понять не смог.
Пробовал без скобок, с использованием плюса, соединять в двойных кавычках, и подобные способы.
P.S. Строки переписал под тестовые, на деле использую нормальный адрес, но проблема даже с этими строками сохраняется.
|
Для решения проблемы нужно каждую логическую строку закончить символом точки с запятой ' **;** '.
Прочитав комментарии понял что проблема кроется в одном или сразу всех далее следующих факторах.
Баг появляется если работать в **windows** , писать **скрипт в файле** , через ide, в данном случае netbeans, но возможно и фв других **ide** повторится, и запускать его через **cygwin** консоль, возможно так же повторится и в других подобных терминалах.
Пример рабочего скрипта.
#!/bin/bash
DIR='/test/test/test/conf/';
conf=${DIR}'nginx/test.conf';
echo $conf;
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "bash"
}
|
MODIS MOD11A2 does not update frequently its LST images?
I am working with the MODIS satellite, product MOD11A2, band LST_Day_1km. To access data I use the MODIS REST SERVICE.
With the following url I get the data from date 2020050 (2020-02-19) to date 2020071 (2020-03-11):
The product has a periodicity of 8 days but I only get one image, the request above returns me only data from day 2020-02-26 when it should return me also data from date 2020-03-05 (8 days after)
I searched in the documentation information about how often the data source is updated with the new data but I can't find anything and it is strange than it takes more than 16 days to add a date.
|
I did a little check on Google Earth Engine and get the same result as you, but get two images if I shift the year to 2019 as expected. I think you are just too early. The 8-day periodicity starts from the image date (as per the documentation the dates do not cross a year end and the 1st of January starts a new period - confirmed by the presence of images for 2019-01-01 and 2020-01-01). So the 2020-03-03 image has only just completed its 8 days (today only being the 11th) so it is not really 16 days late at all but "on-time" as it could not have been composited before the end of today. I expect it will be available tomorrow or soon after.
|
stackexchange-gis
|
{
"answer_score": 3,
"question_score": 1,
"tags": "modis"
}
|
What in the world is .WORLD on the end of a database identifier?
Sometimes I see Oracle databases with names like `SOMEDB` and other times I see `SOMEDB.WORLD`. I can use them interchangeably with no apparent differences. What does the `.WORLD` part mean? Does `WORLD` have any specific meaning, or is it just an arbitrary string that happens to be used? I've seen other extensions also.
|
It's default value of `DEFAULT_DOMAIN` setting in `sqlnet.ora`.
It is supposed to be replaced by your organization's domain, but the admins often leave it as is.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "oracle"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.