text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Why can't open the svg file with inkscape?
There is a svg file ,i can show it with chrome.
svg file
Why can see nothing when to import it(please download it form dropbox and save it as gen.svg) with inkscape?
A:
This svg includes a PNG-File instead of SVG path or fill instructions, where Inkscape is made for:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="880px" height="919px" viewBox="0 0 880 919" enable-background="new 0 0 880 919" xml:space="preserve"> <image id="image0" width="880" height="919" x="0" y="0"
href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA3AAAAOXCAIAAADqyTS6AAAABGdBTUEAALGPC/xhBQAAACBjSFJN
AAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAACA
AElEQVR42uz995sj2XXnCX/PDQeXyMzypqurq71h03uRlEhKlKVGErWa0c7MzuzO+0ftM7O7MyPD
...
ODowMKFcwFEAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjAtMDQtMTFUMTY6MTc6MjQrMDg6MDDQAXjt
AAAAAElFTkSuQmCC" />
</svg>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
spring-cloud-starter-stream-sink-sftp Sftp Sink , file-expression is not working
I am using stfp sink and trying to name the remote file based on header. I am providing following property to name the file on remote
sftp.file-expression=payload.headers['id'] + payload.headers['file_name']
I also tried
sftp.file-expression=headers['id'] + headers['file_name']
but these is not working and in remote the original filename is kept. Is this the right way to write SpEL expression. Also I don't get any error with this property except the prope
A:
Must be sftp.filename-expression:
sftp.filename-expression
A SpEL expression to generate the remote file name. (Expression, default: <none>)
http://docs.spring.io/spring-cloud-stream-app-starters/docs/Bacon.RELEASE/reference/html/spring-cloud-stream-modules-sinks.html#_options_50
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Deploying a docker-compose app on Kubernetes on Docker for Windows
I am trying to follow the instructions at https://docs.docker.com/docker-for-windows/kubernetes/#use-docker-commands for running a docker-compose.yml file against kubernetes on Docker for Windows.
I am using the Edge version of Docker for Windows -- 18.03.0-ce-rc4 -- and I have kubernetes enabled.
I am using the example docker-compose app at https://docs.docker.com/compose/gettingstarted/#step-3-define-services-in-a-compose-file, i.e.
version: '3.3'
services:
web:
build: .
ports:
- '5000:5000'
redis:
image: redis
This example works fine with docker-compose build and docker-compose up
But following the documentation linked above for docker stack, I get the following:
PS C:\dev\projects\python\kubetest> docker stack deploy --compose-file .\docker-compose.yml mystack
Ignoring unsupported options: build
Stack mystack was created
Waiting for the stack to be stable and running...
- Service redis has one container running
PS C:\dev\projects\python\kubetest> kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5d
redis ClusterIP None <none> 55555/TCP 8s
Note that it doesn't create the web service, along with that "ignoring unsupported options: build" error
I also tried using the sample docker-compose.yml file in that documentation linked above, and it didn't work, either, with a totally different error.
In short, by following the documentation, I'm unable to get anything deployed to kubernetes on Docker for Windows.
A:
Due to the lack of support for a build there would be no image to run for the web service containers.
Compose can manage the build for you on a single Docker host. As Swarm and Kubernetes are normally run across multiple nodes, an image should reference a registry available on the network so all nodes can access the same image.
Dockers stack deploy example includes a step to setup a private registry and use that for source of the image:
services:
web:
image: 127.0.0.1:5000/stackdemo
Workaround
In this instance, it might be possible to get away with building the image manually and referencing that image name due to everything running under the one Docker instance, it depends on how Kubernetes is setup.
version: '3.3'
services:
web:
build: .
image: me/web
ports:
- '5000:5000'
redis:
image: redis
Build the image externally
docker-compose build web
or directly with docker:
docker build -t me/web .
A:
there is a project:
https://github.com/kubernetes/kompose
called Docker Kompose that helps users who already have docker-compose files to deploy their applications on Kubernetes as easy as possible by automatically converting their existing docker-compose file into many yaml files.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Deleting a single node in R
I'm trying to visualize a preferential network of products using R. I already have a graph of the product network using igraph, but I want to see what would happen if I were to remove one product. I found that I can delete a node using
g2 <- g - V(g)[15]
but it would also delete all the edges connected to that specific node.
Is there any way to delete just the node and to see how the other nodes reconnect to each other after the deletion of that one node? Any help in this matter is appreciated.
P.S.
Hopefully this will make it clearer:
For example, if we generate the random graph:
set.seed(10)
Data <- data.frame(
X = sample(1:10),
Y = sample(3, 10, replace=T)
)
d <- graph.data.frame(Data)
plot(d)
d2 <- d-V(d)[2] #deleting '3' from the network
plot(d2)
If you notice, when you delete the node '3' from the network, node '9' remains unconnected. Is there a way to see the new edge of node '9' after node '3' is connected? Still following the same plot, we would expect that it would connect to node '2'. Is there a function that does this in igraph? Or should i make a code for it?
A:
Maybe not the most efficient way, but it should work :
library(igraph)
set.seed(10) # for plot images reproducibility
# create a graph
df <- data.frame(
X = c('A','A','B','B','D','E'),
Y = c('B','C','C','F','B','B')
)
d <- graph.data.frame(df)
# plot the original graph
plot(d)
# function to remove the vertex
removeVertexAndKeepConnections <- function(g,v){
# we does not support multiple vertices
stopifnot(length(v) == 1)
vert2rem <- V(g)[v]
if(is.directed(g) == FALSE){
# get the neigbors of the vertex to remove
vx <- as.integer(V(g)[nei(vert2rem)])
# create edges to add before vertex removal
newEdges <- as.matrix(unique(expand.grid(vx,vx)))
# remove the cycles
newEdges <- newEdges[newEdges[,1] != newEdges[,2],]
# sort each row index to remove all the duplicates
newEdges <- t(apply(newEdges,1,sort))
newEdges <- unique(newEdges)
}else{
# get the ingoing/outgoing neigbors of the vertex to remove
vx <- as.integer(V(g)[nei(vert2rem,mode='in')])
vy <- as.integer(V(g)[nei(vert2rem,mode='out')])
# create edges to add before vertex removal
newEdges <- as.matrix(unique(expand.grid(vx,vy)))
}
# remove already existing edges
newEdges <- newEdges[!apply(newEdges,MARGIN=1,FUN=function(x)are.connected(g,x[1],x[2])),]
# add the edges
g <- g + edges(as.integer(t(newEdges)))
# remove the vertex
g <- g - vertex(vert2rem)
return(g)
}
# let's remove B (you can also use the index
v <- 'B'
plot(removeVertexAndKeepConnections(d,v))
Original :
Modified :
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Lifetime of messages in a message queue
How do you control the lifetime of a message in a message queue? What is the default lifetime? I tried running message queues locally and I find that the messages disappear on a system restart. Doesn't this defeat the purpose of the message queue in building loosely coupled applications. Does it mean when messages are sent to another machine for processing it will not be available the next day. Some guidance here is highly appreciated as I am not clear on these aspects of the message queuing system.
A:
There are two kind of non-transactional messages. There is express message and recoverable message. The express message will be gone on a server( or msmq service I think) restart. The express message is the default kind in .net api and in com api. To make the message persistent you have to set the Recoverable property to true. Here is the plumber explanation.
There are other properties to control the lifetime of the message. But their default is forever.
Remember also that those are message properties and not queue properties.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
In Godfather I and/or The Godfather Saga, who played the child star of Woltz?
In the book and Saga it is made clear that Woltz is molesting his juvenile star named "Janie." We see her in two scenes: Right before Hagen meets Woltz for the first time, they are having a party for the kid and then in Woltz's mansion Tom sees the distraught-looking child who is swiftly taken back into her room by her mother who is not concerned about the molestation presumably as long as the kid gets roles. Later in Saga, Hagen tells Vito about this and Vito refers to it as an "infamnia."
Now I am not sure she was in any scenes in Godfather I or if she was referred to in that scene back in New York; maybe it was just in Saga. But IMDB does not have anything about the child or the child's mother listed in either version of GF. My sense is that this is deliberate, the actress maybe did not want to be associated with the role.
In fact, I have the vaguest recollection, no idea from where, that Coppola is keeping it a secret. Many people are still around from the film but this info seems still to be a unavailable. I would be interested in confirmation that Coppola is in fact protecting someone who wished to remain anonymous or any other info. Tiny details about the films are known, but not this one.
A:
Thanks to dbugger we can see in answers.com (which is not perhaps the most easy-to-use website) that Janet Kobelski worked under the professional name of Janet Jordan and passed away from leukemia in 1971 at the age of 13 -- this was before Godfather was released. Assuming this information is correct, she is not listed in any other movies using either name. She went to St. Vincent Ferrer in Manhattan which may turn out to be a source of further information.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I install libglade2-0?
I'm trying to install a Canon MF4450 printer from a network to Ubuntu. I have a driver file from Canon's website Linux_UFRII_PrinterDriver_V270_us_EN.tar.gz. Two *.deb files are contained in the original file. The Printer installer is asking me for a PPD file format to be chosen in driver file selection. I'm using this command:
/folder$ sudo dpkg -i file_name.deb
...in the terminal and it has a dependency problem on libglade2-0 - this package is not installed. How can I install this package?
A:
I don't know if it'll help, this was on Debian Jessie, so YMMV
I was running a ./configure command and getting:
No package 'libglade-2.0' found
So, tried:
$ sudo apt-get install libglade2-0
and getting:
libglade2-0 is already the newest version.
(./configure still generating same error)
Finally tried:
$ sudo apt-get install libglade2-dev
and it seemed to fix the problem
(configure worked, then make worked)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using generating functions show that $\sum^n _{r=1}r\binom{n}{r}\binom{m}{r} =n\binom{n+m-1}{n}$
Using generating functions show that $$\sum^n _{r=1}r\binom{n}{r}\binom{m}{r} =n\binom{n+m-1}{n}$$
I have been thinking about it as follows. The RHS is a coefficient of $x^n$ in the expansion of $$\frac{mx}{(1-x)^{m+1}}$$ The LHS is problematic though. It must be a coefficient of a product of some generating functions. The fact that we have binomial coefficients suggests applying the binomial theorem maybe, but I have not figured out how to do that in this case.
A:
I would prefer complex variables for this one but it can be done using generating functions only. We have for the LHS that it is
$$\sum_{r=1}^n n {n-1\choose r-1} {m\choose r}
= n \sum_{r=0}^{n-1} {n-1\choose r} {m\choose r+1}.$$
Note that when $m-1\gt n-1$ we can extend $r$ to $m-1$ because the first binomial coefficient is zero then. And when $m-1\lt n-1$ or $m\lt n$ we can reduce the sum to $m-1$ because the second binomial coefficient is zero then.
This yields
$$n \sum_{r=0}^{m-1} {n-1\choose r} {m\choose r+1}.$$
Now this is
$$n\sum_{r=0}^{m-1} [z^r] (1+z)^{n-1} [z^{m-r-1}] (1+z)^m.$$
which is precisely
$$n [z^{m-1}] (1+z)^{n-1} (1+z)^m = n [z^{m-1}] (1+z)^{n-1+m}
= n {n-1+m\choose m-1} = n {n+m-1\choose n}.$$
So the two generating functions we were looking for are $(1+z)^{n-1}$ and $(1+z)^m.$
Addendum. In terms of complex variables we put
$${m\choose r+1} =
\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m-r}} (1+z)^m \; dz$$
which yields for the sum
$$\frac{n}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m}} (1+z)^m
\sum_{r=0}^{n-1} {n-1\choose r} z^r\; dz
\\ = \frac{n}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m}} (1+z)^m
(1+z)^{n-1}\; dz
\\ = \frac{n}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m}} (1+z)^{m+n-1}\; dz.$$
This evaluates to $$n{m+n-1\choose m-1}$$ by inspection.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
is "paschalilla" a right translation of this pie (Pascualina)?
I was looking for the word of the pie Pascualina in English , and google translator gave me "paschalilla". I dont think that's the right translation because I made a google search for images for that and I come with no photo of a Pascualina. Then I found another translation which says "spinach and egg pie".
Not sure if you can make a Pascualina with that but the most common ingredient in many places is chard. Does Pascualina have an English name or should I simply call it "chard pie" or something like that? Or perhaps I should use the original name Pascualina? Other usual ingredients are onion, garlic, cheese, pepper and ham
A:
Pies like that are not commonly eaten in Britain (and probably not in other English speaking countries). A quick check of the dictionary confirms that the word "paschalilla" is not used in English. So you have one of the common translator's dilemmas: a concept that does not exist in the target language.
Here you should consider your audience. Are they people who are interested in Latin American cuisine? If so then use "pascualina" but explain its meaning the first time it is used. For example from recipe book:
The Pascualina pie or chard pie is simple to make, delicious and very healthy. This Pascualina is typically Argentinean...
On the other hand, if your readers are not likely to be interested in Latin American food, you can just describe:
Maria cut each of them a slice of spinach and egg pie as the Church bells rang out for Easter...
This is a matter for your judgement.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What file format has 18n, 18g and 18o file extensions?
My professor (who is now unreachable on holiday) gave me files to work with for a mapping project. The files were retrieved from the Ordinance Survey Ireland webpage. They were used to differentially correct GIS data that had been collected in the field.
I don't recognize the file format, and I am unsure how I am meant to interact with these file types. The files have suffixes like .18N, .18G, etc. I have attached a picture. What is this format?
How do I use these files?
I'm working with Grass/QGIS.
A:
Those files are Receiver Independent Exchange Format (RINEX). Which is an open source standard for raw satellite navigation system data. For more information about the file format standards refer to this document. That document is quite thorough but a (very) brief description of the files:
18 in the file extension refers to two digit year the data was collected in.
*o is an observation file. The meat of the data this contains the raw observable(s) collected in the field (C/A code, P or Y code, L1 and L2 or time, phase and range).
*n is a navigation file.
*g is a GLONASS navigation file.
*m is a meteorological data file.
RINEX files are ASCII based files so you can open them with any text editor, although there is not much you can do without processing the files further.
Without knowing what your task is it is difficult to say how you should work with this data but one common way would be to upload your observation file (18o) to the National Geodetic Survey (NGS) Online Positioning User Service (OPUS) to solve for the solution of the observables in the file. Even though your data is from Ireland according to this article from GPS World OPUS can still process data collected outside the US if it meets certain requirements.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
No, he was not wearing a wig
It may be a bit of an overused trope, but my husband-to-be took me to eat in a nice restaurant for my birthday. When we entered the restaurant, I had a strange feeling that this was something I'd seen before... Then I remembered that I had applied for work in the restaurant a few years back, even sent them my CV and everything.
The dinner was excellent – we had wonderful small appetizers, enjoyed some premium beef cuts, tasted some Rhone valley reds, and had coffee with milk afterwards. The only thing I have trouble remembering is what exactly we ordered for dessert.
Can you guess what we had for dessert?
A:
For dessert, you might have had
a gateau St. Honoré, or a marron glacé, or perhaps some delicious crème brûlée.
Let me tell the story again.
(No, he was not wearing a toupée.) Despite the cliché, you and your fiancé went to a nice restaurant. You remembered sending them your resumé. You had some canapés, ate (perhaps) a filet cut of beef, drank (perhaps) some Beaujolais wine, and then enjoyed a latte.
[EDITED to add:] OP has explained in comments that in fact
the actual intention was "words with diacritical marks" rather than specifically requiring e-acute or specifically requiring its sound to be at the end of the word. That resolves the single thing I was least happy about (the wine: Beaujolais is made near but not in the Rhone valley) as well as enabling better answers for the steak and the coffee.
A:
Je pense que c'était...
un parfait.
All credit to @Gareth McCaughan's excellent answer in spotting the pattern, this only really builds off of that (hopefully not too much steals off that), combined with it being, perhaps, fitting the "an overused trope" bit a little (although, granted, so does part of his answer, in the context), along with the mix of something that is also a common word in English... and because, forgiving the pun, it's the perfect finish. But at the same time, the word, while a borrowed word in English, has an actually different (still close, but not the same) meaning in English, which would easily explain the forgetting/confusion.
again, building off of what Gareth spotted, this would have been my rendition in that vein:
No, he was not wearing a toupée. Despite the cliché, your fiancé took you to mangé in a [nice restaurant {this feels like I should have a word for this, but the only thing coming to mind is to simply use italian, rather than french, and then the pronounciation is falling rather than rising at the end... unless the twist is that it's a restaurant à Nice}] for your birthday (tanti auguri a te). Upon entré, you experienced some déjà vu, but had rappelé that you had previously appliqué for a position d'emploi, including sending them your Curriculum Vitae. You had lovely canapés, enjoyed chateaubriand filet, goûté des Beaujolais, and finally ordered some café au lait.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Restart infinite when crawling results to JSON using Puppeteer
I have succeeded in crawling using Puppeteer. Below is a code for extracting a specific product name from the shopping mall. However, I faced one problem.
const express = require('express');
const puppeteer = require('puppeteer');
const fs = require('fs');
const app = express();
(async () => {
const width = 1600, height = 1040;
const option = { headless: true, slowMo: true, args: [`--window-size=${width},${height}`] };
const browser = await puppeteer.launch(option);
const page = await browser.newPage();
await page.goto('https://search.shopping.naver.com/search/all.nhn?query=%EC%96%91%EB%A7%90&cat_id=&frm=NVSHATC');
await page.waitFor(5000);
await page.waitForSelector('ul.goods_list');
await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});
const naver = await page.evaluate(() => {
const data = {
"naver" : []
};
$('ul.goods_list > li._itemSection').each(function () {
const title = $.trim($(this).find('div.info > a.tit').text());
const price = $(this).find('div.info > .price .num').text();
const image = $(this).find('div.img_area img').attr('src');
data.naver.push({ title, price, image })
});
return data;
});
if (await write_file('example.json', JSON.stringify(naver)) === false) {
console.error('Error: Unable to write stores to example.json');
}
await browser.close();
})();
const write_file = (file, data) => new Promise((resolve, reject) => {
fs.writeFile(file, data, 'utf8', error => {
if (error) {
console.error(error);
reject(false);
} else {
resolve(true);
}
});
});
app.listen(3000, () => console.log("Express!!!"));
I send the crawling data to a JSON file(example.json). but I had a problem restarting infinitely. How can I get it to work only once?
A:
nodemon is restarting your process because it detected a file change, ie. your newly written file.
Update the nodemon config to ignore the .json file.
npm
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JMS topic time to live
I'm working on an application consisting of some modules. In one of those module someone created a topic producer that publishes messages on a topic, but this module hasn't a topic consumer to dequeue the messages. The topic producer sets the time-to-live property to 300000 milliseconds using setTimeToLive().
I expect that if there is no consumer, the messages expire within 300000 milliseconds and they are deallocated.
The application is deployed on Tomcat 6.0.36 and it uses an external ActiveMQ server to handle the queues and topics.
Monitoring ActiveMQ with Java VisualVM in the MBeans tab under the topic settings I see that the variable "Enqueue Count" grows, but I don't understand if the time-to-live settings took effect on these messages. I expected to see the counter "ExpiredCount" to increase, but it still remains fixed to 0.
Is there a way to understand if those messages still stay in memory or if they are deallocated?
Thank you very much!
EDIT:
I did some tests using j2ee tutorial examples on netbeans 7.3 using internal glassfish 3.1 as server, monitoring it with jvisualvm and all works as api says:
The JMS API provides no mechanism for browsing a topic. Messages usually disappear from a
topic as soon as they appear: if there are no message consumers to consume them, the JMS
provider removes them. Although durable subscriptions allow messages to remain on a topic > while the message consumer is not active, no facility exists for examining them.
I read that glassfish uses inside activeMQ so I hope that this is valid also for a standalone ActiveMQ server.
END EDIT.
A:
A quote from Creating Robust JMS Applications:
5.1.4 Allowing Messages to Expire
[...]
When the message is published, the specified timeToLive is added to the current time to give the expiration time. Any message not delivered before the specified expiration time is destroyed.
Another quote from the source of javax.jms.Message#getJMSExpiration():
When a message's expiration time is reached, a provider should discard it.
[...]
Clients should not receive messages that have expired; however, the JMS API does not guarantee that this will not happen.
So in case of non durable subscribers:
The server sends the message to each connected subscriber. The expiry value in the message is set to "current time + TTL". Disconnected subscribers will not receive anything.
A connected client receives the message normally, if it has not yet expired.
If a connected client takes too long before receiving a message (the message has expired), it might be discarded by the server (possibly in case the server has not yet pushed it into the client's buffer) or it can be received (possibly in case the message is already in the client's buffer).
So in your case, if there is no consumer, the message is probably not stored at all. Enqueue count is increased, and Expired Count remains at 0. Expired count should only increase in case of a connected (but idle) subscriber.
A quote from How do I find the Size of a Queue
Enqueue Count - the total number of messages sent to the queue since the last restart
Expired Count - the number of messages that were not delivered because they were expired
Note: A test using JBoss 7 shows that in this case the message does not turn up in the client.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
nested ng-repeat always shows the last item in the array
I have a requirement of showing a list of Categories and Subcategories in two tables. For showing the Category data, in HTML :
<tr ng-repeat="item in addNodeCtrl.categoryData track by $index">
<td>{{item.name}}</td>
<td>
<input type="checkbox" ng-model="item.active">
Here it will show the Category and Category active/Inactive switch in the first table.
In the second table, I need to show only the categories in the first table that have been made active through the switch. It will show the subcategories and its active/inactive status. HTML below:
<table ng-repeat="item in ctrl.categoryData | filter:{active:true} track by $index" ng-init="ctrl.getsubCategory(item.id)">
<tbody>
<tr>
<td>{{item.name}}></td>
<td>
<table>
<tr ng-repeat="item1 in ctrl.subCategoryData track by $index">
<td>{{item1.name}}</td>
<td><input type="checkbox" ng-model="item1.active">
</td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
item.id is the category ID and the getsubCategory function in JS is given below
JS Below:
function getsubCategory(categoryid) {
getsubcategservice.getsubcateg({categoryid: categoryid},{})
.$promise.then(success,failure);
function success(response){
vm.subCategoryData = response.data.subCategorys;
}
function failure(reason){
//error message
}
}
The issue here is that when i make the first category switch active , the subcategories are populated, but when the second category switch is made active, the first set of subcategories also changes and lists the subcategories for the second category that was made active.
Please find the JSON data for Category below:
{
"categoryInfoes": {
"categoryInfo": [
{
"active": "true",
"description": "category 1",
"id": "1",
},
{
"active": "true",
"description": "category 2",
"id": "2",
},
{
"active": "true",
"description": "category 3",
"id": "3",
}
]
}
}
Please find the JSON for subcategory below:
{
"subcategoryDetails": {
"subCategorys": [
{
"active": "true",
"name": "1 - subcategory 1",
},
{
"active": "true",
"name": "1 - subcategory 2",
},
{
"active": "true",
"name": "1 - subcategory 3",
},
{
"active": "true",
"name": "1 - subcategory 4",
}
],
"active": "true",
"description": "category 1",
"id": "1",
}
}
{
"subcategoryDetails": {
"subCategorys": [
{
"active": "true",
"name": "2 - subcategory 1",
},
{
"active": "true",
"name": "2 - subcategory 2",
},
{
"active": "true",
"name": "2 - subcategory 3",
},
],
"active": "true",
"description": "category 2",
"id": "2",
}
}
{
"subcategoryDetails": {
"subCategorys": [
{
"active": "true",
"name": "3 - subcategory 1",
},
{
"active": "true",
"name": "3 - subcategory 2",
},
{
"active": "true",
"name": "3 - subcategory 3",
},
],
"active": "true",
"description": "category 3",
"id": "3",
}
}
Could anyone help me out on this?
UPDATE:
I have created a Plunker to demonstrate this:
https://plnkr.co/edit/LqioF8hugsjJCOfmj9Vb?p=preview
If you see in the Plunk, If you check "Category 2" after checking "Category 1", the subcategories get updated for both Category 1 and 2. Same happpens for Category 3. The Subcategory for the last item is updated everywhere.
Please help me out on this and let me know what I am doing wrong,
A:
The problem here is that you are loading the subcategories into scope, and then changing the value in scope each time a category is selected. As far as Angular is concerned, you just wanted to repeat and display that information multiple times. One way to solve this would be to nest the subcategories into their parent category object and bind the ng-repeat to the child sub-categories of their parent.
You can even still load these on the fly when they are selected, if the amount of data is prohibitive to load everything at once.
Let me know if that makes sense.
-- Edit --
Since I haven't heard from you in a day, I decided to add a plunkr to show you what I was talking about:
https://plnkr.co/edit/mquYiX?p=preview
Here is the controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$http) {
// I made the subcategory data an array
$scope.subcategoryData = [];
$http.get("data.json")
.then(function(response) {
$scope.categoryData = response.data;
});
$scope.getsubCategory = function (categoryid) {
$http.get("data"+categoryid+".json")
.then(function(response) {
// the subcategories are keyed on the category Id
// and updated each time the method is called
$scope.subcategoryData[categoryid] = response.data;
console.log($scope.subcategoryData[categoryid]);
})
};
});
And here is your html:
<table ng-repeat="item in categoryData.categorydetail | filter:{active:true} track by $index" >
<tbody>
<tr>
<td>{{item.name}}></td>
<td ng-init="getsubCategory(item.id)">
<table>
<!-- here, I key the subcategoryData in the loop on the Item id. Voila, now it works -->
<tr ng-repeat="item1 in subcategoryData[item.id].subcategoryinfo track by $index">
<td>{{item1.subname}}</td>
<td><input type="checkbox" ng-model="item1.subactive"></td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Writing a more complex Traversal (Lenses)
I'm diving continually deeper into Kmett's lenses; today I'm attempting to write some custom traversals, up until now I've managed to get along by composing existing traversals to create new ones, but I'm doing something a little more complicated and got stuck.
I'm writing a text editor and I'm just adding multiple cursors, originally each buffer had one cursor and had a lens to focus it, now I'm generalizing to a list of cursors and want a traversal over the list. The trick is that in the previous case my lens did some validation inside the setter to ensure that a cursor was clamped to fit within the valid range of the buffer's text. It looked like this:
clampCursor :: Text -> Cursor -> Cursor
cursor :: Lens' Buffer Cursor
cursor = lens getter setter
where getter buf = buf^.curs
setter buf new = let txt = buf^.text
in buf & curs .~ clampCursor txt new
Note how it uses the text info from the context of the buffer to create a lens over the cursor; (Also I'd love to hear about any cleaner ways to do this instead of making custom lenses if anyone has suggestions, I've found myself doing it a lot).
So now that I've got multiple cursors I need to transform this into a Traversal', but of course I can't define a traversal using the lens getter setter method; Looking around for how to define traversals I read this tutorial; Which states the following:
Question: How do I create traversals?
Answer: There are three main ways to create primitive traversals:
traverse is a Traversal' that you get for any type that implements Traversable
Every Lens' will also type-check as a Traversal'
You can use Template Haskell to generate Traversal's using makePrisms since every Prism' is also a Traversal' (not covered in this tutorial)
None of those methods really help out here; I've also seen the style where you create a traversal using applicative style, but it's always been a bit confusing to me and I don't really know how I would use it in this case to get what I want.
I suppose I could write a Lens' Buffer [Cursor] which maps over the cursors in the setter to perform the validation and THEN traverse that list, but I figure there's got to be a way to bake it into the traversal AFTER the traverse (when each single element is focused) somehow. Maybe there's a better way to do this entirely;
Still looking to learn as much as I can about traversals, so any explanations are appreciated! Thanks!
EDIT:
@dfeuer pointed out that when you do this sort of validation you end up with invalid lenses, I really like the clean interface it provides to do them inside the lens; and so far as I know, since the validation is idempotent it shouldn't cause any real issue, but I'm open to suggestions on how to do this better.
A:
My recommendation is to use the Functor / Applicative representation of lenses directly for doing this sort of thing.
To write a non-type-changing (simple) Lens or a Traversal, you need to write a function that takes as arguments a function k :: a -> f a and your structure s and then produces a f s.
k is kind of a generalized modification function, which represents the change that an user of the lens wants to make to the data focused by the lens. But because k is not simply of type a -> a, but instead of type a -> f a, it also allows to carry a "result" out of the update, for example, the value of the field before it was updated (if you use the state monad for f, then you can set the state to the field's old value in the update function and read it out when you run the state monad afterwards).
Our approach in the following code is to change this modification function, to perform some clamping before returning the new value:
-- Takes a cursor update function and returns a modified update function
-- that clamps the return value of the original function
clampCursorUpdate :: Functor f => Text -> (Cursor -> f Cursor) -> (Cursor -> f Cursor)
clampCursorUpdate k = \cur -> fmap (clampCursor txt) (k cur)
We can then turn a non-validating lens into a validating lens (note that as said in the comments, this validating lens is not a law-abiding lens):
-- assuming that _cursor is a lens that accesses
-- the _cursor field without doing any validation
_cursor :: Lens' Buffer Cursor
cursor :: Functor f => (Cursor -> f Cursor) -> Buffer -> f Buffer
cursor k buffer = _cursor (clampCursorUpdate txt k) buffer
where txt = buffer^.text
This approach is easy to generalize to traversals. First, we write the non-validating traversal by composing a Lens' Buffer [Cursor] with traverse, which will turn that into a Traversal' Buffer Cursor:
-- assuming that _cursors is a lens that returns the list of cursors
_cursors :: Lens' Buffer [Cursor]
-- non-validating cursors traversal
_cursorsTraversal :: Traversal' Buffer Cursor
_cursorsTraversal = _cursors . traverse
Now we can use the same approach as we did earlier: since the traversal already does the "mapping" for us, the code is the same, except that we now have an Applicative f constraint on our f, because we want a Traversal':
cursors :: Applicative f => (Cursor -> f Cursor) -> Buffer -> f Buffer
cursors k buffer = _cursorsTraversal (clampCursorUpdate txt k) buffer
whee txt = buffer^.text
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get Sum of Property from Generic list having another generic list
I have below class
public class SearchResponse
{
public string SearchTerm { get; set; }
public List<DataClass> lstDataClass
public string Category { get; set; }
}
public DataClass
{
public String Date { get; set; }
public string NoOfRecord { get; set; }
}
I will be having List<SearchResponse> and
I want to have sum of NoOfRecord by grouping on Searchterm of SearchResponse class and Date of DataClass
Suppose
SearchResponse1
{
SearchTerm="A";
Category="cata";
ListOfDataClass
{
dataclass
{
5 may 2013,
50
}
dataclass
{
6 may 2013,
68
}
}
}
SearchResponse2
{
SearchTerm="A";
Category="catb";
ListOfDataClass
{
dataclass
{
5 may 2013,
52
}
dataclass
{
6 may 2013,
63
}
}
}
SearchResponse3
{
SearchTerm="B";
Category="catc";
ListOfDataClass
{
dataclass
{
5 may 2013,
48
}
dataclass
{
6 may 2013,
21
}
}
}
I want
SearchTerm="A", Date=5 May 2013, TotalRecords=102
SearchTerm="A", Date=6 May 2013, TotalRecords=131
SearchTerm="B", Date=6 May 2013, TotalRecords=48
.
.
.
A:
A linq solution is this:
from x in
(
from sr in SearchResponse
from dc in sr.DataClass
select new { sr.SearchTerm , dc }
)
group x by new { x.SearchTerm, x.dc.Date } into g
select new {
g.Key.SearchTerm,
g.Key.Date,
TotalRecords = g.Sum(g1 => g1.p.NoOfRecord)
}
which first creates a flat list (new { sr.SearchTerm , dc }) in which Searchterm and Date can be grouped together. Subsequently, in each group the Sum is calculated.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
использование random в массивах С++
Как из массива данных типа char вывести случайные пары элементов, чтобы те не повторялись?
Уже сделал работающую программу для вывода этих рандомных пар, но они повторяются.
Буду очень благодарен за помощь!
setlocale(LC_ALL, "Rus");
const char* a1[6] = { "ABC","ACB","BCA","BAC","CAB","CBA" };
srand(time(nullptr));
int c = 6;
for (int i = 1; i < 7; i++)
{
cout << a1[rand() % c] << " - " << a1[rand() % c] << endl;
}
return 0;
A:
#include <iostream>
#include <random>
using namespace std;
int main()
{
const char* a1[6] = {"ABC", "ACB", "BCA", "BAC", "CAB", "CBA"}; // слова
int c = 6, j = 0, r, s, f;
int num[60]; // рабочий массив для хранения индексов напечатанных слов
for (int i = 0; i < 60; i++) num[i] = 0;
setlocale(LC_ALL, "Rus");
random_device rd; // генератор сл.чисел
mt19937 gen(rd());
uniform_int_distribution<> dist(0,5); // сл.числа в нормированном диапазоне от 0 до 5
while (j < 60) {
r = dist(gen);
do {
s = dist(gen);
} while(s == r); // слова в паре не должны повторяться
f = 1; // флажок уникальной пары слов
if(j > 0) // если это не первая пара, ищем ее среди напечатанных
for (int k = 0; k < j; k += 2)
if(r == num[k] && s == num[k+1]) { // если новая пара слов найдена среди напечатанных
f = 0; // сбросить флаг уникальной пары
break;
}
if(f == 1) { // если новая пара слов уникальна, сохраним индексы слов в массиве и печатаем
num[j] = r;
num[j+1] = s;
cout << a1[r] << " - " << a1[s] << " " << (j+2)/2 << endl;
j += 2;
}
}
cout << "Число размещений из 6 по 2 = " << j/2 << endl; // 6!/(6-2)! = 30
return 0;
}
Замечание: Для корректной компиляции в Code::Blocks необходима включенная опция
-std=c++11. Это вызвано использованием продвинутого генератора случайных чисел.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select columns based on sum
I have a data frame with many columns of genes and rows, for example
id treatment time gene1 gene2 gene3 …
1 A 1 2 0 2 …
2 A 2 0 0 3 …
3 A 3 0 0 4 …
4 B 4 0 0 0 …
5 B 5 0 0 2 …
6 B 3 1 0 1 …
7 C 5 0 0 2 …
I would like to keep the all the first several columns (in the example data is three, but there are many columns in real data) and the genes columns that the column sum is > 0.
I would appreciate any help on my question. Thank you very much!
A:
I'm not entirely sure on whether you want to retain rows or columns with the sum of entries > 0.
In case of the former, you can use rowSums like this
df[rowSums(df[, grep("gene", names(df))]) > 0, ]
#id treatment time gene1 gene2 gene3
#1 1 A 1 2 0 2
#2 2 A 2 0 0 3
#3 3 A 3 0 0 4
#5 5 B 5 0 0 2
#6 6 B 3 1 0 1
#7 7 C 5 0 0 2
Or to retain only those columns with the sum of entries > 0 you can use colSums
df[, names(df) %in% c(
names(df)[grep("gene", names(df), invert = T)],
names(which(colSums(df[, grep("gene", names(df))]) > 0)))]
# id treatment time gene1 gene3
#1 1 A 1 2 2
#2 2 A 2 0 3
#3 3 A 3 0 4
#4 4 B 4 0 0
#5 5 B 5 0 2
#6 6 B 3 1 1
#7 7 C 5 0 2
This assumes that all gene columns contain the word "gene" (and all non-gene columns do not contain the word "gene").
Or more concise (thanks @Shree),
df[, c(rep(T, 3), colSums(df[, -c(1:3)]) > 0)]
which assumes that the first 3 columns are non-gene columns (and the remaining columns are all gene columns).
Sample data
df <- read.table(text =
"id treatment time gene1 gene2 gene3
1 A 1 2 0 2
2 A 2 0 0 3
3 A 3 0 0 4
4 B 4 0 0 0
5 B 5 0 0 2
6 B 3 1 0 1
7 C 5 0 0 2", header = T)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to repeat the function N times per second?
How to repeat the function N times per second in Go?
I can:
N := 30 //Repeat 30 times per second
for {
//Do something
time.Sleep(time.Second * time.Duration(N))
}
But that just makes the intervals between repetitions
A:
There are two options, neither will get you a guaranteed x times per second.
Set N not to 30 but 1/30. Thus the sleep will be for 1/30th of a second.
Have an internal for-loop that loops 30 times and executes your 'do something', and then on exit you hit the statement that sleeps for a second.
Option One:
N := 30 //Repeat 30 times per second
for {
//Do something
time.Sleep(time.Duration(1e9 / N)) //time.second constant unnecessary (see kostya comments)
}
Option Two:
N := 1 //Sleep duration of one second
for {
for i := 1; i<=30; i++ {
//Do something
}
time.Sleep(time.Second * time.Duration(N))
}
Note that in option two, everything happens all at once, and then you wait a second. The first option will space out the do something across the second. Because of timing in computers this won't be precise: sleep cannot guarantee it will wake up precisely when you expect.
A:
You can use a time.Ticker to handle all the book-keeping for you. The only "issue" is that if your operation takes longer than expected you'll loose ticks (and thus run fewer than N per second).
func doSomething() {
const N = 30
ticker := time.NewTicker(time.Second / N)
for range ticker.C {
fmt.Println("Do anything that takes no longer than 1/Nth of a second")
}
}
https://play.golang.org/p/Gq-tWMvxIk
|
{
"pile_set_name": "StackExchange"
}
|
Q:
(Random Walk) Compute average relative number of consecutive cookies eaten from the right side of the gap
Currently I am reading the paper 'Excited Random Walk in One Dimension.'
At page $8$ left column, the authors obtain the following:
Probability that the walk eats precisely $r > 0$ consecutive cookies (we term this event a single “meal”) from the right edge of the cookie-free region is
$$P(r) = 2q \frac{\Gamma(L)}{\Gamma(L-2q)} \frac{\Gamma(L+r-1-2q)}{\Gamma(L+r)}$$
where $L-2$ refers to cookie-free gap and $p$ refers to probability of the walk moving to the right and $q$ is the probability of the walk moving to the left.
However, when they calculate the average relative number of consecutive cookies eaten from the right side of the gap, they compute
$$\int_0^\infty \tilde{r} \tilde{P}(\tilde{r})\,d\tilde{r}$$
where $\tilde{r} = \frac{r}{L}$ and $\tilde{P} = LP(r).$
Question: Why do they integrate with respect to $\tilde{r}$ with integrand $\tilde{P}?$
I thought to find the average number of cookie eaten, one just needs to compute
$$\int_0^\infty r P(r)\, dr$$
instead of the above.
A:
The two expressions denote a change of variable (change of scale): they apply
$$
\eqalign{
& 1 = \int_{\,r\, = \,0}^{\;\infty } {P(r)dr} = \int_{\,r\, = \,0}^{\;\infty } {LP(r)d\left( {{r \over L}} \right)} = \cr
& = \int_{\,r\, = \,0}^{\;\infty } {LP\left( {L{r \over L}} \right)d\left( {{r \over L}} \right)}
= \int_{\,\tilde r\, = \,0}^{\;\infty } {LP\left( {L\tilde r} \right)d\tilde r} = \cr
& = \int_{\,\tilde r\, = \,0}^{\;\infty } {\tilde P\left( {\tilde r} \right)d\tilde r} \cr}
$$
to pass from $r,P(r)$ to $\tilde r,\tilde P\left( {\tilde r} \right)$ by putting
$$
\left\{ \matrix{
\tilde r = r/L \hfill \cr
\tilde P\left( {\tilde r} \right) = LP\left( {L\tilde r} \right) = LP\left( r \right) \hfill \cr} \right.
$$
This is a totally licit and very common operation done in probability, for example when reconducing
a Normal distribution with a given $\sigma$ to the standard one.
They explain that such a "standardization" allows to simplify (in some cases) the expressions by "absorbing"
the $L$ parameter, which is in fact a scale parameter. The parallel with the Normal helps
to understand why.
That premised, concerning your doubt on the average,
$$
\int_{\,\tilde r\, = \,0}^{\;\infty } {\tilde r\,\tilde P\left( {\tilde r} \right)d\tilde r}
$$
gives of course the average of $\tilde r$ , denoted as $ \left\langle {\tilde r} \right\rangle$
which tied to $ \left\langle {r} \right\rangle$ by
$$
\left\langle {\tilde r} \right\rangle = \left\langle {r/L} \right\rangle = \left\langle r \right\rangle /L
$$
In fact, soon after eq. (31) they speak of avg.$\tilde r$ as the "average relative number of consecutive cookies ..":
relative is understood to refer to $/L$, and actually immediately below they give
$\left\langle {\tilde r} \right\rangle = \left\langle {r/L} \right\rangle = \cdots $.
Addendum
Going back to eq.(30) reported at the beginning of your post
$$
P(r) = 2q{{\Gamma (L)} \over {\Gamma (L - 2q)}}{{\Gamma (L + r - 1 - 2q)} \over {\Gamma (L + r)}}
$$
The average number of $r$ would be given by
$$
\left\langle r \right\rangle = \sum\limits_{0\, < \,r} {r\,P(r)}
= 2q{{\Gamma (L)} \over {\Gamma (L - 2q)}}\sum\limits_{0\, \le \,r} {\left( {r + 1} \right)\,{{\Gamma (L + r - 2q)} \over {\Gamma (L + r + 1)}}}
$$
In the above $q$ is a real number in the range $(0,1)$; the sum above
can be expressed by means of the Gaussian Hypergeometric Function as
$$
\left\langle r \right\rangle = {{2q} \over L}\;{}_2F_{\,1} \left( {2,\,L - 2q\,;\;L + 1\,;1} \right)
$$
which, in virtue of the Gaussian theorem gives simply
$$
\eqalign{
& \left\langle r \right\rangle = {{2q} \over L}{{\Gamma (L + 1)\Gamma ( - 1 + 2q)} \over {\Gamma (L - 1)\Gamma (1 + 2q)}}
\quad \left| {\,0 < {\mathop{\rm Re}\nolimits} \left( { - 1 + 2q} \right)} \right.\quad = \cr
& = \left\{ {\matrix{ {{{\left( {L - 1} \right)} \over {\left( {2q - 1} \right)}}}
& {\left| \matrix{ \;1 \le L \hfill \cr \;1/2 < q \hfill \cr} \right.} \cr \infty
& {\left| \matrix{\;1 \le L \hfill \cr \;q \le 1/2 \hfill \cr} \right.} \cr } } \right. \cr
}
$$
which, for large $L$, correspond to eq.(32).
To this regard we shall note that:
- the summand $\left( {r + 1} \right)\,{{\Gamma (L + r - 2q)} \over {\Gamma (L + r + 1)}}$ has a series expansion at $r=\infty$ which
is $1/r^{2q} + O(1/r^{2q+1})$ and the sum is therefore convergent for $1<2q$;
- the Hypergeometric $ {}_2F_{\,1} \left( {a,\,b\,;\;c\,;z} \right)$ has a singularity at $z=1$, so that
its value there shall be taken in the limit with due restrictions;
- the restrictions are those provided for the validity of its conversion into the fraction with Gammas, i.e. $0<1-2q$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get continuous dataframe in pandas by filling the missing month with 0
I have a pandas dataframe as shown below where I have Month-Year, need to get the continuous dataframe which should include count as 0 if no rows are found for that month. Excepcted output is shown below.
Input dataframe
Month | Count
--------------
Jan-15 | 10
Feb-15 | 100
Mar-15 | 20
Jul-15 | 10
Sep-15 | 11
Oct-15 | 1
Dec-15 | 15
Expected Output
Month | Count
--------------
Jan-15 | 10
Feb-15 | 100
Mar-15 | 20
Apr-15 | 0
May-15 | 0
Jun-15 | 0
Jul-15 | 10
Aug-15 | 0
Sep-15 | 11
Oct-15 | 1
Nov-15 | 0
Dec-15 | 15
A:
You can set the Month column as the index. It looks like Excel input, if so, it will be parsed at 01.01.2015 so you can resample it as follows:
df.set_index('Month').resample('MS').asfreq().fillna(0)
Out:
Count
Month
2015-01-01 10.0
2015-02-01 100.0
2015-03-01 20.0
2015-04-01 0.0
2015-05-01 0.0
2015-06-01 0.0
2015-07-01 10.0
2015-08-01 0.0
2015-09-01 11.0
2015-10-01 1.0
2015-11-01 0.0
2015-12-01 15.0
If the month column is not recognized as date, you need to convert it first:
df['Month'] = pd.to_datetime(df['Month'], format='%b-%y')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I find the closed form of this integral $\int_0^2\frac{\ln x}{x^3-2x+4}dx$?
How do I find the closed form of this integral:
$$I=\int_0^2\frac{\ln x}{x^3-2x+4}dx$$
First, I have a partial fraction of it:
$$\frac{1}{x^3-2x+4}=\frac{1}{(x+2)(x^2-2x+2)}=\frac{A}{x+2}+\frac{Bx+C}{x^2-2x+2}$$
$$A=\frac{1}{(x^3-2x+4)'}|_{x=-2}=\frac{1}{(3x^2-2)}|_{x=-2}=\frac{1}{10}$$
$$Bx+C=\frac{1}{x+2}|_{x^2-2x=-2}=\frac{1}{(x+2)}\frac{(x-4)}{(x-4)}|_{x^2-2x=-2}=$$
$$=\frac{(x-4)}{(x^2-2x-8)}|_{x^2-2x=-2}=\frac{(x-4)}{(-2-8)}|_{x^2-2x=-2}=-\frac{1}{10}(x-4)$$
Thus:
$$\frac{1}{x^3-2x+4}=\frac{1}{10}\left(\frac{1}{x+2}-\frac{x-4}{x^2-2x+2}\right)$$
$$I=\frac{1}{10}\left(\int_0^2\frac{\ln x}{x+2}dx-\int_0^2\frac{(x-4)\ln x}{x^2-2x+2}dx\right)$$
What should I do next?
A:
$\displaystyle I=\int_0^2\frac{\ln x}{x^3-2x+4}\,dx$
$\begin{align}I=\frac{1}{10}\int_0^2 \frac{\ln x}{2+x}\,dx+\frac{4}{10}\int_0^2 \frac{\ln x}{x^2-2x+2}\,dx-\frac{1}{10}\int_0^2 \frac{x\ln x}{x^2-2x+2}\,dx\end{align}$
$\begin{align}
A&:=\int_0^2 \frac{\ln x}{2+x}\,dx\\
&=\frac{1}{2}\int_0^2 \frac{\ln x}{1+\frac{x}{2}}\,dx\\
\end{align}$
Perform the change of variable $\displaystyle y=\frac{x}{2}$,
$\begin{align}
A&=\int_0^1 \frac{\ln(2y)}{1+y}\,dy\\
&=\int_0^1 \frac{\ln 2}{1+y}\,dy+\int_0^1 \frac{\ln y}{1+y}\,dy\\
&=\ln 2\Big[\ln(1+y)\Big]_0^1-\frac{\pi^2}{12}\\
&=\boxed{\ln^2 2-\frac{\pi^2}{12}}
\end{align}$
It is well-known that,
$\begin{align}\int_0^1 \frac{\ln y}{1+y}\,dy=-\frac{1}{2}\zeta(2)\end{align}$
and,
$\displaystyle \zeta(2)=\frac{\pi^2}{6}$
$\begin{align}B&:=\int_0^2 \frac{\ln x}{x^2-2x+2}\,dx\\
&=\int_0^2\frac{\ln x}{(x-1)^2+1}\,dx
\end{align}$
Perform the change of variable $y=x-1$,
$\begin{align}B&=\int_{-1}^1\frac{\ln(1+y)}{y^2+1}\,dy\\
&=\int_{-1}^0\frac{\ln(1+y)}{y^2+1}\,dy+\int_{0}^1\frac{\ln(1+y)}{y^2+1}\,dy
\end{align}$
Perform the change of variable $x=-y$ in the first integral,
$\begin{align}B&=\int_{0}^1\frac{\ln(1-y)}{y^2+1}\,dy+\int_{0}^1\frac{\ln(1+y)}{y^2+1}\,dy\\
\end{align}$
In the first integral perform the change of variable $\displaystyle x=\frac{1-y}{1+y}$
$\begin{align}B&=\left(\int_0^1\frac{\ln 2}{1+x^2}\,dx+\int_0^1\frac{\ln x}{1+x^2}\,dx-\int_0^1\frac{\ln(1+x)}{1+x^2}\,dx\right)+\int_{0}^1\frac{\ln(1+y)}{1+y^2}\,dy\\
&=\boxed{\frac{1}{4}\pi\ln 2-\text{G}}
\end{align}$
It is well-known that,
$\displaystyle \int_0^1 \frac{\ln x}{1+x^2}\,dx=-\text{G}$
$\begin{align}C&:=\int_0^2 \frac{x\ln x}{x^2-2x+2}\,dx\\
&=\int_0^2\frac{x\ln x}{(x-1)^2+1}\,dx
\end{align}$
Perform the change of variable $y=x-1$,
$\begin{align}C&=\int_{-1}^1\frac{(1+y)\ln(1+y)}{y^2+1}\,dy\\
&=B+\int_{-1}^1\frac{y\ln(1+y)}{y^2+1}\,dy\\
&=\frac{1}{4}\pi\ln 2-\text{G}+\int_{-1}^0\frac{y\ln(1+y)}{y^2+1}\,dy+\int_{0}^1\frac{y\ln(1+y)}{y^2+1}\,dy
\end{align}$
In the first integral perform the change of variable $x=-y$,
$\begin{align}C&=\frac{1}{4}\pi\ln 2-\text{G}-\int_{0}^1\frac{x\ln(1-x)}{x^2+1}\,dx+\int_{0}^1\frac{x\ln(1+x)}{x^2+1}\,dx\\
&=\frac{1}{4}\pi\ln 2-\text{G}+\int_0^1 \frac{x\ln\left(\frac{1+x}{1-x}\right)}{1+x^2}\,dx
\end{align}$
Perform the change of variable $\displaystyle y=\frac{1-x}{1+x}$,
$\begin{align}C&=\frac{1}{4}\pi\ln 2-\text{G}+\int_0^1 \frac{(x-1)\ln x}{x^3+x^2+x+1}\,dx\\
&=\frac{1}{4}\pi\ln 2-\text{G}+\int_0^1\frac{x\ln x}{1+x^2}\,dx-\int_0^1\frac{\ln x}{1+x}\,dx\\
&=\frac{1}{4}\pi\ln 2-\text{G}+\frac{1}{4}\int_0^1\frac{2x\ln(x^2)}{1+x^2}\,dx-\int_0^1\frac{\ln x}{1+x}\,dx\\
\end{align}$
In the first integral perform the change of variable $y=x^2$,
$\begin{align}C&=\frac{1}{4}\pi\ln 2-\text{G}+\frac{1}{4}\int_0^1\frac{\ln x}{1+x}\,dx-\int_0^1\frac{\ln x}{1+x}\,dx\\
&=\frac{1}{4}\pi\ln 2-\text{G}-\frac{3}{4}\int_0^1\frac{\ln x}{1+x}\,dx\\
&=\boxed{\frac{1}{4}\pi\ln 2-\text{G}+\frac{1}{16}\pi^2}
\end{align}$
Therefore,
$\boxed{\displaystyle I=\frac{1}{10}\ln^2 2+\frac{3}{40}\pi\ln 2-\frac{3}{10}\text{G}-\frac{7}{480}\pi^2}$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
For-in loop goes one-too-far and finds 'nil' while unwrapping
It looks like the following Swift for-in loop is trying to go through more elements than are in the array.
For instance, this code:
var list:[Int?] = [1,2,3,4,5,6,7]
print("C-Style for loop")
for var i=0; i<list.count; i++
{
var x:Int = list[i]!
print(x)
}
print("\nFor-in loop")
for var x:Int! in list
{
print(x)
}
Gets this output:
C-Style for loop
1
2
3
4
5
6
7
For each loop
1
2
3
4
5
6
7
fatal error: unexpectedly found nil while unwrapping an Optional value
...
Illegal instruction: 4
I must be missing something here. Shouldn't list.count be the number of elements that the for-in loop tries to unwrap?
Not pictured above, the for-in loop works as expected if use an [Int] list instead of [Int?] with no unwrapping.
I am on Swift version 2.1.1.
A:
Basically you've done something you're not supposed to do, and thus you've stumbled on something that's probably a compiler bug (because the compiler didn't stop you). Very nice!
Now the solution. You are evidently trying to unwrap with your Int!. To unwrap safely, use for case syntax:
let list:[Int?] = [1,2,3,4,5,6,7]
for case let x? in list
{
print(x) // 1, 2, 3, 4, 5, 6, 7
}
Another way (same result):
let list:[Int?] = [1,2,3,4,5,6,7]
list.flatMap{$0}.forEach{print($0)} // 1, 2, 3, 4, 5, 6, 7
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Matlab code to C# code conversion
function [ samples,y, energies] = energy( speech, fs )
window_ms = 200;
threshold = 0.75;
window = window_ms*fs/1000;
speech = speech(1:(length(speech) - mod(length(speech),window)),1);
samples = reshape(speech,window,length(speech)/window);
energies = sqrt(sum(samples.*samples))';
vuv = energies > threshold;
y=vuv;
I have this matlab code and I need to write this code in c#. However I couldn't understand the last part of the code. Also i think speech corresponds to a data List or array according to first part of code. If it does not, please can someone explain what this code is doing. I just want to know logic. fs = 1600 or 3200;
A:
The code takes an array representing a signal. It then breaks it into pieces according to a window of specified length, compute the energy in each segment, and finds out which segments have energy above a certain threshold.
Lets go over the code in more details:
speech = speech(1:(length(speech) - mod(length(speech),window)),1);
the above line is basically making sure that the input signal's length is a multiples of the window length. So say speech was an array of 11 values, and window length was 5, then the code would simply keep only the first 10 values (from 1 to 5*2) removing the last remaining one value.
The next line is:
samples = reshape(speech,window,length(speech)/window));
perhaps it is best explained with a quick example:
>> x = 1:20;
>> reshape(x,4,[])
ans =
1 5 9 13 17
2 6 10 14 18
3 7 11 15 19
4 8 12 16 20
so it reshapes the array into a matrix of "k" rows (k being the window length), and as many columns as needed to complete the array. So the first "K" values would be the first segment, the next "k" values are the second segment, and so on..
Finally the next line is computing the signal energy in each segment (in a vectorized manner).
energies = sqrt(sum(samples.*samples))';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get scroll value on element with position:fixed
I have a page with a header section. In it, two blocks that move sideways after scrolling or dragging on the mobile.
I am trying to set the scrolling for the header, but I want too that the rest of the page stays in place until the side blocks reach left: -50% and right:-50%.
I have an event scroll set to header, with pageYoffset values.
I tried to set the rest of the content the page gives to the section with the position:fixed, but then the scroll does not work anymore, and do not count pageYoffset.
Do you have any ideas how to get around it, so that the rest of the page would scroll only after the full unveiling of the header?
(in short, the pink section should be on top and wait until the header disappears)
let current = $(window).scrollTop();
let windowHeight = $(window).height();
let eleLeft = $(".cd-half-left");
let eleRight = $(".cd-half-right");
let currPositionLeft = eleLeft.position().left;
let currPositionRight = eleRight.position().right;
let headerHeaight = $(".cd-section").height();
let halfBlockWidth = $(".cd-half-block").width();
let windowWidth = $(window).width();
$(window).scroll(function (event) {
current = $(window).scrollTop();
console.log({total:total,current:current});
var newPosition = ((current / headerHeaight)*100) / 2;
console.log(newPosition);
eleLeft.css({left:"-"+newPosition+'%'});
eleRight.css({right:"-"+newPosition+'%'});
});
FIDDLE
A:
A solution would be not to use window scroll but instead handle scroll gesture (from mousewheel and touchmove) to control left and right panel, and prevent actual scroll when the panels are not fully opened.
so instead of $(window].scroll(handler), try with $('.cd-block').bind('mousewheel', handler) and $('.cd-block').bind('mousewheel', handler)
The handler being:
function updateCurrent(event) {
if (current >= 50) {
current = 50;
} else {
if (current <= 0) {
current = 0;
}
// if below 50 we cancel the event to prevent the scroll
event.originalEvent.preventDefault();
}
eleLeft.css({left:"-"+current+'%'});
eleRight.css({right:"-"+current+'%'});
}
Here is a buggy but working solution (keyboard space, up and down should be handled too):
fiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Path to file in server
I am trying to use a PHP file to upload files from an Android app to a web server.
This the PHP file:
<?php
//importing dbDetails file
require_once 'dbDetails.php';
//this is our upload folder
$upload_path = 'usuarios/';
//Getting the server ip
$server_ip = gethostbyname(gethostname());
//creating the upload url
$upload_url = 'http://'.$server_ip.'/danyra/administrar/application/admin/'.$upload_path;
//response array
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
//checking the required parameters from the request
if(isset($_POST['name']) and isset($_FILES['image']['name'])){
//connecting to the database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
//getting name from the request
$name = $_POST['name'];
//getting file info from the request
$fileinfo = pathinfo($_FILES['image']['name']);
//getting the file extension
$extension = $fileinfo['extension'];
//file url to store in the database
$file_url = $upload_url . getFileName() . '.' . $extension;
//file path to upload in the server
$file_path = $upload_path . getFileName() . '.'. $extension;
//trying to save the file in the directory
try{
//saving the file
line 45 --> move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
$sql = "INSERT INTO `images` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');";
//adding the path and name to database
if(mysqli_query($con,$sql)){
//filling response array with values
$response['error'] = false;
$response['url'] = $file_url;
$response['name'] = $name;
}
//if some error occurred
}catch(Exception $e){
$response['error']=true;
$response['message']=$e->getMessage();
}
//displaying the response
echo json_encode($response);
//closing the connection
mysqli_close($con);
}else{
$response['error']=true;
$response['message']='Please choose a file';
}
}
/*
We are generating the file name
so this method will return a file name for the image to be upload
*/
function getFileName(){
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...');
$sql = "SELECT max(id) as id FROM images";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close($con);
if($result['id']==null)
return 1;
else
return ++$result['id'];
}
This file is taken from a tutorial.
This is the scenario:
The PHP file is at:
http://myserver.com/danyra/android_login_api/upload.php
The folder where I want to store the uploaded images is at:
http://myserver.com/danyra/administrar/application/admin/usuarios
I am using POSTMAN to check the script, and I am always receiving this error:
Warning: move_uploaded_file(usuarios/18.png): failed to open stream: No such file or directory in /home2/kokls/public_html/myserver.com/danyra/android_login_api/upload.php on line 45
Warning: move_uploaded_file(): Unable to move '/tmp/phpMciKUa' to 'usuarios/18.png' in /home2/kokls/public_html/myserver.com/danyra/android_login_api/upload.php on line 45
{"error":false,"url":"http:\/\/XXX.XXX.246.130\/danyra\/administrar\/application\/admin\/usuarios\/18.png","name":"fsd"}
I have tried a lot of options changing paths, but with no success.
Any help is welcome.
A:
I think your current path is incorrect. You should be using a relative path.
Try this path
$upload_path = $_SERVER['DOCUMENT_ROOT'].'/danyra/administrar/application/admin/usuarios/';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ERROR/AndroidRuntime(328): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
**How to solve this ERROR/AndroidRuntime(328):
Caused by:
java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10
this problem ...**
**Log cat:**
06-15 05:11:39.499: ERROR/AndroidRuntime(328): FATAL EXCEPTION: AsyncTask #2
06-15 05:11:39.499: ERROR/AndroidRuntime(328): java.lang.RuntimeException: An error
occured while executing doInBackground()
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at android.os.AsyncTask$3.done(AsyncTask.java:200)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.lang.Thread.run(Thread.java:1096)
**06-15 05:11:39.499: ERROR/AndroidRuntime(328): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10**
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.ArrayList.get(ArrayList.java:311)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at $MyGroupByCategorySync.doInBackground(GroupByCategoryProductSearchMainActivity.java:691)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at android.os.AsyncTask$2.call(AsyncTask.java:185)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-15 05:11:39.499: ERROR/AndroidRuntime(328): ... 4 more
Code :
private void createSingleRow(String bycategory_info[],Drawable product_image)
{
Log.e("------------", ".........................................................................................");
Log.v("-->","GroupByCategoryProductSearchMainActivity STARTING createSingleRow()");
String productname = bycategory_info[1];
String city = bycategory_info[4];
String state = bycategory_info[4];
final String strOfferid=bycategory_info[3];
// for(int row_id=0;row_id<no_of_rows;row_id++)
// {
TableRow table_row = new TableRow(this);
TextView tv_blank = new TextView(this);
TextView tv_photo = new TextView(this);
TextView txt_pname = new TextView(this);
TextView txt_city = new TextView(this);
TextView txt_state = new TextView(this);
TextView img_line = new TextView(this);
LinearLayout line_layout = new LinearLayout(this);
LinearLayout row_layout = new LinearLayout(this);
table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT ,LayoutParams.FILL_PARENT));
table_row.setPadding(0, 5, 0, 5);
tv_blank.setWidth(11);
tv_photo.setBackgroundDrawable(product_image);
Log.i("--: VALUE :--", "PRODUCT IMAGE SET TO ROW = "+single_row_id+" "+product_image);
tv_photo.setLayoutParams(new TableRow.LayoutParams(45 ,45));
tv_photo.setGravity(Gravity.CENTER_VERTICAL);
txt_pname.setBackgroundResource(R.drawable.empty);
txt_pname.setText(productname);
Log.i("--: VALUE :--", "PRODUCT NAME SET TO ROW = "+single_row_id+" "+productname);
txt_pname.setTextColor(color_black);
txt_pname.setTextSize(14);
txt_pname.setWidth(110);
txt_pname.setHeight(60);
txt_pname.setPadding(10,0,0,0);
txt_pname.setGravity(Gravity.LEFT);
txt_pname.setGravity(Gravity.CENTER_VERTICAL);
txt_city.setBackgroundResource(R.drawable.empty);
txt_city.setText(city);
Log.i("--: VALUE :--", "location NAME SET TO ROW = "+single_row_id+" "+city);
txt_city.setTextColor(color_black);
txt_city.setTextSize(13);
txt_city.setWidth(65);
txt_city.setHeight(60);
txt_city.setPadding(15,0,0,0);
txt_city.setGravity(Gravity.LEFT);
txt_city.setGravity(Gravity.CENTER_VERTICAL);
txt_state.setBackgroundResource(R.drawable.empty);
txt_state.setText(state);
Log.i("--: VALUE :--", "PRODUCT NAME SET TO ROW = "+single_row_id+" "+state);
txt_state.setTextColor(color_black);
txt_state.setTextSize(13);
txt_state.setWidth(65);
txt_state.setHeight(60);
txt_state.setPadding(15,0,0,0);
txt_state.setGravity(Gravity.LEFT);
txt_state.setGravity(Gravity.CENTER_VERTICAL);
img_line.setBackgroundResource(R.drawable.separater_line);
img_line.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT ,2));
line_layout.setGravity(Gravity.CENTER_HORIZONTAL);
//table_row.setBackgroundColor(color_white);
/* table_row.setGravity(Gravity.CENTER_VERTICAL);
table_row.addView(tv_blank);
table_row.addView(tv_photo);
table_row.addView(btn_name);*/
row_layout.setGravity(Gravity.CENTER_VERTICAL);
row_layout.addView(tv_blank);
row_layout.addView(tv_photo);
row_layout.addView(txt_pname);
row_layout.addView(txt_city);
row_layout.addView(txt_state);
table_row.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
XMLDataParser.parseXML(XMLDataParser.GROUP_PRODUCT_ITEM_DETAIL_PARSER_CODE,strOfferid);
Intent intent_show_detail = new Intent(GroupByCategoryProductSearchMainActivity.this,GroupByCategoryItemDetail.class);
Toast.makeText(GroupByCategoryProductSearchMainActivity.this, "Row pressed", 1000);
startActivity(intent_show_detail);
finish();
}
});
table_row.addView(row_layout);
line_layout.addView(img_line);
tl_group_product_list_by_category.addView(table_row);
tl_group_product_list_by_category.addView(line_layout);
// }
Log.v("-->","GroupByCategoryProductSearchMainActivity ENDING createSingleRow()");
single_row_id++;
}
Problem in :
class MyGroupByCategorySync extends AsyncTask
{
String bycategory_info[] = new String[9];
Drawable product_image = null;
int no_of_rows = list_productname.size();
@Override
protected Object doInBackground(Object... params)
{
Log.i("--: doInBackground :-- ", "no_of_rows = "+no_of_rows);
for(int i=0;i<no_of_rows;i++)
{
bycategory_info[0] = list_productid.get(i).toString();
bycategory_info[1] = list_productname.get(i).toString();
bycategory_info[2] = list_offername.get(i).toString();
bycategory_info[3] = list_offerid.get(i).toString();
bycategory_info[4] = list_location.get(i).toString();
bycategory_info[5] = list_price.get(i).toString();
bycategory_info[6] = list_prdescription.get(i).toString();
bycategory_info[7] = list_catname.get(i).toString();
bycategory_info[8] = list_categoryid.get(i).toString();
product_image = loadImageFromWebOperations(list_thumbnail.get(i).toString());
XMLData.group_by_category_product_image_list.add(product_image);
if(!is_searched)
XMLData.initial_list_of_product_by_category.add(new ByCategory(bycategory_info[0],bycategory_info[1],list_thumbnail.get(i).toString(),bycategory_info[2],bycategory_info[3],bycategory_info[4],bycategory_info[5],bycategory_info[6],bycategory_info[7],bycategory_info[8], product_image));
else
XMLData.searched_list_of_product_by_category.add(new ByCategory(bycategory_info[0],bycategory_info[1],list_thumbnail.get(i).toString(),bycategory_info[2],bycategory_info[3],bycategory_info[4],bycategory_info[5],bycategory_info[6],bycategory_info[7],bycategory_info[8], product_image));
publishProgress();
SystemClock.sleep(15);
}
Log.v("-->","ENDING doInBackground()");
XMLData.is_by_category_product_data_parsed = true;
return null;
}
@Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
pressed_once = false;
single_row_id = 0;
Log.i("--: VALUE AFTER onPostExecute:--","pressed_once = "+pressed_once);
}
@Override
protected void onProgressUpdate(Object... values)
{
createSingleRow(bycategory_info, product_image);
}
}
A:
You have written int no_of_rows = list_productname.size(). Does all the arraylist have size greater than or equal to that of list_productname means if any arraylist have lesser size than list_productname then that will cause ArrayIndexOutOfBoundsExcption.
because you are looping to get data from several arraylist until you reach list_productname size which is wrong. other array list which suffers because of this logic are list_productid, list_offername, list_offerid etc. You are asuming that other arraylist have minimum no_of_rows number of data.
Thanks
Deepak
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Deleted table in database; how to recreate it using Code First
After deleting table X in database, issued update-database command in PackageManagerConsole, and now I get the following error: "Cannot find the object "dbo.X" because it does not exist or you do not have permissions."
Considering this scenario, how to force CodeFirst to create the table from scratch?
A:
These are the work around steps that deals with this scenario:
delete table from db
delete all related stored procedures if any
create a new imitation entity/table class with a different/distinct name (ex. BlahBlah)
create any configs needed for the new entity inside OnModelCreating method
in the PackageConsoleManager, issue an add-migration command
open the migration file and replace all BlahBlah words with the old table name
Comment or delete the old table class
repeat 7 for old configs in OnModelCreating
rename the new table class with the old table class name
repeat 8 for the new table configs in OnModelCreating
in the PackageConsoleManager, issue an add-migration command again
if it creates a new migration, replace its content with the old migration created in step 6
in the PackageConsoleManager, issue update-database command
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bitminter - no rewards when more work was done?
Very new to this concept, why would something like this occur on Bitminter's pool?
Completed Duration Difficulty Pay/Hour at 1 TH/s Total Thps Your Ghps Your work
2014-10-25 15:02 1h 46m 35,985,640,265 being paid now 2,436.1 10.7 15,856
2014-10-25 13:15 2h 15m 35,985,640,265 being paid now 1,896.0 10.9 20,718
2014-10-25 10:59 2h 13m 35,985,640,265 being paid now 1,935.6 10.4 19,340
2014-10-25 08:45 2h 26m 35,985,640,265 being paid now 1,767.4 10.2 20,756
2014-10-25 06:18 2h 30m 35,985,640,265 being paid now 1,721.0 10.3 21,688
2014-10-25 03:48 2h 11m 35,985,640,265 being paid now 1,951.9 10.2 18,872
2014-10-25 01:36 2h 36m 35,985,640,265 being paid now 1,646.6 10.4 22,722
2014-10-24 22:59 2h 35m 35,985,640,265 being paid now 1,653.5 10.2 22,314
2014-10-24 20:23 2h 37m 35,985,640,265 being paid now 1,641.0 10.9 24,036
2014-10-24 17:46 2h 36m 35,985,640,265 being paid now 1,649.8 10.8 23,620
2014-10-24 15:09 2h 35m 35,985,640,265 ? 1,664.1 10.6 22,992
2014-10-24 12:34 2h 37m 35,985,640,265 0.00000000 1,642.0 10.0 21,882
2014-10-24 09:56 2h 36m 35,985,640,265 0.00000000 1,650.2 10.3 22,502
2014-10-24 07:20 2h 29m 35,985,640,265 0.00000000 1,724.3 10.4 21,844
2014-10-24 04:50 2h 09m 35,985,640,265 0.00000000 1,996.7 8.5 15,322
2014-10-24 02:40 2h 34m 35,985,640,265 0.00057673 1,673.0 0.2 432
2014-10-24 00:06 2h 26m 35,985,640,265 0.00057673 1,756.1 0.2 354
2014-10-23 21:38 1h 41m 35,985,640,265 0.00057673 2,544.7 0.2 222
2014-10-23 19:57 1h 34m 35,985,640,265 0.00057673 2,736.5 0.2 212
2014-10-23 18:22 2h 00m 35,985,640,265 0.00057673 2,135.9 0.2 284
In some cases, next to no work was done - and small reward was found. In others, far more was contributed, but the pay is zero.
I ask on the heels of switching from cgminer to bfgminer; could this be the cause? Is the timing otherwise purely circumstantial?
Thanks!
A:
When a block is found the 10 latest shifts get paid. Finding blocks is a random event. Sometimes we find the next block quickly, other times it takes longer.
Sometimes it happens that it takes a lot of work before the next block is found by the pool. With PPLNS what then happens is that some of the work is not paid at all. The opposite happens when many blocks are found in quick succession. The same work gets paid many times and the pay is extremely good. Over time this evens out.
This is the nature of mining. If you were mining solo instead of in a pool the variance would be much greater. You could find a block and get 25 bitcoins after a few seconds. Or it could take you several years.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
nokogiri: relocation error in production environment
We have a build pipeline in the Rails project: we bundle and test application in the test server and then we copy it (code with gems in vendor/) to the staging server and deploy it to a passenger server.
It used to work, but now I get following error in the apache.error.log:
WARNING: Nokogiri was built against LibXML version 2.7.6, but has dynamically loaded 2.6.26
/usr/local/rvm/rubies/ruby-1.9.2-p318/bin/ruby:
relocation error: /home/project/vendor/bundle/ruby/1.9.1/gems/nokogiri-1.5.2/lib/nokogiri/nokogiri.so:
symbol xmlNextElementSibling, version LIBXML2_2.7.3 not defined in file libxml2.so.2 with link time reference
and error 500 in the browser.
When I run webbrick on the staging server U get similar errors on first request. How could I solve it?
EDIT:
Stange thing with nokogiri version. The same binary loads different libxml version depending if I call it standalone or with bundle exec:
vendor/bundle/ruby/1.9.1/gems/nokogiri-1.5.2/bin/nokogiri -v
# Nokogiri (1.5.2)
---
warnings: []
nokogiri: 1.5.2
ruby:
version: 1.9.2
platform: x86_64-linux
description: ruby 1.9.2p318 (2012-02-14 revision 34678) [x86_64-linux]
engine: ruby
libxml:
binding: extension
compiled: 2.6.26
loaded: 2.6.26
$ bundle exec vendor/bundle/ruby/1.9.1/gems/nokogiri-1.5.2/bin/nokogiri -v
WARNING: Nokogiri was built against LibXML version 2.7.6, but has dynamically loaded 2.6.26
# Nokogiri (1.5.2)
---
warnings:
- Nokogiri was built against LibXML version 2.7.6, but has dynamically loaded 2.6.26
nokogiri: 1.5.2
ruby:
version: 1.9.2
platform: x86_64-linux
description: ruby 1.9.2p318 (2012-02-14 revision 34678) [x86_64-linux]
engine: ruby
libxml:
binding: extension
compiled: 2.7.6
loaded: 2.6.26
A:
I resolved the problem. I built libxml2 from source and then I configured bundler to use this new version:
bundle config build.nokogiri --with-xml2-dir=/usr --with-xslt-dir=/usr/local
(Now it I have a warning, because the version that is loaded is newer that the one that was used to built Nokogiri, but it's not a problem).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Она привязала собаку таким узлом, чтобы онa потом легко смоглa отвязаться.
Она привязала собаку таким узлом, чтобы онa потом легко смоглa отвязаться.
Подскажите пожалуйста: выделенное ПП целевое или образа действия с целевым оттенком?
Спасибо!
A:
Это СПП с придаточным, имеющим двойное значение: определение + цель, указательное слово (коррелят) ТАКОЙ и союз ЧТОБЫ.
По виду коррелята (местоименное прилагательное) мы и определяем вид придаточного.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does the pronunciation of “dass” compare to “das”?
I’m reading a book in which these two words often occur right next to each other as so: “… dass das …” Is there a difference in their pronunciation? If so, how can I make that clear? Do I need to use a certain pronunciation to differentiate it from a phrase like “… das das …” for example or is the context sufficient for that purpose?
A:
There is no difference in pronunciation (not in Hochdeutsch at least), and you don't need to differentiate them, since grammar orders them.
That is:
das dass (✗)
is forbidden by grammar rules. In particular, dass requires a punctuation sign, in fact:
das, dass
das. Dass
das; dass
are possible.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I put my iPhone in quiet mode only for a limited period of time?
When going to the movie or attending to a talk, how can I put my iPhone in quiet mode only for a limited period of time, like one hour?
In particular, it is mostly the case that I will forget to disable the quiet mode when the movie / talk is finished and that I would miss calls or notifications.
I tried this by settings, or asking “Siri”, but the answer was that it is not possible. This would be a great feature.
A:
Source
Your best option is to use Do Not Disturb.
There are multiple new limited-time settings for Do Not Disturb in the Control Center, which automatically turn off after the specified time elapses.
For one hour
Until this evening (or afternoon/morning depending on the time - it's generally a few hours)
Until I leave this location
Until this event ends (if you have a timed event set in your calendar) A single tap on the icon without selecting an option turns
on Do Not Disturb until you tap it again.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
An operator on the other side of the Schrödinger equation
A form of the Schrödinger equation is
$$
\left[-\frac{\hbar^2}{2m} \nabla^2 + V(\vec{r}, t)\right]\Psi = i\hbar \frac{\partial}{\partial t} \Psi
$$
The bracketed term is of course the Hamiltonian, and the whole equation can hence be written as
$$
\hat{H}\Psi = i\hbar \frac{\partial}{\partial t} \Psi
$$
My question is, is there a existing/named operator represented by $i\hbar \frac{\partial}{\partial t}$? That is, can we further rewrite the equation as
$$
\hat{H}\Psi = \hat{\Theta}\Psi
$$
For some predefined operator $\hat{\Theta} = i\hbar \frac{\partial}{\partial t}$?
A:
No, it is not an operator, at least with the same status as that of the Hamiltonian operator! The states are described by vectors in a Hilbert space, in this case $L^2(\mathbb R^3)$, i.e. functions $\psi=\psi(x)$ with integrable squared absolute value: $\int_{\mathbb R^3}|\psi(x)|^2 d^3x < +\infty$. Operators representing observables act in that space $A : \psi \mapsto A\psi$ where $A\psi \in L^2(\mathbb R^3)$.
Regarding Schroedinger equation, the situation is different. In that case one considers vector-valued curves $\mathbb R \ni \tau \mapsto \psi_\tau \in L^2(\mathbb R^3)$ representing the temporal evolution of an initially given state $\psi_0$.
The equation says that the time derivative (actually computed in the topology of the Hilbert space) of that curve at a given time $t$:
$$\frac{d \psi_t}{dt}\tag{1}$$
equals the action of an operator on $\psi_t$ at that time
$$-i \hbar^{-1}H\psi_t\tag{2}$$
To compute (2), we need to know just the vector $\psi_t$. Instead, to compute (1) we need to know the curve $\tau \mapsto \psi_\tau$ in a neighborhood of $t$!
Hence $d/dt$ (with some possible constant factor) cannot be considered an operator in the Hilbert space of the theory, $L^2(\mathbb R^3)$, as it acts on curves valuated in that Hilbert space.
Obviously this space of curves enjoys a structure of complex linear space and $d/dt$ is an operator with respect to that vector space structure, but that structure does not play any role in QM.
A:
Yes, the operator you are referring to is the energy operator,
$$\hat{E}=i\hbar \frac{\partial}{\partial t}$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
referencing a textview in a fragment gives a null value
i have 2 xml files, one containing a recyclerview(main_fragment.xml) and another containing the items to render on that recyclerview(main_item.xml). my fragment(MainFragment.java) extends Fragment. main_item contains a textview. In MainFragment.java i am inflating main_fragment.xml. Now i want to reference the textview in main_item.xml so as to listen for a click. but i get a null pointer. I get that is because in MainFragment.java i am inflating main_fragment.xml and not main_item.xml. Pls where should should i setup the onClickListener for the textview in main_item.xml. Thanks
A:
This needs to be done in you RecyclerView.Adapter and more specifically in the ViewHolder of the adapter.
There are many post on SO about that.
RecyclerView onClick
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is an unconsumated marriage still a halachic marriage?
If the wedding ceremony is completed and the man and woman are led off to the yichud room -all the formalities are done, the kesubah is signed etc, however is the act is not actually consummated are they still man and wife?
In addition, if any of the steps are left out of the ceremony, ie chuppah , kesubah etc is the wedding valid?
A:
There are two steps to marriage in Judaism: Kiddushin and Nisuin. Once those two are completed, the couple is married.
In our days, the first act, Kidushin, is generally done by giving the Kallah a ring.
The second act is done in a variety of ways (as what constitutes Nisuin is actually a Machlokes). The Chuppah is one such view, the Yichud room is another [and there are others as well].
But the bottom line is: once Nisuin is done the couple is completely married. There is no need for any additional action.
Aside: Here's where your question may be coming from:
The Rambam (IIRC) who holds that Nisuin is effected by Yichud also holds that such a Yichud needs to be one that is ראוי לביאה (a yichud in which the act may be done). For example, if the Kallah is a Niddah, then even if Yichud was done, the Rambam would hold that it is not enough to accomplish Nisuin.
However, even according to the Rambam the act only need to be able to be done. It does not actually have to be done.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I be worried about my Prefetch/Superfetch settings in Windows 7 on a SSD drive?
I just installed Windows 7 on my new OCZ Vertex 2. I heard that Win7 is optimized for use with SSDs and disables the prefetcher if one is detected, but I decided to check anyway. So I looked at
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters
...and noticed that "EnablePrefetcher" and "EnableSuperfetch" are both set to 3. Why is this and should I set these to 0 to save my drive?
This webpage: http://blogs.msdn.com/b/e7/archive/2009/05/05/support-and-q-a-for-solid-state-drives-and.aspx says:
If the system disk is an SSD, and the SSD performs adequately on random reads and doesn’t have glaring performance issues with random writes or flushes, then Superfetch, boot prefetching, application launch prefetching, ReadyBoost and ReadDrive will all be disabled.
So theoretically it's possible for these settings to be enabled on 'inadequately performing' drives, but I wouldn't expect it from my new drive...
I will also add that
fsutil behavior query disabledeletenotify
yields 0 for my drive, so according to this question: Confirming that Windows 7 is using SSD optimizations it means that it's recognized as an SSD. Also, it doesn't appear in the Disk Defragmenter's schedule.
A:
Windows doesn't disable the prefetching services just because you install an SSD. If you have both an SSD and a hard drive you would still want the prefetching for programs on the hard drive, so Windows doesn't disable it entirely. What it does is disable prefetching of content on the SSD. If you have nothing but the SSD then you can go ahead and disable it in windows.
Beyond updating drivers and the Windows Experience Index there is nothing you need to do.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A java-like class class in cpp
I want to write a program that supports several types of commands.
In order to make it generic and easy to extend for later new commands, i want to write a class for each command (with its own handling), and call the base 'command' class with the handler function.
I know that in Java there is the class class to help with such a thing - to decide 'on the flow' the type of the class it is dealing.
Does cpp has a similar mechanism? If so, what is it and how do i use it?
If not, what can i do in order to keep it easily extended?
Thanks a lot.
A:
You could implement a Command class with a pure virtual method.
http://www.exforsys.com/tutorials/c-plus-plus/c-pure-virtual-function-and-base-class.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What would you do if you coded a C++/OO cross-platform framework and realize its laying on your disk for too much due to no time?
This project started as a development platform because i wanted to be able to write games for mobile devices, but also being able to run and debug the code on my desktop machine too (ie, the EPOC device emulator was so bad): the platforms it currently supports are:
Window-desktop
WinCE
Symbian
iPhone
The architecture it's quite complete with 16bit 565 video framebuffer, blitters, basic raster ops, software pixel shaders, audio mixer with shaders (dsp fx), basic input, a simple virtual file system... although this thing is at it's first write and so there are places where some refactoring would be needed.
Everything has been abstracted away and the guiding principle are:
mostly clean code, as if it was a book to just be read
object-orientation, without sacrifying performances
mobile centric
The idea was to open source it, but without being able to manage it, i doubt the software itself would benefit from this move.. Nevertheless, i myself have learned a lot from unmaintained projects.
So, thanking you in advance for reading all this... really, what would you do?
A:
Throw it up on an open source website and attach a bunch of good keywords to help search engines find it. If someone's looking for it, they'll find it and be able to use it.
A:
I would say that you should open source it.
If you do have the time, it may be helpful for other programmers who are interested in the project to know the status of the project, and what is next to do on the project. Writing a to do list may be helpful, or writing comments in the code may also help.
If you do not have the time to write up a to do list maybe somebody is willing to take the initiative on the project, find out what needs to be done.
Look at it a different way. The worst that can happen is that your work will go unnoticed, and your efforts will be lost. The best that can happen is that you will be recognized for having the foresight to start such a great project, and open sourcing it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linq queries in Entity Framework 4. Horrible performance
In my project I'm using EntityFramework 4 for working with data. I found horrible performance problems with a simple query. When I looked at the profiler on a sql query, generated by EF4, I was shocked.
I have some tables in my entity data model:
It looks pretty simple. I'm trying to select all product items from specified category with all related navigation properties.
I wrote this LINQ query:
ObjectSet<ProductItem> objectSet = ...;
int categoryId = ...;
var res = from pi in objectSet.Include("Product").Include("Inventory").Include("Inventory.Storage")
where pi.Product.CategoryId == categoryId
select pi;
EF generated this sql query:
SELECT [Project1].[pintId1] AS [pintId],
[Project1].[pintId] AS [pintId1],
[Project1].[intProductId] AS [intProductId],
[Project1].[nvcSupplier] AS [nvcSupplier],
[Project1].[ nvcArticle] AS [ nvcArticle],
[Project1].[nvcBarcode] AS [nvcBarcode],
[Project1].[bIsActive] AS [bIsActive],
[Project1].[dtDeleted] AS [dtDeleted],
[Project1].[pintId2] AS [pintId2],
[Project1].[nvcName] AS [nvcName],
[Project1].[intCategoryId] AS [intCategoryId],
[Project1].[ncProductType] AS [ncProductType],
[Project1].[C1] AS [C1],
[Project1].[pintId3] AS [pintId3],
[Project1].[intProductItemId] AS [intProductItemId],
[Project1].[intStorageId] AS [intStorageId],
[Project1].[dAmount] AS [dAmount],
[Project1].[mPrice] AS [mPrice],
[Project1].[dtModified] AS [dtModified],
[Project1].[pintId4] AS [pintId4],
[Project1].[nvcName1] AS [nvcName1],
[Project1].[bIsDefault] AS [bIsDefault]
FROM (SELECT [Extent1].[pintId] AS [pintId],
[Extent1].[intProductId] AS [intProductId],
[Extent1].[nvcSupplier] AS [nvcSupplier],
[Extent1].[ nvcArticle] AS [ nvcArticle],
[Extent1].[nvcBarcode] AS [nvcBarcode],
[Extent1].[bIsActive] AS [bIsActive],
[Extent1].[dtDeleted] AS [dtDeleted],
[Extent2].[pintId] AS [pintId1],
[Extent3].[pintId] AS [pintId2],
[Extent3].[nvcName] AS [nvcName],
[Extent3].[intCategoryId] AS [intCategoryId],
[Extent3].[ncProductType] AS [ncProductType],
[Join3].[pintId1] AS [pintId3],
[Join3].[intProductItemId] AS [intProductItemId],
[Join3].[intStorageId] AS [intStorageId],
[Join3].[dAmount] AS [dAmount],
[Join3].[mPrice] AS [mPrice],
[Join3].[dtModified] AS [dtModified],
[Join3].[pintId2] AS [pintId4],
[Join3].[nvcName] AS [nvcName1],
[Join3].[bIsDefault] AS [bIsDefault],
CASE
WHEN ([Join3].[pintId1] IS NULL) THEN CAST(NULL AS int)
ELSE 1
END AS [C1]
FROM [ProductItem] AS [Extent1]
INNER JOIN [Product] AS [Extent2]
ON [Extent1].[intProductId] = [Extent2].[pintId]
LEFT OUTER JOIN [Product] AS [Extent3]
ON [Extent1].[intProductId] = [Extent3].[pintId]
LEFT OUTER JOIN (SELECT [Extent4].[pintId] AS [pintId1],
[Extent4].[intProductItemId] AS [intProductItemId],
[Extent4].[intStorageId] AS [intStorageId],
[Extent4].[dAmount] AS [dAmount],
[Extent4].[mPrice] AS [mPrice],
[Extent4].[dtModified] AS [dtModified],
[Extent5].[pintId] AS [pintId2],
[Extent5].[nvcName] AS [nvcName],
[Extent5].[bIsDefault] AS [bIsDefault]
FROM [Inventory] AS [Extent4]
INNER JOIN [Storage] AS [Extent5]
ON [Extent4].[intStorageId] = [Extent5].[pintId]) AS [Join3]
ON [Extent1].[pintId] = [Join3].[intProductItemId]
WHERE [Extent2].[intCategoryId] = 8 /* @p__linq__0 */) AS [Project1]
ORDER BY [Project1].[pintId1] ASC,
[Project1].[pintId] ASC,
[Project1].[pintId2] ASC,
[Project1].[C1] ASC
For 7000 records in database and ~1000 record in specified category this query's execution time id around 10 seconds. It is not surprising if look at this:
FROM [ProductItem] AS [Extent1]
INNER JOIN [Product] AS [Extent2]
ON [Extent1].[intProductId] = [Extent2].[pintId]
LEFT OUTER JOIN [Product] AS [Extent3]
ON [Extent1].[intProductId] = [Extent3].[pintId]
***LEFT OUTER JOIN (SELECT ....***
Nested select in join... Horrible... I tried to change LINQ query, but I get same SQL query outputted.
A solution using stored procedures is not acceptable for me, because I'm using SQL Compact database.
A:
You are doing Include("Product").Include("Inventory").Include("Inventory.Storage") and you are wondering why so many records are fetched and why so see such a big SQL query? Please make sure you understand what the Include method is about. If you want a simpler query, please use the following:
var res =
from pi in objectSet
where pi.Product.CategoryId == categoryId
select pi;
Please note however that this will possible load Products, Inventories and Storages lazily, which could cause many more queries to be sent when you iterate over those sub collections.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
converting from dataframe to list introduces factors
I have a dataframe which i need to convert from, df:
group ID
1 23143
1 7273
1 5578
3 10982
2 9722
3 26994
2 6497
.. ...
to a list like:
$C1
[1] "23143" "7273" "5578"
$C2
[1] "9722" "6497"
$C3
[1] "10982" "26994"
I can do this by:
list <- split.data.frame(df,df$group)
list <-lapply(ss,"[[","ID)
but this introduces factors for the ID values, how can i convert this list into characters?
A:
Start by running your code with options(stringsAsFactors=FALSE) to prevent strings from being automatically turned into factors. With that said, the example data you gave doesn't result in strings anyway, so I'm not sure if maybe your actual data is different.
Your data:
df <- data.frame(group=c(1,1,1,3,2,3,2),
ID=c(23143,7273,5587,10982,9722,26994,6497))
newlist <- split.data.frame(df,df$group)
newlist <-lapply(newlist,`[[`,"ID")
class(newlist[[1]])
[1] "numeric"
Some string data:
df2 <- data.frame(group=c(1,1,1,3,2,3,2),
ID=c("Joe","Sam","Rod","Mike","Steny","Larry","Chris"))
newlist2 <- split.data.frame(df2,df2$group)
newlist2 <-lapply(newlist2,`[[`,"ID")
class(newlist2[[1]])
[1] "factor"
With options set:
options(stringsAsFactors=FALSE)
df3 <- data.frame(group=c(1,1,1,3,2,3,2),
ID=c("Joe","Sam","Rod","Mike","Steny","Larry","Chris"))
newlist3<- split.data.frame(df3,df3$group)
newlist3 <-lapply(newlist3,`[[`,"ID")
class(newlist3[[1]])
[1] "character"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Floor division in go
I'm translating some old come from Python to Go. In this code, I used the floor division with the floor operator in Python.
d = b // c
# (c isn't a comment, I use the // operator from python)
My problem is, this operator doesn't exist in Go. What's the easiest way to translate in Go?
A:
If b and c are integers, b / c is already the floor division. If they are float64s, use math.Floor(b/c). If using float32 (or any other numeric type), you must convert first: math.Floor(float64(b)/float64(c))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL Replace Command needed
I have a database with name shop and I want to replace some fields value's I mean I have a table products and in this table I have a tablefield product_country and one more tablefiled product_price. Now all product_price are same 9.20 but the product_country are different like USA, CANADA, Australia etc. I want to change the product_price of only the product_country field where is USA only I want to replace 9.20 to 3.20.
please assist me about command .
A:
This is a very basic update command. I would recommend reviewing this tutorial : http://www.w3schools.com/sql/
I will give you the command for now though :
UPDATE shop SET product_price = 3.2 WHERE product_country = 'USA';
This is assuming product_price is a decimal type and product_country is a varchar or some other type of text based fields.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Introductory biology text for an outsider
I'm a maths major and I have an interest in learning biology. I know very, very little; I know how babies are made and that's about it. Could anyone recommend a stimulating text to read for its own sake and also to use to learn biology?
A:
I found the Campbell Biology textbook to be quite comprehensive and approachable. I think many introductory biology courses use it.
http://www.amazon.com/Campbell-Biology-Edition-Jane-Reece/dp/0321558235
A:
There are tons of books and it is quite hard to find one that gives such a broad overview. Campbell Biology is a book that basically covered the first year of my Bachelor degree in biology. I am not sure it would be very stimulating though! If there is a specific branch of biology that interests you, let us know we'll be able to give you a better advice.
As a math Major you might enjoy some fields of biology that are highly mathematized. For example, system biology or theoretical evolutionary biology. For the latter, you might like to read Evolutionary Dynamics: Exploring the Equations of Life book from Martin Nowak. But I am afraid it might not be a nice idea to directly jump into some specific subject before having a good overview of the life sciences.
Otherwise you might appreciate some books of popular (but good level) science such as the Extended Phenotype from Richard Dawkins. This book is very stimulating and I think it starts with some basic definitions of biological concepts such those of "alleles" or "phenotype".
I gave you two examples of books from the field of theoretical evolutionary biology. For more recommendations in this field, please have a look at Books on population or evolutionary genetics?.
Hope this helps a bit!
A:
You should check out Richard Dawkins' book The Greatest Show on Earth: The Evidence for Evolution
It does focus heavily on evolution but it is an amazing book on biology in general. He covers a wide rage of other topics, from how birds flock so elegantly to dating fossils using dendrochronology. The chapter on embryology is fascinating.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to format JSON from PHP array
this is my PHP Code:
<?php
$i = 0;
$output = array();
$kurse = array();
$zusatz = array();
while (isset($_POST['kurs'.$i]))
{
$kurse[$i] = $_POST['kurs'.$i];
$i++;
}
$anzahl = count($kurse);
/* Bestimmt den aktuellen Tag*/
$timestamp = time();
$dw = date( "w", $timestamp);
$day = array('So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So');
$rday= array('Mo', 'Di', 'Mi', 'Do');
$tag1 = $day[$dw];
$tag2 = $day[($dw+1) % 7];
/* read html */
$homepage = "";
if ($dw >= 1 && $dw <= 5) $homepage .= file_get_contents('xyz'.$tag1.'.html');
if (in_array($tag1, $rday) ) $homepage .= file_get_contents('xyz'.$tag2.'.html');
for( $i = 0; $i < $anzahl; $i++){
if ( strpos( $homepage, $kurse[$i] ) !== false )
{
$output[] = $kurse[$i];
}
}
if(empty($output)) {
$response = array();
$response["success"] = 0;
$response["message"] = "Keinen Kurs gefunden";
// echo no users JSON
echo json_encode($response);
}
else {
$response = array();
// success
$response["success"] = 1;
// user node
$response["get"] = $output;
echo json_encode($response);
}
exit();
?>
My JSON output looks like this:
{"success":1,"get":["9b,"6m"]}
But it should look like this:
{"success":1,
"get":[{
"kurs":"9b"
}
},
{
"kurs":"6m"
}
}]
}
What can I do to format this, because I want to use it in my Android Application.
I think the solution is quite simple but I don't get it, maybe you can help me...
Thank you in advance :)
A:
$output[]["kurs"] = $kurse[$i];
maybe?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Identifying mobile devices paired via bluetooth with PixelSense
I want to be able to pair Microsoft PixelSense hardware with multiple mobile devices via bluetooth and I want PixelSense to know which device is which. So if I place two phones on a table, PixelSense should be able to label them by device name. My initial thought was to have the phone display an Identity Tag that has encoded its Bluetooth MAC address so that it could associate them but PixelSense sees in infrared and can't read the phone screen so that idea is out. Can anyone think of another way to do this?
A:
Microsoft has demonstrated a way to do this in their Mobile Connect sample application. They've ingeniously used the fact that almost all phones have a camera that faces down when the phone is placed on a flat surface. So they created an app that will read incoming color data from Surface while the phone is sitting on it.
So it goes like this:
The Surface app starts and makes the Surface computer itself visible on bluetooth (although you may have to do this manually in admin mode, can't remember)
you run the mobile app on your phone, click connect, and place it on the Surface at a designated spot
the Surface flashes a serious of colors into the phone's camera
the phone decodes those colors into a pin and scans through all the open bluetooth devices it can see until it finds one that is a desktop running the appropriate service and accepts the decoded pin.
Now the two are connected with no need for manual input and the Surface knows which physical device it's talking to because it knows which pin it displayed to each device.
*Note - They don't actually allow multiple simultaneous connections in this sample app, but I see no reason why it wouldn't work.
One issue with this approach (other than being pretty complicated to code), is the need for the app on the phone. One way to make it easier for people to get the app is to display a Microsoft Tag or qrcode on the Surface for people to scan (they're much more likely to have a scanning app already). I don't think there's any getting around the need to have something installed on the phone if you're using bluetooth anyway.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to catch enwrapped exception in Junit test case?
I have a test case as
@Test(expected = IllegalArgumentException.class)
public void test() throws Exception{
..test content...
}
Because I'm using Java Reflection in my test case so the IllegalArgumentException is enwrapped in InvocationTargetException, how can I catch expected IllegalArgumentException instead of InvocationTargetException.
Error message shows as
java.lang.Exception: Unexpected exception, expected<java.lang.IllegalArgumentException> but was<java.lang.reflect.InvocationTargetException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
A:
I don't believe there's a JUnit way of doing it - you probably have to do it manually in the test, e.g.:
@Test
public void test() {
try {
runTest();
fail();
} catch (InvocationTargetException x) {
if( ! (x.getCause() instanceof IllegalArgumentException)) {
fail();
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can the flipper gem return a count of enabled users?
We are exploring using the flipper gem (https://github.com/jnunemaker/flipper) to gate who sees new features. In one of our first tests, we want to show a specific feature to only the first X users that see a banner promoting it.
We looked at using a percentage, but the business is very specific on the number, and also wants to reach that number right away, then disable the feature for all other users, without disabling it for those that saw it first. Using a percentage, we weren't able to see a way to ensure the correct number would see it, and that everyone of the first x would see it.
Inside the gates/actor.rb, there is this:
enabled_actor_ids = value
which implies we could get the list of enabled ids, and perform a count on that, but we couldn't find whether or where that list may be exposed.
Since we are using the AR adapter as a trial, we instead created a scope on an actor object that joins to the flipper_gates table, but this feels extremely fragile and getting very much into the inner workings of the gem.
Any advice is greatly appreciated.
A:
Nowadays you can do Flipper[:some_feature].actors_value.size, assuming you've configured your default flipper instance with Flipper.configure.
https://github.com/jnunemaker/flipper/blob/196946c63aee1eaa09fa25e945cdbff896fe71e5/lib/flipper/feature.rb#L258-L260
A:
You should be able to accomplish this by programmatically turning the feature on for Individual Actors until an upper limit is reached.
IMPORTANT NOTE: according to the documentation:
The individual actor gate is typically not designed for hundreds or
thousands of actors to be enabled. This is an explicit choice to make
it easier to batch load data from the adapters instead of performing
individual checks for actors over and over. If you need to enable
something for more than 20 individual people, I would recommend using
a group.
Now that we've agreed that we want to move forward with this anyways.. Let's talk about implementation.
Enabling the feature for an actor
The first thing you need to do is to ensure that the actor (probably a User) responds to flipper_id and that the flipper_id is unique for every actor. Once that is set up, you should be able to simply do enable the feature for a user when they see the banner like this:
flipper[:stats].enable_actor user
Counting actors enrolled in a feature
Now, in order to determine if we should enable the feature for a user, we need to determine how many users have been enrolled in the feature.
To do this we can query the Gate directly:
Flipper::Adapters::ActiveRecord::Gate.where(
feature_key: "stats",
key: "actors"
).count
This will return a count of the number of actors enrolled in a feature.
How do we know that works?
Well, let's take a look at the gem.
flipper[:stats].enable_actor actually calls Feature#enable_actor with the user we passed in earlier (that responds to flipper_id) being passed in as the actor.
Next, Feature#enable_actor passes the actor into Types::Actor.wrap which creates a new instance of Types::Actor which checks to make sure the actor isn't nil and that it has a flipper_id and then sets two instance variables, thing which is set to the actor, and value which is set to the flipper_id of the actor.
Now that we have an instance of Types::Actor, we pass it into Feature#enable which looks up the gate which in our case would be a Gates::Actor instance. Finally we call enable on the adaptor (which in your case is ActiveRecord).
In Adapters::ActiveRecord.enable we first look at gate.data_type which in our case, is :set. From there we do:
@gate_class.create! do |g|
g.feature_key = feature.key
g.key = gate.key
g.value = thing.value.to_s
end
Where, as mentioned earlier, thing.value is the flipper_id. Bingo! @gate_class is the active record class responsible for the gates table and the default table name is "flipper_gates".
Now we know exactly what to query to get a count of the actors enrolled in the feature!
number_of_actors_enrolled_in_stats_feature = Flipper::Adapters::ActiveRecord::Gate.where(
feature_key: "stats",
key: "actors"
).count
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use Facebook Web Hosting for my Unity Game for both WebGL and GameRoom
As can be seen from the
Facebook's official Docs
It says that
To have both a Gameroom and a Facebook Web Game, you should leave your Facebook Web Games URL (https) unchanged. For example, https://friendsmashsample.herokuapp.com/
and also
Otherwise, if you only have a Gameroom title, you should enter https://localhost/ as shown here:
I wanted to know if there is a way to get both of them working instead of hosting WebGL game on my server and putting it's URL?
I have even tried to enable the Simple Web Hosting but the toggle just reverts Back to off upon saving.
A:
It's now fixed.
Seems like the recent issue with Facebook various API deprecation and changes of terms and condition caused this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Windows 8 secondary tile pin
We implemented the code as in the msdn sample. But the navigation from secondary tile not works well. i.e, Assume we pinned from a page "A", and then navigated to another page "B", while clicking on secondary tile, it navigates to the Page "B". This is an issue, or should we specify navigation arguments anywhere while creating the tile?
A:
When you create the secondary tile you define the tileActivationArguments
string tileActivationArguments = "Page=3";
and when creating creating the the secondary tile you give tileActionvationArguments as a parameter. Then when someone starts your application from the secondary tile you need to catch the tileActivationArguments.
MainPage rootPage = MainPage.Current;
if (MainPage.Current.LaunchArgs != null)
{
if (!String.IsNullOrEmpty(MainPage.Current.LaunchArgs.Arguments))
{
//Get information from arguments where to navigate
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cute as a button
Since buttons aren't particularly cute (IMO), where did this common phrase come from? I know it's old; I've seen it in 19th century literature.
A:
While I can't find any scholarly answers, most answers I'm finding say that 'button' refers to something pretty or attractive in a dainty way. After all, you're using the word 'cute' so you wouldn't be using it to describe a large, muscular man. This phrase would be best suited for a small child or flower.
CUTE AS A BUTTON - "cute, charming, attractive, almost always with the
connotation of being small, 1868 (from the original 1731 English
meaning of 'acute' or clever). Cute as a bug's ear, 1930; cute as a
bug in a rug, 1942; cute as a button, 1946. Cute and keen were two of
the most overused slang words of the late 1920s and 1930s." From
"Listening to America" by Stuart Berg Flexner (Simon and Schuster, New
York, 1992.)
Flexner may have an idea about the word "cute," but he provides no
guidance on the question of how a button can be cute. The key to the
issue is that it is not the button on a shirt that is meant here, but
a flower bud seen in the popular name of small flowers, such as
bachelor's button (q.v. "button" (n) in the OED, meanings 2 and 3).
The British version is "bright as a button". This makes sense if you
think of a polished brass button. The phrase is really only ever used
of small people - you'd say that a child, or maybe a small dog, was as
bright as a button, but you'd never say it of a six-foot man. So the
image is of a small sparky thing.
http://www.phrases.org.uk/bulletin_board/41/messages/652.html
You can read more here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sending data using Avro objects, is there an advantage to using schema registry?
I have an application where I generate avro objects using an AVSC file and then produce using them objects. I can consumer then with the same schema in another application if I wish by generating the pojos there. This is done with an Avro plugin. The thing I noticed is that the schema doesn't exist in the schema registry.
I think if I change my producer type/settings it might create it there (I am using kafka spring). Is there any advantage to having it there, is what I am doing at the minute just serialization of data, is it the same as say just creating GSON objects from data and producing them?
Is it bad practice not having the schema in the registry?
A:
To answer the question, "is there an advantage" - yes. At the least, it allows for other applications to discover what is contained in the topic, whether that's another Java application using Spring, or not.
You don't require the schemas to be contained within the consumer codebase
And you say you're using the Confluent serializers, but there's no way to "skip" schema registration, so the schemas should be in the Registry by default under "your_topic-value"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Lottie event listeners and states for web - javascript
Messing with Lottie for playing animations on the web. The documentation seems fairly straightforward to get going but I can't find any documentation/examples of a very basic workflow in javascript: show pre-animation state => animate => detect animation complete => show post-anim state. Here's an example of what I'm doing with a liking system:
Unliked Post:
1: Display default state thumb graphic
2: User clicks thumb, play thumb animation
3: Animation completes, display liked state thumb graphic
Liked Post:
4: If user clicks already liked thumb...play reverse animation
5: Reverse animation complete, display default thumb graphic
Any help is much appreciated!
A:
Figure it out using goToAndStop. When the animation is created I'm checking if the users liked (hearted) the post and displaying the first frame or last frame of the animation accordingly:
handleAnimation(anim: any) {
this.anim = anim;
if (this.isHearted) {
this.anim.goToAndStop(25, true); //last frame. on state.
}
else {
this.anim.goToAndStop(0, true); //first frame. off state.
}
}
So when a user likes a post I will play the heart animation this.anim.play() and if the user unlike's the post I will set the animation state to the first frame this.anim.goToAndStop(0, true). What's nice about using the frames of the animation is I don't need seperate graphics for the off and on state of the icon, i can just use the animation object like shown.
One final note...I also noticed that a strange pink stroke was being added to my animation objects making them look kind of blurry. It seems the lottie plugin creates an SVG from the json data and for some reason was applying a stroke to the svg. So I had to remove it in css via:
lottie-animation-view {
stroke: none !important;
}
Just figured I'd mention that in case it happens for anyone else. FYI I am using the ng-lottie lib in ionic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I bind a transform function to a property?
I would like to have a subclass of TextField that applies a transform to the value, but I would like the particular transform to be dynamic.
I naively did this:
{{transforming-input transformer=myTransformer ...}}
TransformingInputComponent = Ember.TextField.extend({
transformedValue: function() {
var transformer = this.get('transformer');
return transformer.apply(this, [this.get('value')]);
}.property('value'),
})
Controller = Ember.ObjectController.extend({
myTransformer: Ember.String.camelize
})
but it doesn't work; when you bind a function to a property, you get undefined on the other side. (I verified it was not a typo or other error by changing the binding to a string)
A:
What I ended up doing was binding a dotpath to transformer, and looking up the transform function:
{{transforming-input type='text' transformer="Ember.String.handleize" ... }}
transformFunction: function() {
var path = this.get('transformer').split('.');
var scope = window;
if (Ember.isNone(window[path[0]])) {
scope = this.get('_parentView.controller');
}
for(var i=0;i < path.length; i++){
scope = scope[path[i]];
if (Ember.isNone(scope)) {
break;
}
}
return scope;
}.property('transformer'),
transformedValue: function() {
var transformer = this.get('transformFunction');
if(Ember.isEmpty(transformer)){
transformer = this.get('noop')
}
return transformer.apply(this.get('_parentView.controller'), [this.get('value')]);
}.property('value'),
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Test for successful firebase connection
var fb = new Firebase("https://badspelling.firebaseio.com/")
Will generate the following warring in the console:
FIREBASE WARNING: Firebase error. Please ensure that you spelled the name of your Firebase correctly (https://badspelling.firebaseio.com)
How can I pragmatically test for a valid connection?
fb.validConnection(); //error
Reason: I'm redoing the Getting Started page to set up Firefight js examples once the users enter a valid firebase app url.
A:
I’m going to monkey patch console.warn.
var orgWarn = console.warn;
console.warn = function(message) {
if(-1 !== message.indexOf("FIREBASE WARNING: Firebase error. Please ensure that you spelled")) {
error(message);
}
return orgWarn.apply(console, arguments);
};
try {
var firebase = new Firebase(url);
firebase.once("value", enterUrl);
function enterUrl(snap) {
setUpButtons(database);
};
}
catch (e) {
error(e.message);
};
Thanks for your help, but testing for connectivity causes a trimming issue. My goal is to display buttons on a valid url and an error on an invalid url. A valid url may not be connected yet (false negative). I would have to wait before I can test an invalid url. Boo
https://www.firebase.com/docs/web/guide/offline-capabilities.html#section-connection-state
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the meaning characterizing a model as "conditional mean"
I've been going through time series material of late, trying to re-invent myself as a practitioner in the field. Until I got to the point of actually trying to Matlab some models, I had never run across the characterization of models as "conditional mean". This term is pervasive throughout the entire documentation set; from what I can tell, it carries a particular significance in terms of modelling.
I haven't been able to wrap my head around what this significance is. It is explained as the expression of the expectation of a variable of interest, conditional upon the values of other variables. All the time series models that I've seen (indeed, all regression models) fall under this definition. So I'm not sure how the term classifies models of interest, or identifies a subset, or identifies features that have modelling implications. Nothing I've found on line makes it any clearer.
Thanks if anyone can provide a clarification, elaboration, or explanation of this. My question arose in the context of Matlab (it just happens to be what I am using), but it is a conceptual question that isn't necessarily tied to Matlab. It has been posted to:
What is the meaning characterizing a model as "conditional mean",
https://stackoverflow.com/questions/30406645/what-is-the-meaning-characterizing-a-model-as-conditional-mean, and
http://groups.google.com/forum/#!topic/comp.soft-sys.matlab/zQK8yScPFkk
A:
The first time you usually see this concept is in linear regression.
Let's suppose that we have a hypothetical relationship between two random variables that looks like
$$ Y = aX + b + \epsilon $$
where $\epsilon$ is some unobserved variable that is symmetric about it's mean of zero. Now suppose we take some observations of $X$ and $Y$ and want to use them to figure out a good guess at the parameters $a$ and $b$ in the relationship. Well, the value of $X$ clearly influences the value of $Y$, so we may want to proceed in two stages:
Given that I know a value of $X$ already, what can I deduce about the distribution of $Y$?
What is the distribution of $X$?
A first cut at the first question is asking:
If I know a value of $X$ already, what is the mean of $Y$?
And this is the conditional expectation of $Y$ given $X$, usually notated $E(Y \mid X)$ (and referred to as some as the conditional mean). This is the quantity that linear regression aims to estimate, because:
$$ \begin{align}
E(Y \mid X) &= a*E(X \mid X) + bE(1 \mid X) + E(\epsilon \mid X) \\
&= aX + b + 0 \\
&= aX + b
\end{align}
$$
Figuring out what's going on in each of these steps, and possibly what I left unsaid that is needed to make the calculation go through, is a nice way to test your understanding of the concept.
In time series, you often build autoregressive models, which assume a relationship like:
$$ Y_k = a_0 + a_1 Y_{k-1} + a_2 Y_{k-2} + \epsilon_k $$
for example. Here the same kind of reasoning tells you that you would really like to know the mean of $Y_k$, given that you already know the values of $Y_{k-1}$ and $Y_{k-2}$. This is called $E(Y_k \mid Y_{k-1}, Y_{k-2})$. The comma on the right of the condition symbol means and in this context.
I get what you explained, and I guess my confusion is...what regression or projection model of interest isn't conditional mean? In other words, how is that characterization adding any information about the model that one is interested in? If there were models of interest that don't fall under that characterization, I can understand how that characterization conveys information. But the only characterization I can think of that isn't conditional mean is a pure noise source. But as I said, I'm new in the field, so I think I must be missing an entire body of models (of interest).
Notice that I got to the conditional mean by asking myself:
What's something simple I would want to know about the distribution of $Y$, given that I already know $X$?
Well, there are plenty of things I could ask:
Whats the mean of $Y$ given $X$?
What's the median of $Y$ given $X$?
What's the $90$'th percentile of $Y$ given $X$?
All these are valid questions, and there is a model for each of them. To get at the conditional mean of $Y$ given X, you minimize the expected squared error:
$$ E(Y \mid X) = arg\,min_f E\left( (Y - f(X))^2 \right)$$
To get at the conditional median you minimize the expected absolute error:
$$ Median(Y \mid X) = arg\,min_f E\left( \left| Y - f(X) \right| \right)$$
To get at the 90'th percentile you do something else clever. The last two cases are covered by a theory called quantile regression. It has nice properties like resilience to outliers and asymmetry in the same way that the median does.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
autonomousSingleAppModePermittedAppIDs Key in Restrictions payload - iOS 7 MDM
I have recently started working with Apple Configurator to use features meant for Supervised devices.
In the Restrictions payload there's a key called autonomousSingleAppModePermittedAppIDs with the description below
Optional. Supervised only. If present, allows apps identified by the bundle IDs listed in the array to autonomously enter Single App Mode.
Availability: Available only in iOS 7.0 and later.
I tried sending this key in the restrictions payload with a couple of app identifiers, but could not find any change in the behaviour of the OS. The Guided Access allowed all apps to enter into the SingleApp mode.
What I understand (and expect) from this is we can allow a list of apps to enter Guided Access (Single App) mode and no other app except the allowed ones will be visible on the device. Can you help me understand the things I'm missing or misunderstanding.
A:
I believe the idea of this key that application itself can request a guided mode (vs guided mode triggered by a user or AppLock profile).
I believe application should use following API to request a guided mode:
void UIAccessibilityRequestGuidedAccessSession(BOOL enable, void(^completionHandler)(BOOL didSucceed));
In the case, if it's not on this list, this request will be rejected.
P.S. A device needs to be supervised.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
programming with a touch screen
I have RSI and no one has been able to help me
I am considering to buy an ipad to do programming with visual studio. i would like to just tap on the screen to type instead of using a keyboard
does anyone know have experience programming using a touchscreen keyboard?
A:
I'm not sure spending £600 + on an iPad is going to do anything other than deplete you bank balance and make your condition worse. Apple market a keyboard to go with an iPad because it is not particularly suited to be typing on for extended periods of time.
I would advise investing in a considerably cheaper ergonomic keyboard, and speaking to a doctor for practical advice on how to reduce rsi pain.
And there is the fact that I'm not sure it's even possible to use an Ipad as a remote keyboard to a Windows machine :)
A:
I have chronic wrist and forearm pain, and the last thing I would ever do is use a touchscreen for a keyboard. Let's look at the scenarios:
You have the touchscreen in front of you. Your typing will become more uncomfortable and far less natural.
A touchscreen keyboard takes up lots of real estate, thus you can see less code at once.
Assuming you could even use an iPad for the keyboard only, you put the iPad facing upward, which is a more natural position. However, since you can't feel the keys (I assume you are a touch typist), you have to always look down. And in this scenario, if you're looking down at the keyboard, you don't see what's going on on the screen.
iPad doesn't help you keep your wrist at the right level / angle, but an ergonomic keyboard does.
You are far better off evaluating $600 worth of ergonomic keyboards, than to invest in an iPad, which probably doesn't do what you want anyway... unless you're just looking for another reason to justify buying one (I would, just to play Angry Birds HD!)
I have evaluated at least 15 different keyboards to help with my problem. I have found that the true ergonomic ones like GoldTouch are nice, but they always trash the button layout, which drives me nuts. Lame ergonomic keyboards like the ones from Kingston make my arms hurt even more -- they keep the keys in one plane but skew them to alter the general placement relative to your hands. I like the feel of Thinkpad keyboards, because the travel and force is just right. Lenovo sells the Thinkpad keyboard alone as a USB keyboard, but the feel is not identical. So my choice right now is the Microsoft Natural 4000. It just feels good to me. The problem with this keyboard is that is has the 10key section, and many ergonomic keyboards don't so you can move the mouse closer. My solution was to cut off the right side of the keyboard with a hacksaw and move my mouse closer. Works great!
Sorry for the long "answer" -- I got a little carried away because your problem is one that's very relevant to me and has caused me tons of pain over the years. You really need to find a physical keyboard that sets your body up correctly. It might take a lot of experimentation, but it will be worth it and far better than a touchscreen / onscreen keyboard.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I combine a JTextField and a JRadioButton?
I would like to have a JRadioPanel with three options. The first two are hardcoded options, and I want the third to be an 'Other' button. I would like to have a JTextField instead of text as the title of that button, but I'm not sure how to do that. I tried simply putting the field as the argument for the radio button, but it didn't like that much. I haven't found anything online to tell me how, except maybe through NetBeans, and that doesn't do me much good. Is there any way to easily do this, or will I have to do some fancy stuff with the layout?
Okay, new problem. The buttons are all looking right, but for some reason they're in a row instead of in a column. Here's the code for it. Not sure why it's doing this.
tf2 = new JTextField("Other", 20);
newName.setActionCommand("newname");
fulfillment.setActionCommand("fulfillment");
fulfillment.setSelected(true);
type.add(fulfillment);
type.add(newName);
fulfillment.addActionListener(this);
newName.addActionListener(this);
GridBagConstraints rC = new GridBagConstraints();
JPanel radioPanel3 = new JPanel(new GridBagLayout());
rC.gridwidth = 2;
radioPanel3.add(fulfillment);
rC.gridy = 1;
radioPanel3.add(newName);
rC.gridy = 2;
rC.gridwidth = 1;
radioPanel3.add(other);
rC.gridx = 1;
radioPanel3.add(tf2);
c.gridx = 10;
c.gridy = 4;
pane.add(radioPanel3, c);
A:
Place the third radiobutton without text and add JTextField. E.g. Use GridBagLayout where the first and the second radiobuttons take 2 columns and in the third row the "empty" radiobutton has row=2 col=0 and JTextField row=2 col=1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android: Read GPS + Accelerometer Sensor Simultaneously
I am attempting to make it so that I can read the GPS data which is triggered as an event every one minute, and as a result will also read the accelerometer data at the same time. However I am unable to do this I have attached what I have in my main file. Any help would be appreciated.
https://gist.github.com/4395787
A:
You are making request for GPS updates at 60000 milliseconds
Line 151
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0,
locationListener);
So make also accelerometer requests also at 60000 milliseconds (60000000 microseconds)
Line 71
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
60000000 );
This will give you updates on almost same time if both your listeners start almost same time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I convert BTC to USD without a bank account?
Just asking. Say, I want to switch BTC to USD inside Steam Wallet. Is it possible?
A:
To my knowledge, Steam does not support BTC (at least yet). Moreover, Steam does not allow one to send another user money transfers, so you can't really exchange your funds with other people. You could, however, purchase a game gift for another person and sell that gift for Bitcoins, but that would probably be against Steam's policy.
If you generally want to exchange Bitcoins for any currency without having a bank account, you could always try finding another user that also wants to trade like that and exchange money with them, either in person or through services like Western Union. This way however, is less reliable than using a Bitcoin exchange.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Julia MAC Installation
I am trying to install Julia on my MAC. I came up with the following error during installation:
Any idea is appreciated about what the problem can be.
Edit:
"test.jl is like this:
using JuMP
using Gurobi
m = Model(solver=GurobiSolver())
m = Model()
@variable(m, x ) # No bounds
@variable(m, x >= lb ) # Lower bound only (note: 'lb <= x' is not valid)
@variable(m, x <= ub ) # Upper bound only
@variable(m, lb <= x <= ub ) # Lower and upper bounds
@variable(m, x == fixedval ) # Fixed to a value (lb == ub)
@variable(m, x[1:M,1:N] >= 0 )
aff = AffExpr([x, z], [3.0, 4.0], 2.0) # 3x + 4z + 2
quad = QuadExpr([x,y],[x,z],[3.0,4.0],aff) # 3x^2 + 4yz + 3x + 4z + 2
@constraints(m, begin
x >= 1
y - w <= 2
sum_to_one[i=1:3], z[i] + y == 1
end)
@expression(m, shared, sum(i*x[i] for i=1:5))
@constraint(m, shared + y >= 5)
@constraint(m, shared + z <= 10)
expr = @expression(m, [i=1:3], i*sum(x[j] for j=1:3))
A:
A few suggestions:
- use the full path in your code to be sure where the file is located
- Julia is case sensitive, so Test.jl and test.jl are different
- check the permissions on the file
- Julia makes heavy use of "test.jl" type names, potential confusion?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Find $f(x,y,z) = 0$ that excludes $q$ and $v$ parameters
I have the following problem:
$$x = e^q \sin (q) + v$$
$$y = e^q\cos (q) + 2v$$
$$z = e^q + 3v$$
I want to find a function $$f(x, y, z) = 0$$, that is i want to remove the $q$ and $v$ parameters from the equation.
How can I do it ?
Here is my attempt: $$ (x-v)^2 + (y -2v)^2 = e^{2q}$$
$$ (z-3v)^2 = e^{2q}$$
from which I get:
$$x^2 + y^2 - 2vx -4vy = z^2 -6vz + 4v^2$$
Now $q$ is excluded but i don't know how to exclude $v$ too.
A:
Here $$v(x,y,z)=3z-x-2y\pm \sqrt{(3z-x-2y)^2-z^2+x^2+y^2}.$$
and $$q(x,y,z)=\arctan \frac{x-v}{y-2v}+\pi k,$$ so
$$f(x,y,z)=e^{q(x,y,z)}+3v(x,y,z)-z=0.$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to send message to stop polling and exit from application
I have spring integration application and I need to close it after all data were processed. If I explicitly call appContext.close() then not all data could be processed in time(unless I set Thread.sleep()). If I do not call close on application context then application doesn't stop since I have background poller that does not allow application to close automatically. So how to signal to stop whole application in one of my service activator(last in the chain of processing)?
first bean reads data from storage line by line and send it via gateway.send(data) in while loop
processing chain that is happening in parallel
than all threads sends messages into single thread via Pollable Queue
And here I should stop application if I realise that all messages read in the first bean were processed
I tried to stop last service activator using controlbus but it didn't help
Thanks
UPDATE
here are some code examples:
Runner:
public class Runner {
static Logger log = LoggerFactory.getLogger(Service2.class);
public static void main(String[] args) throws InterruptedException {
log.info("START APP");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
RootService service = context.getBean(RootService.class);
service.start();
service.stop();
context.close();
log.info("END APP");
}
}
RootService:
@Component
public class RootService {
Logger log = LoggerFactory.getLogger(RootService.class);
@Autowired
MyGateway gateway;
int totalSize = 0;
public void start() {
List<String> source = generateSource();
totalSize = source.size();
//imitate very long but finite process
for (String s : source) {
gateway.send(s, totalSize);
}
log.info("end sending data");
}
public void stop() throws InterruptedException {
log.info("sending stop signal...");
while (gateway.sendStop(totalSize)<0) {
Thread.sleep(100);
log.info("sending stop signal...");
}
log.info("THE END");
}
private List<String> generateSource() {
List<String> result = new ArrayList<String>();
for (int i = 0; i < 15; i++) {
result.add("data" + i);
}
return result;
}
}
Service1
@Component
public class Service1 {
public String dodo(String data) throws InterruptedException {
//doing a job in parallel
Thread.sleep(100);
return data + "-" + Thread.currentThread().getName();
}
}
Service2:
@Component
public class Service2 {
Logger log = LoggerFactory.getLogger(Service2.class);
int counter = 0;
public void dodo(String data) {
log.info("data: {}-{}", data, Thread.currentThread().getName());
counter++;
log.info("counter: {}", counter);
}
public Integer dodo(Integer data) {
if (counter < data) {
return -1;
} else {
return 0;
}
}
}
@Component
public class ErrorHandler {
Logger log = LoggerFactory.getLogger(Service2.class);
public void handleError(Message<?> message) {
log.info("ERROR: {}", message);
}
}
and xml config
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/integration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task">
<gateway id="myGateway"
service-interface="com.dimas.MyGateway"
default-request-channel="channel1"
error-channel="errorChannel"
default-reply-timeout="3000">
<method name="send" request-channel="channel1"/>
<method name="sendStop" request-channel="channel2" reply-channel="channel3"/>
</gateway>
<channel id="channel1">
<dispatcher task-executor="executor"/>
</channel>
<channel id="channel2">
<queue/>
</channel>
<channel id="channel3">
<queue/>
</channel>
<channel id="errorChannel"/>
<service-activator input-channel="errorChannel" ref="errorHandler" method="handleError"/>
<service-activator input-channel="channel1" output-channel="channel2" ref="service1"/>
<service-activator input-channel="channel2" output-channel="channel3" ref="service2">
<poller fixed-delay="0"/>
</service-activator>
<task:executor id="executor" pool-size="2"/>
</beans:beans>
Now it works - app is stopped when all data is processed and it returns stop code 0 but i see in log a lot of errors like:
ErrorMessage
[payload=org.springframework.messaging.core.DestinationResolutionException:
no output-channel or replyChannel header available,
headers={id=639ca939-8110-4486-6a2b-5d36c7bfdbcd,
timestamp=1475872251269}]
Error handler successfully catch it but something is wrong
I realized where was the issue. Last Service2 returns soemthing for any income message. Redid it so it responds code only for stopRequest request.
Just wondering if there is simpler solution
A:
It's not clear why, if you can detect you are complete, you can't close the application context.
You could replace the default taskScheduler with one that uses daemon threads.
EDIT
First of all, you don't need all those queue channels; simply having channel1 being an executor channel will give you the concurrency - using queue channels after that just adds overhead.
In any case, to determine when the process is complete, just add a getCounter() method to Service2; then, in your main method, get service2 from the context and wait until the counter has incremented to the number you expect.
Or, you can add a countdown latch to service2 - add a method to set it...
CountDownLatch latch = new CountDownLatch(source.size());
service2.setCountDownLatch(latch);
for (
...
if (!latch.await(...)) { // add a timeout in case is never completes)
// failure
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C++ explicit constructor that takes a pointer
I've recently stumbled across an explicit constructor that receives a single pointer argument. I wonder if the explicit keyword is necessary in this case? as there is no constructor for a pointer so there cannot be any implicit conversion.
class Foo {
public:
explicit Foo(int* int_ptr);
}
A:
The following code:
void f(Foo) {}
int main()
{
int* p;
f(p);
}
Fails to compile with explicit.
Happily compiles without it.
live example on godbolt.org
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the relationship between A Colder War and the Laundry Series?
The novella A Colder War by Charles Stross seems thematically quite similar to his Laundry series (cold war + Cthulhu and Lovecraftian spy thriller, respectively). Are they supposed to belong to the same universe? Alternate histories of the same universe? Or are they independent? The ending of A Colder War seems to suggest that some or all of what has happened is
A simulation created by Cthulhu to torment the protagonist.
Which leaves the state of the world ambiguous, especially as to its compatibility with the Laundry novels.
A:
Charles Stross's afterword to the story in his collection Wireless states that 'A Colder War' was written well before 'The Atrocity Archive', which is unrelated, but explores similar themes:
A couple of years later, some of the questions raised by this story came back to haunt me in a different context as I began writing “The Atrocity Archive.” But I can’t maintain that level of existential bleakness at greater length (which is probably a good thing) …
A recent interview in Lightspeed magazine goes into much more detail regarding the development of 'A Colder War' and the adaption of the themes for the Laundry series.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Call to a member function fetch_field() on a non-object MySQLiDB
Hi i cant use INSERT UPDATE function with this class: MySQLiDB.
Im trying write data to mysql and if exists this data then need update. So i use INSERT ... ON DUPLICATE KEY UPDATE.... My code like this:
$db->rawQuery("INSERT INTO table1 (field1,field2,field3) VALUES (?,?,?) ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)", array("value1",value2,value2));
this code works fine. But when use this code in cycle and give values by another array shows me this error: Call to a member function fetch_field() on a non-object in.... This is code in cycle:
$db->rawQuery("INSERT INTO table1 (field1,field2,field3) VALUES (?,?,?) ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)", array($value[$i][value1],$value[$i][value2],$value[$i][value3]));
What i can do in this situation?
A:
Do not use MySQLiDB. It is unusable in many ways.
You can use safemysql instead:
$sql = "INSERT INTO table1 (field1,field2,field3) VALUES (?s,?s,?s)
ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)";
$db->query($sql, $value[$i]['value1'],$value[$i]['value2'],$value[$i]['value3']);
Or, in a much simpler way:
foreach ($value as $row)
{
$sql = "INSERT INTO table1 SET ?u
ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)";
$db->query($sql, $row);
}
(only if $value coming from the trusted source though)
You could also create a query for the single insert
$ins = array();
foreach ($value as $row) {
$ins[] = $db->parse("(?s,?s,?s)",$row['value1'],$row['value2'],$row['value3']);
}
$instr = implode(",",$ins);
$sql = "INSERT INTO table1 (field1,field2,field3) VALUES ?p
ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)";
$db->query($sql, $ins);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
i am trying to get a value from a .csv file in python and facing this error
ValueError: invalid literal for int() with base 10: '405,000'
the code is as follows :
for d in csv.DictReader(open(c_name + '.csv'), delimiter=','):
global d_value
d_value = int(d['Debt Value'])
A:
405,000 isn't a valid int. You either need to remove that comma:
d_value = int(d['Debt Value'].replace(',', ''))
Or use the locale module:
import locale
# You might need to set a locale
# locale.setlocale(locale.LC_ALL, '')
d_value = locale.atoi(d['Debt Value'])
A:
It looks like you have a comma in your value, which is why you're seeing the error. You may want to sanitize your numbers by doing something like this:
d_value = int(d['Debt Value'].replace(",", ""))
While you're at it, it's a good idea to close your files when you're done with them. You can use a with statement to make sure it will close after your block.
with open(c_name + ".csv") as csvfile:
for d in csv.DictReader(csvfile, delimiter=','):
global d_value
d_value = int(d['Debt Value'].replace(",", ""))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Issue in saving the dropdown list in magento admin
I had created the dropdown list in magento admin.But i am not getting how to save the dropdown list.I have added the dropdown list in below files.Please any one can Help me.
A:
Try this. i see issue in your select box name it should be "bloodgroup" as per your code in controller for save
$fieldset->addField("Bloodgroup", "select", array(
"label" => Mage::helper("serviceprovider")->__("Bloodgroup"),
"name" => "bloodgroup",
"values" => array(
'-1'=> array( 'label' => 'Please Select....', 'value' => '-1'),
'1' => array(
'value'=> array(array('value'=>'2' , 'label' => 'A') , array('value'=>'3' , 'label' =>'AB'), array('value'=>'4' , 'label' => 'AB+') , array('value'=>'5' , 'label' =>'AB-'), array('value'=>'6' , 'label' => 'A+') , array('value'=>'7' , 'label' =>'B+') , array('value'=>'8' , 'label' => 'O+ ') , array('value'=>'9' , 'label' =>'O-')),
),
),
));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cout a class object using conversion operator
#include <iostream>
#include <cmath>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
// Default constructor
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i)
{}
// magnitude : usual function style
double mag()
{
return getMag();
}
// magnitude : conversion operator
operator int ()
{
return getMag();
}
private:
// class helper to get magnitude
double getMag()
{
return sqrt(real * real + imag * imag);
}
};
int main()
{
// a Complex object
Complex com(3.0, 4.0);
// print magnitude
cout << com.mag() << endl;
// same can be done like this
cout << com << endl;
}
I don't understand how the compiler is resolving to call the conversion operator for cout << com << endl;.
I can also have more than one conversion operator in the same class. How will the resolution be done in that case?
A:
You have declared a conversion operator to int. Since this operator is not explicit, the compiler considers it when finding the best overload of ostream::operator<<. Keep in mind that C++ compiler always attempts to automatically convert types to find a matching call, including conversion constructors, conversion operators and implicit type conversions.
If you do not want this behavior, then starting from C++11 you can mark the operator as explicit:
explicit operator int() {
return getMag();
}
Regarding the second part of your question, if there are multiple conversions that are equally good, a compile error is invoked. If you added, say, operator double, then as there exists ostream::operator(double), the call would be ambiguous and you would need to cast com to Your desired type.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Run two webservers with twisted
I have a task to run a webserver with twisted capable of working with websockets and standard HTTP functionality. Say, I need to use websockets and connect to hostname:9000. I need to get webpage and use hostname:80/webpage to get it. How I am supposed to do it?
I tried something like:
internet.TCPServer.__init__(self,9000, WebSocketFactory(factory))
internet.TCPServer.__init__(self,80, server.Site(HandlerHTTP))
And it's not working: server on 80 port starts, but one at 9000 doesn't.
A:
An instance of twisted.application.internet.TCPServer represents one TCP server. You can't initialize it twice and get two servers out of it.
I expect a more complete code snippet than you gave would look like:
from twisted.application import internet
class TwoServers(TCPServer):
def __init__(self):
internet.TCPServer.__init__(self,9000, WebSocketFactory(factory))
internet.TCPServer.__init__(self,80, server.Site(HandlerHTTP))
This doesn't work. It's like trying to have an int that is two integers or a list that is two sequences. Instead, make two TCPServer instances:
from twisted.application import service, internet
from websocket import WebSocketFactory
factory = ...
HandleHTTP = ...
holdMyServers = service.MultiService()
internet.TCPServer(9000, WebSocketFactory(factory)).setServiceParent(holdMyServers)
internet.TCPServer(80, server.Site(HandlerHTTP).setServiceParent(holdMyServers)
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
spring data mongodb NearQuery add another criteria
Is it possible to add a Criteria to a NearQuery?
Currently I am doing this:
public List<UserLocation> getUserNearLocation(Point p, double min, double max){
NearQuery query = NearQuery.near(p).minDistance(new Distance(min, Metrics.KILOMETERS)).maxDistance(new Distance(max, Metrics.KILOMETERS));
GeoResults<UserLocation> results = mongoTemplate.geoNear(query, UserLocation.class);
List<UserLocation> all = new ArrayList<UserLocation>();
Iterator<GeoResult<UserLocation>> iter = results.iterator();
while (iter.hasNext()){
GeoResult<UserLocation> temp = iter.next();
all.add(temp.getContent());
}
return all;
}
I would like to add another criteria to the query, is it possible and how?
A:
just add an additional query like shown below.
NearQuery query = NearQuery.near(new Point(1, 2)).query(Query.query(Criteria.where("foo").is("bar")));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convergence of $\sum \frac{k+1}{3k^3+2k^2+k}$
Does the series $\sum \frac{k+1}{3k^3+2k^2+k}$ converge?
Basically this series behaves like $\frac{1}{3}\sum \frac{k}{k^3} = \frac{1}{3}\sum \frac{1}{k^2}$ which we know converges (this can be proved by using the integral test). To make this formal we use the comparison test.
For any $k\geq 1$ we have
\begin{equation*}
k< k+1,
\end{equation*}
and so
\begin{equation*}
\frac{k+1}{3k^3+2k^2+k}> \frac{k}{3k^3+2k^2+k}> \frac{k}{3k^3}= \frac{1}{3k^2}
\end{equation*}
for all $k\geq 1$. But the series
\begin{equation*}
\frac{1}{3}\sum \frac{1}{k^2}
\end{equation*}
converges, so by the comparison test $\sum \frac{k+1}{3k^3+2k^2+k}$ converges.
This doesn't seem to be correct (in particular the inequality). Do I have to factorise the bottom of the fraction and compare with a different function? Any help would be good!!!
A:
You bounded your series from below by a convergent one, that isn't helpful. The second inequality is also false.
Comparison is the way to go however. Note that $k+1\leq 2k$ for $k\geq 1$, so that
$$
\frac{k+1}{3k^3+2k^2+k}\leq \frac{2k}{3k^3+2k^2+k}\leq \frac{2k}{3k^3+2k^2}=\frac{2}{3k^2+2k}\\
\leq\frac{2}{3k^2}
$$
which is summable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to sniff HTTPS traffic of Android apps that ignore the system proxy setting?
I saw a very similar question about this on macOS just 20hrs ago but I'm always needing to do this on Android and I keep forgetting the name of the app. So this is just for reference.
A:
Drony
Acts as a local VPN and redirects all traffic to a HTTP proxy. Its meant to be used with Orbot (TOR for Android) but can just as easily be used for this purpose using something like Fiddler to act as proxy server.
Android App Store
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Issue in downloading image from Firebase Storage and saving it in SD Card
I had uploaded the image on Firebase Storage successfully. I have the URI and using Glide, I'm able to show the image on an ImageView. I want to save this image on my SD card but I'm getting an exception
java.io.FileNotFoundException: No content provider:
https://firebasestorage.googleapis.com/..
In here:
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
SaveImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Here is my complete code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_pic);
Intent intent = getIntent();
String str = intent.getStringExtra("pic");
Uri myUri = Uri.parse(str);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
SaveImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
ImageView imageView = (ImageView)findViewById(R.id.displayPic);
Glide.with(getApplicationContext()).load(myUri)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
URI looks like this:
https://firebasestorage.googleapis.com/example.appspot.com/o/pics%2Fc8742c7e-8f59-4ba3-bf6f-12aadfdf4a.jpg?alt=media&token=9bsdf67d-f623-4bcf-95d7-5ed97ecf1a21
A:
Using Glide Try this.
Bitmap bitmap= Glide.
with(this).
load(mDownloadUrl).
asBitmap().
into(100, 100). // Width and height
get();
SaveImage(bitmap);
where mDownloadUrl is your image URL.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python decorators in classes Error
class A(object):
def wrapped(self, func):
func.string = self.get_something()
return func
def get_something(self):
return "something"
@wrapped
def main(self):
print self.main.string
a = A()
a.main()
TypeError: wrapped() takes exactly 2 arguments (1 given)
A:
wrapped() is called at the definition of main(). When it is called, it is not given self, because there is no instance of A that can be given to wrapped(). To do what you want, don't use decorators. Instead, define an __init__() method that assigns the right attributes. I don't know why you want it to be an attribute of self.main(), however. Generally it is not a good idea to add attributes to functions. You already have a class; use it. Just define self.string instead of self.main.string.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
DatePicker angular
I have datepicker with Angular . here is the question:
How can to prevent user write to in input? I just want to let user add date from pop up.
A:
use readonly propery of html
<input type="text" readonly>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Have a class have access to a parameter from another class
I have two classes, classA and classB. classA has an attribute named image that contains data that is changing all the time. I want to be able to have an instance of classB that when I call a method on this instance, it can access self.image from classA. Unfortunately my attempts are failing.
Example code:
classA:
def __init__(self):
self.image = None #initialise
analysis = classB(self)
def doingstuff(self):
self.image = somethingchanginghere()
measurement = analysis.find_something_cool()
print measurement
classB:
def __init__(self, master):
self.image = master.image #get a reference to the data from other class
def do_something_cool(self):
return type(self.image) #find something about the data at the point when method is called
main = classA()
main.doingstuff()
I get an error that says the data is still None, i.e. it's still in the state when it was initialised and the reference to classA from classB hasn't updated when self.image in classA changed. What have I done wrong?
Why does the working example give NoneType? I'm expecting a random number.
A:
There are two problems with your code:
analysis is a variable local to the classA.__init__ and classA.doingstuff functions. If you wish to re-use it in other functions, you should define it as an attribute: self.analysis = classB(self).
Python doesn't pass variables by reference. When you do analysis = classB(self), you create an object of classB, passing the object self as an argument. It is not a reference to the object, so classB.image is set and/or changed only once, in classB.__init__. If you wish to keep it updated, you should either do:
classB:
def __init__(self, master):
self.master = master
and then use master.image to get the image, or implement a classB method e.g.
def update(self, image):
self.image = image
and call it every time image changes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I run a Console Application, capture the output and display it in a Literal?
I see that I can start processes with System.Diagnostics.Process. I'm trying with the following code, but its not working. The page just hangs and I have to restart IIS...
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
public partial class VideoTest : System.Web.UI.Page
{
List<string> outputLines = new List<string>();
bool exited = false;
protected void Page_Load(object sender, EventArgs e)
{
string AppPath = Request.PhysicalApplicationPath;
Process myProcess = new Process();
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = AppPath + "\\bin\\ffmpeg.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
myProcess.Exited += new EventHandler(ExitHandler);
myProcess.Start();
while (!exited)
{
// This is bad bad bad bad....
}
litTest.Text = "";
foreach (string line in outputLines)
litTest.Text += line;
}
private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
outputLines.Add(outLine.Data);
}
// Handle Exited event and display process information.
private void ExitHandler(object sender, System.EventArgs e)
{
exited = true;
}
}
A:
I've done something very similar to your solution -- this is working fine for me:
ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe");
pInfo.FileName = exePath;
pInfo.WorkingDirectory = new FileInfo(exePath).DirectoryName;
pInfo.Arguments = args;
pInfo.CreateNoWindow = false;
pInfo.UseShellExecute = false;
pInfo.WindowStyle = ProcessWindowStyle.Normal;
pInfo.RedirectStandardOutput = true;
Process p = Process.Start(pInfo);
p.OutputDataReceived += p_OutputDataReceived;
p.BeginOutputReadLine();
p.WaitForExit();
// set status based on return code.
if (p.ExitCode == 0) this.Status = StatusEnum.CompletedSuccess;
else this.Status = StatusEnum.CompletedFailure;
The interesting differences seem to be the use of WaitForExit(), and possibly the BeginOutputReadLine().
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PHP Doctrine DBAL Schema Autoincrement doesn't work
I'm using Silex with Doctrine DBAL. I try to create a table:
$schema = new \Doctrine\DBAL\Schema\Schema();
$table = $schema->createTable('admins');
$table->addColumn('id', 'smallint', array('unsigned' => true, 'autoincrement' => true));
$table->addColumn('username', 'string', array('length' => 10));
$table->addColumn('password', 'string', array('length' => 45));
$table->setPrimaryKey(array('id'));
$table->addUniqueIndex(array('username'));
$queries = $schema->toSql(new \Doctrine\DBAL\Platforms\PostgreSqlPlatform());
// or $queries = $schema->toSql(new \Doctrine\DBAL\Platforms\MysqlPlatform());
foreach ($queries as $query)
{
echo $query . ";\n";
}
This is the output for the MySQL platform:
CREATE TABLE admins (
id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL,
username VARCHAR(10) NOT NULL,
password VARCHAR(45) NOT NULL,
UNIQUE INDEX UNIQ_A2E0150FF85E0677 (username), PRIMARY KEY(id)
) ENGINE = InnoDB;
It's absolutely right ! We can notice the "AUTO_INCREMENT" for the "id" column.
But If I choose the PostgreSQL platform, this is the output:
CREATE TABLE admins (
id SMALLINT NOT NULL,
username VARCHAR(10) NOT NULL,
password VARCHAR(45) NOT NULL,
PRIMARY KEY(id)
);
CREATE UNIQUE INDEX UNIQ_A2E0150FF85E0677 ON admins (username);
The auto_increment doesn't work on PostgreSQL platform...
But in the documentation, "autoincrement" is in the "Portable options" section.
What's the problem ?
Thank you
A:
You need to create a sequence manually or use a serial type since AUTO_INCREMENT like magic flag doesn't exist on PostgreSQL platform. It's documented as "portable" because of DBAL can handle this requirement on all platforms, but via different ways.
Try this:
$table = $schema->createTable('admins');
$schema->createSequence('admins_seq');
$table->addColumn('id', 'smallint', array('unsigned' => true));
$table->addColumn( ... );
// ...
Hope it helps.
Update : Ah, after comments i think i figured out what's happening. @Thomas, how and where did you get that $schema instance? What is the output of the get_class($schema)?
You have to use a Schema Manager instance which can be easily grabbed from $connection instance and you should issue your commands over that instance for maximum portability.
Example:
$sm = $connection->getSchemaManager();
$table = new \Doctrine\DBAL\Schema\Table('admin');
$id = $table->addColumn('id', 'integer');
$id->setAutoincrement(true);
$table->addColumn('username', 'string');
$sm->createTable($table);
This should work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Division returns unexpected 0 if result is declared as double
From the following code
x = 2 / 5
double y = 2 / 5
double z = 2.0 / 5
println(String.format("%f %f %f", x, y, z))
we get the output
0.4 0.0 0.4
Why is the value of y 0.0? What is the reason for this unintuitive behaviour?
A:
Because dividing two integers (2 and 5) gives that result 0, which is then converted to double.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sencha Touch 2 Beta 2 Store Sync Issues
In ST1.x I had no problem syncing an onlinestore to an offlinestore with the below method, now it seems that sync doesn't work in STB2. I can see the records being output on the console. Anyone else having this issue? I believe it may be a bug...
var remoteStore = Ext.getStore('UpdateConfig');
var localStore = Ext.getStore('UpdateLocalConfig');
remoteStore.each(function (record) {
localStore.add(record.data);
console.log(record.data);
});
localStore.sync();
A:
This was answered on the Sencha Touch 2 Forums by TommyMaintz, but I wanted to give the answer here as well.
"One thing I think I see which is wrong is that you are adding a record to the LocalStore using the record.data. In ST2 we now have a Model cache. This means that if you create two instances with the exact same model and id, the second time you create that instance it will just return the already existing instance. This means that if you sync your local store, it won't recognize that record as a 'phantom' record because it already has an id. What you would have to do in your case if you want to make a "copy" of your record by using all the data but removing the id. This will generate a new simple id for it and when you save it to your local storage it will generate a proper local id for it.
When I tried doing this I noticed the "copy" method on Model hasn't been updated to handle this. If you apply the following override you should be able to do localStore.add(record.copy()); localStore.sync()"
Ext.define('Ext.data.ModelCopyFix', {
override: 'Ext.data.Model',
/**
* Creates a copy (clone) of this Model instance.
*
* @param {String} id A new id. If you don't specify this a new id will be generated for you.
* To generate a phantom instance with a new id use:
*
* var rec = record.copy(); // clone the record with a new id
*
* @return {Ext.data.Model}
*/
copy: function(newId) {
var me = this,
idProperty = me.getIdProperty(),
raw = Ext.apply({}, me.raw),
data = Ext.apply({}, me.data);
delete raw[idProperty];
delete data[idProperty];
return new me.self(null, newId, raw, data);
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add a newline to JLabel without using HTML
How can I add a new line to a JLabel? I know if I use simple HTML, it will work. But if I use HTML, JLabel is not showing the font which embedded with the application. I am embedding the font using the method - createFont() and using JLabel.setFont() for applying the font.
A:
SwingX supports multiline labels:
JXLabel label = new JXLabel();
label.setLineWrap(true);
A:
I don't think there is direct(and easy) way of doing JLabel with multiple lines without recurring to HTML. You can use JTextArea instead.
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setOpaque(false);
textArea.setBorder(BorderFactory.createEmptyBorder());
add(textArea, BorderLayout.CENTER);
It should look almost the same. If you have different fonts for different components, you can add the following line to ensure that the font of JTextArea is the same with JLabel
textArea.setFont(UIManager.getFont("Label.font"));
Hope this helps.
A:
JLabel is not originally intended for multiline text, from what I recall. You would need to override the various rendering methods to do the text line splitting manually.
Perhaps you should rather use a non-editable JTextArea if you want multiline labels.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Microsoft Teams azure botframework ICON
I'm looking way to change icons of my bot (botframework botbuilder c# azure web app) using manifest.json (https://docs.microsoft.com/en-us/microsoftteams/platform/resources/schema/manifest-schema) they work like a charme for green icon and doesn't work for the 2 red circle ? :' :
I didn't know if it's a problem due to the picture but i have following the site
and preconization : https://docs.microsoft.com/en-us/microsoftteams/platform/resources/schema/manifest-schema
Note : All icon work if i'm deploy the bot using channel link registration on Azure portal.
Sincerely,
Pascal.
A:
Solution :
In my case it's not a problem due too icon image present on manifest zip.
But it's a problem due the icon present on setting of ("bot channel registration") in Azure portal.
After change you icon in the setting "bot channel registration" you have to disconnected and reconnected from teams and after a small time (1 or 2 minutes) the icons work in teams.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VBA Date + For logic
can someone help me? It seems my for logic is not working at all because it keeps returning me 12:00AM for starttime
Here is my code
Sub forlogic()
Dim i As Single
Dim totalrow As Double
Dim startdate As Date
Dim mydate As Date
totalrow = Sheet1.Range("A1", Sheet1.Range("A1").End(xlDown)).Rows.Count
mydate = Date
Debug.Print mydate
mydate = mydate - 90
Debug.Print mydate
For i = 1 To i = rowtotal Step 2
startdate = Format(Range("E" & i).Value, "short date")
startdate = Format(Date, "mm/dd/yyyy")
If mydate > startdate Then
Range("M" & i).Value = "Expired"
End If
i = i + 1
Next i
Debug.Print startdate
End Sub
it keeps returning me
12:00:00 AM for startdate
A:
Below code is tested and working as expected. List of updates:
1) To refer to sheet, Thisworkbook.Sheets("Sheet1") which I dimmed as ws
2) Updated totalrow calculation
3) Since you are only acting on one outcome of the IF statement, you can condense to 1 line.
4) Add Option Explicit to catch errors like swapping totalrow with rowtotal (This also would have caught your sheet reference error)
5) Adjusted the i increment (this defaults to 1, no need to state Step 1)
This is tested and working fine on my end.
Option Explicit
Sub forlogic()
Dim totalrow As Long, i As Long
Dim startdate As Date, mydate As Date
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
totalrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
mydate = Date - 90
For i = 1 To totalrow
startdate = Format(ws.Range("E" & i).Value2, "mm/dd/yyyy")
If mydate > startdate Then ws.Range("M" & i).Value = "Expired"
Next i
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Transfer data between dataframes
I regularly need to transfer data between dataframes. Often the dataframe from where the data comes from is a smaller subset of the dataframe where the data is going to.
Lets say I have this dataframe:
df <- data.frame(ID = c(1,3,6,9), variable = c(-0.1, 0, 0, 0.1))
ID variable
1 1 -0.1
2 3 0.0
3 6 0.0
4 9 0.1
I need to transfer variable from df to sleep, but only at rows where ID is the same in both df and sleep.
To do this, I normally use a for loop like this:
sleep$variable <- NA
for (i in seq_along(sleep$ID)) {
x <- which(sleep$ID == df$ID[i])
sleep$variable[x] <- df$variable[i]
}
sleep
extra group ID variable
1 0.7 1 1 -0.1
2 -1.6 1 2 NA
3 -0.2 1 3 0.0
4 -1.2 1 4 NA
5 -0.1 1 5 NA
6 3.4 1 6 0.0
7 3.7 1 7 NA
8 0.8 1 8 NA
9 0.0 1 9 0.1
10 2.0 1 10 NA
11 1.9 2 1 -0.1
12 0.8 2 2 NA
13 1.1 2 3 0.0
14 0.1 2 4 NA
15 -0.1 2 5 NA
16 4.4 2 6 0.0
17 5.5 2 7 NA
18 1.6 2 8 NA
19 4.6 2 9 0.1
20 3.4 2 10 NA
I'm looking for a function that will achieve the same result, but requires less code. Ideally, I would like the function to take just 3 arguments: the vector where the data is coming from, the vector where the data is going to and the vector used to match rows in the two dataframes.
Is there such a function currently available in R? Alternatively, can anyone provide such a function?
A:
How about match:
sleep <- data.frame(extra = runif(100), group = rep(1:10, each = 10), ID = rep(1:10, times = 10))
sleep$variable <- df$variable[match(sleep$ID, df$ID)]
This requires four arguments (ID is repeated, arguably unnecessarily).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to create a regular language from an non regular language? (details inside)
I am wondering, is it is possible to create a regular language from a non regular language if we add or remove finite number of words from it?
say L is irregular, if we add or remove finite number of words can we create a regular language?
i might be mistaken, but since all regular languages are finite - if we add a finite amount to a non regular language - it still stays non regular, but if we substract, let's say a finite amount from infinity, it is still infinity.
so is it safe to say that in both cases a regular language cannot not be obtained by adding/substracting a finite amount of words?
i was told to ask this question here rather then in softwareengineering.
thank you very much for your help. really curious about that
A:
We have a language $L$ which is non-regular. We subtract a finite subset $S \subset L$ of words in $L$ to get the rest: $R = L \setminus S$.
Assume that $R$ is regular. Since regular languages are closed under union, and finite sets of words are trivially regular, we can construct a language $L' = R \cup S$ which is also regular.
Since $S \subset L$, we have $(L \setminus S) \cup S = L$, thus $L' = L$. But $L'$ is regular while $L$ is not - a contradiction. Thus our assumption that $R$ is regular was wrong.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Significato di "copione" in questo passaggio
Nel romanzo Vita di Melania G. Mazzucco ho letto:
Quando tornai a Roma, frugai tra le carte di mio padre. Erano conservate nella casa di famiglia che avevo lasciato da anni, in volenteroso disordine, in due stipi di metallo. C’erano pile di cartelle colorate, scatole da scarpe stracolme di fogli, carta velina, giornali scompagnati, dattiloscritti, copioni. Speravo che avesse scritto dell’America.
Ho cercato il termine "copione" in parecchi dizionari, ma non mi sembra che quello che ho trovato, cioè, la sceneggiatura di un film o di uno spettacolo teatrale o del testo di una trasmissione radiofonica o televisiva, sia il senso di questo vocabolo nel brano sopra citato. Potreste spiegarmi che cosa vuol dire?
A:
Da Treccani per copione:
copióne s. m. [accr. di copia]. – Nel linguaggio di teatro, testo di
un lavoro drammatico affidato alla compagnia (un tempo manoscritto),
che viene distribuito per l’apprendimento e le prove agli attori
(oltre che al regista e al suggeritore), e dal quale vengono estratte
le parti staccate per i personaggi secondarî: recitare a c., attenersi
al c.; battuta non prevista dal c. (o fuori c.), improvvisata
dall’attore; estens. e fig.: è sempre il solito c.; non com., parlare,
agire a c., senza spontaneità, secondo quanto già stabilito in
precedenza, o seguendo indicazioni e prescrizioni esterne. Per
estens., la sceneggiatura di un film, il testo di una trasmissione
radiofonica o televisiva.
Nel contesto da te citato era il manoscritto detto anche sceneggiatura e serviva agli attori per prepararsi alla parte.
Secondo Hoepli:
Copia del testo di un'opera drammatica destinata alla
rappresentazione, utilizzata spec. dagli attori e dal regista durante
le prove || Sceneggiatura di un'opera cinematografica || Testo di una
trasmissione radiofonica o televisiva
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a good free DWG viewer for Mac OS X?
There are new Autodesk products (AutoCAD LT or similar) for Mac OS and iOS, but I couldn't find a simple free DWG viewer for Mac.
A:
AutoCAD WS is a free app on the Mac App Store. I've never tried it.
A:
A360 Viewer
AutoCAD's A360 Viewer is a browser based tool for viewing DWG files:
A360 Viewer Free online viewer - View designs in more than 50 file formats, including .dwg, right in your browser—no downloads or plug-ins needed.
LibreCAD
LibreCAD is open source, free, and can read and write DWG files.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to clone and run another user's Rails app
I'm attempting to do something I've never done before: clone another user's (codeforamerica) repository and run it locally on my computer with the intention of making my own changes to it.
I've managed to fork it to my own repositories, and cloned it:
git clone https://github.com/martynbiz/human_services_finder.git
...but when I do the following straight out the box:
cd human_services_finder
rails s
...it tell me:
The program 'rails' is currently not installed. You can install it by typing:
sudo apt-get install rails
...however, if I go into one of my own apps and run rails s it runs the server OK. Is there something missing I need to run this as a Rails app? Sorry, bit of a beginner with this one. Thanks
A:
Below are the setups to run Ruby on Rails application on your system.
Make sure Ruby is installed on your system. Fire command prompt and run command:
ruby -v
Make sure Rails is installed
rails -v
If you see Ruby and Rails version then you are good to start, other wise Setup Ruby On Rails on Ubuntu
Once done, Now
Clone respected git repository
git clone https://github.com/martynbiz/human_services_finder.git
Install all dependencies
bundle install
Create db and migrate schema
rake db:create
rake db:migrate
Now run your application
rails s
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to delete all contacts in contact list on android mobile programatically
I want to delete all the contact on one button press from my application so can any one nice person can told me how to delete all the contacts from android mobile programmatically on only one button press? answer would be greatly appreciated...
Actually I was surfing from a couple of hours but not got any appropriate answer. That's why I need to post my problem in this nice forum...thanks to such forum....
A:
It is very simple, This code will remove all your contacts.
ContentResolver contentResolver = <your app context>.getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
contentResolver.delete(uri, null, null);
}
Done.
A:
Specify READ_CONTACTS and WRITE_CONTACTS permissions in your AndroidManifest.xml.
Iterate through each contact and delete each record: Content Providers
Contacts
Be careful with deleting Contacts! Deleting an aggregate contact
deletes all constituent raw contacts. The corresponding sync adapters
will notice the deletions of their respective raw contacts and remove
them from their back end storage.
With regards to permissions, see Permission groups:
Caution: Future versions of the Android SDK might move a particular permission from one group to another. Therefore, don't base your app's logic on the structure of these permission groups.
For example, READ_CONTACTS is in the same permission group as WRITE_CONTACTS as of Android 8.1 (API level 27). If your app requests the READ_CONTACTS permission, and then requests the WRITE_CONTACTS permission, don't assume that the system can automatically grant the WRITE_CONTACTS permission.
Note: Your app still needs to explicitly request every permission it needs, even if the user has already granted another permission in the same group. In addition, the grouping of permissions into groups may change in future Android releases. Your code shouldn't have logic that depends on a set of particular permissions being in the same group.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you merge branch such that the new commits are on top?
Suppose I have branch A. Now I create new branch B from A and make some commits. Suppose during this time A got a bunch of commits as well. Is there a way to merge those new commits to B such that the commits I made on B will be that the top ?
To illustrate:
A -> a1 -> a2 -- B created here -- -> a3 -> a4
B -> a1 -> a2 -> b1 -> b2
How do I merge such that B ends up like
B -> a1 -> a2 -> a3 -> a4 -> b1 -> b2
A:
You want to rebase, not merge
When on B, do
git rebase A
This won't affect the A branch, but it will rewrite the recent history of the B branch.
Beforehand, you had
... -> a1 -> a2 -> a3 -> a4 -> A
\--> b1 -> b2 -> B
and after you will have:
... -> a1 -> a2 -> a3 -> a4 -> A
\--> b1 -> b2 -> B
|
{
"pile_set_name": "StackExchange"
}
|
Q:
association in rails 3 associate 1 survey to 1 user
i'm working with ruby 1.9.2, rails 3.1.3, devise 1.5.3, mysql, my app is about surveys, now all users can see all surveys, but I need that user1 just could see surveys created by user1, now user1 and user2, etc. can see all surveys, the authentication module is done with devise, recognize every user by login, in my database I put user_id as foreign key, or just by alter table tablename add column user_id int(11)not null; but when I tried to create a new survey I get this message: Mysql2::Error: Column 'user_id' cannot be null: INSERT INTO asurveys (created_at, name, updated_at, user_id) VALUES ('2012-02-29 12:39:34', 'encuesta musical', '2012-02-29 12:39:34', NULL)
*my controller:*
asurveys_controller.rb
class AsurveysController < ApplicationController # GET /asurveys #
GET /asurveys.json
def index
@asurveys = current_user.asurveys
respond_to do |format|
format.html # index.html.erb
format.json { render json: @asurveys }
end end
@asurvey = Asurvey.find(params[:id])
#@asurvey = current_user.asurveys.find(params[:id])
#current_user.asurveys = User.find(1)
respond_to do |format|
format.html # show.html.erb
format.json { render json: @asurvey }
end end
# GET /asurveys/new # GET /asurveys/new.json #def new
#@asurvey = Asurvey.new
#3.times { @asurvey.questions.build }
#respond_to do |format|
# format.html # new.html.erb
# format.json { render json: @asurvey }
#end #end #ejemplo railscast para 3 preguntas y 4 respuestas def new
@asurvey = Asurvey.new
3.times do
question = @asurvey.questions.build
4.times { question.answers.build } end end #
# GET /asurveys/1/edit def edit
@asurvey = Asurvey.find(params[:id]) end
# POST /asurveys # POST /asurveys.json def create
@asurvey = Asurvey.new(params[:asurvey])
respond_to do |format|
if @asurvey.save
format.html { redirect_to @asurvey, notice: 'Encuesta creada exitosamente.' }
format.json { render json: @asurvey, status: :created, location: @asurvey }
else
format.html { render action: "nueva" }
format.json { render json: @asurvey.errors, status: :unprocessable_entity }
end
end end
# PUT /asurveys/1 # PUT /asurveys/1.json def update
@asurvey = Asurvey.find(params[:id])
respond_to do |format|
if @asurvey.update_attributes(params[:asurvey])
format.html { redirect_to @asurvey, notice: 'Encuesta actualizada exitosamente.' }
format.json { head :ok }
else
format.html { render action: "editar" }
format.json { render json: @asurvey.errors, status: :unprocessable_entity }
end
end end
# DELETE /asurveys/1 # DELETE /asurveys/1.json def destroy
@asurvey = Asurvey.find(params[:id])
@asurvey.destroy
respond_to do |format|
format.html { redirect_to asurveys_url }
format.json { head :ok }
end end end
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
def after_sign_in_path_for(resource) stored_location_for(resource) || bienvenido_path end end
my models
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
#codigo de asociacion, un usuario puede tener muchas encuestas, esta asociacio se hace para que 1 usuario pueda
#tener muchas encuestas, pero cada encuesta solo tiene 1 usuario
#codigo de prueba para asociar encuestas a un solo usuario
#has_many :asurveys
has_many :asurveys
#, :foreign_key => :user_id, :class_name => 'User'
#fin asociacion
devise :database_authenticatable, :registerable,:confirmable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:tipo_tarjeta, :numero_tarjeta, :fecha_vencimiento, :nombre_en_tarjeta,
:cvv, :nombre, :apellidos, :mail_facturacion, :mail_facturacion_alternativo,
:nombre_empresa, :pais, :direccion,:codigo_postal, :telefono, :numero_orden_compra
#validacion de presencia de campos, no pueden estar en blanco
#validacion de presencia de campos, no pueden estar en blanco
validates_presence_of :numero_tarjeta,
:message => ": ingrese numero de tarjeta (15 digitos)"
validates_presence_of :nombre_en_tarjeta,
:message => ": ingrese el nombre que aparece en su tarjeta"
#validates_presence_of :fecha_vencimiento,
#:message => ": ingrese fecha de vencimiento de su tarjeta"
validates_presence_of :cvv,
:message => ": ingrese cvv "
#validacion de ingreso de campos "datos personales"
validates_presence_of :nombre,
:message => ": ingrese su nombre"
validates_presence_of :apellidos,
:message => ": ingrese sus apellidos"
validates_presence_of :mail_facturacion,
:message => ": ingrese mail de facturacion"
validates_presence_of :mail_facturacion_alternativo,
:message => ": ingrese mail alternativo de facturacion"
validates_presence_of :nombre_empresa,
:message => ": ingrese nombre de su empresa"
validates_presence_of :direccion,
:message => ": ingrese direccion de su empresa"
validates_presence_of :codigo_postal,
:message => ": ingrese codigo postal"
validates_presence_of :telefono,
:message => ": ingrese telefono de su empresa"
validates_presence_of :numero_orden_compra,
:message => ": ingrese numero de orden de compra"
#largo de campos, formato mail
validates_length_of :numero_tarjeta, :minimum => 16, :allow_blank => true, :message => "El numero debe tener al menos 16
digitos de longitud"
validates_length_of :nombre_en_tarjeta, :minimum => 2, :allow_blank => true, :message => "minimo 2 caracteres"
validates_length_of :cvv, :in => 3..4, :allow_blank => true, :message => "(en Mastercard y Visa son los 3 ultimos digitos impresos
al dorso de la tarjeta, en American Express son los 4 numeros impresos
en el frente de la tarjeta arriba de los ultimos digitos grabados en
relieve)"
validates_length_of :nombre, :minimum => 2, :allow_blank => true, :message => "minimo 2 caracteres"
validates_length_of :apellidos, :minimum => 4, :allow_blank => true, :message => "minimo 4 caracteres"
validates_format_of :mail_facturacion,
:with => /^[A-Z0-9._%-]+@([A-Z0-9]+.)+[A-Z]{2,4}$/i, :message => "formato incorrecto"
validates_format_of :mail_facturacion_alternativo,
:with => /^[A-Z0-9._%-]+@([A-Z0-9]+.)+[A-Z]{2,4}$/i, :message => "formato incorrecto en mail alternativo"
validates_length_of :nombre_empresa, :minimum => 4, :allow_blank => true, :message => "minimo 4 caracteres"
validates_length_of :direccion, :minimum => 4, :allow_blank => true, :message => "minimo 4 caracteres"
validates_length_of :codigo_postal, :minimum => 7, :allow_blank => true, :message => "minimo 7 caracteres"
validates_length_of :telefono, :minimum => 7, :allow_blank => true, :message => "minimo 7 caracteres"
validates_length_of :numero_orden_compra, :minimum => 2, :allow_blank => true, :message => "minimo 2 caracteres"
#validates_length_of :password, :minimum => 6, :allow_blank => false
> end
class Asurvey < ActiveRecord::Base #asociacion para que las
encuestas puedan ser vistas solo por el usuario que la crea
belongs_to :user #belongs_to :user #belongs_to :user, :class_name => "User", :foreign_key => 'user_id' belongs_to :user #, :foreign_key => "user_id" #attr_accessible :user_id #has_many
:asurveys_users #has_many :users, :through => :asurveys_users
has_many :asurveys_users, :class_name => "User", :through => :asurveys_users #fin asociacion, una encuesta pertenece a solo un
usuario has_many :questions, :dependent => :destroy #:dependent =>
:destroy para que cuando eliminemos una encuesta se eliminen también
todas sus preguntas. accepts_nested_attributes_for :questions,
:reject_if => lambda { |a| a[:content].blank? } , :allow_destroy =>
true #accepts_nested_attributes_for para poder gestionar las
preguntas a través de Survey. Con esto podremos crear, actualizar y
destruir preguntas cuando actualicemos los atributos de una encuesta.
el nombre de atributo para la caja de selección: _destroy. Cuando tenga un valor true (cuando haya sido marcada), el registro será
eliminado al enviar el formulario. #User.find(1).asurveys end
views
Encuesta Nombre: <%=h
@asurvey.name %> <% for question in
@asurvey.questions %> <%= h question.content %>
<% for answer in question.answers %>
<%= h answer.content %>
<% end %> <% end %> <%= link_to "Editar", edit_asurvey_path(@asurvey) %> | <%= link_to "Eliminar",
@asurvey, :confirm => 'Estas seguro/a?', :method => :delete %> |
<%= link_to "Ver todas las encuestas", asurveys_path %>
asurvey_helper
module AsurveysHelper end
A:
To create new surveys you should do something like this:
current_user.asurveys.create(params[:assurvey])
To get the surveys created only by the loged user:
@asurveys = current_user.asurveys
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Easy to use (Gui Win) Version Control Software
I'm in search for a friend who studies economic science for an easy Version Control Software. For the moment he needs it for his thesis which has to be written in LaTeX. Since he has to learn LaTeX too (and he has enough problems with it) the VCS should be easy to use - at best with Gui for Windows. He is the only one who has to use the VCS.
A few years ago I used a VCS for the same purpose, but I can't find it any more. It was a bit like Git. It made in the working directory a hidden directory where it stored it's information.
I tried to teach him Git, but he said it is to complicated (I only use Git on command line and don't know any good Gui's) with his thesis and LaTeX.
Is there a good Gui for Git or an easy to learn/use VCS (it should be free)?
Thanks
A:
If your friend doesn't want to use SVN there is nice GUI for Mercurial: http://www.sourcetreeapp.com/.
Mercurial is really easy to learn. There are lot of tutorials for quick learning (for example: http://hginit.com/, https://www.mercurial-scm.org/guide/).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does Bash support command.subcommand structure in addition to command subcommand structure? If yes, how to incorporate this in bash scripts?
After installing microk8s (Micro Kubernetes) on my local machine, one of the commands I encountered was microk8s.enable dns which can also be run as microk8s enable dns. This doesn't seem to be a universal thing. git status is a valid command but git.status is not. How do Linux systems support such type of command structures? How can I incorporate this behavior in my Bash scripts?
A:
You'll sometimes see programs (and scripts) inspect the name of the file that was used to invoke the program and condition behavior off of that.
Consider for example this file and symbol link:
$ ls -l
-rwxr-xr-x ... foo
lrwxr-xr-x ... foo.bar -> foo
And the content of the script foo:
#!/bin/bash
readonly command="$(basename "${0}")"
subcommand="$(echo "${command}" | cut -s -d. -f2)"
if [[ "${subcommand}" == "" ]]; then
subcommand="${1}"
fi
if [[ "${subcommand}" == "" ]]; then
echo "Error: subcommand not specified" 1>&2
exit 1
fi
echo "Running ${subcommand}"
The script parses the command name looking for a subcommand (based on the dot notation in your question). With that, I can run ./foo.bar and get the same behavior as running ./foo bar:
$ ./foo.bar
Running bar
$ ./foo bar
Running bar
To be clear, I don't know that that's what microk8s.enable is doing. You could do a ls -li $(which microk8s.enable) $(which microk8s) and compare the files. Is one a link to the other? If not, do they have the same inode number?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How close would the Tesla Roadster with Starman have to get to Earth in order to become attracted and fall on Earth?
In 2091 the Tesla Roadster is said to maybe get closer to Earth than the Moon is. At Starman's current speed, would its location in 2091 be sufficient for the Earth to re-attract the Starman to let it reenter the Earth's atmosphere? How close must the Tesla be in order to get attracted by Earth strong enough to fall on Earth? And as for falling onto other planets: is the critical distance determined by the distance according to the Earth's and their masses times the Earth's? Such as: Mars has about 0.11 the Earth's mass so the critical distance for Mars would be about 0.11 that of Earth for the Tesla to get attracted by Mars?
A:
According to Keplerian orbital mechanics, it will never come so close to earth "to get attracted by Earth strong enough to fall on Earth" (unless it will hit the earth directly).
Everything entering Earth's Hill Sphere from "outside" is on a hyperbolic orbit, so it is going to pass earth no matter how close it passes Earth (here also: except a "direct hit").
EXCEPT: You take into account Earth's atmosphere: Earths atmosphere can slow down an object.
This is not directly connected to Earth's mass but to atmosphere density. So for earth, the minimum altitude is about 80 km (depending on many factors). For mars it will be much lower due to less atmospheric density. For the moon, you can theoretically pass a millimeter above surface without touching it (assuming it's a perfect sphere).
EDIT:
As mentioned in one comment:
Just one additional clarification: of course earths gravity affects the objects path, and of course more mass means the object is affected more. An object that collides with earth would not do so without first being affected by the gravity of earth or other celestial bodies. BUT the point is: objects from "outside" move in hyperbolic orbits. As long as the periapsis (closest point) does not hit earth nor it passes the dense part of the atmosphere, it will always pass.
A:
How close would the Tesla Roadster with Starman have to get to Earth in order to become attracted and fall on Earth?
tl;dr: If Roadster approached the Earth with $v_{inf}$ of 3000 m/s and an impact parameter of about 24,000 km from Earth's center (about 3.8 Earth radii), Earth's gravity would deflect it just enough for a grazing collision.
From Wikipedia's Hyperbolic Trajectory; Impact parameter and the distance of closest approach
$$r_p = -a(e-1) = \frac{GM}{v^2_{inf}} \left(\sqrt{1 + \left(\frac{bv^2_{inf}}{GM} \right)^2} - 1 \right) $$
See also What's the planetary exploration word for “impact parameter” (distance of closest approach if gravity were “turned off”)?
With Earths standard gravitational parameter $GM$ of 3.986E+14 m^3/s^2 and an approach velocity of 3000 m/s we can find out what impact parameter $b$ would result in a distance of closest approach $r_p$ equal to Earth's radius.
On earth when things fall into things they start from rest, or from a low speed.
"Falling into" isn't exactly the right way to think about moving bodies in the solar system because they are all generally going fast with respect to each other.
When Roadster was launched from Earth Elon Musk mis-tweeted that it had achieved 12 km^2/sec^2 excess C3 ("energy") relative to Earth after launch. He got the number wrong but the point is that once Roadster had this positive energy relative to Earth it could never "fall back" to Earth.
See Starman/Roadster in a=1.795 AU orbit, now what's the method to this madness? and this answer.
So Earth orbits the Sun at about 30 km/sec and when Roadster passes 1 AU from the Sun it will be going 33 km/sec (also around the Sun) in roughly the same direction, so if it was moving towards Earth it would slam into it at about 3 km/sec.
It's true that if it were going to miss the Earth by a diameter or two, then Earth's gravity could "pull it in" somewhat so that they still hit. We would probably call that a deflection rather than a "falling in".
Now the deflection could happen just before impact, or hundreds or thousands of years earlier! For more on that see
Do all dangerous asteroids first pass through keyholes?
Gravitational keyhole for spacecraft flyby?
import numpy as np
import matplotlib.pyplot as plt
vinf = 3000.
GM = 3.986E+14
Re = 6378137.
def r_closest(b):
term = np.sqrt(1 + (b * vinf**2 / GM)**2)
return (GM/vinf**2) * (term - 1.)
b = np.linspace(0, 10*Re, 101)[1:]
r = r_closest(b)
if True:
plt.figure()
plt.plot(b/Re, r/Re)
plt.plot(b/Re, np.ones_like(b), '--k')
plt.title('approach velocity (v_inf) 3000 m/s', fontsize=14)
plt.xlabel('impact parameter (Earth radii)', fontsize=14)
plt.ylabel('closest approach (Earth radii)', fontsize=14)
plt.show()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Conditional IF EXIST Statement for multiple filenames in BATCH file
I'm working on the following batch script and I'm not sure how I can achieve the results I'm looking for. I searched here as well as online, but I didn't see anything that looked like what I'm looking for. Any help is appreciated.
I need to check if two files exist as well as if they don't. Currently I've got the code below working, however if one file exists or is missing it goes in a 3rd direction (I've updated the code to account for the 3rd direction so now it works fine, but I know there is much room for improvement!). I know it's not pretty, but it works and the pretty code doesn't.
Please note that there are other files in the same directory with the same extensions, so searching by extension will not work.
Working Code:
@echo off
echo checking file structure...
if exist "file1.exe" (
if exist "file2.zip" (
goto ok
)
)
if not exist "file1.exe" (
if not exist "file2.zip" (
goto download
)
)
if not exist "file1.exe" (
goto download
)
)
if not exist "file2.zip" (
goto download
)
)
:download
echo downloading missing files.
:ok
echo Install successful
What I would like to do:
(The following code isn't expected to work, it's my thoughts written out)
@echo off
set file1=setup.exe
set file2=package.zip
if exist $file1 && $file2 then goto ok
else if not exist $file1 || $file2 goto download
Example of why checking for the two files alone will not work
echo checking file structure...
if exist "setup.exe" if exist "package.zip" goto TEST1
if not exist "setup.exe" if not exist "package.zip" goto TEST2
ECHO [Error!] - 1 File is present, the other is missing!
PAUSE
:TEST1
ECHO [Success!] - Found both files, YAY!
PAUSE
:TEST2
ECHO [Error!] - No matching files found.
PAUSE
A:
The parentheses are neccessary for the else clause.
@echo off
echo checking file structure...
if exist "file1.exe" (
if exist "file2.zip" (
goto :ok
) else goto :download
) else goto :download
:download
echo downloading missing files.
:ok
echo Install successful
But the else isn't required at all because the program flow falls through to the download label
@echo off
echo checking file structure...
if exist "file1.exe" if exist "file2.zip" goto :ok
:download
echo downloading missing files.
:ok
echo Install successful
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML 5 postMessage (same domain)
I am trying to get the HTML postMessage function working?
I have a found a few sites giving the example but for some reason a struggling.
The code for the 2 pages is shown below, any help would be apprecaited.
Thanks and Regards,
Ryan
test.php
<iframe src="postmessage-target.html" id="iframe"></iframe>
<form id="form">
<input type="text" id="msg" value="Message to send"/>
<input type="submit"/>
</form>
<script>
window.onload = function(){
var win = document.getElementById("iframe").contentWindow;
document.getElementById("form").onsubmit = function(e){
win.postMessage( document.getElementById("msg").value );
e.preventDefault();
};
};
</script>
postmessage-target.html
<div id="test">Send me a message!</div>
<script>
document.addEventListener("message", function(e){
document.getElementById("test").textContent =
e.domain + " said: " + e.data;
}, false);
</script>
Thanks again in advance.
Ryan
UPDATE
Is this correct as per user advice?
test.html
<iframe src="postmessage-target.html" id="iframe"></iframe>
<form id="form">
<input type="text" id="msg" value="Message to send"/>
<input type="submit"/>
</form>
<script>
window.onload = function(){
var win = document.getElementById("iframe").contentWindow;
document.getElementById("form").onsubmit = function(e){
win.postMessage( document.getElementById("msg").value, "*");
e.preventDefault();
};
};
</script>
postmessage-target.html
<div id="test">Send me a message!</div>
<script>
document.addEventListener("message", function(e){
document.getElementById("test").innerHTML = e.origin + " said: " + e.data;
}, false);
</script>
A:
The norm specifies that you should provide the targetOrigin to the postMessage function :
win.postMessage( document.getElementById("msg").value, "*");
I don't think there is a e.domain. Try e.origin in the listener :
document.getElementById("test").innerHTML = e.origin + " said: " + e.data;
(I also replaced the non standard textContent by innerHTML)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Word VBA Code to select text in a cell, cut and paste special back into the same cell
I have a table with two columns and "x" number of rows.
In the 2nd column is formatted text which I would like to change to unformatted text.
The manual way of doing so is:
Select the whole cell in the 2nd column » Cut » Click Edit » Click Paste Special » Click Unformatted
The idea is to paste the unformatted text back into the cell it was Cut from and then move down to the cell below.
I would really appreciate some code that can apply this to all the cells in the 2nd column of a table.
A:
Here is the solution to my problem. A friend had a piece of code which I manipulated to suit my needs:
Sub CutAndPasteSpecialUnformatted()
Dim value As Variable
' Process every row in the current table. '
Dim row As Integer
Dim rng As Range
For row = 1 To Selection.Tables(1).Rows.Count
' Get the range for the rightmost cell. '
Selection.Collapse Direction:=wdCollapseStart
Set rng = Selection.Tables(1).Cell(row, Column:=2).Range
' For each, toggle text in rightmost cell. '
rng.Select
Selection.Copy
Selection.Delete
rng.Select
Selection.Style = ActiveDocument.Styles("Normal")
Selection.Delete
Selection.Collapse Direction:=wdCollapseStart
Selection.Range.PasteSpecial DataType:=wdPasteText
Next
End Sub
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What happened to Live GPS Tracking in 1.8.0-Lisboa?
Dang, I was just getting used to Live GPS Tracking in 1.7.4-Wroclaw.
I downloaded the new version 1.8.0-Lisboa on another computer. The Live GPS Tracking
thing was in the View pull-down menu in 1.7.4. But, in 1.8.0-Lisboa, it's not there!!!
Was Live GPS Tracking taken out of 1.8.0-Lisboa? or maybe Live GPS Tracking is hidden somewhere?
A:
It's still in the View menu, but in the Panels submenu as GPS Information.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.