INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to view/open PowerScript file without PowerBuilder
I've got a PowerBuilder project that I want to inspect
but I don't have PowerBuilder installed .
I tried PB Peeper but it freezes when I try to browse through pbl files.
Does anyone know any sort of software that I can open and see the source Powerscript with ?
Thank you | the most simple I know is pbdumper (< ) so you can extract source code as *.sr? files and view with any text editor. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 6,
"tags": "powerbuilder"
} |
Manually add data to MySQL query array
I've just started using Codeigniter, and am loving MVC. I have a simple mysql query in a model that returns an array of rows to my controller.
$query = $this->db->get('shows');
return $query->result();
Date information is stored in the database as mysql date `(yyyy-mm-dd)` and I explode to get month `mm` and day `dd`.
What I'm wondering is, is there any way to manually add the variables for month and day of each row to the query result using a simple foreach? I know I could manually add each database field's value to an array, and include the month and day variables, but I'm hoping there's a simpler way of inserting them into the already existing array created by the query. | @slier had the code, but below is transformed to codeigniter
$this->db->select("*, MONTH(date_column) as date_month, DAY(date_column) as date_day");
$query = $this->db->get('shows');
return $query->result(); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, arrays, codeigniter"
} |
prove that $\int(f(x)+g(x))dx= \int f(x)dx+\int g(x)dx$
Let $f,g$ be two functions defined on $A$. Supposed that $F$ and $G$ are anti-derivative of $f$ and $ g$. Prove that
$\int(f(x)+g(x))dx= \int f(x)dx + \int g(x)dx$
Here is what I got.
Let $H(x)$ be a function such that $H'(x)=f(x)+g(x)$
Since $F$ and $G$ are anti-derivative of $f$ and $ g$
$F'(x)=f(x)$ and $G'(x)=g(x)$
so $H'(x)=f(x)+g(x)=F'(x)+G'(x)=(F(x)+ G(x))'$
thus $H(x)= F(x)+G(x)+C$
what do I do next? | Your proof has all the right pieces, but is not laid out in the usual order.
1. $F,G$ are anti-derivatives of $f$, $g$.
2. Let's define $H(x)=F(x)+G(x)$.
3. Calculate $H'(x)$, and (using properties of derivatives), see that $H'(x)=F'(x)+G'(x)=f(x)+g(x)$.
4. Hence, $\int f(x)+g(x)dx =H(x)$.
5. Consequently, $f(x)+g(x)$ is integrable, with integral $H(x)$.
6. Further, $\int f(x)+g(x)dx=H(x)=F(x)+G(x)=\int f(x)dx + \int g(x)dx$, as desired. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "calculus, proof writing"
} |
Problems with confidence intervals in R
Is it possible to use `function` to create an equation which will produce a normal distribution and simultaneously produce a 95% confidence interval of said data? I know that I can use `rnorm(n,mean,sd)` to generate a random normal distribution but how do I get the output to tell me the confidence interval?
I have attempted `sample_CI<- function(n,j,k){list(g<-rnorm(n, mean=j, sd=k), confint(g, level=.95))}`.
All help appreciated. | It may be this what you were looking for:
sample_CI <- function(n,j,k){
error <- qnorm(0.975)*k/sqrt(n)
left <- j-error
right <- j+error
paste("[",round(left,4)," ; ",round(right,4),"]")
}
sample_CI(1000,2,4) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "r, normal distribution, confidence interval"
} |
How to create a 2D array with variable row and each row has 3 columns?
I am thinking like :
int i,z[3];
int q[i][z[3]];
Can this declaration be right?
If no this suggest a approach where I can store `i` rows and each row have 3 integers in it. | @dbush already mentioned in his answer about _variable-length arrays_ (VLAs)
This answer will offer an alternative.
You can use `std::vector` to achieve it:
std::vector<std::vector<int>> vec2d; // 2D vector
int row = 2; // row is variable
for (int i = 0; i < row; i++) {
vec2d.push_back(std::vector<int>(3)); // each row has 3 columns
}
// just for checking the size
for (auto const& v: vec2d) {
std::cout << v.size() << " "; // 3 3
// ^ ^ each row has 3 columns
} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "c++, arrays, multidimensional array"
} |
YouTubeQuery(..) take too long to show uploaded video
YouTubeQuery(..) take too long to show published video. Approximately 24h after upload video. Anyway to speed up this? | The amount of time that passed in between when a video is uploaded to YouTube and when it shows up in the YouTube search index can vary. We can't make any guarantees about that.
In general, one common practice that can lead to delays in indexing which you can avoid is uploading the video as unlisted/private and then later flipping it to public when you want the video to be "published". I'm not sure if you're doing that or not, but if you are, try uploading it as public initially instead. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "java, youtube api, gdata api"
} |
Sorting a tuple of strings alphabetically and reverse alaphabetically'
Lets say you have a list of tuples (last_name, first_name) and you want to sort them reverse alphabetically by last_name and then if two people have the same name for them to be sorted alphabetically by first name. Is there a way to do this with one line?
e.g.
Sorted(names, key = ?) = [('Zane', 'Albert'), ('Zane', 'Bart'), ('Python', 'Alex'), ('Python', 'Monty')]
With two lines I guess you could rely on sort stability and first sort by first name and then sort by last name reversed. | Here's an `itertools.groupby` solution:
from itertools import groupby
from operator import itemgetter
li = [('x', 'y'), ('s', 'e'), ('s', 'a'), ('x', 'z')]
[p for k, g in groupby(sorted(li, reverse=True), itemgetter(0)) for p in reversed(list(g))]
# [('x', 'y'), ('x', 'z'), ('s', 'a'), ('s', 'e')] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, string, sorting"
} |
What's the Java equivalent of this declaration in Flex
[Embed("assets/BorderContainer.png")]
public const BorderContainerIcon:Class;
The xml string of my application menu is formed entirely in java and I can't the iconField="@icon" property of the menuBar component otherwise. It has to be there.
EDIT: I'm shamefully sorry for that phrasing. | If I'm understanding you correctly, you're looking for a way to embed a resource in a Java class.
The Java compiler won't automatically embed resources in a class file. However, you can package `BorderContainer.png` into a .jar file along with the rest of your program. A .jar file is the most common way of distributing client-side executable Java programs (fun fact: a .jar file is just a disguised .zip file). Then you can access `BorderContainer.png` from your class by using `Class.getResourceAsStream("BorderContainer.png")`. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "java, apache flex, actionscript"
} |
Cannot find tREST_request and tREST_response components in Talend for Data Integration v 7.3.1.20200219_1130
I'm using Talend for Data Integration v 7.3.1.20200219_1130 and I want to use tREST_request and tREST_response as server side in order to convert an Excel file to XML file. My problem is that I cannot find both components in ESB section, as described in Talend documentation, I looked also in "Palette Settings", there's only tRESTClient. I'm wondering if this is a version problem (those components are omitted in this version) or those components are not avaible in free version? | You have to download Talend Open Studio for ESB in order to get those components. I don't know why, but this version is not available anymore on talend website. You have to go to sourceforge to find it. <
With Talend Open Studio for ESB you can develop job to provide services (through tRestRequest/tRestResponse components, are SOAP components), as well as developing classic Talend Data Integration jobs. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "talend"
} |
Problems with the modality of a JDialog (mouse events for main window both fired and buffered)
I made a JDialog and the modality works presumably fine
dialog.setModalityType(JDialog.ModalityType.APPLICATION_MODAL);
dialog.setVisible(true);
But then my problem is:
* I´m throwing Jdialog after a jcombobox.setSelection() and I need to click twice in Accept button in order to hide the dialog, because dropdown popup is consuming the first click for closing himself. I fixed it by manually calling jcombobox.hidePopup() before calling the dialog, but I cannot understand if the later is modal, why the mouse events trigger things outside the window?`
* My Main window buffers somehow the mouse events, so for those mouse events which are not activated when the modal dialog is drawn (as happens with the previous point), it seems they get buffered and are applied after dialog closure. Is this an expected behavior?
Thank u! | * replace `jcombobox.hidePopup("doesn't make me sence")` with `ActionListener` or `ItemListener` added to the `JComboBox`
* add RequestFocusListener by @camickr for setting the `FocusOwner` correctly
* for why reasons are there another `MouseListeners`, maybe in the case that fird any events to the `JComponents` that you can't to set `Focus` correctly | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "java, swing, events, modal dialog, jcombobox"
} |
how to change the flash builder generate HTML to call function in actionscript?
I have an actionscript project, and I have provided the function that I want it to be called from HTML(the flash builder generated html file).
ExternalInterface.addCallback("getURL", getURL);
This is the code in actionscript, how can I modify the flash builder generated html file so that it can call getURL()? | Just add your function between `<script>` tags in `index.template.html` file that is located in `html-template` folder of your project. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "html, apache flex, actionscript"
} |
delete rows based on date
Hi there is probably an easy answer for this, I'm just struggling to understand how to deal with it.
I create a table with:
"CREATE TABLE IF NOT EXISTS PERSONS (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER, DT DATETIME DEFAULT CURRENT_TIMESTAMP)";
and im trying to delete a person based on there name,age and the date it was register, in order to avoid deleting a person who happened to have the same name and age of another person (therefore the current date should distinguish)
and the delete statement is:
[NSString stringWithFormat:@"Delete from persons where name is '%s','%s'",[p.name UTF8String],[p.date UTF8String]]];
The problem im having is that '%s" must not be right for the date as its not deleting any.
thanks for the help. | I think you are quite a ways off with that delete statement. It should be something more like:
[NSString stringWithFormat:@"Delete from PERSONS where NAME = \"%@\" and DT = \"%@\"", p.name, p.date];
PERSONS and NAME need to be caps, because that's how you defined them in your create. Your p.data will need to correspond with how sqlite stores dates. danypata's link should help you there. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "ios, objective c, sqlite"
} |
Centering a button in html
I am trying to place a button in my blogger post. I have designed the button, but i am unable to center it properly on the page.
How i do center this button?
<html>
<head>
<style>
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Buttons</h2>
<a class="button" href="#">Link Button</a>
<button class="button">Button</button>
</body>
</html> | Use `margin: 0 auto;` in a parent element.
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
body {
text-align: center;
}
<h2>Buttons</h2>
<a class="button" href="#">Link Button</a>
<button class="button">Button</button> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "html, blogger"
} |
Creating a docker-compose.yaml file for php composer manager
Сan someone explain what exactly command: install means in below compose.yaml file:
composer:
image:composer/composer
volumes:
- ./document_root:/var/www/html
command: install | Find Command doc here
as per doc it overrides the default command `command: bundle exec thin -p 3000` and executes whatever command you give in that filed. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "docker, docker compose"
} |
React: Prop Not Displayed in React Component
I am passing a prop in react route component as listed below:
<Route exact
path='/'
component={HomePage}
display_notification={this.display_notification.bind(this)}
/>
But When I print the props of HomePage I cannot find display_notification.
Please help.
I am using react-router-v4 | Route does not recompose props for you, it passes internal location related props only. you need to use the `render={}` API - <
so something like
<Route exact
path='/'
render={() => <HomePage display_notification={this.display_notification} />} /> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "reactjs"
} |
Implementing SLDS in Lightning Application/component
I've a question on implementing SLDS in lightning apps and commponents. I was going through a tutorial where I saw the instructor is installing slds unmanaged package and then referring the static resource using **_ltng:require_** on the app like
<aura:application>
<ltng:require styles="/resource/slds100/......."
</aura:application>
On trailhead I don't see anything like that and all they say is to use extends="force:slds" on the app as below -
<aura:application extends="force:slds">
<c:AccountCmpTest />
</aura:application>
I'm currently using this and it's working, so is this the correct approach or we still have to associate the **ltng:require** tag? | force:slds was recently introduced in winter'16; with which we can skip the additional step of having a static resource:
> Your application automatically gets Lightning Design System styles and design tokens if it extends force:slds. This method is the easiest way to stay up to date and consistent with Lightning Design System enhancements.
The mentioned tutorial would be based on older version, at that moment this feature was not available. | stackexchange-salesforce | {
"answer_score": 15,
"question_score": 6,
"tags": "lightning, lightning design system"
} |
GitPython: Determine files that were deleted in a specific commit
Using gitpython, I am trying to get a list of changed paths; that is, of all the added, changed and deleted files.
I can retrieve the changed and added files from the commit:
* checkout commit 'X'
* traverse repo.tree() and collect all the blobs' abspath
If a file was deleted in a specific commit, it will not show up in the tree anymore. How can I get the names of all the deleted files? | You can look at the commit's parents and compare the contents of the two (or more, depending on the number of parents) trees. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 3,
"tags": "python, git, python 2.7, gitpython"
} |
Explain the use of Dominated Convergence Theorem
In the proposition below from Measure Theory and Probability by Athreya and Lahiri, DCT was used to justify the existence of $t$ in the first line of the proof.
|\chi_{\\{|f|>t\\}}=0 ~~~~\text{a.e.}$$
(Because $f\in L^1$ if we had a set of positive measure that was infinite, the integral would be infinite as well)
And $|f(x)|\chi_{\\{|f|>t\\}}$ is dominated by an integrable function, namely $|f|$ (as $f\in L^1$), so we have:
$$\lim_{t\to\infty} \int_{|f|>t}|f|~d\mu=\lim_{t\to\infty} \int_{\Omega} |f(x)|\chi_{\\{|f|>t\\}} ~d\mu=\int_{\Omega}0~d\mu=0$$
Then just apply definition of convergence of numbers. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "measure theory, self learning"
} |
Is there a way to not refresh the iframe each time i change tabs?
I have jquery tabs on my page, each tab has a single iframe in it. Everything works, except... The iframes refresh each time I switch tabs.
The source for the Iframes is set in the Page_Load and is only executed once. The jquery does not do anything except change the tab...no other code.
Is there a way to not refresh the iframe each time? | This is why I never want to ask anything on this site...I know it's gonna be something simple, but for anyone that may be helped in the future from my pain...
In the code for the jquery tabs to select or hide tabs, I had a call to a button click event that was used to keep track of the current state of the tabs. This is what caused the postback and why my iframes were getting reinstantiated.
$(function () {
$("#tabs").tabs({
select: function (event, ui) {
var sel = ui.index;
$("[id*=SelectedTab]").val(sel);
$("[id*=ChangeTabButton]").click();
},
selected: $("[id*=SelectedTab]").val()
});
});
Thanks Kevin and Vishal... | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "c#, jquery, iframe"
} |
JMeter: how can I disable a View Results Tree element from the command line?
I have a number of tests that all have the View Results Tree element in them.
They are very useful in creating and debugging the tests, however inevitably some of the tests are saved with them enabled.
When the tests are run (from the command line), the ones with this element enabled blow out the JVM memory requirements hugely causing memory issues on the host (it runs many of these at the same time).
Is there any way to disable this particular element from the command line? | One way I've found is to programmatically disable this component in the file: Changing
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
to
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="false">
Using this command:
sed -i 's/View Results Tree\" enabled=\"true\"/View Results Tree\" enabled=\"false\"/' <test file.jmx> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "jmeter"
} |
Unable to import WSO2ISschema into openldap
I'm trying to import wso2person.ldif (< into openldap 2.4.4. I see that openldap expects ldif file to contain different elements from what I have. However I can import the same ldif files in to ApacheDS.
I see the following error.
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "cn=schema"
ldap_modify: Invalid syntax (21)
additional info: attributeTypes: value #0 invalid per syntax
Do i need to manually convert the ldif file or is there an utility that does the conversion? | Manually edited those schema files to match what is expected by openLDAP | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "openldap, apacheds, wso2 identity server"
} |
Picking randomly one card till we get the first heart
From a standard pack of cards $(\spadesuit, \heartsuit, \diamondsuit, \clubsuit)$ we are picking randomly one card in a each time (with replacement) until we get the first heart $\heartsuit$.
$(A.)$ Find the probability that there will be **exactly** $5$ cards picked.
$(B.)$ Find the probability that there will be **more** then $5$ cards picked.
* * *
**My attempt:**
$(A.)$
Let $X$ be a random variable $X\sim G(\frac{13}{52}=1/4)$
So $P[X=5]=(1-1/4)^{4}\cdot\frac 1 4=\frac{81}{1024}$
$(B.)$
$$P[Y=1]=(1-1/4)^0\cdot\frac 1 4=\frac{3}{16}\\\ P[Y=2]=(1-1/4)^1\cdot\frac 1 4=\frac{3}{16}\\\ P[Y=3]=(1-1/4)^2\cdot\frac 1 4=\frac{9}{64}\\\ P[Y=4]=(1-1/4)^3\cdot\frac 1 4=\frac{27}{256}\\\ P[Y=5]=\frac{81}{1024}$$
$$P[Y>5]=1-\underbrace{\bigg(P[Y=1]+\dots+P[Y=5]\bigg)}_{=(307)/(1024)}\\\ \Longrightarrow 1-\frac{307}{1024}=\frac{717}{1024}$$
Is my attempt correct? | For B), we want the probability of five non-hearts in a row. This is $(3/4)^5$.
Your way of attacking the problem is also correct, it is a bit more work. Note that $\Pr(Y=1)$ was not computed correctly, it should be $1/4$. | stackexchange-math | {
"answer_score": 3,
"question_score": 2,
"tags": "probability"
} |
Borel measure of half-open and open intervals
the Borel set is the $\sigma$-ring generated by the open sets. One possible Borel measure on the real line is defined, for a closed interval, as:
$$\mu([a,b])=b-a$$
But, from my understanding, intervals of the type $[a,b)$, or $(a,b)$ are also part of the Borel set, as it is also generated by the compact sets.
How do you compute the measure of those half-open and open intervals ? Is it $b-a$ too ?
Thanks,
JD | Let $k$ be an integer such that $k > \frac{1}{b-a}$.
$[a, b - 1/n] \subset [a, b - 1/(n+1)]$ for $n \ge k$.
$[a, b) = \bigcup_{n\ge k} [a, b - 1/n]$.
Hence $\mu([a, b)) = \lim_{n\ge k} \mu([a, b - 1/n]) = b - a$. Hence, similiarly $\mu((a, b)) = b - a$ | stackexchange-math | {
"answer_score": 3,
"question_score": 2,
"tags": "measure theory"
} |
When is the union of $p^n$-extensions a field?
A question inspired by the concept of constructible numbers.
Let $K$ be a field, $\Omega$ some algebraic closure of $K$ and $p$ a prime number. Let $L$ be the set of all elements $\alpha \in \Omega$ for which $\dim_K(K[\alpha])$ is a power of $p$. Is $L$ a subring/subfield of $\Omega$ in general? If not, under what conditions on $p$ or $K$ is it?
The answer is positive for the constructible numbers ($p = 2, K = \mathbb{Q}$). | $\newcommand{\Size}[1]{\left\lvert #1 \right\rvert}$$\newcommand{\C}{\mathbb{C}}$$\newcommand{\Q}{\mathbb{Q}}$Let $K = \Q$, $\Omega = \C$, $p = 3$, and $\omega \in \C$ a primitive third root of unity.
Then $\sqrt[3]{2}, \omega \sqrt[3]{2} \in L$, but $\omega = (\sqrt[3]{2})^{-1} \cdot \omega \sqrt[3]{2} \notin L$, as $\Size{\Q[\omega] : \Q} = 2$
So $L$ is not a subfield in this case, nor a subring, as $(\sqrt[3]{2})^{-1} \in \Q[\sqrt[3]{2}]$.
You can do the same, mutatis mutandis, for any odd prime $p$. The reason the argument fails for $p = 2$ is of course that $\Size{\Q[-1] : \Q} = 1 = 2^{0}$. | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "galois theory, extension field"
} |
A set theoretic question
Is the following statement true?
If a nonempty collection $\mathcal{A}$ of sets is closed under countable union, it is also closed under finite union.
* * *
My guess is it is not true unless $\emptyset \in \mathcal{A}$, but I don't know where to look for a counter example. | Yes. Let $A_1, ..., A_k$ be a finite collection of sets of $\mathcal{A}$. Set $A_{k + j} = A_k$ for $j \ge 1$. Then $\bigcup_{n=1}^{\infty} A_n = \bigcup_{n=1}^{k} A_n$ | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "elementary set theory"
} |
Eclipse 3.4 package explorer question
is it possible to do something like this: Let's say I have a lot of projects in my package explorer. I want to make different views. For example a view for projects I don't use very often, my main things, common things. Basically i want to clean up my package explorer to get a better overview of all my things. At the moment everything is in my head and all projects are overcrowding the package explorer. Is there any similar or recommended way to do this. Or let's just say how do you organize your things in the package explorer.
thx.
kuku | Use different **workspaces**. So you can use one workspace for project 1, 2 and 5 and the second for 3,4 and 6.
You can create a new workplace via **File --> Switch workspace --> Other**. Then you can choose a new folder and copy settings from the current workspace.
Otherwise, you can use **Working Sets**. Just play with them.
Good luck! | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "eclipse, eclipse 3.4, package explorer"
} |
Can I delete php5's "error_log.txt"?
On our IIS6 server (running on a Microsoft Server 2003), the error_log.txt file located in the php5 folder has grown to a huge size of 500MB, and is massively fragmented. It's so huge I can't even load it into a viewer to examine.
Can I just delete that file to reclaim space? While IIS is running? | Yes. You can delete it. However PHP is going to continue to write its errors there, re-creating the file if it doesn't exist.
You can modify `error_log` in your php.ini to disable it, or direct it to Windows Event Log.
I would suggest using a _good_ text editor like Notepad++ or TextPad to examine the contents of it before you delete it in case there is an error you need to know about. Those two generally don't try to load the entire file into memory at once like Notepad/Wordpad do. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, iis, iis 6"
} |
List comprehension, but for dictionaries?
A more pythonic way of doing the following? In this example, I'm trying to build comments (a dict) to be key-value pairs where the key is the unmodified-version, and the value is the return value from a function where the key was passed as an arg.
def func(word):
return word[-1:-6:-1].upper()
subs = {
'ALLOWED': ['one', 'two'],
'DISALLOWED': ['three', 'four']
}
comments = {}
for sub in subs['ALLOWED']:
# reverse and uppercase
comments[sub] = func(sub)
print(comments)
Anyone have recommendation? It's not exactly important to have this done, but I love learning python idioms and ways to make my code more pythonic. Thanks! | Use a dict comprehension instead of building your dictionary in a `for` loop:
comments = {key: func(key) for key in subs['ALLOWED']} | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "python, python 3.x, list comprehension, dictionary comprehension"
} |
Getting Number Of Downloads Of Android and IOS and Distinct Unique Users
I am using the below query to get the number of downloads for IOS and Android using Firebase,
SELECT
COUNT(DISTINCT user_pseudo_id)
, app_info.firebase_app_id
FROM
`xxx.analytics_xxx.events_*`
WHERE
event_name = "first_open"
AND (app_info.firebase_app_id = "1:xxx:android:xxx" OR app_info.firebase_app_id = "1:xxx:ios:xxxx")
GROUP BY app_info.firebase_app_id
If I remove `event_name = "first_open"` then the count is difference (around 200-300). So, why distinct unqiue user count is different using first_open and not using first_open? | Assuming the count is higher when you remove the `WHERE event_name = "first_open"` clause. Your BigQuery export most likely does not contain the `first_open` event for those users. Perhaps the BigQuery export was enabled after the users had already installed and opened the app.
You can try the following simplified query to provide similar results:
SELECT
device.operating_system,
COUNT(DISTINCT user_pseudo_id) AS user_count
FROM `xxx.analytics_xxx.events_*`
GROUP BY 1 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, ios, firebase, google analytics, google bigquery"
} |
Pausing downloads in iTunes on Windows platform
I have used many iterations of iTunes to download videos on Windows platform . However , only one iteration of iTunes the pause option did what it said , it paused the video to the point where I downloaded and restarts downloading where I left off ; something like the downthemall addon on Firefox . Now is that a feature or a bug of iTunes software on Windows platform or this is how every downloads using iTunes is supposed to work. I often have to download large files ; and restarting from the initial position is a havoc . | I got my own answer : this is a feature not a bug of Apple . There are some files that are non-resumable , and some are not . | stackexchange-apple | {
"answer_score": 0,
"question_score": 0,
"tags": "itunes, windows"
} |
Natural Deduction: Universal Quantifiers in Predicate
How do we prove the conclusion: ∀x(Ax ∨ ⇁Ax)
This is also called LEM, i.e. the Law of Excluded Middle. I'm confused while proving this because for ∀x, deduction assuming some constant is required. So, using universal quantifier Introduction and Elimination rules, how can the conclusion be reached? | Prove $(Aa \lor \neg Aa)$ from no premisses.
Then universally generalize. Which you can since $a$ appears in no live assumption. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "logic, predicate logic, natural deduction"
} |
Advanced Module Manager Assignments
Using Joomla 3.9.11 and AMM 2.7.1
I have a blog with the url `www.example.com/news`
I need to display some modules on the right hand side of this page, but **only** on that exact URL.
If the URL contains anything after `/news` then the modules should not be displayed. For example `www.example.com/news/my-great-story` should not display the modules.
How can I achieve this? | In URL assignments section:
* Set the option to **Include**
* In URL matches enter `/news/?$`
* Enable **Use Regular Expressions**
*The `/?` part is used for the case your `/news` page is also loading via `/news/` and you need to show the module in both cases. | stackexchange-joomla | {
"answer_score": 3,
"question_score": 2,
"tags": "module, module display, joomla 3.9"
} |
Change function prefix name in caption with algorithm2e
`\SetAlgorithmName` changes the prefix that comes in caption with `\begin{algorithm}...\caption{lol...}\end{algorithm}` from `\usepackage{algorithm2e}`.
But how to change that prefix/name for functions? Procedures? Etc? Is there `\SetFunctionName`? | There exist
\SetAlgoProcName{a name}{an autoref name}
\SetAlgoFuncName{a name}{an autoref name}
see the user manual of `algorithm2e` v5.2, sec. 6, page 17 (near the end of that page). | stackexchange-tex | {
"answer_score": 1,
"question_score": 0,
"tags": "algorithm2e"
} |
Возможно ли настроить webpack-dev-server, чтобы он открывал сразу несколько браузеров?
Мне необходимо работать сразу с несколькими браузерами, чтобы видеть результат работы скрипта (скрипт меняет DOM, кое-что отрисовывает и т.п.). webpack-dev-server у меня настроен, и по команде: `$ npm run server` открывается < браузером, который установлен в системе по умолчанию и это понятно.
Но возможно ли настроить webpack-dev-server, чтобы он открывал сразу несколько браузеров, установленных в системе ? Может кто задавался таким вопросом?
Зачем?: Из-за особенностей скрипта и его работы, и в частности из-за некоторых отличий в парсинге DOM разных браузеров. (Использую так же task runner(build + watch), вот и хочется связать это для нескольких браузеров сразу).
Кто что может подсказать? Хотя бы примерно. (Ни в оф.документации ни поиск не помогли). | С плагином `webpack-browser-plugin` это возможно.
var plugins = [];
plugins.push(new WebpackBrowserPlugin({
browser: 'Firefox',
port: 9000,
url: '
}));
И в конфиг потом добавляете:
var config = {
[...]
plugins: plugins,
}
module.exports = config; | stackexchange-ru_stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "webpack dev server"
} |
loop mysql results in php outside of mysql query
i am having a bit of issue with a mysql query. for some reason i can echo all all associated rows inside of the mysql query but outside of the query it only return the last row. here is my code. any suggestions?
//Get all associated
$q=mysql_query("SELECT * FROM `ACCOUNT` WHERE ACCOUNT_ID='$act_id'");
while ($row = mysql_fetch_assoc($q)){
$act_name=$row['ACT_NAME'];
echo "$act_name<br>"; // This returns all rows fine
}
echo "$act_name<br>"; // This only return the last row. i would like to get all rows. | The only way that you can fetch all of the records is by using PDO or MySQLi. Here is an example:
$conn = new mysqli($hostname, $username, $password, $database);
$query = "SELECT * FROM `ACCOUNT` WHERE ACCOUNT_ID='$act_id'";
$results = $conn->query($query);
$resultArray = $results->fetch_all(MYSQLI_ASSOC);
As @esqew said, you need to stop using the `mysql_*` functions. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "php, mysql"
} |
Brightness control not working on HP Pavilion dm3t (Intel GMA 4500MHD)
I picked up an hp dm3t laptop with intel HD graphics and installed ubuntu 10.10 64 bit on it. It works great -- the only problem is that the brightness controls on the keyboard don't work. The brightness is always at full. When I try to adjust it down, the indicator graphic indicates that it's going down but the actual brightness doesn't change. Is there anything that I can try to make this work? I'd really appreciate any help.
I asked this on superuser.com and someone commented that I should play around with the intel hd drivers. I'm a total noob -- how do I do that? What else can I try? I really don't want to go back to windows. | This seems to be a kernel bug.
You might be interested in reading this bug report, where an Ubuntu kernel developer posted a link to his PPA with a patched kernel (including steps on how to install it). | stackexchange-askubuntu | {
"answer_score": 3,
"question_score": 1,
"tags": "10.10, intel graphics, hp, brightness"
} |
Best method to store data in android application?
I am new at Android programming and trying to create an application which shows up pre-defined quotes, poems etc. I want to know what is the best way to store these strings in the application? SQLite Database, XML file, text file? Any suggestions for cloud storage and how to achieve that in an android app?
Thanks in advance! | It feels absolutely absurd to go for Sqlite, even if it's a thousand strings. Reading a plain text file one line at a time and storing the strings in a List or Array takes absolutely no time at all. Put a plain text file in /assets and load it like this:
public List<String> readLines(String filename) throws IOException {
List<String> lines = new ArrayList<String>();
AssetManager assets = context.getAssets();
BufferedReader reader = new BufferedReader(new InputStreamReader(assets.open(filename)));
while(true) {
String line = reader.readLine();
if(line == null) {
break;
}
lines.add(line);
}
return lines;
}
Alternatively go for JSON (or possibly XML), but plain text should be fine. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 6,
"tags": "android, database, cloud storage"
} |
fluxxor add more than 1 set of actions to a flux instance
I have set up a React application using Fluxxor, I am trying to use a controller view which gets multiple stores and actions, similar to this carousel example.
However in the fluxxor example it uses multiple stores but only the one set of actions. I wanted to know how to pass in multple actions.
var React = require('react/addons'),
Fluxxor = require("fluxxor"),
authorActions = require("../actions/author-actions"),
authorStore = require("../stores/author-store"),
productActions = require("../actions/product-actions"),
productStore = require("../stores/product-store");
var stores = { ProductStore: new productStore(), AuthorStore: new authorStore() };
// how do I combine my actions here?
var flux = new Fluxxor.Flux(stores, actions); | Fluxxor supports adding actions dynamically:
var flux = new Fluxxor.Flux(stores);
flux.addActions(authorActions);
flux.addActions(productActions);
If the namespaces don't conflict, you can also merge them together with something like Underscore's extend:
var actions = _.extend({}, authorActions, productActions);
or `Object.assign` (or a polyfill):
var actions = Object.assign({}, authorActions, productActions); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "javascript, reactjs, flux"
} |
When to use $\lim_{x\to a}\frac{f(x)-f(a)}{x-a}$ vs $\lim_{h\to0}\frac{f(a+h)-f(a)}{h}$ to find the slope of the tangent line
I was given 2 formulas but I am unsure of when to use each one. Both of them got the same answer for a given question
> Find the slope of tangent at $x = 2$ for the function $y = 2x^2$
Formula 1:
$$\lim_{x \to a} \frac{f(x)-f(a)}{x - a}$$ Formula 2:
$$\lim_{h \to 0} \frac{f(a + h) - f(a)}{h}$$
Answer 1:
$$\lim_{x \to 2} f(x) = 8$$
Answer: 2
$$\lim_{h \to 0} f(x) = 8$$
My question is:
> What is the difference between the two answers/formulas? And when should I be using each method? | They are the same formula, except for a shift in the limiting variable. Specifically, if you let $x = a+h$, then both are the same, since $$\lim_{x \to a} \frac{f(x)-f(a)}{x-a} = \lim_{a+h \to a} \frac{f(a+h)-f(a)}{(a+h)-a} = \lim_{h \to 0} \frac{f(a+h)-f(a)}{h}$$
I prefer to use the second formula (with $h$) almost always. I find it easier to find a general derivative as well using this one, but it is up to your personal preference about which one to use. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "calculus, limits, functions"
} |
how can I add animate.css to nuxt js app?
How do I install animate.css and have it working on my nuxtjs project? I have tried using the animate.css installation guide but still doesn't work. | For npm users add animate.css on your project using this command `npm i animate.css --save`
For yarn users `yarn add animate.css`
Then add animate.css onto you `nuxt.config.js` file
export default {
// ...
css: ['animate.css/animate.min.css']
// ...
}
Then use it in your HTML like so
<h1 class="animate__animated animate__bounce">
An animated element
</h1> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "css, vue.js, nuxt.js, animate.css"
} |
Log dual flight time and certificates which have been revoked due to enforcement action
As with the case of Martha Lunken, who had all of her pilot certificates and ratings revoked for dammed fool stunt where she intentionally flew under a bridge, The FAA does allow people to reapply for new certificates not less than a year after the revocation as an enforcement action. That being said, is all the flight time that a pilot has previously accumulated prohibited from being used toward the new certificate? Or does such an aviator essentially have to start from scratch and acquire all of the required aeronautical experience flight hours listed in part 61 again? | Yes, flight time from before the revocation still counts. This is from Order 2150.3C - _FAA Compliance and Enforcement Program_:
> A person whose certificate has been revoked may be issued a new certificate provided that the person meets the qualification requirements for the new certificate. To be issued an airman certificate following revocation, an individual must retake all tests, whether written, oral, or practical. Any experience requirements for the new certificate may be met with experience obtained before the revocation. | stackexchange-aviation | {
"answer_score": 6,
"question_score": 1,
"tags": "faa regulations"
} |
clear memory allocated by R session (gc() doesnt help !)
I am doing machine learning in large scale but after while my compute getting so slow because of R memory occupation.
I cleared my objects and also I tried `gc()` and the result:
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 4460452 231.5 15288838 1116.6 36599071 1954.7
Vcells 29572776 349.4 324509788 2712.9 350796378 3376.4
My task manager shows R session still allocated over 3GB of my memory and my computer is still slow.
How can I release the memory taken by R? (I don't want restart the pc) | best solution i found is restarting R session. in R studio `ctr+shft+f10`
and if you dont want to save workspace
makeActiveBinding("refresh", function() { system(paste0(R.home(),"/bin/i386/R")); q("no") }, .GlobalEnv)
paste0(R.home(),"/bin/i386/R --no-save") #--save will save workspace
cheers. | stackexchange-stackoverflow | {
"answer_score": 11,
"question_score": 23,
"tags": "r, memory, garbage collection"
} |
Field not algebraic over an intersection but algebraic over each original field
What is an example of a field $K$ which is of degree $2$ over two distinct subfields $E$ and $F$ respectively, but not algebraic over $E \cap F$? | Let $X$ be an indeterminate and consider $E=\mathbb C(X^2),F=\mathbb C(X^2+X),K=\mathbb C(X)$. Clearly $K$ is quadratic over both $E$ and $F$. We claim $E\cap F=\mathbb C$.
Suppose first $p(X^2)=q(X^2+X)$ for some rational functions $p,q$ over $\mathbb C$. Consider them as equal to a function $f(X)$ over $\mathbb C$ in a variable $X$. This equality tells that if $z$ is a zero (resp. a pole) of $f$, then $-z$ and $-1-z$ are also zeros (resp. poles) of $f$. Unless $f$ is constant, it has either a zero or a pole, and by repeatedly applying $z\mapsto -z,z\mapsto -1-z$ we find it has infinitely many of these. But this is impossible for rational function unless it's identically zero. It follows that $f$ is constant, so $p(X^2)=q(X^2+X)\in\mathbb C$. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "abstract algebra, field theory, extension field"
} |
Multiply a range of numbers - Python2.x
I apologize for the beginner question, I'm teaching myself. I've done some searching and have only found factorials. What I'm looking for is, given a range(2, 10) to multiply all of those numbers out:
In the above example of 2-10 we would have something like this:
> 2 * 1 = 2
>
> 2 * 2 = 4
>
> ...
>
> 3 * 1 = 3
>
> 3 * 2 = 4
...
and so on, until you've gone through your list.
What I have:
def product(number):
for i in range(2,10):
return number * i
for number in range(2,10):
print product(number)
This only seems to work for my 2 case. so I get to 18 and it doesn't go back through and move to the next integer. | As others have pointed out, you return the value on the first iteration and so your loop never gets exausted.
You could either do it as a `generator`, which is better, as suggested in the comments, or you could simply return the list of value with a list comprehension:
def product(number):
return [number * i for i in range(2, 10)]
You could of course ditch the function in this case, but that's not the issue here. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, python 2.7"
} |
Animate jQuery
Добрый день/вечер.
На мой взгляд, достаточно сложный вопрос. Имеется `div`, нужно для jquery события hover прописать `animate` изменение высоты, ширины и позиции (`top` и `left`), когда же блок теряет курсор возвращать высоту, ширину и позицию обратно. В общем-то с этим проблемы нет, вот как я это сделал:
$('#button').hover(function () {
$('#button').animate({
width: '+=20px',
height: '+=20px',
left: '-=10px',
top: '-=10px'
}, 200);
}, function () {
$('#button').animate({
width: '-=20px',
height: '-=20px',
left: '+=10px',
top: '+=10px'
}, 200);
})
Собственно вот в чем вопрос: мне нужно изменять все величины не в пикселях, а в процентах. Помогите, пожалуйста.
P.S. Немного поясню, зачем нужно позиционирование: блок увеличивается, а его центральная точка остается неизменной. Как-то так.
Пример: < | По-моему, это не сложно. Переделаю ваш пример под проценты:
var w = $(this).width(), //ширина картинки
h = $(this).height(), //высота картинки
zoom = 0.5; //зум картинки. это означает увеличение на 50%
$(this, '#buttons a').animate({
width: w+w*zoom,
height: h+h*zoom,
left: "-="+(w*zoom/2),
top: "-="+(h*zoom/2)
}, 200, 'easeOutElastic');
},
function () {
$(this, '#buttons a').animate({
width: w,
height: h,
left: "+="+(w*zoom/2),
top: "+="+(h*zoom/2)
}, 200, 'easeOutElastic');
Вот переписал первый попавшийся в гугле пример под процентное увеличение мой пример (пример из гугла с абсолютным смещением)
Вот, собственно, ваш пример переделанный на фидле | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "jquery, javascript"
} |
In sequelize, how do I select records that match all values that i am searching for?
As an example, I have the following table:
T | S
------
1 | 5
1 | 6
1 | 7
2 | 6
2 | 7
3 | 6
Query: array [1,2]
I want to select all values in S that have the value 1 AND 2 in the T Column.
So in the above example I should get as a result (6,7) because only 6 and 7 have for column T the values 1 and 2.
But i do not want to have 5 in my results as 5 does not have 2 in the T column. How would I do this in sequelize? | > how do i make (1,2) to be used as an array?
Either you insert the array joined as comma-separated literal into the query text (variant 1) or you join the array into one string literal and transfer it iinto the query as a parameter (variant 2).
Variant 1
SELECT s
FROM sourcetable
WHERE t IN (1,2) -- separate filter values
GROUP BY s
HAVING COUNT(DISTINCT t) = 2 -- unique values count
Variant 2
SELECT s
FROM sourcetable
WHERE FIND_IN_SET(t, '1,2') -- separate filter values
GROUP BY s
HAVING COUNT(DISTINCT t) = 2 -- unique values count
If `(s,t)` is unique then DISTINCT keyword may be removed. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql, sequelize.js"
} |
How to increment the amount of documents shown in the Recent Document List
How can i increment the amount of Recent Documents in the Recent Document List since 10 Items is very small for the kind of files i open in a day.
Am using Ubuntu Classic (No Effect) | Yep, the number of the recent document list is hardcoded in Gnome and can't be changed afaik. | stackexchange-askubuntu | {
"answer_score": 3,
"question_score": 8,
"tags": "11.04, document management"
} |
Eloquent select from database, get results newer than a given unix timestamp
I would like to select rows from my database newer than some specified UNIX timestamp specified in the parameters.
The column `created_at` is a datetime in the table `tracks`. The parameter `$timestamp` is a UNIX timestamp (an integer).
So I am trying with `Tracks::where('created_at','>=',$timestamp)->get();` which simply returns all tracks, no matter which $timestamp I specify.
However I can see the type problem, and I have tried different things like writing 'UNIX_TIMESTAMP(created_at)' instead of created_at, but with no luck.
So I assume there is some elegant and simple way of doing this. Can you help me? | There are 2 ways to solve this.
1. Use `Tracks::where(DB::raw('UNIX_TIMESTAMP(created_at)'),'>=',$timestamp)`
2. Use a `DateTime` or `Carbon` object.
like this:
$timestamp = Carbon\Carbon::createFromTimestamp($timestamp);
Tracks::where('created_at','>=',$timestamp)->get(); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 2,
"tags": "php, laravel, eloquent"
} |
Use switchyard property in jpa binding native query
Lets say I have a property defined in my switchyard.xml
!Switchyard Property Definition
If I have a JPA native query, also in my switchyard.xml that includes
(select sysdate + interval '720' minute from dual)
I would like to use the property in the native query such as
(select sysdate + interval '{horizonWindowMinutes}' minute from dual)
Is there a way using switchyard that I can achieve this property substitution? | Nearly had it. Just needed to add the $ sign at the start of the property substitution.
(select sysdate + interval '${horizonWindowMinutes}' minute from dual) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, jpa, switchyard"
} |
Select Style attribute using ExtJS on IE7 not working
A very stripped down example here.
Code:
function changeBackground() {
var testDiv = Ext.get("test");
var allStyleDivs = testDiv.select("*[style*='background-color'], *[style*='BACKGROUND-COLOR']");
allStyleDivs.each(replaceBackground);
}
function replaceBackground(element) {
element.setStyle('background-color','blue');
}
In FF, IE8, Chrome this page works fine. IE7 says _Object doesn't support this property or method._ **What's the dealy yo?** | See this post on the ExtJs Forum | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "extjs"
} |
Query criteria: from public variable or from form
After a few hours searching, I couldn't find any solution to this little problem I'm having.
I have a query that retrieves one of its criteria from a form. I have referenced correctly the value on the form from the query, and it works, but what I wanted to do is a bit more complicated: when the form is closed, I want to launch the query with a "default value".
I tried to do it in 2 different ways: a) Defining an "IIf" at the query criteria: I would need a function that checks if the form from which I retrieve the values is open. b) Defining public variables with a default value, which would be changed from the form: I don't know where/when to initialize the value of the variable.
Does anyone have a better idea on how to do this?
TL;DR: Query gets criteria from form when it's open. If form is closed, query uses default value. HELP! | You can create a VBA function in a module to do this :
Function MyCriterion() As Long
MyCriterion = 1234 ' default value
If CurrentProject.AllForms("MyForm").IsLoaded Then
MyCriterion = Forms("MyForm").MyControl.Value
End If
End Function | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "forms, ms access"
} |
Calculating Sums Of Maths
I was wondering whether I got the correct answer. I'm supposed to solve by logs and get the exact value of x using my calculator. My question:
$9^{x -5} = 2^{x - 8}$ | We have:
$$6^{x-2}=4^{x-1}\to(2^{x-2})(3^{x-2})=2^{2x-2}$$ $$\to3^{x-2}=2^{x}$$
* * *
We take logs so that: $$x=\log_{2}{3^{x-2}}$$ $$\to x=(x-2)\log_2{3}$$
Then use an iteration:
$$x_{n+1}=(x_n-2)\log_2{3}$$
Plugging in values proves this iterate diverges.
* * *
We can also take logs for: $$(x-2)=\log_3{2^x}$$ $$\to x=x\log_3{2}+2$$ and use the iteration: $$x_{n+1}=x_n\log_3{2}+2, x_0=1$$ We get $$\lim_{n\to\infty}x_n\approx 5.419022583...$$ and so this is a solution. The divergence of the first iterate shows that this is the only solution. | stackexchange-math | {
"answer_score": 1,
"question_score": -1,
"tags": "logarithms"
} |
Should a NAS always be on?
I'm thinking of purchasing a NAS that can do RAID1, to have a local backup. Can such a device be left always on ? What happens in case of a power outage ? | To elaborate on @ta.speot.is answer - Yes, a NAS (or computer) can be left on 24/7 - there are arguments to be made that this is actually good for devices as they are not subject to the stresses caused by changes in temperature or the sudden rush of current on startup.
In the case of a power outage, you should ideally have a UPS which can be used to do a controlled shutdown - failing which, of-course the NAS will just turn off. (There might be a battery backed write cache to hold your data for a few hours/days, but I wouldn't count on it).
I suspect the real answer to the second question would be that a NAS will generally use a journalled filesystem (most filesystems are nowdays I think), so if there is a sudden power outage it can roll back a short while to the last "known good" write and you don't corrupt the filesystem. | stackexchange-superuser | {
"answer_score": 3,
"question_score": 1,
"tags": "nas, power"
} |
Checking if no elements in IEnumerable(Of T) - Linq element and quantifier operators
For my function
IEnumerable<CallbackListRecord> LoadOpenListToProcess(CallbackSearchParams usp);
This line errors when the sequence contains no elements (as it should)
CallbackListRecord nextRecord = CallbackSearch.LoadOpenListToProcess(p).First();
I have changed it to the following
CallbackListRecord nextRecord = null;
IEnumerable<CallbackListRecord> nextRecords = CallbackSearch.LoadOpenListToProcess(p);
if (nextRecords.Any())
{
nextRecord = nextRecords.First();
}
Are there better, easier or more elegant ways to determine if the IEnumerable sequence has no elements? | You should try to avoid enumerating it more times than necessary (even if short-circuited, like `First` and `Any`) - how about:
var nextRecord = CallbackSearch.LoadOpenListToProcess(p).FirstOrDefault();
if(nextRecord != null) {
// process it...
}
This works well with classes (since you can just compare the reference to null). | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "c#, linq, ienumerable, element"
} |
What does $[m](T)$ mean in the context of algebraic curve divisors?
In Silverman's _Arithmetic of Elliptic Curves_ (page 95), it says
> Letting $T \in E$ [an elliptic curve] with $[m]T' = T$, there is similarly a function $g$ satisfying $$\text{div}(g) = [m]*(T) - [m]*(\mathcal{O}) = \sum_{R \in \text{the m-torsion}} (T' + R)-(R)$$
I know that $[m]T$ refers to multiplication by $m$ (addition $m$ times), and (.) refers to the point as a divisor, but what does $m$ mean? | Silverman's notation here is $[m]^*(T)$ **not** $[m]*(T)$ and **not** $m$.
Here $[m]$ is the "multiplication by $m$" map from $E$ to $E$ and $[m]^*(T)$ is the pullback operator on divisors induced by $[m]$. For a separable isogeny $\phi$, then by definition (earlier in the book) $\phi^*(P)$ is the sum of $(Q)$ over the $(Q)$ for which $\phi(Q)=P$. So $[m]^*(T)$ here is the sum of the $(U)$ with $m=T$. These are the $T'+R$ for one fixed $T'$ with $m=T$ and $m=O$, as stated in the given formula. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "notation, elliptic curves, divisor sum"
} |
Securely Deleting A File In Ram
I'm running a live distro in ram. I need to write a password to a file. Later, I need to delete it securely.
I don't know how live file systems work, so I'm unsure if I open the file for writing, then write over it with data the length of the password, if it actually will write over that exact memory location or not. The goal is to securely delete the file by writing over it.
I don't know if journaling happens in Live Linux distos. If so, is it possible to create a virtual file system in ram? I could then just write the password there and dd will securely write from beginnig to end of the volume.
What are my options? | Journalling depends on the filesystem being used, but if you're using a live Linux distribution, there usually isn't any persistence by default (with some exceptions). If your filesystem is journalling (check `/proc/mounts` to find out which filesystem is being used) I would not rely on anything to try and "securely delete" a file (unless that filesystem is entirely in memory, in which case the data will be lost shortly after the RAM loses power).
If you want to be safe, mount a `ramfs` ( _not_ `tmpfs` as this may swap!) filesystem and write it there. The data will be lost entirely once the RAM has lost charge (if you're paranoid, leave it unpowered for a minute or so). | stackexchange-unix | {
"answer_score": 2,
"question_score": 2,
"tags": "security, livecd"
} |
How can I get data with key
I want to find data with `key` from google datastore
in normal RDB
select * from items where key = '123124124234221'
in GQL Query
SELECT * from items WHERE __key__ HAS ANCESTOR KEY(item, 123124124234221)
it works!
but in nodejs
let query = datastoreClient.createQuery('items')
.hasAncestor(datastoreClient.key(['item', '123124124234221']))
datastoreClient.runQuery(query, (err, entity) => {
if (err) { reject(err) }
console.log(entity)
})
result is empty []
please help how to get a data with key in node. | Rather than doing a query, you should do a direct get on the entity.
var key = datastoreClient.key(['item', datastore.int('123124124234221')]);
datastoreClient.get(key, function(err, entity) {
console.log(err || entity);
}); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "node.js, database, google cloud datastore, google cloud platform"
} |
Running scheduled task in current profile with another user
I have a doubt about Windows scheduler: I created a domain user ( _backupuser_ ) appositely to launch a batch file that starts the backup. The problem is that the batch is launched in the " _backupuser_ " profile and it is not shown to the current user. How can I make sure that it is started as _backupuser_ (profile which does not undergo a change of password) and it is displayed by the current user? I do not know if I have explained. Thanks! | * Use a log file and have the bat job email it to yourself using a tool like blat or bmail
Or
* Execute the bat using psexec -s -i backup.bat. The command window will appear on the current users desktop. BEWARE the bat will run as SYSTEM user. | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 0,
"tags": "windows, backup, scheduled task, batch file"
} |
What is a test case?
I'm having difficulties finding a hard definition of the word "test case". Some sources claim that a test case is a class that extends `TestCase`. Other sources claim that a test case is a single test method. The JUnit documentation is unclear, it appears to me the words "test case" and "test" mean the same:
> The `Test` annotation tells JUnit that the `public void` method to which it is attached can be run as a **test case**. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the **test** will be reported by JUnit as a failure. If no exceptions are thrown, the **test** is assumed to have succeeded.
So what exactly is a "test case", and what is its relationship to a "test"? | I'd point you over to the JUnit documentation on TestCase. In it, it describes three conditions for what it denotes a TestCase:
1. implement a subclass of TestCase
2. define instance variables that store the state of the fixture
3. initialize the fixture state by overriding setUp()
4. clean-up after a test by overriding tearDown().
The setUp and tearDown portion I think are critical to understanding here. It's not just simply that a test case is but one annotated method. The test case is that method plus the initialization and destruction of the frame on which a test will be run.
So to answer your question, a test is one annotated method which attempts to verify the workings of a single method while a test case is that test plus the frame in which it will be run. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 5,
"tags": "testing, junit, terminology, testcase"
} |
memory usage history from command line in Debian
I need to know the memory/CPU usage history from command line. My server is Debian (text mode only). Is it possible? | You can run the top command in batch mode by using the -b option, then dump that to a file.
On start up of your server, open a terminal, run the following commmand.
top -b > ~/cpu.txt
The sysstat collection of tools contains sar which is able to save system activity information: <
Regards, Paresh | stackexchange-superuser | {
"answer_score": 2,
"question_score": 2,
"tags": "memory, debian, logging, cpu usage"
} |
Как создать аналог event listener на php?
Нужен метод который будет отслеживать изменения в свойствах другого класса. Подскажите, пожалуйста, как можно это реализовать или где об этом почитать. | Данный паттерн носит название **Observer**. Описывать тут нет смысла - идите в источники.
Сюда)
и сюда
и ещё сюда
да и вообще | stackexchange-ru_stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "php, ооп, методы"
} |
Why 0.1 represented in float correctly? (I know why not in result of 2.0-1.9)
I've read a lot about float representation recently (including this: How To Represent 0.1 In Floating Point Arithmetic And Decimal). Now I understand that 0.1 can't be represented correctly, and when I do this:
System.out.println(2.0f - 1.9f);
I'll never get precise result.
So the question is: How represented 0.1f in the following code in order to print 0.1 correctly? Is that some kind of syntatic sugar? In the article that I above mentioned says: 0.1 represented in memory as 0.100000001490116119384765625. So why I don't get this output for this code:
System.out.println(0.1f);
How does Java deal with this? | `System.out.println` performs some rounding for floats and doubles. It uses `Float.toString()`, which itself (in the oraclew JDK) delegates to the `FloatingDecimal` class - you can have a look at the source of `FloatingDecimal#toJavaFormatString()` for gory details.
If you try:
BigDecimal bd = new BigDecimal(0.1f);
System.out.println(bd);
You will see the real value of 0.1f: 0.100000001490116119384765625. | stackexchange-stackoverflow | {
"answer_score": 18,
"question_score": 12,
"tags": "java, floating point"
} |
How to create an array from flattened data in BigQuery
There is a lot of information online to go from flattened data to arrays or structs, but I need to do the opposite and I am having a hard time archiving it. I am using Google BigQuery.
I have something like:
| Id | Value1 | Value2 |
| 1 | 1 | 2 |
| 1 | 3 | 4 |
| 2 | 5 | 6 |
| 2 | 7 | 8 |
I would like to get for the example above:
1, [(1, 2), (3, 4)]
2, [(5, 6), (7, 8)]
If I try to put an array in the select with a group by it is not a valid statement
For example:
SELECT Id, [ STRUCT(Value1, Value2) ] as Value
FROM `table.dataset`
GROUP BY Id
Which returns:
1, (1, 2)
1, (3, 4)
2, (5, 6)
2, (7, 8)
Which is not what I am looking for. The structure I got is: `Id, Value.Value1, Value.Value2` and I want `Id, [ Value(V1, V2), Value(V1, V2), ... ]` | You can do that with `SELECT Id, ARRAY_AGG(STRUCT(Value1, Value2)) ... GROUP BY Id` | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "google bigquery"
} |
curl request headers in Apache default error_logs
some uncontrolled logging on the web server inside apache error_log
< Connection: Keep-Alive
< Keep-Alive: max=10
< Expires: Thu, 01 Jan 1970 00:00:00 GMT
< Set-Cookie: BIGipServerabcd_prod_serv=4116270402.20480.0000; expires=Thu, 03-Apr-2014 00:19:32 GMT; path=/
* Connection #0 to host services.abcd.com left intact
* Closing connection #0
* About to connect() to services.abcd.com port 80
* Trying 99.97.124.97... * connected
* Connected to services.abcd.com (99.97.124.97) port 80 here | These are the verbose output from curl. Generated for this line:
curl_setopt($ch, CURLOPT_VERBOSE, 1);
So find this line from your code and make it `0` or `false`(only if you do not wish to see the prints). Or simply delete this. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, curl"
} |
TextView and Scroll View
I have put textview in scrollview it's working fine. I want to do that if user should not to scroll textview, inspite of textview should pro-grammatically scroll to the last line.
does is possible? How? | You can actually let your scrollView to scroll to the bottom. In that way whenever that event gets triggered automatically your ScrollView will scroll and cursor will be at las line.
You can use `getScrollView().fullScroll(ScrollView.FOCUS_DOWN);` which you can actually spawn as a new thread and run. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android"
} |
Finding a PDF for a two variable function $W = X - Y$
Problem:
Let $X$ and $Y$ be independent r.v.'s each uniformly distrbuted over $(0,1)$. Let $W = X - Y$. Find the marginal pdf of $W$.
Answer:
\begin{eqnarray*} P(W <= w_0 ) &=& P( X - Y <= w_0 ) = P( X <= w_0 + Y ) \end{eqnarray*} Now, consider the case where $w_0 < 0$. \begin{eqnarray*} P( X <= w_0 + Y ) &=& \int_0^1 \int_0^{y+w_0} dx dy \\\ P( X <= w_0 + Y ) &=& \int_0^1 y + w_o dy = \frac{y^2}{2} + w_0 y \Big|_{y=0}^{y = 1} \\\ P( X <= w_0 + Y ) &=& \frac{1}{2} + w_0 \\\ F(w) &=& w + \frac{1}{2} \\\ F(x,y) &=& x - y + \frac{1}{2} \\\ F_x(x,y) &=& -y \\\ F_y(x,y) &=& x \\\ \end{eqnarray*} I know this is not right but where did I go wrong? The book got: \begin{eqnarray*} f_w(w) &=& -w + 1 \\\ \end{eqnarray*}
Bob | $$F_W(w) = P(X-Y \leq w) = \int_{y=-\infty}^{\infty}\int_{x=-\infty}^{y+w}f_{XY}(x,y)\text{dxdy}$$
$$ \begin{align} f_W(w) & = \frac{dF_W(w)}{dw} \\\ & \\\ & = \int_{y=-\infty}^{\infty}\left[\frac{\partial}{\partial{w}}\int_{x=-\infty}^{y+w}f_{XY}(x,y)\text{dx}\right]\text{dy} \\\ & \\\ & = \int_{-\infty}^{\infty}f_{XY}(y+w,y)\text{dy} \\\ & \\\ & = \:\: \\{\text{independence}\\} \\\ & \\\ & = \int_{-\infty}^{\infty}f_{X}(y+w)f_{Y}(y)\text{dy} \\\ \end{align} $$ | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "probability, probability theory"
} |
Apache Ivy: Difference between local Ivy cache and local repository
By default Ivy installs a "local cache" under your `<HOME>/.ivy2` directory. But if I decide to "host" a local repository on the same machine, say, at `<HOME>/workbench/ivy/`, then how are these two concepts different? Isn't a cache the same thing as an artifact repository? | The concepts page describes the function of the ivy cache and the kinds of file it contains:
<
In a nutshell, the ivy cache is designed to improve performance, it's not meant to be the definitive copy of the files a build depends on. One never publishes to the cache. This is what an ivy repository is used for.
Additonal notes:
* There is an ivy cleancache task designed to purge ivy's cache (Something which is recommended, periodically, to cater for misbehaving repositories)
* In Maven-land the "local" repository is also used as a cache..... ivy has a cleaner separation of purpose. | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 9,
"tags": "java, apache, ant, ivy"
} |
Android gridview like in flickr
Hi im interested in achieving effect like in this screenshot
!enter image description here
Question is how to add images to gridview with not discarding the aspect ratio and cropping it but adding them side by side | I think StaggeredGridView is what best suited for your requirement.
this is the link go and download and attach this library to your project.
<
I used this and it works very beautifully..! | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "android, image, android gridview"
} |
What is wrong with this RSpec expectation?
I am using rspec version 2.14.8 and Ruby 2.1.1.
I have the following in test_spec.rb
describe 'My code' do
it 'should work' do
expect ( nil ).to be_nil
expect ( "test" ).to eq( "test")
end
end
When I run this simple spec (`rspec test_spec.rb`), I get the following error:
Failures:
1) My code should work
Failure/Error: expect ( nil ).to be_nil
NoMethodError:
undefined method `to' for nil:NilClass
# ./test_spec.rb:3:in `block (2 levels) in <top (required)>'
What is wrong!? | You must not put a space between `expect` and the opening paren `(`.
The working code sample is as follows:
describe 'My code' do
it 'should work' do
expect( nil ).to be_nil
expect( "test" ).to eq( "test")
end
end | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "ruby, rspec, rspec2, matcher"
} |
Probability of at least one success in large sample
I toss 1000 _unfair_ coins. I wish to calculate the probability that out of the outcomes of the 1000 tosses, at least one head will be obtained. The probability of getting head in any one toss is 0.03125.
I know how to solve this with fair coins where each of the two outcomes is equally likely. But I have no idea where to begin when the probabilities are unequal. | Let $X$ be the number of heads among the total $n$ tosses of the unfair coin. You are interested in computing $\Pr\left(X > 0\right)$. Since $X$ is certainly non-negative, we have $$ \Pr(X>0) = \Pr(X \geqslant 0) - \Pr(X=0) = 1 - \Pr(X=0) $$ The event $\\{X=0\\}$ means that all of $n$ _independent_ tosses resulted in the tail, i.e. $\Pr(X=0) = \left(1-p\right)^n$, thus $$ \Pr(X>0) = 1 - \left(1-p\right)^n $$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "probability"
} |
Synchronicity of web service calls
Are web service calls synchronous or asynchronous by default? How is synchronicity determined, by the service or by the client?
I have code similar to the following:
try
{
string result = MakeWebServiceCall_1(); // this is a third party webservice
MakeWebServiceCall_2(result); // another webservice which must happen *after* the first one is complete
}
catch()
{
SetStatus(Status.Error); // this calls my own stored procedure
throw;
}
SetStatus(Status.Sucess);
In the above, `SetStatus` is writing to the same tables that the third party web services read from. If I change the status before both web service calls have completed, it's going to make a big mess and I'm going to get fired. How do I know/ensure that the webservice calls are synchronous? | According to MSDN when you add a reference to a Web Service it will implement methods to call the Web Service both synchronously and asynchronously in the proxy class. You just need to make sure you call the right one.
_After you have located an XML Web service for your application to access by using the Add Web Reference dialog box, clicking the Add Reference button will instruct Visual Studio to download the service description to the local machine and then generate a proxy class for the chosen XML Web service. The proxy class will contain methods for calling each exposed XML Web service method both **synchronously** and **asynchronously**._ Source | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "c#, asp.net, web services, synchronization"
} |
SharePoint Online Questions
I have SharePoint Online, If somebody can help to answer it.
1. Can we make SharePoint Online as public facing website ?
2. SharePoint Online can supports multilingual website ? Can we make site variation ?
3. We have already **on premise SharePoint 2013 intranet website** and due to security reason we don't want to make that SharePoint as Public website. We want to make same website on **SharePoint Online**. So now my question is that, can we sync on **Premise SharePoint 2013 with SharePoint Online.**
Hope I will get some expert reply on this. | 1. The Public Website in SharePoint Online – which is part of Office 365
2. SharePoint online Support multi-language, check this link for all supported languages, Variations is not available for Office 365 public websites But if you have SharePoint online plan(Plan1 or Plan2), then you have it but not sure about public sites. check this
3. Their is no OOTB way to sync the On prem to SharePoint Online. But couple of things you can do.
* Manually copy the data from On prem to SPO (depending upon the data). may be using the windows explorer but you will lose the meta data.
* Hybrid Farm(very expensive)
* Write your own application /Code to move the content from On prem to online.
* use 3rd party tool to move the data. i.e sharegate, metalogix. | stackexchange-sharepoint | {
"answer_score": 3,
"question_score": 0,
"tags": "sharepoint enterprise, sharepoint online, sharepoint on prem"
} |
Input from command line
I have a program in C++ which I run for many values of a parameter. What I want to do is the following: Let's say I have two parameters as:
int main(){
double a;
double b;
//some more lines of codes
}
Now after after I compile I want to run it as
./output.out 2.2 5.4
So that `a` takes the value 2.2 and `b` takes the value 5.4.
Of course one way is to use `cin>>` but I cannot do that because I run the program on a cluster. | You need to use _command line arguments_ in your `main`:
int main(int argc, char* argv[]) {
if (argc != 3) return -1;
double a = atof(argv[1]);
double b = atof(argv[2]);
...
return 0;
}
This code parses parameters using `atof`; you could use `stringstream` instead. | stackexchange-stackoverflow | {
"answer_score": 22,
"question_score": 8,
"tags": "c++, command line arguments"
} |
Connecting Tomcat and IIS
When running on Linux I know how to connect Tomcat to Apache. But how is it done when running Windows and IIS? | i've done this in the past using the apache mod-jk project. It is a .dll used by IIS that when configured properly, allows IIS to communicate with tomcat and serve jsps.
< | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 2,
"tags": "iis, tomcat"
} |
web3 alternative languages (aside from javascript)?
Are there any implementations of **web3** that are not in Javascript but preferably a compiled language with full multithreading support? | Almost by definition, web3 is Javascript as it's a Javascript API to bind to a contract ABI (its public interface). However there are bindings for other languages, for example:
Go (as part of go-ethereum): <
HTTP: < | stackexchange-ethereum | {
"answer_score": 2,
"question_score": 0,
"tags": "web3js"
} |
why the time complexity is T(n) = 2n^2 + n + 1?
T(n) = 2n^2 + n + 1 I understand the 2n^2 and 1 parts, but I am confused about the n.
test = 0
for i in range(n):
for j in range(n):
test = test + i*j | This really depends on how your professor/book really break down the operation cost but I think we can kind of figure it out from here. Let's break `2n^2 + n + 1` down. The `n^2` comes from the two loops.
for i in range(n):
for j in range(n):
The `2` coefficient comes from the two operations presumably. Note: this alone is just constant time complexity AKA O(1)
test = test + i * j
The initial calculation of `range(n)` could cost `n` (being the `+ n` in your calculation). Then second call to `range(n)` could be optimized to use a cached value.
Finally it could be the `test = 0` statement in the beginning could be the `+ 1`. This could total in `2n^2 + n + 1`. However, the worse case time complexity to this is still `O(n^2)`. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "algorithm, big o"
} |
Matching pattern on multiple lines
I have a file as below
NAME(BOLIVIA) TYPE(SA)
APPLIC(Java) IP(192.70.xxx.xx)
NAME(BOLIVIA) TYPE(SA)
APPLIC(Java) IP(192.71.xxx.xx)
I am trying to extract the values NAME and IP using sed:
cat file1 |
sed ':a
N
$!ba
s/\n/ /g' | sed -n 's/.*\(NAME(BOLI...)\).*\(IP(.*)\).*/\1 \2/p'
However, I'm only getting the output:
NAME(BOLIVIA) IP(192.71.xxx.xx)
What I would like is:
NAME(BOLIVIA) IP(192.70.xxx.xx)
NAME(BOLIVIA) IP(192.71.xxx.xx)
Would appreciate it if someone could give me a pointer on what I'm missing.
TIA | Your first `sed` commands reformats the file into one long line. You could have used `tr -d "\n"` for this, but that is not the problem.
The problem is in the second part, where the `.*` greedy eats as much as possible until finding the last match.
Your solution could be "fixed" with the ugly
# Do not use this:
sed -zn 's/[^\n]*\(NAME(BOLI...)\)[^\n]*\n[^\n]*\(IP([^)]*)\)[^\n]*/\1 \2/gp' file1
Possible solutions:
cat file1 | paste -d " " - - | sed -n 's/.*\(NAME(BOLI...)\).*\(IP(.*)\).*/\1 \2/p'
# or
grep -Eo "(NAME\(BOLI...\)|IP\(.*\))" file1 | paste -d " " - -
# or
printf "%s %s\n" $(grep -Eo "(NAME\(BOLI...\)|IP\(.*\))" file1) | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "sed"
} |
Add README.md to published npm package
I already published a package to NPM, but forgot the README. I updated the package, tried `npm publish ./` again, but it says I can't publish on top of a published package.
So, how do I send a README to a published package? | You should increment the version. Like `0.0.0` to `0.0.1`.
Just open `package.json` in your text editor, find `"version":"0.0.0"` and type in the new value. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "npm"
} |
How to use *this* in a javascript onlick function and traverse with jquery
I don't know if this is possible but I'm trying to use `this` in an onclick javascript function in order to traverse in jquery.
**HTML**
<input type="text" />
<button onclick="javascript:$.addItem(this)">Add</button>
**JS**
$.addItem= function(e) {
var n = parseFloat($(e).siblings('input').val());
};
Is this even possible or am I missing something? | There is no point in putting the function in the jQuery object, just declare a regular function.
function addItem(e) {
var n = parseFloat($(e).siblings('input').val());
};
Don't use the `javascript:` protocol in an event handler attribute. That's used when you put code in an `href` of a link.
<input type="text" />
<button onclick="addItem(this);">Add</button>
Demo: < | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "javascript, jquery"
} |
Trustees Being Ignored on NSS Volume
I'm trying to figure out what's going on here. I migrated a server from NW6.5SP8 to OES2 Linux. All the trustees on the NSS volumes came over and at some point in the past week, they started being ignored. It's almost as if all the users have supervisor rights from the top down. I don't see this set anywhere. What's going on?
Tom | Holy cow... someone had given the Organization supervisor rights to the TREE :O | stackexchange-serverfault | {
"answer_score": 1,
"question_score": 1,
"tags": "linux, sles, nss, novell"
} |
Compiled documents appearing with extra wide right margin
This problem appeared after I installed XeTeX from TeX Live 2011. Now, many of my files are rendering with a very wide right-hand margin.
Here is some sample code:
\documentclass{octavo}
\usepackage{lipsum}
\begin{document}
\lipsum
\end{document}
When running `pdflatex` or `xelatex` on the file, the right 60% of the file is white and the text is all of the right. With `xelatex`, the output PDF always ignores my custom page dimensions and only gives A4 paper with my text printed very small in the top left corner. | Octavo does not set `\pdfpagewidth` and `\pdfpageheight`. You need to do it yourself, for example
\documentclass[crown]{octavo}
\pdfpagewidth=5in
\pdfpageheight=7.5in
\usepackage{lipsum}
\begin{document}
\lipsum[1-12]
\end{document}
(see < or octavo source code for other classic sizes). | stackexchange-tex | {
"answer_score": 7,
"question_score": 3,
"tags": "margins, templates"
} |
Kotlin JPA: How to deal with @OneToOne initialization
In Java I was doing this:
public class User {
//one-to-one
private Profile profile = new Profile(this);
}
public class Profile {
private User user;
public Profile(User user) {
user.setProfile(this);
this.user = user;
}
}
So I just was creating a user and profile was creating _automatically_. Now I cannot understand how to do it with Kotlin's primary constructor:
class User(
var profile: Profile = Profile(this) //error, since `this` is not in that context
)
class Profile (
var user: User?
) {
constructor(user: User): this(user)
}
How would you deal with this? | This works:
class User {
var profile = Profile(this)
}
class Profile(var user: User?) {
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "kotlin"
} |
Populate table view with filenames
Is there a way to populate the data in a table view with the filenames from a certain folder? Thanks. | `NSFileManager`'s documentation has a section under Tasks called 'Discovering Directory Contents'. Use these methods to get the contents of a directory and then populate your data source for the table view with the results.
You can use that data to display the directory contents in the table view. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "iphone"
} |
Creating a Transparent Checkbox with Background on Top
I have a checkbox that I want replaced with an image. I'm able to successfully have the image overlap the checkbox. The problem is that the image has a transparent background thus causing the user to still see the checkbox. Is there any way I can make the actual checkbox invisible while I still maintain the image background.
CSS
input[type=checkbox]:before {
content:"";
display:inline-block;
width:12px;
height:12px;
background-image: url('
background-size: 12px;
}
HTML
<input type="checkbox" id="chk1" />
Fiddle here. | Corrected.....
I added this `background-color: #fff !important;` to make the 'button box' invisible, or white, either way this replaces the button box display. (don't know why, but if you don't add `content: "";` it doesn't work :/) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "html, css, checkbox, background image"
} |
What to do when all the display elements are stuck on on my Canon XT LCD and viewfinder displays?
I have a Canon Digital Rebel XT. For the most part, it is an incredibly reliable camera. however, this past week I had an issue develop with my displays. On both the top back screen and the viewfinder LCD, all of the bottom elements for Aperture, Shutter Speed and shots remaining are constantly on. Additionally, the exposure level indicator is on for -4/3, 0, 1/3, and 2/3. I'm assuming that this is a software issue, since the same thing is happening to both screens. I have no idea what could have caused this. Does anybody know how to fix this?
Edit: I have also tried a hard reset, to no avail. | It's actually more probable that a display driver/multiplexer chip or one of its associated resistors (hardware) is the problem if one of the segments is "stuck" across characters. That's the circuit that translates between the values to display and the character segments that need to be activated (and such displays, whether LCD, LED, or fluorescent, normally only update one character at a time). It's very likely that the same driver/multiplexer circuit is used for both displays.
If the affected character segment is one that doesn't leave you with ambiguous values you can't decipher, it might not be worth bothering with—except that spare parts aren't "forever" and the display will affect the resale value of the camera should you ever decide to upgrade. (It'll never be worth a fortune, but there's a big difference between "used" and "used and busted", and that couple of hundred bucks difference can make an upgrade easier on the old bank account.) | stackexchange-photo | {
"answer_score": 1,
"question_score": 0,
"tags": "display, canon 350d"
} |
Are there non-Diggles in Diggle Hell?
I am doing a Vegan run, and a consequence of this is that Diggles don't attack me (they are classified as Animals). Is every creature that can appear in Diggle Hell a Diggle ? | **Yes** , there are non-Animals in Diggle Hell - Mini-boss Vlad Digula is not considered Animal:
!Vlad Digula
He is also very tough guy, meeting him may quickly end one's permadeath run. | stackexchange-gaming | {
"answer_score": 2,
"question_score": 4,
"tags": "dungeons of dredmor"
} |
How to call a function with jQuery blur UNLESS clicking on a link?
I have a small jQuery script:
$('.field').blur(function() {
$(this).next().children().hide();
});
The children that is hidden contains some links. This makes it impossible to click the links (because they get hidden). What is an appropriate solution to this?
This is as close as I have got:
$('.field').blur(function() {
$('*').not('.adress').click(function(e) {
foo = $(this).data('events').click;
if(foo.length <= 1) {
// $(this).next('.spacer').children().removeClass("visible");
}
$(this).unbind(e);
});
});
The uncommented line is suppose to refer to the field that is blurred, but it doesn't seem to work. Any suggestions? | You can give it a slight delay, like this:
$('.field').blur(function() {
var kids = $(this).next().children();
setTimeout(function() { kids.hide(); }, 10);
});
This gives you time to click before those child links go away. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "javascript, jquery, jquery events"
} |
How to fix shading problems with this object?
I have these models of two labeled plastic buckets: one of the labels has some kind of shading problem with dark line in the middle. I tried to fix it but nothing seems to be working. I got more meshes with the same problem. Is there a fix? Please help
< | Your scale is absolutely tiny for that object! Apply the scale and it will have perfect shading.
*sizeof(char));
int thread=99;
int jobcounter=88;
sprintf(jc, "%d", jobcounter);
sprintf(tn, "%d", thread);
strcpy(result,"file_");
strcat(result,jc);
strcat(result,"_");
strcat(result, tn);
strcat(result,".html");
printf("%s",result);
Output:
> file_88_Þ*m.html | In your case
sprintf(jc, "%d", jobcounter);
sprintf(tn, "%d", thread);
causes undefined behavior as none of those pointers (first arguments) point to any _valid_ memory.
You need to make sure that the pointer(s) you're using to access a(ny) memory location points to a valid memory. You can either
* make them point to statically/automatic allocated variable or
* use a memory allocator function like `malloc()` or family. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "c, strcpy, strcat"
} |
OpenLayers 3 Stroke style
I want to modify style of the method select . I'm able to change the style of this method but i'm not able to duplicate the white border of blue stroke.
Someone is able to style vector with a stroke and put a border to the stroke?
See this example, for understand what i'm talking about: < | The trick is that you have two styles. With the first style you are drawing a white line, with the second style a thinner blue line on top:
var width = 3;
var styles = [
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'white',
width: width + 2
})
}),
new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: width
})
})
]; | stackexchange-stackoverflow | {
"answer_score": 13,
"question_score": 7,
"tags": "styles, openlayers 3, stroke"
} |
How to get a border on UIBezierPath
I have this
CGRect container = CGRectMake(conX, conY, 220, 50);
UIBezierPath* path = [UIBezierPath bezierPathWithRoundedRect:container cornerRadius:5.0];
[[UIColor blueColor] setFill];
[path fillWithBlendMode:kCGBlendModeNormal alpha:0.7];
I want to get a gray borer around it, have looked at a lot of stuff online but can't see a way to do it easily, is it possible? | If you're not opposed to using layers, something like this could work for you:
//create triangle path
UIBezierPath* path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(0, 30)];
[path addLineToPoint:CGPointMake(100, 30)];
[path addLineToPoint:CGPointMake(100, 0)];
[path addLineToPoint:CGPointMake(0, 30)];
//apply path to shapelayer
CAShapeLayer* greenPath = [CAShapeLayer layer];
greenPath.path = path.CGPath;
[greenPath setFillColor:[UIColor greenColor].CGColor];
[greenPath setStrokeColor:[UIColor blueColor].CGColor];
greenPath.frame=CGRectMake(0, 0,100,30);
//add shape layer to view's layer
[[self layer] addSublayer:greenPath]; | stackexchange-stackoverflow | {
"answer_score": 20,
"question_score": 6,
"tags": "iphone, objective c, ios"
} |
How can you serve a dynamically generated file w/ Tomcat & Java technology?
Having a hard time figuring out how to send dynamic data to a web-app's user without having to create a file & using a dynamic link to static content using java technology. (The main reasons for avoiding the file creation on disk are security and speed)
This is something I have previously done in python, but this web-app is intended to be strictly java technology for maintenance purposes.
After doing a few searches in google I haven't gotten any further. Has anyone done this before or has a good idea for a starting point? | You can output any kind of content type from a servlet. Just set the headers right, and dump to the body of the request the content you want to send.
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + file);
// generate the content and send it to response.getOutputStream()
This will set the content-type to an excel file, and force the browser to download the file.
As a bonus, you can tell your servlet to listen to a specific path, and set the link with a real filename.
<servlet-mapping>
<servlet-name>Export</servlet-name>
<url-pattern>/export/*</url-pattern>
</servlet-mapping>
<a href="<%=request.getContextPath()%>/export/Myreport.xls">
Myreport.xls
</a> | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "java, jsp, tomcat, servlets"
} |
How to create an array of dimension n+1 given a function returning an array of dimension n
With numpy and python3 I have to following problem:
I have a function which returns a 2 dimensional array of integers of fixed size (2x3 in this case). What is the most idiomatic way to run this function `n` times and stack these together to a 3 dimensional 2x3xn array? What about performance? Something which only does the minimum number of allocations would be nice. | You are probably looking for `np.dstack`:
>>> import numpy as np
>>> arrs = [np.random.rand(2, 3) for x in range(5)]
>>> np.dstack(arrs).shape
(2, 3, 5)
If you know the final shape you can do something like the following:
>>> out = np.empty((2, 3, 5))
>>> out[..., 0] = np.random.rand(2, 3) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, python 3.x, numpy"
} |
understanding syb boilerplate elimination
In the example given in <
-- Increase salary by percentage
increase :: Float -> Company -> Company
increase k = everywhere (mkT (incS k))
-- "interesting" code for increase
incS :: Float -> Salary -> Salary
incS k (S s) = S (s * (1+k))
how come increase function compiles without binding anything for the first Company mentioned in its type signature.
Is it something like assigning to a partial function? Why is it done like that? | Yes, it's the same concept as partial application. The line is a shorter (but arguably less clear) equivalent of
increase k c = everywhere (mkT (incS k)) c
As `everywhere` takes two parameters but is only given one, the type of `everywhere (mkT (incS k))` is `Company -> Company`. Because this is exactly what `increase k` returns for each Float k, the resulting type of `increase` is `Float -> Company -> Company`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "generics, haskell, boilerplate"
} |
Why is this reasoning for the problem "What is the probability of picking a second ace after already picking one?" wrong?
I am taking a look at the the following problem: We pick 2 cards at random from a standard deck of cards. Find $P(\text{both aces}| \text{first card is ace})$. I already know that the answer should be computed as follows:
$P(\text{both aces} | \text{first card is ace}) = \dfrac{P(\text{both aces} \cap \text{first card is ace})}{P(\text{first card is ace})} = \dfrac{P(\text{both aces})}{P(\text{first card is ace})} = \dfrac{\binom{4}{2}/\binom{52}{2}}{1-\binom{48}{2}/\binom{52}{2}} = \dfrac{1}{33}$
But my intuition tells me that if I already picked one ace, there are just 3 aces left in the remaining 51 cards which leads to a probability of $\dfrac{1}{17}$. Why is this reasoning wrong? | You did not compute the probability that first card is an ace correctly. It is given by
$\frac{\text{#ways to choose 1 ace}}{\text{#ways to choose any 1 card}} = 4/52$.
That way,
$\mathbb{P}[\text{both aces}|\text{first card is an ace}] = \frac{\frac{4 \cdot 3}{52 \cdot 51}}{4/52} = 3/51 = 1/17$
exactly as you claim. | stackexchange-math | {
"answer_score": 7,
"question_score": 1,
"tags": "probability"
} |
Regular Expression - Only first character check non-letter characters
I've started to study on javascript and regexp specially. I am trying to improve myself on generating regular expressions.
What I am trying to do is - I have a name field in my html file (its in a form ofc)
...
<label for="txtName">Your Name*: </label>
<input id="txtName" type="text" name="txtName" size="30" maxlength="40">
...
And in my js file I am trying to check name cannot start with any NON-letter character, only for the first character. And whole field cannoth contain any special character other than dash and space.
They cannot start with any non-letter character ;
/^[A-Z a-z][A-Z a-z 0-9]*$/
They cannot contain any symbol other than dash and space ;
/^*[[&-._].*]{1,}$/
When I am testing if it works, it doesn't work at all. In which part am I failing ? | Try `/^[A-Za-z][A-Za-z0-9 -]*$/`
When you include a space in the character listing (`[]`), it's going to be allowed in the string that's being searched.
`^[A-Za-z]` matches the first character and says that it must be a letter of some sort.
`[A-Za-z0-9 -]*$` will match any remaining characters(if they exist) after the first character and make sure it's alpha numeric, or contains spaces or dashes. | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 7,
"tags": "javascript, html, regex"
} |
Elastic Search: Why my filtered query returns nothing?
I want to get the result of documents which contains the word "Obama" in their titles using filter. this query returns nothing but the second one using query returns 17000 results. Using Filter:
{
"query": {
"filtered": {
"filter": {
"term": {
"title": "Obama"
}
}
}
}
}
Using Query:
{
"query": {
"match": {
"title": "Obama"
}
}
} | The first one is not analyzed (Term). The second one is (Match).
If you change the first one to 'obama' (lowercase), it will work.
Why? Because your text has been analyzed at index time and the inverted index contains 'obama' and not 'Obama'. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "elasticsearch"
} |
How to handle multiple clients connected to a server in CPP?
I am trying to learn winsock2 by following a tutorial. The problem is that the last section where it tells you about handling multiple clients, has empty code. How would this be achieved with multi-threading in a nice-mannered way?
Code: <
Since links to pastebin must be accompanied by code, I need to add this. | To clarify: I would not use threads to handle multiple clients.
To your question:
* 1 thread should listen for new connections.
* When a connection is accepted a new socket is created.
* For each accepted socket: create a thread for reading/writing to that socket.
The reason I would not implement it this way, is because it will not scale well. After ~100 concurrent connections (maybe more, maybe less) the process will crash due to out of memory. (Threads are expensive).
Google "multi thread socket windows C++" you should find numerous examples including videos with explanations.
If you really want to create a scalable server review libraries such as libevent (which wrap asynchronous mechanisms such as epoll). | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, multithreading, server, winsock2"
} |
Convert elements of a Numpy array to lists
I have a numpy array, which might look something like this
[[1 2]
[3 4]]
I would like to convert it to have one extra dimension, as such:
[[[1]
[2]]
[[3]
[4]]]
Is there a simple way to do this? | Use `np.newaxis` and `tolist`:
a = np.array([[1, 2], [3, 4]])
a[:, :, np.newaxis].tolist()
Output:
[[[1], [2]], [[3], [4]]] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, arrays, python 3.x, list, numpy"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.