INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to Open Addressbook New Contact Screen
In my application I have `UIBarButtonSystemItemAdd` on right side of the navigation controller. On tapping of that plus icon I want to open address book in editable mode. Please refer the following image.
How to open address book UI for new contact in editable mode directly?
!enter image description here
|
In the `AddressBookUI.framework`, there is a class called `ABNewPersonViewController`. Basically, what you want to do is this:
ABNewPersonViewController *abnpvc = [[ABNewPersonViewController alloc] init];
[abnpvc setNewPersonViewDelegate: self];
[self presentViewController: abnpvc animated: YES completion: nil];
This brings up the view you are looking for.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "addressbook, abaddressbooksource"
}
|
Import Certificate to Machine\personal script/automation?
Is there a automated way to perform this task:
I need to import a PFX certificate to computer / personal path on multiple IIS 7.5 servers (Windows Server 2008 R2).
I already tried with GPO but there is no way to import personal certificate using GPO.
Thanks !
|
certutil -f -p <password> -importpfx <filePathToPFX>
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iis, iis 7.5, certificate"
}
|
Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?
I am using Xcode in a newly created app and when I run the project it does not show in the iOS Simulator and I get the following message:
> Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?
I've Googled about it of course and everybody points out that this is happening because Xcode does not know yet which view controller is the initial one. But the weird thing is that I created the app as a page based (also tried single-view and tabbed app options) app and Xcode already had defined a Storyboard for it.
Also, when I go to the main interface option of the project the storyboard (named "Main" by Xcode itself) is set, and in the Storyboard, my view controller is set as the "Initial View Controller"
!Is Initial View Controller
What is wrong?
|
So this also happened to me too. I checked 50 times and my "Is Initial View Controller" was checked, believe me. It happened out of the blue. So how did I fix it?
1. Create a new Storyboard in your project, name it something like Main_iPhoneV2 (or iPadV2 depending on your original storyboard style)
2. Open the broken storyboard, click anywhere in the white area and press command-a, then command-c (select all and copy)
3. Open your new storyboard and press command-v to paste the same exact setup
4. Go to your project settings, change your "Main Interface" to the new Main_iPhoneV2 (If it's your iPad and you're writing a universal app, you'll have to edit the -Info.plist and look for the value "Main storyboard file base name (iPad)
5. Recompile, and stop pulling your hair out
|
stackexchange-stackoverflow
|
{
"answer_score": 57,
"question_score": 102,
"tags": "ios, iphone, objective c, xcode, xcode5"
}
|
Make Application available via Facebook only
I've an application at < and I want this application to be available only via facebook at <
In short, I want the application to be available only via facebook. Does someone know how to do this??
|
Yes its possible. Have a look at the following example:
<
It will redirect the user each time he is calling the application out of facebook. The Trick is to handle with the Referer's, Facebook Linter calls etc.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "facebook, facebook apps"
}
|
How can I make css generate an ellipsis on text overflow?
I'm working with this jsfiddle. I would like the `<p>Super long words here</p>` to look like `Super lon...` instead of showing the full text. I tried adding
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
But it didn't work. How can I get my overflow text to end in an ellipsis?
|
You have to specify a width to achieve this effect, like this:
.pClass p {
margin: 0 !important;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width:20px;
}
**Fiddle**
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, css, ellipsis"
}
|
sysconf(_SC_CLK_TCK) vs. CLOCKS_PER_SEC
I was wondering what is the difference between the return value of the aforementioned constants.
`sysconf(_SC_CLK_TCK)` returns `100`
`CLOCKS_PER_SEC` returns `1,000,000`
So, suppose that I have this:
...
start = clock();
// Process starts here
/* does something */
// Process ends here
end = clock();
double time = ((double) end-start)/CLOCK_PER_SEC; // this would return in seconds
...
How do I calculate the amount of ticks used by the process, instead of the time? Do I use time used against `sysconf(_SC_CLK_TCK)` or `CLOCK_PER_SEC`?
I am trying to understand the usage of those.
|
As per the documentation, `clock()` returns time in resolution of `CLOCKS_PER_SEC`.
Other time functions return values with resolution in _ticks_. `sysconf(_SC_CLK_TCK)` provides the number of ticks per second. One such time function is `times()`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 5,
"tags": "c, linux, time, process, clock"
}
|
Erro com ponteiro -Wint- conversion ?? Int para int *
#include<stdio.h>
#include<stdlib.h>
int *a;
int b;
int main()
{
b = 5;
*a = &b;
printf("%x \n",a);
printf("%d",*a);
printf("\n %d",b);
return 0;
}
Na saída do código aparece esse erro :
>
> ponteiros.c: In function ‘main’:
> ponteiros.c:13:8: warning: assignment to ‘int’ from ‘int *’ makes integer from pointer without a cast [-Wint-conversion]
> *a = &b;
>
|
O formatador para um ponteiro é o `p` e não o `x`:
#include <stdio.h>
int main() {
int b = 5;
int *a = &b;
printf("%p\n", a);
printf("%d\n", *a);
printf("%d", b);
}
Veja funcionando no **ideone**. E no **repl.it**. Também coloquei no **GitHub** para referência futura.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c, ponteiro"
}
|
Implement function call after user taps on screen rhythmically
Have a question, would like to implement a function call, wherein the user taps the screen in a rhythm like Morse Code, then we can execute the function.
(building a little easter egg thing) Would be building this for both IOS and Android
Have absolutely no clue where to even begin. For IOS I'd start with a gesture tap recogniser...
If registering the morse code thing is too much work, a preset number of taps before the function is executed would be easier to implement I imagine. For example the user taps a spot on the screen 15 times or something like that.
Does anyone have any suggestions? Then I can start googling in the right direction.
Thanks in advance!
|
There is absolutelly no mistery...
you will have an list of touch timestamps and for every time users taps the desired item you add one more
public void onClickListener(){
rhythm.add(System.currtentTimemillis());
if(findPattern(rhythm))
doEasterEgg();
}
how you will detect a pattern in the intervals you decide... but morse code shall be way more simple than detect musical rhythm.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "java, android, ios, swift"
}
|
CasperJS - Click button based on value stored in variable
Based on the input variable "feeling", I would like to click a button (good,bad or ok). How do i specify the input variable in casper.click?
var feeling = 'bad'; //User can choose good, bad or ok
.
.
logit_feeling(feeling); //fucntion call
.
.
// fucntion defnition
var logit_feeling = function (feeling){
casper.then(function (){
casper.click(x('//*[text()='feeling']'));
});
}
|
You have to properly quote and build the string that you would pass to the XPath helper:
x('//*[text()="'+feeling+'"]')
Oftentimes HTML is written with a lot of whitespace which is not shown when it is rendered. You would need to make this a little more robust:
x('//*[contains(text(),"'+feeling+'")]')
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, casperjs"
}
|
Rename endpoint in AWS Api Gateway and keep backward compatibility
I have an API deployed on AWS with API Gateway, and everything is in the plural form, except one route, `/user`, like:
`
* How can I rename it to `/users`
* And create a redirection from `/user` to `/users`
I will delete later the redirection, but I need to wait that the latest release of my App on the Stores is deployed for 100% of end users.
|
You should not perform a redirection, you may lose authentication headers and if its a post request the body contents will not be redirected.
You have 3 choices:
* Keep the 2 as they are now, then once the app has been fully updated in the future then remove it.
* Replace the `/user` endpoint to forward to a Lambda function that will perform the request against the API Gateway endpoint again.
* Replace the `/user` endpoint to use `http_proxy` to forward the request back to the same API Gateway endpoint.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "amazon web services, rest, aws api gateway"
}
|
K-Means, how to access points in a cluster?
Let's say we have a K-means init with 5 clusters. Cluster 0, Cluster 1, Cluster 2, Cluster 3, and Cluster 4.
We insert 100 points each that should fit into all 5 of these clusters.
If we predict something that lands in Cluster 3. How can we get all the points in Cluster 3? Is there a method to retrieve an array of all the points that landed in Cluster 3?
|
The **_labels__** attribute holds the corresponding cluster index of each data point (sklearn documentation). Using this data you can establish your desired linking.
See this thread for a possible solution.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, machine learning, scikit learn"
}
|
What algorithm does table.sort use?
I'm curious what algorithm Lua's default `table.sort` uses, only because it's slower than some other sorting algorithms I've come across. I'm also curious if Lua's `table.sort` is written in the Engine in C, or if it's in a library in Lua.
|
> What algorithm does table.sort use?
The comment in `tablib.c` (scroll up a bit) states
/*
** {======================================================
** Quicksort
** (based on `Algorithms in MODULA-3', Robert Sedgewick;
** Addison-Wesley, 1993.)
** =======================================================
*/
You can read the source code at the link I provided.
> I'm also curious if Lua's table.sort is written in the Engine in C, or if it's in a library in Lua.
At this time, all libraries that come directly with Lua (`io`, `table`, `math`, ...) are written in C.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 5,
"tags": "sorting, lua, lua table"
}
|
Sql Server subscription agent in running state
We have a snapshot replication setup with push subscription. Now we have setup a second subscriber. We followed below steps: a) Run snapshot agent - completed. b) Run the old distribution agent - completed. c) Run the new distribution agent to another database - running. The snapshot agent for this new subscription is still in running state. More details in replication shows the message "Delivered snapshot from unc/...' , 'No more replicated transactions are available'. Checked the new secondary database the data is getting replicated. Now why the agent status is still in running state ? Do we continue to wait for it to complete, because its been over 4 hrs the state has not changed also no new message in the replication monitor.
Server configuration: Publisher -- Sql server 2008 R2 ; Old subscriber = sql server 2005 ; new subscriber = sql server 2012
|
The issue was with one extra parameter in the distributor job agent '-Continuous'. This was causing the distributor agent to remain alive even after finishing the replication job. On removing this parameter the job agent would finish replication and end instead of continuous polling.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql server, transactional replication"
}
|
Continuity of $f(x)=x \cdot g(x)$ on $\mathbb{R}_{\geq 0}$ where $g(x)$ has a positive upper bound
I am trying to prove continuity of $f(x)=x \cdot g(x)$ where $g(x)$ has the positive upper bound $\bar c$. This means that the upper bound of $g(x)$ does not depend on $x$. Furthermore, it is known that $x \geq 0$ and $g(x) \geq 0$.
I have tried different approaches (Lipschitz definition, espilon-delta definition) but I am not sure if $f(x)$ is continuous on $\mathbb{R}_{\geq 0}$.
Is this an obvious case of continuity/discontinuity?
I am glad if someone can give me a hint
|
Take $g \equiv \chi_\mathbb{Q}$, that is
$$ g(x) = \cases{1 \text{ if $x$ is rational} \\\ 0 \text{ otherwise}} $$
Now, $f(x) = xg(x)$ is not continuous. Can you see why?
A proof follows,
> Take a sequence of rational numbers $(q_n)_{n \geq 1}$ that converge to $\sqrt{2}$. Now, we have that $f(q_n) \equiv 0 \not \rightarrow \sqrt{2} = f(\sqrt{2})$, and so $f$ is not continuous.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "real analysis, continuity"
}
|
If $\|Ax\|\equiv\|x\|$, then $(Ax)\cdot(Ay)\equiv x\cdot y$
I am trying to solve this problem:
> Let A be a complex square matrix. If $\|Ax\|=\|x\|$ for every vector $x$, then $(Ax)\cdot(Ay)=x\cdot y$ for every pair of vectors $x$ and $y$.
Solution: $$\operatorname{Re}(x\cdot y)=\frac12(\|x+y\|^2 - \|x\|^2 - \|y\|^2).$$ Hence $$\operatorname{Re}\left((Ax)\cdot(Ay)\right)=\operatorname{Re}(x\cdot y).$$ But I can't do anything about the imaginary parts.
|
**Hint**. Note that $\def\Im{\mathop{\rm Im}}\def\Re{\mathop{\rm Re}}$ $$ \Im(X\cdot Y) = -\Re(iX \cdot Y) $$ Now use what you have proved on $iX$ and $Y$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linear algebra, matrices, complex numbers"
}
|
Entropy and Clausius inequality
From the Clausius inequality we can derive that the efficiency of a Carnot (reversible) cycle is given by: $$e= 1 - \frac{T_c}{T_h}$$
Is this true for every reversible cycle? Is the efficiency of all reversible cycle equal to the efficiency of a Carnot Cycle? If not, what is responsible of this difference? (Is it due to the fact that the temperature are not the same throughout the whole cycle as they are during the isothermal transformation of the Carnot cycle?)
|
> Is this true for every reversible cycle? Is the efficiency of all reversible cycle equal to the efficiency of a Carnot Cycle?
Yes. They are indeed.
The equality in Clausius' Inequality $$\oint \frac{đq_\textrm{sys}}{T_\textrm{source}}=0$$ is strictly valid for **all _reversible_** cycles.
Temperature of a reversible engine is at all times equal to the temperature of the heat sources that it is in contact with.
Thus, the entropy of the universe would be zero always when the cycles are reversible and that means efficiency of all reversible cycles would be the same viz.
$$e~=~ 1-\frac{T_\mathrm C}{T_\mathrm H}\;.$$
As summed up by Fermi in his lectures:
> If there are several cyclic heat engines, some of which are **reversible** , operating around cycles between the same temperatures $t_1$ and $t_2,$ **all the reversible ones** have the **same** efficiency, while the nonreversible ones have efficiencies which can never exceed the efficiency of the reversible engines.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "thermodynamics, entropy, reversibility, carnot cycle"
}
|
Detect when input focuses
**_Sorry if this has already been asked, but all the results I've found use jQuery._**
I have the following code:
<script>
var nameBox = document.getElementById('name');
if(nameBox == document.activeElement) {
console.log('name element focused')
}
</script>
But, nothing gets logged to the console when I click on the input. What am I doing wrong? (I would like to do this without jQuery)
|
In your case you are detecting if the element is active during the script's run, so you get false. After it you don't have any detectors. So you need to use `addEventListener()` function and add handler for `focus` event. It will fire when element is focused.
document.getElementById('inp').addEventListener('focus', function(){
console.log('Focused');
});
<input id="inp" />
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript"
}
|
en el orden de jerarquia matematica me da 410 y en la compilacion del codigo me da 400 cual debe ser el error?
#include <iostream>
#include <conio.h>
using namespace std;
main()
{
double x = ( 4 * 5 * ( 7 + ( 9 * 3 / ( 2 ) ) ) ) ;
cout<<"el resultado de x es: "<<x;// el resultado es 400
getch();
}
|
Todas tus operaciones son con enteros, con lo cual todos los resultados son enteros.
Eso significa, que al dividir `27 / 2` obtendrás `13` (`13.5` no es un entero). Así:
* 9 * 3 = 27
* 27 / 2 = 13
* 7 + 13 = 20
* 20 * 20 = 400
Lo más sencillo es convertir algún número (lo más interno que tengas), a punto flotante, eso hace que la aritmética pase a ser con punto flotante.
Por ejemplo, pasas `3` a `3.0`, y te queda:
* 9 * 3.0 = 27.0
* 27.0 / 2 = 13.5
* 7 + 13.5 = 20.5
* 20 * 20.5 = 410.0
Otra opción es asegurarte de que los divisores son siempre números flotantes, ya que la fuente del error es el usar la división entera en vez de la división en plunto flotante.
|
stackexchange-es_stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "c++, dev c++"
}
|
MySQL query check two value in one column
I am writing one query where I have 4 types in column
Xtype
-----
P
C
D
R
I want to check where `Xtype=P` and `Xtype=D` so how can I use both for the same column? I know I can use for different column using `WHERE id=1 AND status=online` but not sure how to check two value for the same column
|
You can use `WHERE .. IN` like this:
WHERE XType IN ('P','D') -- checks whether the Xtype is P or D
Which incidentally gets expanded into OR:
WHERE (XType = 'P' OR Xtype = 'D')
If you want to check whether that column contains records for both 'P' and 'D' then you could use a EXISTS & sub-query:
WHERE EXISTS (SELECT 1 FROM TableName WHERE Xtype = 'P')
AND EXISTS (SELECT 1 FROM TableName WHERE Xtype = 'D')
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -2,
"tags": "mysql"
}
|
Do I need to install SQL Express to use an MDB in App_Data
If i have a server with ASP.NET 3.5 installed, where no one explicitly installed SQL Express. Can my web application still connect to an MDF file in the App_Data folder
|
No, you need SQL Express installed, see <
You could always deploy your DB to another server which has SQL Server installed though. Just have to also update connection string.
You can do this if you are using SQL CE 4 though, <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "asp.net, sql server express"
}
|
Spring CrudRepository same erasure
I have my own custom repository but when I try to override/use CrudRepository it gives me "both methods have same erasure, yet neither overrides the other". Please see below.
public interface MyRepository extends CrudRepository<Person, String> {
//<S extends T> S save(S entity); //Parent method
Person save(Person person);//It accepts this
//<S extends T> Iterable<S> saveAll(Iterable<S> entities);//Parent method
Iterable<Person> saveAll(Iterable<Person> persons);//But does not accept this. why can I not use/override this?
//This Gives error "both methods have same erasure, yet neither overrides the other"
}
|
Java generics work through the concept known as erasure, meaning that under the hood all generics get transformed into `<Object>`. This unfortunately is one of the limitations of Java making sure it is backwards compatible with code written before Java 5 and generics.
Compiler sees both methods with identical names and identical parameters. Just change the name of one of the methods from `saveAll` to `saveAllPeople` or whatever and it will work.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "java, spring, spring boot, spring data jpa, spring repositories"
}
|
Find common values in multiple arrays with PHP
I need to find common values in multiple arrays. Number of arrays may be infinite. Example (output from `print_r`)
Array1
(
[0] => 118
[1] => 802
[2] => 800
)
Array2
(
[0] => 765
[1] => 801
)
Array3
(
[0] => 765
[1] => 794
[2] => 793
[3] => 792
[4] => 791
[5] => 799
[6] => 801
[7] => 802
[8] => 800
)
now, I need to find the values that are common on all 3 (or more if available) of them.... how do I do that?
Thanx
|
`array_intersect()`
$intersect = array_intersect($array1,$array2,$array3);
If you don't know how many arrays you have, then build up an array of arrays and user `call_user_func_array()`
$list = array();
$list[] = $array1;
$list[] = $array2;
$list[] = $array3;
$intersect = call_user_func_array('array_intersect',$list);
|
stackexchange-stackoverflow
|
{
"answer_score": 58,
"question_score": 22,
"tags": "php, arrays"
}
|
Generating WPA/WPA2 Key in linux bash?
How can I generate a new random wpa/wap2 key in the linux terminal? I tried pwgen but this is not generating hexadecimal values.
|
For instance, if you want a password with the maximum character length, i.e. 63, you can enter either of the following 2 commands:
1. `makepasswd --chars=63`
2. `openssl rand -base64 63`
**UPDATE:**
Here is a better command I've found for this purpose since I first wrote this answer:
dd if=/dev/urandom bs=48 count=1 status=none | base64 | tr +/ -_
Actually I use this zenity-powered script to generate such a password from time to time:
#!/bin/bash
RNDPWD="$(dd if=/dev/urandom bs=48 count=1 status=none | base64 | tr +/ -_)"
echo $RNDPWD | tr -d '\n' | xclip -i -selection clipboard
zenity --question --title="Random Password" --text="<i>Password Copied to Clipboard:</i>\n\n$RNDPWD\n\n<b>Would you like to generate another one?</b>" --width=500 --height=150
if [ $? = 0 ]
then
"~/.bin/Password-Generator-GUI"
fi
|
stackexchange-askubuntu
|
{
"answer_score": 3,
"question_score": 2,
"tags": "wireless, security, wpa2, wpa"
}
|
How to simulate java socket connection break?
I have written java application that makes socket connections with a legacy system.
How can I simulate the connection failure _(Eg Socket connection timeout, read timeout, network failure)_ , so that i can add necessary code based on the exception trace ?
|
Use a mock framework such as Mockito or EasyMock, mock a Socket object.
Look at the Javadoc for Socket and make your mocked object fail at some point with an Exception thrown by it in your unit tests.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "java"
}
|
Replacing elements with lxml.html
I'm fairly new to lxml and HTML Parsers as a whole. I was wondering if there is a way to replace an element within a tree with another element...
For example I have:
body = """<code> def function(arg): print arg </code> Blah blah blah <code> int main() { return 0; } </code> """
doc = lxml.html.fromstring(body)
codeblocks = doc.cssselect('code')
for block in codeblocks:
lexer = guess_lexer(block.text_content())
hilited = highlight(block.text_content(), lexer, HtmlFormatter())
doc.replace(block, hilited)
I want to do something along those lines, but this results in a "TypeError" because "hilited" isn't an lxml.etree._Element.
Is this feasible?
Regards,
|
Regarding lxml,
In `doc.replace(block, hilited)`
**block** is the lxml's Element object, **hilited** is string, you cannot replace that.
There is 2 ways to do that
block.text=hilited
or
body=body.replace(block.text,hilited)
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 10,
"tags": "python, lxml"
}
|
In a metric space X, if A is connected, is its interior connected?
I believe that int(A) is also connected. I tried to use an argument by contradiction, that is to say I supposed that int(A) is not conneted, but without success
|
How about this? Two closed disks tangent to each other at a point.
. very new with svelte and very excited.
I found some code in stackoverflow, which worked for v2. Here is the link
<button on:click="loadChatbox()">
chat to a customer service representative
</button>
{#if ChatBox}
<svelte:component this={ChatBox}/>
{/if}
<script>
export default {
methods: {
async loadChatbox() {
const { default: Chatbox } = await import('./Chatbox.html');
this.set({ Chatbox });
}
}
};
</script>
|
The same functionality exists in Svelte 3, but you only need to assign the dynamically imported component to a regular variable that you use for the `this` property on the `svelte:component`.
**Example (REPL)**
<!-- App.svelte -->
<script>
let Chatbox;
function loadChatbox() {
import('./ChatBox.svelte').then(res => Chatbox = res.default)
}
</script>
<button on:click="{loadChatbox}">Load chatbox</button>
<svelte:component this="{Chatbox}" />
<!-- ChatBox.svelte -->
<h1>Dynamically loaded chatbox</h1>
<input />
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 7,
"tags": "svelte"
}
|
PREG_REPLACE if string ends with char X, then the last X character replace it with a Y character
If a string ends with the `character X`, i want to replace that particular character with the `character Y`.
**Example 1**
anything_number_alphabet_dashes_anythingX[END OF STRING]
to
anything_number_alphabet_dashes_anythingY[END OF STRING]
**Example 2**
DontReplaceThis_X_JustOnlyThisLast_X[END OF STRING]
to
DontReplaceThis_X_JustOnlyThisLast_Y[END OF STRING]
I want to do this in PHP with `preg_replace` or `ereg_replace`.
|
Dollar sign is the end of string anchor, so:
$new_str = preg_replace('/X$/', 'Y', $old_str);
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 1,
"tags": "php, regex"
}
|
Добавление в ListBox StackPanel'ов программно
Есть приложение, которое генерирует текстовые значения. Есть ListBox, в который эти значения нужно выводить, но не только значения, но еще и определенный значек, им соответствующий, который должен помещаться слева от них. Вот пример того, что должно добавляться в ListBox:
<StackPanel Orientation="Horizontal">
<Image Source="Examplesource.jpeg"/>
<Label Content="Сгенерированный текст" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
Как это сделать программно?
* * *
P.S Если кто-либо подскажет более удобный способ сделать это, то буду не против.
|
Используйте ItemTemplate и DataTemplate у ListBox для формирования разметки элементов. Шаблоны позволяют настроить практически любой вид для содержимого.
<ListBox ItemsSource="{Binding КоллекцияЭлементов}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="Examplesource.jpeg"/>
<Label Content="{Binding СвойствоСгенерированногоТекста}" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, wpf"
}
|
Setting User ID for Google Universal Analytics
I'm trying to set the User-ID for Google's new Universal Analytics, but it keeps erring saying " SyntaxError: Unexpected token '{' ".
Here is my code;
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto');
{if logged_in}
ga('set', '&uid', {{{member_id}}});
{/if}
ga('send', 'pageview');
</script>
I have tried this with $env_config['protect_javascript'] = 'y' and $env_config['protect_javascript'] = 'n';.
|
Why do you have 3 sets of parenthesis around the member_id tag?
Does it work if you simply use {member_id}?
**EDIT** (after comments) I'm not completely sure how this should be set up as I've never used this (will need to get up to speed on it though) but based on what I see in the docs does this work;
{if logged_in}
ga('create', 'UA-XXXX-Y', { 'userId': '{member_id}' })
{if:else}
ga('create', 'UA-XXXXXXXX-X', 'auto');
{/if}
I'm not sure why the docs show UA-XXXX-Y for the user ID section.
|
stackexchange-expressionengine
|
{
"answer_score": 2,
"question_score": 1,
"tags": "members, javascript, analytics, google analytics"
}
|
The requested URL /practice/public/admin was not found on this server
My url i.e. localhost/practice laravel's default method 'welcome' working perfectly which is in routes.php file
Route::get('/', function () {
return view('welcome');
}
);
whereas in case if just wants to access anything on the same url via routes.php say eg:
Route::get('/admin', function () {
//return view('welcome');
return "Admin URL.";
}
);
Then the following below mentioned error occurs.
> The requested URL /practice/public/admin was not found on this server. Apache/2.4.23 (Ubuntu) Server at localhost Port 80 Not Found
|
try calling the following url in your case
localhost/practice/public/index.php/admin
maybe some route issue..
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, linux, url, laravel 5, routes"
}
|
How to make an id field in SQL Server?
I want to make a field, which will be automatically filled, and stay unique.
More explanation: I have an ID field, which should be filled by my program not the user, and is my primary key.
How may I do it in SQL Server?
I'm using Visual Studio 2010
|
On your ID column, set "identity" to yes and set the "seed" to 1.
Enjoy!
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "sql server, visual studio 2010"
}
|
Matplotlib: how to increase the area saved without increasing the figure size
Currently the area of the figure that gets saved by is fixed, so if I have the legend outside the figure, it gets cropped off, like that:

> `bbox_inches`:
>
> Bbox in inches. Only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure.
### Example
plt.plot(range(10))
plt.legend(['abc'], loc='upper right', bbox_to_anchor=(1.2, 0.9))
results in this png:

SELECT color_value, COUNT(color_value) FROM db GROUP BY color_value
For the second one (return 3 most used colors) :
SELECT color_value FROM db GROUP BY color_value ORDER BY
COUNT(color_value) DESC LIMIT 3
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "mysql"
}
|
Trace norm of a matrix
Let $A$ be a matrix in $SL_2(\mathbb R)$. Define the trace norm to be
$$\|A\| = \sqrt{\mathrm{tr}(A^* A)}. $$
Is it true that this norm satisfies some kind of multiplicative property; for example:
$$\|AB\| \leq \|A\|\cdot\|B\|.$$
Can someone give me a brief reference where basic properties of this norm are stated and proved?
Thanks.
|
As I said in my comment, this is also (and perhaps more commonly) called the _Frobenius norm_. The argument in the PDF that alex and I mentioned, showing that $\|AB\\}\le\|A\|\cdot\|B\|$, also shows that the Frobenius norm of an $m\times n$ matrix $A$ is simply the ordinary Euclidean $2$-norm of $A$ (given by the Pythagorean theorem) if you think of $A$ as a vector in $\mathbb{R}^{mn}$, say be reading it out by rows. Thus, the basic properties of the Frobenius norm follow immediately from those of the $2$-norm.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "matrices"
}
|
Java: What does subtracting a char by a char mean?
Recently while going through a program I ran into a question. Below is part of the program
public static int numberNeeded(String first, String second) {
int[] lettercounts = new int[26];
for(char c : first.toCharArray()){
lettercounts[c-'a']++;
}
I don't understand what this line of code does:
lettercounts[c-'a']++;
I guess that it's incrementing the value (which is initially 0) in lettercounts array for the particular character; I'm guessing index of 'a' is 0 and 'z' is 25. But I want to understand how that little piece of code works.
|
The goal is count the occurrences of each character.
c - 'a'
is a kind of clever way to get the position of the character in the alphabet. `'a' - 'a'` would give you 0. `'b' - 'a'` would give you 1. `'c' - 'a'` would give you 2, and so on.
That value is used as an index into the array (which as you correctly stated is initialised with zeros) and the count is incremented.
* * *
It's worth noting that this will break if any character other than `a-z` is present in the string (including uppercase characters), and you'd see an `IndexOutOfBoundsException`
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 4,
"tags": "java, arrays"
}
|
Can the DM change his/her mind after a player has rolled?
I'm new to D&D, and have been participating in adventures that are meant to be completed within a single night.
Last weekend, the DM requested that I make a Sleight of Hand check for an action that I wanted to perform. I rolled a 19, and the DM became visibly annoyed. After a pause, the DM said, "Actually, roll at a disadvantage, because [x] is currently happening."
I immediately thought it was unfair, but I didn't want to object, because I've only showed up to a couple of these weekend sessions. So I rolled again and had a critical miss, which pleased my DM and (obviously) annoyed me.
Question: Can a DM change their mind on the requirements for a roll **after** the roll has already been made?
|
### Can a DM change their mind on the requirements for a roll after the roll has already been made?
**Yes** ; they're the DM, there really isn't anything you can do to force the DM to accept the original roll.
### _Should_ a DM change their mind on the requirements for a roll after the roll has already been made?
**No** ; especially not when it was a good roll - that's just dirty pool. If the DM forgets something as simple as advantage/disadvantage or an ad hoc modifier, they should gracefully accept the "DM error in player's favor" and keep going.
In ages past, the player-DM relationship was often adversarial; this is no longer the general case in modern gaming. The only person the DM should have an emotional response towards is themselves. They should not play favorites, either between the players or between the players and NPCs.
|
stackexchange-rpg
|
{
"answer_score": 126,
"question_score": 55,
"tags": "dnd 5e, problem gm"
}
|
How to print html without breaks using python, beautifulsoup?
im trying print html using beautifulsoup like this:
load = urllib2.urlopen(url)
soup = BeautifulSoup(load, 'lxml')
characteristics = soup.find('table', { 'class' : 'characteristics-table'})
print characteristics
Get this:
<table class="characteristics-table">
<tr class="characteristics alt">
<td class="name">
Zīmols
</td>
<td>
Emporio Armani</td>
</tr>
<tr class="characteristics">
<td class="name">
<b>Mehānisma tips</b>
</td>
<td>
<b>Mehāniskie automātiskie</b></td>
</tr>...
But need something like this:
<table class="characteristics-table"><tr class="characteristics alt"><td class="name">Zīmols</td><td>...
How to do it?
|
''.join(characteristics.split('\n')) #or \r\n on Windows
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, beautifulsoup"
}
|
Setting background image of a ListItem created using ListAdapter for a while in Android
I would like to set background image or a list item when selected or pressed and then back to normal state, just like a normal listview works.
I have created list using custom listadapter.
Cheers, Prateek
|
You can use StateListDrawables in Android for this.
This post includes some sample code.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, listview"
}
|
Mysql login via CLI on Linux with complicated password
So I trying to login to mysql on Gentoo with the following syntax
mysql --user=myUsername --password=passWord
However, my password is something like this
2k*`pI5G=BT86/5\"[]DBdTCo
I am wondering what characters I should escape in order to login.
Thanks.
|
No clue why but it works this way.
touch myfile.txt
inside [myfile.txt]
[mysqld]
user=the username
password=the password
and voila, `mysql --defaults-extra-file=myfile.txt` works like a charm ... Don't know why it doesn't work with stdin as others have suggested though ...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, linux"
}
|
How to prove D70 = {1, 2, 5, 7, 10, 14, 35, 70} is a Boolean algebra
Prove that the set $D_{70}$ = {1, 2, 5, 7, 10, 14, 35, 70} of positive factors is a Boolean algebra under the operation (+), (.), (') defined by $$x + y = lcm(x, y)$$ $$x . y = gcd(x, y)$$ $$x' = \frac{70}{x}$$
Attempt: To Prove $D_{70}$ is a boolean algebra we have to satisfy below 4 properties of boolean algebra
1. `+` & `.` are commutative.
2. `+` is distributive over `.` and vice versa.
3. $\exists$ two distinct identity element 0, I for ($D_{70}$, +) and ($D_{70}$, .) respectively.
4. $\forall a \in D_{70}$, a + a' = I & a + a' = 0
Property 1: Satisfied since lcm, gcd are commutative
Property 2: ?
Property 3: I = 70, 0 = 1
Property 4: Satisfied
I'm having trouble proving the `Property 2` can anybody help.
|
Let $x=\prod_{i=1}^{k}p_{i}^{r_{i}}$, $y=\prod_{i=1}^{k}p_{i}^{s_{i}}$ and $z=\prod_{i=1}^{k}p_{i}^{t_{i}}$ for primes $p_{i}$ and nonnegative integers $r_{i},s_{i},t_{i}$ for $i=1,\dots,k$. Then:
$$x.(y+z)=\gcd\left(x,\text{lcm}\left(y,z\right)\right)=\prod_{i=1}^{k}p_{i}^{\min\left(r_{i},\max\left(s_{i},t_{i}\right)\right)}$$
$$x.y+x.z=\text{lcm}\left(\gcd\left(x,y\right),\gcd\left(x,z\right)\right)=\prod_{i=1}^{k}p_{i}^{\max\left(\min\left(r_{i},s_{i}\right),\min\left(r_{i},t_{i}\right)\right)}$$
It remains to prove that in general: $$\min\left(r,\max\left(s,t\right)\right)=\max\left(\min\left(r,s\right),\min\left(r,t\right)\right)$$ Can you do that?
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "abstract algebra, boolean algebra"
}
|
given a definition of node, calculate the sum of the nodes in binary tree
class Node{
int value;
List<Node> childNodes;
}
Above is the definition of the Node, and I have no idea how to implement the sum of the binary tree.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
However, I can understand this version of node and the sum of nodes of binary tree can be implemented by recursion.
* * *
public static int sumTree(Node root) {
int sum = 0;
if (root == null) {
return 0;
}
// Line 1
for (int i = 0; i < root.childNodes.size(); i++) {
sum = sum + root.childNodes.get(i).value + sumTree(root.childNodes.get(i));
}
return sum;
}
Actually, this is a tree instead of binary tree. This is my code
|
public int sum(Node root) {
if (root == null) {
return 0;
} else if ( root.childNodes == null) {
return root.value;
}
int sum = root.value;
for ( Node child : root.childNodes ) {
sum += sum(child);
}
return sum;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, recursion, binary tree, binary search tree, treenode"
}
|
Length of each vector in a list, then add into a vector (R)
I have a list like so:
s <- list(
a = c(2, 32, 949),
b = c(3, 19, 564, 23),
c = c(4, 34)
)
And you can get the length of each vector in the list:
length(s[[1]])
[1] 3
length(s[[2]])
[1] 4
length(s[[3]])
[1] 2
I want a single vector containing the length of each vector in order, which you can do manually like so:
vec <- c(length(s[[1]]),length(s[[2]]),length(s[[3]]))
vec
[1] 3 4 2
How do you make a function which takes the list (s) as an argument and returns the vector of lengths (vec)?
|
I don't know where those numbers, 3, 4, 2, came from. An way to get a vector as they way you want is by applying `sapply` combined with `as.vector`:
as.vector(sapply(s, length))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, list, vector"
}
|
UITableView is not showing inside a UIScrollView
I have in my View a long UIScrollView (about 1000 px in height), and at the end of this UIScrollView I have a UITableView.
The cellForRowAtIndexPath is never called (surely i checked the delegate and datasource if they are connected right, and the IBOutlet of the table is strong) but numberOfRowsInSection is getting called.
I tried reloading the TableView when the UIScrollView scrolls so when the table is at focus the cellForRowAtIndexPath might get called, but with no luck.
Did anyone encounter a similar behaviour when trying to use tableview and scrollview together?
|
Your hierarchy is like this:
A parentView is there. Inside the parent view there is a scroll view and there is a table view. So, your tableview is somewhere at 1000 from origin of parentview.
So, tableview will never become visible to your parentview and no delegates will be fired.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ios, uitableview, uiscrollview"
}
|
Rolling forward the archivelog and online redo logs to the restored database
I'm currently using Oracle db11g on Red Hat Enterprise Linux 5.0. I make an incremental level 0 one time a week and incremental level 1 everyday. I can restore this backup on my new Linux server without any problems because I have all archive logs generated after level 1 backup.
However, if online redo log is not yet filled (I mean that I have some redo info in the online log), how can I use this online log to roll forward to my restored database on the new Linux server? I don't want to lose the valuable information that is not yet archived.
Best regards, Sarith
|
1. Restore your backed up files.
2. Copy your current online redo log files (from the "damaged" production instance) to the new server.
3. RECOVER DATABASE;
This scenario assumes you have total continuity with archived logs and online logs. In doing the recovery, Oracle will apply necessary archived redo, then move to the online redo logs to recover to the point of failure. Important! Don't restore online redo logs from the backup you have! Use the current online logs from your crashed instance.
Finally, don't believe anything you read without practicing it for yourself!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "oracle"
}
|
Is it Possible to Cache the Result of my Custom ActionFilterAttribute?
I have an MVC website that uses AD authentication to display data for users that are also CRM 2011. The CRM Rights of the user are determined by their role in CRM, so currently the `OnActionExecuting` method gets the executing user's domain name, and queries CRM for their role. If they don't have a valid role, an invalid rights view is instead returned.
The call to CRM is slow and can get expensive if it has to happen for every request. I can see in the MVC 3 release notes that the filters are aggressively cached, but wasn't quite sure what that meant for me.
I'd like to be able to cache the rights of the user based on their domain name, but it sounds like that may already be happening?
|
If you are referring to following statement, I think you have understood this point wrong:
> In ASP.NET MVC 3, filters are cached more aggressively. Therefore, any custom action filters which improperly store instance state might be broken.
This does not mean, that the result of the filter is cached. It means that the filter itself will be cached and will be reused for multiple requests. It is comparable with CRM Plugins. You should not track state in it or if you do, you have to be careful to not enter the joys of concurrency.
In your case I would use for example MemoryCache to cache the roles/privileges of the user in memory for a period of time.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "asp.net mvc 4, dynamics crm 2011"
}
|
How to treat a shelved CL in Perforce as a patch?
Suppose I created a shelved change list (CL) numbered `2903395` on Monday. The change was never submitted, but other modifications were, and they touched the files of my CL.
On Tuesday, I want to apply the shelved CL and submit it:
p4 unshelve -s 2903395
But here's what happens: the changes to my file made by others are now discarded and my original change is applied. That's not what I want: I want my change to be applied on top of the changes made by others. How can I do that?
I'm coming from Git, so I'm thinking in terms of doing a `git format-patch` on Monday and `git am` on Tuesday.
|
No need to mess around with patching; Perforce handles this automatically! Do:
p4 unshelve -s 2903395
p4 sync
p4 resolve -am
When you `p4 unshelve` the files are restored to the state they were in when you `p4 shelve`d, including the "have revision" that tracks which depot revision they were based on -- only when you `p4 sync` does this get updated to reflect the newly submitted revisions, and then `p4 resolve` merges the changes in.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "perforce"
}
|
how to self-reference a class in Python?
I want this Template class to accept children of itself and other types with `type(i) in self._allowed_types`.
class Template():
_allowed_types = [str, Template, SafeHtml]
Above code throws this:
NameError: name 'Template' is not defined
|
Add the class after the class is defined:
class Template():
_allowed_types = [str, SafeHtml]
Template._allowed_types.append(Template)
The class body, by necessity, is run before the class object can be created, so the name `Template` is not defined _yet_. But you can always alter class attributes after the object has been created.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 3,
"tags": "python"
}
|
Setting management.endpoints.web.base-path to root when server.servlet.context-path is set
I'm trying to set the base path of the actuator to / so that PCF can access it.
I am Using SpringBoot 2.1.4
The applications all have configured context roots. Setting management.endpoints.web.base-path only changes the path relative to the application context root.
Is there a way to set the management path to root when there is an application context root? Or is there some way to hack SB2 so all requests to a path get routed to all my RequestMappings?
|
If by "so that PCF can access it", you mean Pivotal Apps Manager, and you are using a context path with your app then you need to apply this workaround.
That will allow you to use a context path with your app, but still expose the actuator endpoints so that Pivotal Apps Manager can consume them.
Hope that helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "spring boot, cloud foundry, spring boot actuator, actuator"
}
|
Exponents manipulation
When I type`(a^2)^s` Mathematica does not give me $a^{2s}$ instead it gives ${(a^2)}^s$. Is there a way to make it print $a^{2s}$.
It made some real difference where I wanted to compute
Sum[((n \[Pi]/T)^2)^-s, {n, 1, Infinity}]
vs
Sum[((n \[Pi]/T))^(-2 s), {n, 1, Infinity}]
In the first case it gave me $\sum _{n=1}^{\infty } \pi ^{-2 s} \left(\frac{n^2}{T^2}\right)^{-s}$ but in the second case it gave me $\pi ^{-2 s} \left(\frac{1}{T}\right)^{-2 s} \zeta (2 s)$
I had to take the s-derivative of the result so I would like to get the result like the second one.
So, my question:
Is there any Mathematica function which helps me make Mathematica evaluate the first command and give back me the result like that of the second one?
|
FullSimplify[Sum[((n \[Pi]/T)^2)^-s, {n, 1, Infinity}],Assumptions->{T>0}]
Take your First input and assume $T>0$, that gives you the same result as the second one.
|
stackexchange-mathematica
|
{
"answer_score": 3,
"question_score": 2,
"tags": "simplifying expressions, summation"
}
|
Получить значения из json
Есть обработчик.
$('.test').click(function() {
var test = [];
$(".inputs input").each(function(id) {
var screens = ("\"" + $(this).attr('id') + "\" : " + $(this).val() + ",");
test.push($(this).val());
});
$.ajax({
type: "POST",
url: "/ajax/test",
type: 'POST',
data: 'jsonData=' + $.toJSON(test),
success: function(data) {
alert(data);
$(".total_count").text(data.total_count + " шт.");
$(".sum").text(data.total_price);
$('#set_modal').reveal({});
},
error: function(data) {
console.log('error');
}
});
});
`success` Данные возвращаются в формате
{"total_count":21,"total_price":"3 655 106"}
Пытаюсь получить `data.total_count`, но оно не выводит. В чём проблема?
|
Добавьте настройку `dataType: 'json'` и сможете получить данные таким образом `data.total_count`
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery, ajax"
}
|
Regex in JS - Add match to replace
I can't find the solution to this anywhere, but I think it's because I don't have the terminology right.
I have this:
var text = "Foo:Bar"; // I want -> "Foo: Bar"
text = text.replace(new RegExp("Foo:[a-z]", "ig"), "Foo: ");
I have lots of `foo`s, and I want to add a space after the colons. I only want to do it if I can tell the colon has a letter right after it. However, when I do the above, I get:
// -> "Foo: ar"
How do I take that `[a-z]` match, and throw it into the end of the replace?
|
What you need is a positive lookahead assertion. `[a-z]` in your regex consumes an alphabet but a lookaround won't consume a character. `(?=[a-z])` this positive lookahead asserts that the match (`Foo:`) must be followed by an alphabet. So this regex will match all the `Foo:` strings only when it is followed by an alphabet. Replacing the matched `Foo:` with `Foo:<space>` will give you the desired output.
text = text.replace(new RegExp("Foo:(?=[a-z])", "ig"), "Foo: ");
OR
text = text.replace(/Foo:(?=[a-z])/ig, "Foo: ");
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, regex"
}
|
Google Cloud Endpoints in Android Studio: how to generate Endpoints class in a different package
One of the Google examples for building a java backend on Google App Engine which is accessed through Cloud Endpoints is to be found here: <
The backend module in the sample app is organized with the following packages:
com.google.sample.mobileassistantbackend.models —> Includes the Entity files
com.google.sample.mobileassistantbackend.apis —> Contains Endpoint files that expose REST APIs
In Android Studio you can automatically generate the Endpoints from the Entity classes. But by default an Endpoint class is generated in the SAME package than the Entity class.
QUESTION:
How can I configure Android Studio in such a way that from a class in the "models" packages the Endpoint class is generated in the "apis" package.
|
This is a good question. Currently there is no way to specify that but there should be.
In the meantime you can simply move the generated endpoint to your desired package after generation.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "google app engine, android studio, google cloud endpoints"
}
|
Remove colon in the caption of a figure if the caption is empty
One of my figures should not have a caption, only the normal numbering. To get this, I use this code:
\begin{wrapfigure}{l}{4cm}
\begin{center}
\includegraphics[width=3cm]{graphic.pdf}
\caption[Caption for the list of figures]{}
\label{fig:figureX}
\end{center}
\end{wrapfigure}
But now I get "Figure x.y:" as caption of my figure. How can I remove the ":", **if the caption is empty**? I found some solutions with renewcommand, but this changes the caption style in the whole document. I want to remove the colon only if the caption is empty. In any other case, it is good to have "Figure x.y: My Caption".
|
Just loading the `caption` package should solve this. It makes the colon a proper "separator", i.e. it only appears when there is something to separate.
\documentclass{article}
\usepackage{wrapfig}
\usepackage[demo]{graphicx}
\usepackage{caption}
\begin{document}
\begin{wrapfigure}{l}{4cm}
\begin{center}
\includegraphics[width=3cm]{graphic.pdf}
\caption[Caption for the list of figures]{}
\label{fig:figureX}
\end{center}
\end{wrapfigure}
\begin{wrapfigure}{l}{4cm}
\begin{center}
\includegraphics[width=3cm]{graphic.pdf}
\caption[Caption for the list of figures]{With caption}
\label{fig:figureX}
\end{center}
\end{wrapfigure}
\end{document}
!figures
|
stackexchange-tex
|
{
"answer_score": 46,
"question_score": 37,
"tags": "captions, punctuation"
}
|
What is the result set returned as?
So I have this stored procedure that queries a table and return a result set, but I am using that result set as a param for a store procedure that I execute inside my store procedure.
SELECT employeeID FROM employeeList where LastName = 'Zhou'
..... Some stuff .....
exec my_store_proc @employeeID = 'a comma separated string of employee ID'
Where `my_store_proc` has a param `@employeeID AS VARCHAR(8000) = '',`. I know I can use a cursor to traverse the result set and concatenate them into a comma separated string. But I was wondering **what is the result set returned from the select statement alone, does it have a data type?** I was hoping the answer would be a comma separated string already so that I can just set `employeeID = employeeID`. But my gut feeling says no.
|
As it is your SELECT produces a result-set, which is techically a table. But you can collect result of this SELECT into a comma separated Varchar:
DECLARE @sResult VARCHAR(8000)
SET @sResult = ''
SELECT @sResult = @sResult + ',' + CAST(employeeID as varchar(10))
FROM employeeList where LastName = 'Zhou'
SET @sResult = STUFF(@sResult,1,1,'')
Basically you declare a varchar variable then use a form of SELECT that collects values into a single string (assuming employeeID is an INT hence CAST)
Last line removes leading comma.
After that you can make a call
exec my_store_proc @employeeID = @sResult
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "sql, sql server"
}
|
What lint configuration to use to eliminate the warning : Invalid JSDoc tag name
I am using eslint to set up my node js project but I keep getting the following warnings:
}=\sqrt{-5\cos(x)\cot(x)}$$
One of the solutions is $$\cos(x)=-\frac23$$
The solution to this is divided into two sequences as follows, in order to make sure the final solution complies with the condition that $\sin(2x)\ge0$
=-\cos \theta\tag 1$$ Let, $$\cos \theta=x\iff \theta =\cos^{-1}(x)$$ Where, $\color{blue}{-1\leq x\leq 1}$
Then substituting the value of $\theta$ in (1), we get $$\cos (\pi-\cos^{-1}(x))=-\cos(\cos^{-1}(x))$$
$$\cos (\pi-\cos^{-1}(x))=-x$$ $$\pi-\cos^{-1}(x)=\cos^{-1}(-x)$$ $$\cos^{-1}(-x)=\pi-\cos^{-1}(x)$$
Hence, we have $$\cos^{-1}\left(-\frac{2}{3}\right)=\color{red}{\pi}-\cos^{-1}\left(\frac{2}{3}\right)$$
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 1,
"tags": "algebra precalculus, trigonometry"
}
|
Is there a way to format one line into multiple lines with continuation?
I have a long line like this below in Python:
patterns = re.compile(r'(^/afs|^/pkg|^/bin|^/dev|^/etc|^/usr|^/usr2|^/sys|^/sbin|^/proc)')
And then I tried and changed it to this format below. However, it does not work as expected anymore:
patterns = re.compile(r'(^/afs|\
^/pkg|\
^/bin|\
^/dev|\
^/etc|\
^/usr|\
^/usr2|\
^/sys|\
^/sbin|\
^/proc)')
I know Python is using indentation for syntax so probably this format would not work maybe? or is there a right way to format this in Python if there is?
|
If you want to keep everything in one single set of quotations you can use a docstring, that will remove the need for line breaks or multiple `r'^...'` symbols, i.e.
patterns = re.compile(r"""
...
""")
As described in the following post: How do I do line continuation with a long regex?
I generally find this approach more readable.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, python 3.x"
}
|
Doesn't ASP.Net MVC Differentiate URLs on number of arguments?
Somehow I had the impression that ASP.Net differentiates URLs based on the number of arguments too. But it doesn't seem to work in my project.
Consider the following function prototypes
public PartialViewResult GetMorePosts(string param1, string param2, string param3, int param4, int param5) AND public PartialViewResult GetMorePosts(string param1, string param2, string param3, int param4)
I thought if my URL had one extra argument it should resolve to the second function... Instead I am getting an ambiguous URL error.
Why?
|
You need to make sure that the route table has the url wit the least arguments first, otherwise the one with more arguments will hide the rest.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "asp.net mvc, url routing, asp.net mvc routing"
}
|
phpExcel does not render borders
I'm trying to get phpExcel to draw a border around a bunch of cells.
This code:
print "<pre>";
print "{$aFirst['x']}{$aFirst['y']}:{$aLast['x']}{$aLast['y']} ";
print_r($aStyle);
$oCurrentSheet->getStyle("{$aFirst['x']}{$aFirst['y']}:{$aLast['x']}{$aLast['y']}")->applyFromArray($aStyle);
print "</pre>";
prints this:
B2:AS5 Array
(
[borders] => Array
(
[outline] => Array
(
[style] => THIN
)
)
)
The excel workbook I am trying to render comes out perfectly except for the fact that there is no border. Any ideas?
|
Use the built-in constants: PHPExcel_Style_Border::BORDER_THIN.
Border styles are case-sensitive, and "THIN" should be "thin"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php, phpexcel"
}
|
How to create a new instance of a class with a certain constructor dynamically
package company;
public abstract class A {
public A(int i) {}
public abstract void func();
}
public class B extends A {
public B(int i) { super(i); }
public void func() {}
}
public class C extends A {
public C(int i) { super(i); }
public void func() {}
}
How do I dynamically instantiate company.C or company.B by invoking the constructor function (with a certain integer argument) and invoking the func() method? I know we can use the following method and pass an argument, but not sure how to invoke func() method on it.
|
You can use the Java Reflection .
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java"
}
|
How to pass variable in Webdriver-Sampler | Jmeter Webdriver
I got a Testscript with more than 8 Webdriver-Sampler and a variable, which change in some of the Webdriver-Sampler.
For Example:
**First Sampler:** status = "login successful"
**Second Sampler:** status = "login successful, search for something failed"
**Third Sampler:** status = "login successful, search for something failed, logout successful"
So I have to pass the variable everytime and then edit this variable. I know it is possible to pass a varibale about the Parameter-field. But how can I edit a user define variable in script?
|
You can access JMeterVariables class instance via JMeterContext.getVariables()) method like:
var vars = org.apache.jmeter.threads.JMeterContextService.getContext().getVariables()
vars.put('foo','bar')
var foo = vars.get('foo')
//etc
;
a.setAction("com.service.Service");
startService(a);
|
Here is a tutorial for this.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "java, android"
}
|
Distinct MST Edge Proof
Suppose that T1 and T2 are distinct MSTs for an undirected graph G. Let (u,v) be the lightest edge that is in T2 and not in T1. Let (x,y) be any edge that is in T1 and not in T2. What can you say about (u,v) and (x,y)?
Would it be correct to say that the w(u,v) < w(x,y) because adding (u,v) to T1 would create a cycle and thus contradict the MST property?
|
Take the complete graph $K_4$ with all weights to 1, and two of its spanning trees $T_1$ and $T_2$. Then $w(u,v) = w(x, y)$ for any $uv$ in $T_2$, and any $xy$ in $T_1$, so it cannot be true in general.
In fact if $w(u, v) < w(x, y)$, take $xy$ to be the edge with smallest weight in $T_1$ and not in $T_2$. Then of course $w(x, y) > w(u, v)$ which makes your statement false when you swap $T_1$ for $T_2$.
Another question would be : can you really have $w(x,y) > w(u, v)$, where $xy$ in $T_1$ and $uv$ in $T_2$ are the smallest edges of each tree not in the other ? Well, no. Add $uv$ to $T_1$. This creates a cycle with $uv$ being the lightest edge. Thus removing any edge on the cycle other than $uv$ would give you a smaller spanning tree than $T_1$, a contradiction.
So $w(u, v) \leq w(x, y)$, and if $w(u, v) = w(x, y)$ if and only if $xy$ is the lightest edge in $T_1$ not in $T_2$.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "graph theory, trees"
}
|
Проводник не находит файл при его создании
Изучаю язык Kotlin, узнал как записывать данные в файл, но не могу сам файл найти, то есть, вот код для записи в файл:
File(filesDir, "hello.txt").writeText("Hello World")
так я считываю файл:
val content = File(filesDir, "hello.txt").readText()
Log.v("file", content)
И в консоль я получаю свой текст, но в файловой системе(в провднике) а также в проэкте я не могу найти сам файл, что я делаю не так? И если файла нет, как программа может считывать данные?
Вот проект:  его никак не может быть, даже если вы запускаете приложение в эмуляторе.
Для просмотра файлов Андроида в студии есть Device File Explorer \- выведите в лог путь созданного файла и ищете по этому пути его там.
**Во-вторых:** `File(filesDir, "hello.txt")` \- здесь вы указываете родительский каталог как `filesDir` (`Context.getFilesDir()`), который расположен в приватной директории вашего приложения и не виден никому, кроме самого приложения и вышеозначенного Device File Explorer (в случае debug-версии приложения).
Про варианты хранения данных на устройстве можно начать читать от сюда: <
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "android, файлы, запись"
}
|
Which version of Stratio Lucene Index should we use with Cassandra 4.x?
We are using Stratio Lucene Indexer for V3.11.5 and currently planning to upgrade to V4.x. As specific Cassandra Lucene index versions are targeted to specific Apache Cassandra versions.
<
Kindly let me know if anyone using this Stratio Lucene Indexer with V4.x and which plagin to select.
|
From what I can tell in the project's GitHub repository, there is an outstanding request to add Cassandra 4.0 support (issue #408) but no one from the project has responded to it.
The last supported Cassandra version is 3.11.3 which was released in September 2018 (over 4 years ago).
To me this is an indication that the project is no longer active. In fact, the repository has been archived by the owners on May 2020.
If you want to continue using the plugin, I think you're only recourse is to get in contact with the owner Stratio Big Data. Cheers!
**[UPDATE]** I've discussed with Andres de la Peña (project contributor, formerly from Stratio) who confirmed that Instaclustr maintains a fork here < and Stefan Miklosovic/Instaclustr confirmed that their fork supports Cassandra 4.0 + 4.1.
|
stackexchange-dba
|
{
"answer_score": 1,
"question_score": 1,
"tags": "index, cassandra, stratio, lucene"
}
|
Clojure assoc vector behaviour
Clojure `assoc` applied to vector seems have inconsistent behaviour
When index is present in vector, assoc replace the value
(assoc [1 2 3 4 5] 3 42) => [1 2 3 42 5]
When index is next to last one, the vector grows (`conj` equivalent)
(assoc [1 2 3 4 5] 5 42) => [1 2 3 4 5 42])
Otherwise `IndexOutOfBoundsExcpetion` is thrown
though it useful in some cases like `reduce assoc`, this may lead to subtle bugs in a program
Is it expected behaviour or probably bug in assoc for vector?
|
It is expected. See the docstring for `assoc`, especially the last note regarding the `index` argument.
This is described at the top of p. 101 of _Clojure Programming_.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "clojure"
}
|
Starting Datalab from Cloud Shell
The Datalab documentation shows how to run datalab on:
* your own machine or,
* on Google Cloud Platform.
Unfortunately if you are restricted to a Windows 7/8 machine without the required Docker support, I don't think you have easy* options to deploy datalab.
What is the recommended way to deploy Datalab, since the datalab deployer is now deprecated?
*You could of course run Linux in Virtualbox and deploy everything from there, but it's not really easy.
|
Two quick comments:
1. There are issues with using Cloud Dev Shell - one mentioned above plus problems with the communication protocol between the notebook server and the kernel and a few others. So we decided against documenting this as an alternative to Docker installation at this point.
2. There is a better alternative now that is documented here: < It requires the ability to create an SSH tunnel from your client (Mac/Windows etc) to the GCE VM running Datalab but should otherwise free you from the Docker installation requirement.
Thanks.
Dinesh
(Cloud Datalab Product Manager)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "docker, google kubernetes engine, google cloud datalab, google cloud shell"
}
|
Math.floor(Math.random()) not displaying random numbers after first use
I'm programming this really simple game, and want the damage done by each player random each hit. For some reason, the first hit has a random value, but then the next following values are exactly the same. It is almost like the `Math.floor(Math.random())` function runs once, then stops and uses the value it was given the first time.
Here's the code:
this.attackpoints=Math.floor((Math.random()*10)+5);
this.attack=function(opponent) {
opponent.hitpoints-=this.attackpoints;
console.log(this.name + " has " + this.hitpoints + " hitpoints and " + this.energy + " energy.");
console.log(this.name + " just hit " + opponent.name + ".");
}
|
this.attackpoints=function(){ return Math.floor((Math.random()*10)+5); };
this.attack=function(opponent) {
opponent.hitpoints-=this.attackpoints();
console.log(this.name + " has " + this.hitpoints + " hitpoints and " + this.energy + " energy.");
console.log(this.name + " just hit " + opponent.name + ".");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, math, random, floor"
}
|
how to add status message onto status box in facebook programmatically
i need to post message on the wall of the facebook.
for this i am fallowing this Facebook tutorial.
i need some enhancement for this tutorial that is i need place status message programmatically.
means when user login with username and password then automatically display the status message in status box.
like welcome to my facebook.
i found that this is the url to get message box.
then how can i add status message into this box.
can any one please help me.
Thank u in advance.
(Let me add comment if any one did n't get my question)
|
I took a guess and added the message parameter. It worked! See:
You might consider using newer APIs as I believe this one is deprecated.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "iphone, facebook"
}
|
C# enabled для табов?
Добрый день! Возможно ли как-то отключить один таб из нескольких в C# и как это реализовать? Заранее спасибо.
|
У TabPage нельзя установить свойство Enabled, с тем же результатом, что и для обычного контрола, но можно запретить переход на тот, или иной таб в TabControl:
private void tabControl1_Selecting(object sender, TabControlCancelEventArgs e)
{
if (e.TabPage == tabPage2)
e.Cancel = true;
}
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#"
}
|
django update forms, who pass object id?
I've tried to create a simple `ModelForm`, and I notice that even if I pass an instance for update like that
mymodel = MyModel.objects.get(pk=1)
MyModelForm(instance=mymodel)
django does not create an hidden field or include in some way the pk of the object in the template. So I need to pass this by myself? I prefer not passing the my id's like 1,2,3.. to the templates, so I would prefer passing something like uuid, or using `signing.dumps(object_id)`, and then `signing.loads(object_id)`, from django signing library.
So if I want to include this id in my template with the form POST data, I didn't understand who is exactly responsible for the retrieve of that id - Is that the view or the form itself? By view I mean to the built-ins `FormView`, or `UpdateView`, how these views find the object id? Assume to store the output of `signing.dumps(object_id)` in a hidden field
|
By the time you are in the template the form construction has completed. You can try accessing form.instance.id if its modelForm.
However, most likely you do not need the pk in the template, do you ? You can also inject a hidden form field with the instance pk value if you like. Why do you need the pk in the template ?
If you want to redirect to another page from the POST data you will have access to the object pk in the view itself.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "django, forms, object, signing"
}
|
CakePHP load all plugins except one using CakePlugin::loadAll()
I have known that the method `loadAll()` to load all plugins and the method `load('PluginName')` to load a plugin.
* CakePlugin::loadAll(); // Loads all plugins at once
* CakePlugin::load('DebugKit'); //Loads a single plugin named DebugKit
However, my requirement is to load all plugins except one. For example, I have 5 plugins including DebitKit; I want to load 4 plugins excluding DebitKit. Is it possible to accomplish with `CakePlugin::loadAll()` at one shot.
I'm using Cake 2.1.3
|
I don't think it is possible with `loadAll` (unless you use `unload` afterwards).
An alternative approach is to specify all the plugins you want to load with: `CakePlugin::load(array('PluginA', 'PluginB'));`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "cakephp, plugins"
}
|
CakePHP How to echo just one record
I want to echo a full name from my MySQL database in my header. When that name is clicked in a list it filters all the records and displays all the records related to that name only. I managed to get the filter working, but not able to display the name in header.
<? $this->read('$jobs as $row'); ?>
<h1><?=$row['Employee']['first_name']?> <?=$row['Employee']['last_name']?>'s Jobs</h1>
<? $this->end(); ?>
|
If I'm not wrong, you are trying to retrieve this array, I'm assuing **$jobs** contains single row.
try this
<?php
if (isset($jobs)) {
foreach($jobs as $row){
if (isset($row['Employee']['last_name']))
$last = $row['Employee']['last_name'];
$first = 'N/A';
if (isset($row['Employee']['first_name']))
$first = $row['Employee']['first_name'];
?>
<h1><?php echo $first.' '. $last?>'s Jobs</h1>
<?php } }?>
OR
<h1><?php isset($jobs[0]['Employee']['first_name']) ? $jobs[0]['Employee']['first_name'] : 'N/A' .' '. isset($jobs[0]['Employee']['last_name']) ? $jobs[0]['Employee']['last_name'] : 'N/A'?>'s Jobs</h1>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "cakephp, echo, record"
}
|
ES6 arrow / function equivalency
I'm just getting around to changing some of my code to ES6 and I ran across some code where the arrow function did not work and I am not sure I understand why. The code is from a plugin for Hapi to decorate the `reply` interface.
ES5:
server.decorate('reply', 'test', function(schema, response) {
return this.response(mask(schema, response));
});
ES6:
server.decorate('reply', 'test', (schema, response) => {
return this.response(mask(schema, response));
});
The E66 doesn't work and throws an error:
Uncaught error: this.response is not a function
Why is this?
|
In this particular case, the library is changing what `this` refers to inside the callback for `decorate`. When using arrow functions (`=>`), `this` is equivalent to the `this` of the outer scope. This means that you're basically stuck using `function` for this.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "javascript, ecmascript 6"
}
|
Magento shipping method to product page
I am new to Magento. Now I am customizing Magento built-in theme. I want to add available shipping info to the product view page. Please help me. Thank you
|
you will not get shipping method unless haven't specify any parameter like country,pincode or state.
Below url give you fair idea about shipping method on product page
< page.html
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "php, magento"
}
|
Error While compiling U-Boot
/bin/bash: arm-linux-gcc: command not found
/bin/bash: arm-linux-gcc: command not found
dirname: missing operand
Try 'dirname --help' for more information.
Generating include/autoconf.mk
/bin/bash: line 2: arm-linux-gcc: command not found
Generating include/autoconf.mk.dep
/bin/bash: line 2: arm-linux-gcc: command not found
Configuring for zynq_zybo board...
akhil@akhil-Aspire-E1-571:~/zee-bow/u-boot-Digilent-Dev$
|
Install `gcc-arm-linux-gnueabi` and create a symbolic link
sudo apt-get install gcc-arm-linux-gnueabi
sudo ln -s /usr/bin/arm-linux-gnueabi-gcc /usr/bin/arm-linux-gcc
sudo ln -s /usr/bin/arm-linux-gnueabi-ld /usr/bin/arm-linux-ld
Can you see the system? **;)** Create a symbolic links with the original name, simply remove `gnueabi-`.
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 2,
"tags": "command line, bash, compiling"
}
|
type 'List<Widget>' is not a subtype 'List<Map<String,Object>>' of function... flutter
I've got variable
final List<Map<String, Object>> _pages = [
{'page': Page1(), 'title': 'Page1'},
{'page': Page2(), 'title': 'Page2'}
];
and then in the appBar title I want to use this variable
title: Text(_pages[1]['title']),
But I get error
> type 'List' is not a subtype of type 'List<Map<String,Object>>'....
I've tried to use dynamic instead of Object, that did not help. Is there any way around ?
|
do it like this:
title: Text(((_pages[1])['title']).toString()),
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "string, flutter, dictionary, object, widget"
}
|
How to show $h=g$ a.e. $[m]$?
Let $\mathfrak{M}$ be the $\sigma$-algebra consisting of the Lebesgue measurable subsets of $R^k$ and $\mathfrak{B}$ the $\sigma$-algebra consisting of the Borel measurable subsets of $R^k$.
If $\mu$ is a positive bounded measure on $\mathfrak M$ and $\mu\ll m$, We also have $\mu|_{\mathfrak B}\ll m|_{\mathfrak B}$.
By The Theorem of Lebesgue-Radon-Nikodym, there is a unique $h\in L^1(m)$ such that $\mu(E)=\int_Eh\,dm$ for every set $E\in \mathfrak M$, and a unique $g\in L^1(m|_{\mathfrak B})$ such that $\mu|_{\mathfrak B}(S)=\int_Sg\,d(m|_{\mathfrak B})$ for every set $S\in \mathfrak B$.
Do we have $h=g$ a.e. $[m]$?
|
Let $S \in \mathfrak{B}$. It's not difficult to prove that
$$\int \limits_S g \, \mathrm{d} m = \int \limits_S g \, \mathrm{d} m|_{\mathfrak{B}}$$
given that the second integral exists (which is true in our case). Now
$$\int \limits_S g \, \mathrm{d} m = \int \limits_S g \, \mathrm{d} m|_{\mathfrak{B}} =\mu |_{\mathfrak{B}}(S) = \mu(S) = \int \limits_S h \, \mathrm{d} m.$$
Now if $E \in \mathfrak{M}$, there is $S \in \mathfrak{B}$ such that $m(E \Delta S) = 0$. Thus
$$\int \limits_E g \, \mathrm{d} m = \int \limits_S g \, \mathrm{d} m + \int \limits_{E \setminus S} g \, \mathrm{d} m - \int \limits_{S \setminus E} g \, \mathrm{d} m = \int \limits_S g \, \mathrm{d} m$$
and similarly $\displaystyle \int \limits_E h \, \mathrm{d} m = \int \limits_S h \, \mathrm{d} m$, hence $\displaystyle \int \limits_E g \, \mathrm{d} m = \int \limits_E h \, \mathrm{d} m = \mu(E)$. By uniqueness in the Lebesgue-Radon-Nikodym theorem we get $g = h$ in $L^1(m)$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 3,
"tags": "real analysis"
}
|
How to add folders in Source Safe?
I have a static site of html and css files. It has folders on my computers. I see an 'add files' option in Source Safe 8 but it only copies files from the root folder.
How can I get Source Safe to copy the whole folder tree structure and their files?
|
To copy the entire directory tree, create the root folder ("Create Project") in visual source safe. Then from Windows Explorer select all files and folders you want to add to this new project (folder).
It should prompt you for a comment. Enter your note and click `ok`. That should add all files and folders.
If you only need to add a folder, drag the folder in to it's root in VSS. It will create the folder in VSS.
I think VSS always calls folders "projects".
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 7,
"tags": "visual sourcesafe"
}
|
Is my proof of showing a helicoid and catenoid are isometric, correct?
This is the question I have:
Let $S$ denote the surface of revolution $$(x,y,z)=(\cos\theta \cosh v, \sin \theta \cosh v, v)$$ $0 < \theta < 2 \pi$ and $-\infty < v <\infty$
and $S'$ the surface $$(x',y',z')=(u \cos \phi, u \sin \phi, \phi)$$
$0 < \phi < 2\pi$ and $ -\infty < u < \infty$
Let $f$ be the mapping which takes the point $(x,y,z)$ on $S$ to the point $(x',y',z')$ on $S'$ where $\theta =\phi$ and $u=\sinh v$.
Show that $f$ is an isometry from $S$ onto $S'$
This is my proof.
I reparametrise the helicoid as $$S'=(\sinh v \cos \theta, \sinh v \sin \theta ,\theta )$$
I then find the first fundamental forms of the reparametrized helicoid and the first fundamental forms of the catenoid and show that they are the same.
> Is the outline of the proof correct?
>
> Have I re-parametrized the helicoid correctly?
>
> Do I need to reparametrise the catenoid?
|
You have not shown that they share the same first fundamental form coefficients in your brief outline. You have correctly given the result.
EDIT1:
This is quite standard and can be found in several DG text books, and other sites. including code.
Finding surface of revolution isometric to helicoid
<
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 2,
"tags": "differential geometry"
}
|
On which step should use SMOTE technique for over sampling?
I want to use SMOTE technique for over sampling but I don't know on which step on pre-processing I should use it.
My preprocessing steps are:
* Missing values
* Removing Outliers
* Smoothing Data
Should I use SMOTE before all of these steps or its better to use it after these steps?
|
If you are using python, you can't use SMOTE in the presence of null values.
In this case:
1. Remove Outliers
2. Smooth Data
3. Impute null values (there are some smart options for that in R: using random forests to impute)
4. SMOTE
Removing outliers first let you do better smoothing and imputing.
|
stackexchange-datascience
|
{
"answer_score": 2,
"question_score": 2,
"tags": "data mining, preprocessing, overfitting, class imbalance, smote"
}
|
Does a countered Mimeoplasm still exile creatures?
If I use Counterspell on a The Mimeoplasm that's being cast, are the 2 creatures that have to be removed still removed? Or is this a ETB effect? I ask because of the fuzzy wording on The Mimeoplasm that says as he comes into play first...
|
The wording clearly says
> As The Mimeoplasm **enters the battlefield** , you may exile two creature cards from graveyards. If you do, it enters the battlefield as a copy of one of those cards with a number of additional +1/+1 counters on it equal to the power of the other card.
(emphasis mine)
So if it's countered, it will not enter the battlefield, the replacement effect won't happen and the creature cards won't be exiled from their graveyards.
|
stackexchange-boardgames
|
{
"answer_score": 5,
"question_score": 2,
"tags": "magic the gathering"
}
|
Do protocol relative URLs affect search crawler behavior, and how?
We are working on a web application that will have a preview environment (https) and live which would be (http). Now considering there would be two different schemas involved we have used href for links in HTML page as protocol-relative URLS as we wanted to use absolute URL for links and we didn't want to bother about HTTP/HTTPS in url.
Now we would like to understand how it would affect search crawler behaviour, if at all.
|
It should be completely fine to use them to serve assets ( Wikipedia uses protocol relative urls.) Using protocol relative URLs within links or canonical URLs, should be avoided.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "http, google crawlers, protocol relative"
}
|
LINQ method like List.Exists(predicate)?
I'm looking for LINQ method like `List.Exists(predicate)`.
bool exists = mylist.Exists(p => p.Name == "Kamila");
bool exists = collection.??????(p => p.Name == "Kamila");
|
Use the `.Any`.aspx) method:
//Will return true (and stop future iteration the moment the predicate is met)
//Otherwise false
bool exists = collection.Any(p => p.Name == "Kamila");
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "c#, linq"
}
|
Will Square webhook subscriptions tied to merchant ID (not location ID) work reliably?
The Square documentation for updating webhook events shows this URL format: `PUT /v1/{location_id}/webhooks`. However, creating a webhook event listener for every merchant location could be a lot of separate API requests, and it would be far easier to use the **`merchant_id`** instead of the `location_id` (even though this is not documented) and make one request for each merchant.
Attempting to do this actually works - when I `PUT /v1/{merchant_id}/webhooks` the webhook is saved in Square and transactions for _any_ of that merchant's locations successfully send the webhook.
My question is, since this is undocumented (although it works) is it safe to rely on this approach?
|
While it may work currently, since it's undocumented, the behavior may change in the future and cause unintended side-effects. I strongly encourage you to follow the current documentation for subscribing to webhooks.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "webhooks, square connect"
}
|
Not able to set terminal title with Django runserver
I am using the following `set-title` function from this post on How to rename terminal tab title in gnome-terminal?
function set-title() {
if [[ -z "$ORIG" ]]; then
ORIG=$PS1
fi
TITLE="\[\e]2;$@\a\]"
PS1=${ORIG}${TITLE}
}
I have the following in my `.env` file
set-title SERVER
python manage.py runserver
I am running the above as follows:
. .env
The problem is that it doesn't work when `python manage.py runserver` is present. But when I kill the current running server instance, it changes the title automatically to what I want.
Why is the above behaviour happening when clearly `set-title` should execute first.
|
I usually have script that launches **new** gnome terminal using the `gnome-terminal` command, optionally with several tabs (for example, if I need tow django servers to run in parallel, or django server and DB console).
The drawback is that this is new terminal, however, if you need several tabs it can start you fresh new terminal with all your tabs - you just need to write your script once.
Man page is here
gnome-terminal --tab -t django1 --working-directory="dir1" -e "python manage.py runserver 8000" \
--tab -t django2 --working-directory="dir2" -e "python manage.py runserver 8002"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, django, bash"
}
|
Quirky URl, Something I Am Missing?
Bear my ignorance please!
I always believed there were not so much Top Domain Name Extensions. What I knew were .com, .net,.edu, ect. And I was quit happy with all of those! (ignorance=happiness?)
Until recently I found more and more companies are adopting strange domain extensions like: < < and I was totally puzzled. What does it mean? Obviously what I care is SEO significance, but I am also interested in other related aspects, like what is it differences between well-known extensions? for ordinary users? It seems clear that those new extensions are quit easy to write and memorize, does it mean I should buy domain names like bu.mp or <
Thanks for your time?
|
.us and .mp are country extensions. See here a list of those extension.
If you should register domains like bu.mp is up to you. I found out that here in The Netherlands people (ordinary users) find .nl and .nu confusing. I always advise to register the .nl as well if clients want to use .nu So the well-known extensions still have their value.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "seo"
}
|
AngularJS Passing ng-repeat value to ng-click
Angular 1.5
I am trying to pass noteNumber into a function call in ng-click.
How is that bound? This is in error.
<span ng-repeat="noteNumber in row.Notes">
<a href="#" ng-click="showNote({{noteNumber}})">{{noteNumber}}</a><span ng-show="!$last">, </span>
</span>
|
Use **`ng-click="showNote(noteNumber)"`** and you'd be fine!
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "javascript, angularjs, angularjs ng repeat, angularjs ng click"
}
|
Receiving a service call, checking the certificate and if it was allowed call the backend service on Azure
## The problem
I have an app service and I want people with specific certificates to be able to call me and then also send the thumbprint of the Certificate to the service. How should I do it in Azure?
## More explanation
So lets say there is 10 different systems that should be able to call my service using their own Certificate (signed by). I would want to check them with the ones in my certificate store and if it was one of them put the Thumbprint in the HTTP header and send it to my app service.
## What I've found until now:
It seems like a job of a firewall to me, so I've checked the "Application Gateway" seems to be the solution. But I couldn't find where I could set it to add the thumbprint to HTTP headers.
Any ideas?
|
Azure Application Gateway is limited to handling certificate in your case. In your case, one of the very common solutions is to use Azure Key Vault certificate to store your certificate. Every time when someone sends a request to your web app, your app will need to call to Azure Key Vault certificate identifier to retrieve and verify thumbprint.
This article can be a good start <
If you use REST API, you can retrieve thumbprint of your certificate using Get Certificate operation (< The x5t value in the response is the thumbprint info.
Why do I suggest Azure Key Vault? Because it is designed for certificate and cryptographic management. I'm not going to say Azure Key Vault is the best or highly secure but at least it is designed to address your problem for sure.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ssl certificate, azure, azure networking, azure app services"
}
|
Do I need "wordpress hosting" to host wordpress?
I am a beginning wordpress user and am unsure about wordpress hosting. Some hosting sites (for example, Godaddy) have hosting plans and then they have _wordpress hosting_ plans. do I _need_ the special wordpress hosting? Is it possible to host a wordpress site without having special wordpress hosting?
|
You don't need WordPress-specific hosting, just a hosting package that meets the requirements.
> PHP 5.4 or greater
>
> MySQL 5.5 or greater
>
> The mod_rewrite Apache module (to enable Pretty Permalinks)
|
stackexchange-wordpress
|
{
"answer_score": 4,
"question_score": 2,
"tags": "hosting"
}
|
How to open another view when button is clicked in iOS app development?
I am trying to build an app, and I want another view to open up once I click a button. I have searched for an answer, but nothing came up. I already have the button done, but I don't know how to get another view to show up. The view should be another view within the app. I am just a beginner in xCode. Thanks.
I am currently using xCode 9, and swift 4. Thanks.
|
You can approach this either using the storyboard or programmatically. Using the storyboard, you can ctrl-drag from the button to the other view controller and the segue will be wired up for you, like so:">
However, when Javascript is not activated, the user gets stuck at this page.
What other method could I possibly use directly in PHP to solve this problem?
|
Just do the relevant request in PHP, for example using the curl binding.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, javascript, forms, paypal, submit"
}
|
PL/SQL - Let the variable behave as source code
I have a stored procedure in which I need to "switching" between 2 names of schemas. Here is an example:
declare
schema1 varchar2(16) := 'left';
schema2 varchar2(16) := 'right';
begin
if (some condition) then
select * from ???schema1???.tbl1 where id = 1;
else
select * from ???schema2???.tbl1 where id = 1;
end if;
end;
How can I let **the value** of variable (e.g. `schema1`) behave as a part of source code? I mean that the code will be understood as:
...
select * from left.tbl1 where id = 1;
else
select * from right.tbl1 where id = 1;
...
|
You would have to go with dynamic sql if you want to use variable for schema reference, which would like this:
declare
schema1 varchar2(16) := 'left';
schema2 varchar2(16) := 'right';
myVar varchar2(100);
begin
if (some condition) then
execute immediate 'select * from ' || schema1 || '.tbl1 where id = 1' into myVar;
else
execute immediate 'select * from ' || schema2 || '.tbl1 where id = 1' into myVar;
end if;
end;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "oracle, variables, plsql"
}
|
Fix joystick buttons only detect specific spots pressed
I have a joystick. On top of the joystick there are 3 buttons perfectly accessable with my thumb. They are the most important buttons after the trigger, so I really want them to work. 2 of the buttons only detect when a certain part of the button is pressed. The buttons are basically useless in this condition. Could someone tell me how to fix the buttons? Is it even possible?
Joystick specs:
Microsoft Sidewinder Joystick (USB)
No force feedback or vibration
Bought used so maybe really old
|
The switches are probably either dirty or wearing out.
First test would be to take it apart [best] or try to aim through the cracks [hit & miss] with a can of contact cleaner. Disconnect it from power first & allow plenty of time for it to dry out afterwards - at least an hour if you take it apart, a day if you don't.
If this doesn't improve things, then you can often get new switches - for mere pence if you can wait for them to ship from China. The main problem is how fiddly they are to actually change. Some skill &/or patience will be required.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "gaming, game controller, joystick"
}
|
Rounding up c# giving wrong answer
I am programming a stocks/production program for a school project (bike factory) and I have to round some numbers up such as the bikes that have to be produced (due to fallout it are doubles).
If I use the following code:
double test = Math.Ceiling(100 * 1.09);
label75.Text = Convert.ToString(test);
I get as an answer 110, but that's not right, it should be 109 (9% of 100). Although it seems to work with values below 9%.
What am I doing wrong?
|
`double`s and `float`s are binary floating point types. This means they cannot precisely represent many decimal numbers (like `1.09`). This leads to some subtle round off errors. In your case 100 * 1.09 actually results in a number very slightly larger than 109, so the `Ceiling` function correctly rounds it up to the nearest integer, 110.
Change it to a `decimal` and you'll get the result you expect:
decimal test = Math.Ceiling(100 * 1.09m); // 109
Note the `m` in `1.09m` identifies it as a `decimal` literal. This works because the `decimal` type is specifically designed to represent decimal numbers (rather than just their binary approximations, as `double` and `float` do).
|
stackexchange-stackoverflow
|
{
"answer_score": 28,
"question_score": 9,
"tags": "c#, .net, math, floating point, double"
}
|
"Generator noise" on boot
Since I bought this computer, every time I boot up, I hear this weird noise. You could compare it to a generator generating energy, or kind of like a formula 1 car, it goes from soft to loud and then it ends with a click.
This just happened when I started google chrome, my pc had been turned on for an hour, i just went to take a shower, a shave and breakfast, and when I came back, this happened.
So really, I want to make sure that this is nothing bad. I'm assuming it's the processor, it's an Intel i7 920.
|
Based on your description, and this is just a guess, this could your hard disk starting to spin.
|
stackexchange-superuser
|
{
"answer_score": 6,
"question_score": 0,
"tags": "boot, intel core i7, noise"
}
|
Get the host IP from my django app container
There is a feature on our web app that we need to send the IP of our server but I always send `172.17.0.2` because that is the value of `request.META['REMOTE_ADDR']` which is usually `127.0.0.1` when using django in localhost and which I assume is the TCP address of our NGINX container which where the request is coming from. **How will I send the IP of my docker host instead?**
Containers:
* Nginx
* Django with gunicorn
* PostgreSQL
* Redis
|
Pass it as an environment variable to your container when you create it. Then, read that environment variable in your Django code.
You can do it with option `-e HOST_IP=$(/sbin/ip route | awk '/default/ { print $3 }')` in `docker run` command.
In `docker-compose.yml`, you could do something like this.
django:
environment:
- HOST_IP=$(/sbin/ip route | awk '/default/ { print $3 }')
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "django, nginx, docker"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.