text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
biwavelet package: "cex.axis" not working in plot.biwavelet(); A bug?
I am using biwavelet package to conduct wavelet analysis. However, when I want to adjust the label size for axis using cex.axis, the label size does not changed. On the other hand, cex.lab and cex.main are working well. Is this a bug? The following gives a reproducible example.
library(biwavelet)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
# Continuous wavelet transform
wt.t1 <- wt(t1)
par(oma = c(0, 0.5, 0, 0), mar = c(4, 2, 2, 4))
plot(wt.t1,plot.cb = T,plot.phase = T,type = 'power.norm',
xlab = 'Time(year)',ylab = 'Period(year)',mgp=c(2,1,0),
main='Winter station 1',cex.main=0.8,cex.lab=0.8,cex.axis=0.8)
Edit
There was a previous question on this site a month ago: Wavelets plot: changing x-, y- axis, and color plot, but not solved. Any help this time? Thank you!
A:
Yeah, it is a bug. Here is patched version: my.plot.biwavelet()
This version accepts argument cex.axis (defaults to 1), and you can change it when needed. I will briefly explain to you what the problem is, in the "explanation" section in the end.
my.plot.biwavelet <- function (x, ncol = 64, fill.cols = NULL, xlab = "Time", ylab = "Period",
tol = 1, plot.cb = FALSE, plot.phase = FALSE, type = "power.corr.norm",
plot.coi = TRUE, lwd.coi = 1, col.coi = "white", lty.coi = 1,
alpha.coi = 0.5, plot.sig = TRUE, lwd.sig = 4, col.sig = "black",
lty.sig = 1, bw = FALSE, legend.loc = NULL, legend.horiz = FALSE,
arrow.len = min(par()$pin[2]/30, par()$pin[1]/40), arrow.lwd = arrow.len *
0.3, arrow.cutoff = 0.9, arrow.col = "black", xlim = NULL,
ylim = NULL, zlim = NULL, xaxt = "s", yaxt = "s", form = "%Y", cex.axis = 1,
...) {
if (is.null(fill.cols)) {
if (bw) {
fill.cols <- c("black", "white")
}
else {
fill.cols <- c("#00007F", "blue", "#007FFF",
"cyan", "#7FFF7F", "yellow", "#FF7F00", "red",
"#7F0000")
}
}
col.pal <- colorRampPalette(fill.cols)
fill.colors <- col.pal(ncol)
types <- c("power.corr.norm", "power.corr", "power.norm",
"power", "wavelet", "phase")
type <- match.arg(tolower(type), types)
if (type == "power.corr" | type == "power.corr.norm") {
if (x$type == "wtc" | x$type == "xwt") {
x$power <- x$power.corr
x$wave <- x$wave.corr
}
else {
x$power <- x$power.corr
}
}
if (type == "power.norm" | type == "power.corr.norm") {
if (x$type == "xwt") {
zvals <- log2(x$power)/(x$d1.sigma * x$d2.sigma)
if (is.null(zlim)) {
zlim <- range(c(-1, 1) * max(zvals))
}
zvals[zvals < zlim[1]] <- zlim[1]
locs <- pretty(range(zlim), n = 5)
leg.lab <- 2^locs
}
else if (x$type == "wtc" | x$type == "pwtc") {
zvals <- x$rsq
zvals[!is.finite(zvals)] <- NA
if (is.null(zlim)) {
zlim <- range(zvals, na.rm = TRUE)
}
zvals[zvals < zlim[1]] <- zlim[1]
locs <- pretty(range(zlim), n = 5)
leg.lab <- locs
}
else {
zvals <- log2(abs(x$power/x$sigma2))
if (is.null(zlim)) {
zlim <- range(c(-1, 1) * max(zvals))
}
zvals[zvals < zlim[1]] <- zlim[1]
locs <- pretty(range(zlim), n = 5)
leg.lab <- 2^locs
}
}
else if (type == "power" | type == "power.corr") {
zvals <- log2(x$power)
if (is.null(zlim)) {
zlim <- range(c(-1, 1) * max(zvals))
}
zvals[zvals < zlim[1]] <- zlim[1]
locs <- pretty(range(zlim), n = 5)
leg.lab <- 2^locs
}
else if (type == "wavelet") {
zvals <- (Re(x$wave))
if (is.null(zlim)) {
zlim <- range(zvals)
}
locs <- pretty(range(zlim), n = 5)
leg.lab <- locs
}
else if (type == "phase") {
zvals <- x$phase
if (is.null(zlim)) {
zlim <- c(-pi, pi)
}
locs <- pretty(range(zlim), n = 5)
leg.lab <- locs
}
if (is.null(xlim)) {
xlim <- range(x$t)
}
yvals <- log2(x$period)
if (is.null(ylim)) {
ylim <- range(yvals)
}
else {
ylim <- log2(ylim)
}
image(x$t, yvals, t(zvals), zlim = zlim, xlim = xlim,
ylim = rev(ylim), xlab = xlab, ylab = ylab, yaxt = "n",
xaxt = "n", col = fill.colors, ...)
box()
if (class(x$xaxis)[1] == "Date" | class(x$xaxis)[1] ==
"POSIXct") {
if (xaxt != "n") {
xlocs <- pretty(x$t) + 1
axis(side = 1, at = xlocs, labels = format(x$xaxis[xlocs],
form))
}
}
else {
if (xaxt != "n") {
xlocs <- axTicks(1)
axis(side = 1, at = xlocs, cex.axis = cex.axis)
}
}
if (yaxt != "n") {
axis.locs <- axTicks(2)
yticklab <- format(2^axis.locs, dig = 1)
axis(2, at = axis.locs, labels = yticklab, cex.axis = cex.axis)
}
if (plot.coi) {
polygon(x = c(x$t, rev(x$t)), lty = lty.coi, lwd = lwd.coi,
y = c(log2(x$coi), rep(max(log2(x$coi), na.rm = TRUE),
length(x$coi))), col = adjustcolor(col.coi,
alpha.f = alpha.coi), border = col.coi)
}
if (plot.sig & length(x$signif) > 1) {
if (x$type %in% c("wt", "xwt")) {
contour(x$t, yvals, t(x$signif), level = tol,
col = col.sig, lwd = lwd.sig, add = TRUE, drawlabels = FALSE)
}
else {
tmp <- x$rsq/x$signif
contour(x$t, yvals, t(tmp), level = tol, col = col.sig,
lwd = lwd.sig, add = TRUE, drawlabels = FALSE)
}
}
if (plot.phase) {
a <- x$phase
locs.phases <- which(zvals < quantile(zvals, arrow.cutoff))
a[locs.phases] <- NA
phase.plot(x$t, log2(x$period), a, arrow.len = arrow.len,
arrow.lwd = arrow.lwd, arrow.col = arrow.col)
}
box()
if (plot.cb) {
fields::image.plot(x$t, yvals, t(zvals), zlim = zlim, ylim = rev(range(yvals)),
xlab = xlab, ylab = ylab, col = fill.colors,
smallplot = legend.loc, horizontal = legend.horiz,
legend.only = TRUE, axis.args = list(at = locs,
labels = format(leg.lab, dig = 2)), xpd = NA)
}
}
Test
library(biwavelet)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
# Continuous wavelet transform
wt.t1 <- wt(t1)
par(oma = c(0, 0.5, 0, 0), mar = c(4, 2, 2, 4))
my.plot.biwavelet(wt.t1,plot.cb = T,plot.phase = T,type = 'power.norm',
xlab = 'Time(year)',ylab = 'Period(year)',mgp=c(2,1,0),
main='Winter station 1',cex.main=0.8,cex.lab=0.8,cex.axis=0.8)
As expected, it is working.
Explanation
In plot.biwavelet(), why passing cex.axis via ... does not work?
plot.biwavelet() generates the your final plot mainly in 3 stages:
image(..., xaxt = "n", yaxt = "n") for generating basic plot;
axis(1, at = atTicks(1)); axis(2, at = atTicks(2)) for adding axis;
fields::image.plot() for displaying colour legend strip.
Now, although this function takes ..., they are only fed to the first image() call, while the following axis(), (including polygon(), contour(), phase.plot()) and image.plot() take none from .... When later calling axis(), no flexible specification with respect to axis control are supported.
I guess during package development time, problem described as in: Giving arguments from “…” argument to right function in R had been encountered. Maybe the author did not realize this potential issue, leaving a bug here. My answer to that post, as well as Roland's comments, points toward a robust fix.
I am not the package author so can not decide how he will fix this. My fix is brutal, but works for you temporary need: just add the cex.axis argument to axis() call. I have reached Tarik (package author) with an email, and I believe he will give you a much better explanation and solution.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to change a specific datagridview column format
I have a datagridview which displays my records in currency format. I set the DefaultCellStyle property permanently for the format BUT I have a particular column which I wanna display it values as an Integer.
The column i wanna change and what it displays:
[AreaCode]
15,00 €
25,00 €
60,00 €
My expectation:
[AreaCode]
15
25
60
And here is my code which isn't working:
private void dgv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var columnname = "AreaCode";
if (e.ColumnIndex == dgv1.Columns[columnname].Index)
{
//Get the datagridview cell
DataGridViewCell cell = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell != null)
{
this.dgv1.Columns["AreaCode"].DefaultCellStyle.Format = "D4";
}
}
}
Thnx in advance
A:
try this
this.dgv1.Columns["AreaCode"].DefaultCellStyle.Format = "N0";
using N0 this will format your areacode column to numeric with 0 decimal placess
private void dgv1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
var columnname = "AreaCode";
if (e.ColumnIndex == dgv1.Columns[columnname].Index)
{
//Get the datagridview cell
DataGridViewCell cell = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (cell != null)
{
this.dgv1.Columns["AreaCode"].DefaultCellStyle.Format = "N0";
}
}
}
Note: If you want some decimal places to then you can use "N1","N2" and so on....
| {
"pile_set_name": "StackExchange"
} |
Q:
pig latin practice on vb
I am a newb practising vb code by attempting a piglatin translator.
I'm stuck on the part where I need to send any consonant letters to the back of the word and loop this process until the first letter becomes a vowel.
For example,
dragon--> loop once
Ragond--> loop again
Agondr--> the first word is a vowel- now stop!
How do I do this? I've attempted it in my code but it gives me nothing. Also, how would I keep correct case in this code? Dragon= Agondray DRAGON = AGONDRAY etc.
Public Class Form1
Private Sub translatebtn_Click(sender As Object, e As EventArgs) Handles translatebtn.Click
Dim wordlist() As String = englishtext.Text.Split(" ") 'this splits up the english word/sentence into an individual words.
Dim i As Integer
'this loops translation code through each word
For i = 0 To wordlist.Length - 1
piglatin(wordlist(i))
Next
End Sub
Public Const Vowels As String = "aeiouyAEIOUY"
Public Const upperconsonant As String = "BCDFGHJKLMNPQRSTVWXZ"
Public Const consonant As String = "bcdfghjklmnpqrstvwxz"
Public Function hasavowel(ByVal intheword As String) As Boolean 'the word has a vowel
Dim i As Integer
For i = 0 To 11
If (intheword = Vowels(i)) Then
Return True
End If
Next
Return False
End Function
Public Function hasaconsonant(ByVal intheword As String) As Boolean 'the word has a consonant
Dim i As Integer
For i = 0 To 19
If (intheword = consonant(i)) Then
Return True
End If
Next
Return False
End Function
Private Function moveLetter(ByVal strWord As String) As String
Dim intheword As Char
If hasavowel(strWord(0)) Then
Return strWord 'this is for the vowel starting words
Else
Do While hasaconsonant(strWord(0))
intheword = Char.ToLower(strWord(0))
Loop
Return moveLetter(strWord.Substring(1) + intheword) 'this is for the consonant starting words
End If
End Function
Private Sub piglatin(ByVal strWord As String)
If hasavowel(strWord(0)) Then
piglatintext.Text += strWord + "way " 'if the vowel is in the first position of the word. way is added on end.
Else
piglatintext.Text += moveLetter(strWord) + "ay " 'otherwise, ad ay.
End If
End Sub
A:
Your loop should be updating strWord since you are using it to compare in the while.
Private Function moveLetter(ByVal strWord As String) As String
If Not hasavowel(strWord(0)) Then
Do While hasaconsonant(strWord(0))
strWord = strWord.Substring(1) & strWord(0)
Loop
End If
Return strWord
End Function
| {
"pile_set_name": "StackExchange"
} |
Q:
How to store a reference to a property
Is there a way to store a reference to a property into a variable that will allow me to access it just as if I were accessing that objects property, like so:
var ReferenceVariable = Object.Property;
ReferenceVariable = "SOMETHING";
If (Object.Property == "SOMETHING")
//It worked! Yaay!
If so, how do I go about doing that?
EDIT: For a bit of clarity, this is what is going on:
private void UpdateColor(){
if (radioButton1.Checked){
Object.Color1 = Color.Red
}
if (radioButton2.Checked){
Object.Color2 = Color.Blue
}
.
.
.
if (radioButtonN.Checked){
Object.ColorN = Color.ColorN
}
}
This is very sub-optimal. Ideally the issue would be handled in the function that fires when the radio button is changed, so that it would be something like...
private void RadioButton_CheckChanged(object sender, eventargs e){
//Something is done here to tell the program that we are interested in Object.Color...Whatever
}
private void UpdateColor(){
//Now we know what color we're looking at, we can just do it in one step rather than looking at a thousand (I exaggerate of course) radio buttons checked states.
}
I hope that helps you help me a little bit more...
A:
Assuming I'm understanding your need correctly, you could use an Action<> delegate to set your properties. The following example code (in a Windows Forms app) uses a Dictionary to store a delegate for each radio button. The radio buttons all share the same event handler, which retrieves the delegate from the dictionary and sets it as the current delegate in the colorSetter variable. I'm just using some buttons on the form to change color, and depending on which radio button is checked, the appropriate color property will be changed.
public partial class Form1 : Form {
private readonly ColorPropertyObject cpo = new ColorPropertyObject();
private Action<Color> colorSetter;
private readonly Dictionary<RadioButton, Action<Color>> setterDictionary =
new Dictionary<RadioButton, Action<Color>>();
public Form1() {
InitializeComponent();
setterDictionary.Add(radioButton1, c => cpo.Color1 = c);
setterDictionary.Add(radioButton2, c => cpo.Color2 = c);
setterDictionary.Add(radioButton3, c => cpo.Color3 = c);
}
private void radioButton1_CheckedChanged(object sender, EventArgs e) {
colorSetter = setterDictionary[(RadioButton)sender];
}
private void button1_Click(object sender, EventArgs e) {
colorSetter(Color.Blue);
}
private void button2_Click(object sender, EventArgs e) {
colorSetter(Color.Black);
}
private void button3_Click(object sender, EventArgs e) {
colorSetter(Color.Red);
}
private void button4_Click(object sender, EventArgs e) {
Console.WriteLine(cpo.Color1 + " - " + cpo.Color2 + " - " + cpo.Color3);
}
}
public class ColorPropertyObject {
public Color Color1 { get; set; }
public Color Color2 { get; set; }
public Color Color3 { get; set; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Unknown iphone code
I am looking at a project which was provided me by my organization, for study.
The problem is that in this project I found some code which I never saw before.
Please tell me why the following code is written.
-(void)notifications
{
[[NSNotificationCenter defaultCenter] addObserver: self selector:
@selector(hideViews) name: @"Hide" object:nil];
}
This problem arose because this project has only some code for designing.
Sorry if this is a silly question...
A:
You should read up on how notifications work in Cocoa. Consult Apple's documentation for more information: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html
Basically, NSNotificationCenter is a class that broadcasts NSNotifications from one object to potentially many observing objects. One object can post a notification
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:self];
and other objects can listen for this notification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) object:theObjectThatPostedTheNotification];
Then, when the first object posts the notification, NSNotificationCenter will notify the other observing object, and notificationHandler: gets called.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the max number of devices (disks) that can be mounted?
And obviously I am meaning practically - is it dozens, or hundreds?
A:
On unix or Linux, individual device volumes are manifested through device files, traditionally held in the /dev directory. Depending on the device driver architecture or disk controller hardware you may be constrained in the number of devices actually supported, but this is a hardware or device driver constraint rather than an O/S specific constraint. The theoretical maximum is constrained by the number of bits available to the Major number, but will be 28, 216 or some other fairly large number. Note that a disk could be partitioned and therefore have multiple volumes on it. The space for device drivers is similarly large on Windows (note that Windows NT based systems support mount points so you aren't constrained by drive letters).
If you use hardware RAID or SAN based disks, a volume will be based on a group of disks presented by the controller, so the number of physical disks can be even larger.
In practice, the limitations of physical hardware is going to be a constraint before the number of available device handles becomes a problem. This will be the case on most O/S platforms.
To take a more practical example, a typical SAS disk array such as an HP MSA70 has (IIRC) four SAS ports and internal port multipliers connecting multiple SAS disks to each port. It will also allow a second array to be daisy chained off it. These arrays hold 25 disks each, so a group of 4 SAS ports can support up to 50 disks in two shelves.
A typical SAS RAID controller has 8-24 ports, so a single controller could take up to 4-12 arrays, or 100-300 disks. A large server such as an HP DL785 might be able to take several such controllers, so you could in theory put 1,000 or more disks on the machine.
However, this is probably not a very useful configuration. Dedicated SAN or NAS hardware or parallel file systems are much more likely to be appropriate for storage requirements needing 1,000+ physical disks. Database servers with 1,000+ direct attach disks are pretty rare outside of TPC-C benchmark configurations and the next few years will probably see SSDs taking over the market for storage on high-volume transaction processing applications.
Large SANs can scale to several thousand physical disks. A single fibre channel loop can support up to 254 disks and a high-end SAN controller can support many F/C loop interfaces. A logical volume manager can concatenate multiple physical volumes into a large file system, so a machine could potentially consolidate data from multiple SAN controllers into a single global volume.
The largest SAN I have seen documented had around 6,000 physical disks on it, but the limits are dependent on individual hardware.
Parallel file systems can scale outward by adding more nodes. With hardware like a Sun X4500 (thumper) one could scale outward by adding servers until you run out of network ports. The largest infiniband switches have several hundred ports, so a parallel file system based on Sun X4500s could support tens of thousands of physical disks.
However, any of thse large scale storage architectures will present RAID volumes spanning multiple physical disks to the host, so the number of logical units (devices) seen by the host will typically be much smaller. In almost all cases the physical limits of the hardware will restrict the number of disks before the name space on the host is exhausted.
These configurations can all be purchased off-the-shelf (for a price) from specialist vendors without having to go to any sort of exotic proprietary supercomputer architecture, so the answer to your question is:
Thousands or tens of thousands at the top end (without needing custom hardware). In fact, clustered file systems based on Sun X4500s or X4540s appear quite frequently as the storage components of Top 500 supercomputers.
Somewhere between 100 and perhaps 1,000-1,500 (at a guess - based on 4 28 port SAS RAID controllers with 2 shelves per 4 ports) on a Wintel or Lintel server. Oviously this will vary depending on the specific hardware.
External arrays notwithstanding, a desktop PC will be limited by the number of drives you can fit in the case. External desktop arrays might extend that limit to a few dozen, but this is niche market hardware.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flutter - Bypass Silent and Dot Not Disturb Mode on iOS and Android?
I have this app where it receives notifications from Firebase using firebase messaging. The notifications are very important and needed to be sound even if the phone is on silent or do not disturb mode. I searched through pub but cannot find any packages that will achieve it. I think I can use Flutter's android alarm manager to achieve this on Android but will I be able to do it on the iOS without writing native code?
A:
Short Answer: You can't.
Long Answer: You can, but only if the user allows the app to bypass Do Not Disturb, which they can only do if their Android version supports it. With regards to silent mode, you're out of luck. I guess you could try using an Alarm, but I wouldn't recommend misusing it like that. With regards to iOS, I don't know for sure, but I think it's even more locked down than Android, so you're probably out of luck there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the PivotItem header template?
By default, the PivotItem's header uses a large font.
I was hoping I could change the HeaderTemplate but no such property is available.
Is there a workaround?
A:
You can certainly edit the PivotItems' header. The answer lies in this thread.
| {
"pile_set_name": "StackExchange"
} |
Q:
Exponential equation with three summands
I had a simple looking math problem the other day:
Solve for $y(x) = 0$:
$$ 10^{2x} - 101 \cdot 10^x + 100 = 0$$
Since I have three summands, I cannot just put them to either side of the equation and apply $\log_{10}$ to it. And I cannot see how I could factor this to get it into a product to use $\log_{10}$.
Mathematica gave me $x = 2$ as a result which seems correct. How can I find the solution to this one? It is supposed to be an elementary problem for an applied math class.
A:
The key here is to note that $10^{2x} = (10^x)^2$. So we have $$10^{2x} - 101\cdot 10^x + 100 = (10^x)^2 - 101\cdot 10^x + 100.$$ Now letting $y = 10^x$, we are trying to solve $$y^2 - 101y + 100 = 0.$$ This has solutions $y = 1$ and $y = 100$ which correspond to $x = 0$ and $x = 2$.
| {
"pile_set_name": "StackExchange"
} |
Q:
append variables from a while loop into a command line option
I have a while loop, where A=1~3
mysql -e "select A from xxx;" while read A;
do
whatever
done
The mySQL command will return only numbers, each number in each line. So the while loop here will have A=1, A=2, A=3
I would like to append the integer number in the loop (here is A=1~3) into a command line to run outside the while loop. Any bash way to do this?
parallel --joblog test.log --jobs 2 -k sh ::: 1.sh 2.sh 3.sh
A:
You probably want something like this:
mysql -e "select A from xxx;" | while read A; do
whatever > standard_out 2>standard_error
echo "$A.sh"
done | xargs parallel --joblog test.log --jobs 2 -k sh :::
| {
"pile_set_name": "StackExchange"
} |
Q:
pass selected jqGrid rows to button with action
I have a grails view with this
<script type="text/javascript">
/* when the page has finished loading.. execute the follow */
$(document).ready(function () {
jQuery("#customer_list").jqGrid({
url:'jq_customer_list',
datatype: "json",
colNames:['customer','location','id'],
colModel:[
{name:'customer'},
{name:'location',stype:'select', searchoptions:{value:':All;USA:USA;Canada:Canada;Carribean:Carribean;USPacific:USPacific;'}},
{name:'id', hidden:true}
],
rowNum:2,
rowList:[1,2,3,4],
pager: jQuery('#customer_list_pager'),
viewrecords: true,
gridview: true,
multiselect: true
});
$("#customer_list").jqGrid('filterToolbar',{autosearch:true});
});
</script>
<g:link controller="MyController" action="downloadFile">Download</g:link><br>
</div>
<br/><br/>
Now I would like to pass into this action the data from the selected rows. However, I can't find this anywhere.
My method on my controller currently is blank. I would just like to print to the console all the IDs of the selected values.
Any suggestions? Thanks
A:
This should do it.
onSelectRow: function(rowid, iRow, iCol, e){
console.log('Id of Selected Row: ' + $(this).jqGrid('getCell', rowid, 'id'));
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Resolve the Inequality $a<b<c<d$?
We are given four discrete integers $a$, $b$, $c$, and #d# such that
$a < b < c < d$ how can we find values for which $(ac+bd) < (bc+ad)$ holds?
A:
Rewrite your last inequality as
$$ b(d-c) < a(d-c), $$
and then the problem should be clear.
Edit:
Subtracting the RHS gives
$$ (b-a)(d-c) < 0, $$
which is not possible since $b-a>0$ and $d-c>0$ by assumption.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is Java not printing all the words in the line (when words are added to an ArrayList)?
When printing out the user input as indvidual words within a line I get a printout of all the words in that line.
System.out.println(userInput.next());
However, when I add the indvidual words to an ArrayList I appear to be getting random words back:
al.add(userInput.next());
Could someone explain to me what's going on?
Thanks.
This is a full copy of the code:
import java.util.*;
public class Kwic {
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
ArrayList<String> al = new ArrayList<String>();
while(userInput.hasNext()){
al.add(userInput.next());
System.out.println(userInput.next());
}
}
}
A:
while(userInput.hasNext()){
al.add(userInput.next()); //Adding userInput call to ArrayList
System.out.println(userInput.next()); //Printing another userInput call
}
You are not printing the value stored in your ArrayList but actually another call to the userInput.next()
Revision
@Sheldon This is working for me.
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
ArrayList<String> al = new ArrayList<String>();
while(userInput.hasNext()){
al.add(userInput.next());
System.out.println(al); //LINE CHANGED FROM YOUR QUESTION
}
}
I tested your code with input
1 2 3 4 5 6 7 8 9 0
Then I pressed enter and Got:
2
4
6
8
0
the userInput.next() is alternating between the one added to the ArrayList and the one captured by your System.out.println
A:
Because next() consumes the next token from the scanner. Thus, when you have:
al.add(userInput.next());
System.out.println(userInput.next());
You are actually consuming two tokens from the scanner. The first is being added to the ArrayList and the other is being printed to System.out. A possible solution is to store the token in a local variable, and then add it to the array and print it:
while (userInput.hasNext()) {
String token = userInput.next();
al.add(token);
System.out.println(token);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Pushbutton Callback types in MATLAB GUIDE
While specifyfing the callback type for a pushbutton using Matlab's GUIDE, there are several options, two of which are described below:(words quoted from Matlab's documentation)
ButtonDownFcn:Executes when the user presses a mouse button while the pointer is on or within five pixels of a component or figure
Callback:Control action. Executes, for example, when a user clicks a push button or selects a menu item.
The description seems to suggest that they do the same thing.What is the difference between these two callback type?
A:
The ButtonDownFcn callback should fire when you press the mouse button down over the uicontrol, whether or not you release the mouse button, and whether or not your action eventually activates the uicontrol.
The Callback callback should fire when the uicontrol is activated. Activated means different things for different uicontols - for a pushbutton it means that the pushbutton is pushed, for a checkbox it means that the checkbox is selected or deselected, for an editbox it means that the text contents are modified.
Let's say you have a pushbutton with a Callback callback, but no ButtonDownFcn callback. If you hover over the pushbutton, click and hold the mouse, move away from the pushbutton, and then release, the Callback callback should not be fired, as the pushbutton was not activated. But if it had a ButtonDownFcn callback instead, that would have fired as soon as you clicked the mouse the first time, even though the pushbutton was not eventually activated.
If it had both, and you fully clicked and released on the pushbutton to activate it, the ButtonDownFcn should fire first, as it fires on the down-click, which is before the activation.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does the word "world" mean in John 3:16, in the light of John 17:9?
John 3:16
“For God so loved
the world, that He gave His only begotten Son, that whoever
believes in Him shall not perish, but have eternal life.
John 17:9
9 I pray for them. I am not praying for the world, but for those you
have given me, for they are yours.
It is commonly believed, among many, that the word world in John 3:16, indicates that God loves all men and offers them salvation. Yet in John 17:9 Jesus says "I am not praying for the world".
How are these two sayings of Jesus reconciled ?
A:
The word "world" (κοσμος) can have a number of meanings other than "every human being without exception," which is how it is often taken. A.W. Pink maintained that there are 7 uses for the word "world" and John Own offered (I believe) 16.
In John's gospel there are a few meanings present, ranging from "every human being without exception" to "all nations of the earth" to "non-elect humanity." In John 3:16, I believe John is referring to this first use, reflecting a real love of God for all that he has made, and to the universal call to repentance and faith in Christ. In John 17:9, however, he is speaking about the world which does not (and will not–John 17:20) believe in him for salvation, or "non-elect humanity."
The importance of this is that Jesus intercession and prayer are tied to his sacrifice. As the High Priest of our confession (Hebrews 3:1), his prayers for his own will be as effective as his sacrifice for them. Jesus prays for his own, and not the world, and his prayer is heard.
To directly answer the question, I'd just say that we reconcile these two seemingly contradictory statements in John by examining their contexts. Upon doing so, I think the answer that emerges is that in John 3, Jesus is speaking about God's love for all mankind which moved him to send his Son as a real offer of love and salvation to all who would receive him. In John 17, Jesus is not praying for the world, that is, those whom he knows will not receive him because they are not his; they were not given to him by the Father and in that sense do not belong to him (cf. John 10).
| {
"pile_set_name": "StackExchange"
} |
Q:
Ignore all fields and properties by default
I am using Newtonsoft.Json to serialize my objects. I want that by default no field or property gets serialized, only if I decorate it with a [JsonProperty(PropertyName = "name")] Attribute. I couldn't find anything in the newtonsoft docs.
A:
You can add [JsonObject(MemberSerialization.OptIn)] attribute to your class, everything will be ignored unless you explicitly Opt-In by using a [JsonProperty] attribute.
[JsonObject(MemberSerialization.OptIn)]
public class MyClass
{
[JsonProperty]
public string NotIgnored { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
}
More info here: Newtonsoft Documentation
| {
"pile_set_name": "StackExchange"
} |
Q:
Sub drawable Folders in minSDK v3 Project?
When you create a project with min SDK version = 3 , you will not see the three auto-generated folders drawable-ldpi, drawable-mdpi, and drawable-hdpi.
Is it possible to add them ? I know that I can add the folders I need in the project but I want to know if the Android System will consider the resources as alternative or will take the default folder (drawable) and scale what's inside it?
Thanks
A:
After I did some research, and as stated here, you can not have such folders when you targeting 1.5.
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
Input and dropdown have different values
I have an bootstrap datetimepicker. I set the defaults but input and dropdown have different values.
You can see printscreen from the link : http://prntscr.com/i172wq
This is my code:
HTML
<div class="form-group ">
@Html.LabelFor(model => model.dTarih, new { @class = "col-md-3 control-label" })
<div class="col-md-4">
<div class="input-group date formDateTime" id="formDateTime">
@Html.TextBoxFor(model => model.dTarih, new { @Class = "form-control input-datetime", id = "talept", @readonly = "", size = "16" })
@*<input size="16" readonly="" class="form-control" type="text">*@
<span class="input-group-btn">
<button class="btn default date-set" type="button"><i class="fa fa-calendar"></i></button>
</span>
</div>
</div>
JS
$('.formDateTime').datetimepicker({
isRTL: false,
format: 'dd.mm.yyyy hh:ii',
autoclose: true,
language: 'tr',
defaultDate: new Date()
});
How can I set correct values both of them?
A:
To begin with, formDateTime is associated to a DIV while it should be associated to your INPUT. Secondly, to set a default value you can use:
HTML:
:
<input class="form-control" type="date" id="formDateTime">
:
JS:
$("#formDateTime").val = new Date() ;
Hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I kill the Spike Traps?
I know that in this game, one of the more common traps is the spike trap, which triggers a little time after your character walks on top of it (unless they have the P.A.D. trait).
So, my question is, is it possible to destroy them, temporarily disable them (other than P.A.D.), or are they just invulnerable objects? I have heard that Retribution Runes can damage enemies upon taking damage from them. But, does this property also apply to the spike traps as well?
Thanks for the assistance folks!
A:
Yes, spike traps, along with every other thing in the game that deals damage, can be destroyed with Retribution Runes. Unfortunately, you can only achieve that by allowing them to damage you enough that the returned damage is enough to destroy them, which I think depends on what area of the castle you are in.
| {
"pile_set_name": "StackExchange"
} |
Q:
Binary Tree Induction Example
I have been given this induction problem as practice, and I haven't worked with induction in a few months so I'm lost on how to approach the problem. Here's the example:
"Prove by induction: In a non-empty binary tree, the number of nodes is equal to the number of links between the nodes plus one".
I have a basic idea of how to start it, like how the base case is 1 node with 0 links. However, I'm not sure how to represent "links" in my solution. Any help is greatly appreciated.
A:
I'd start by inductively defining a nonempty binary tree.
Inductive nonemptyTree :=
| Endpoint
| Single (l : nonemptyTree)
| Double (l : nonemptyTree) (r : nonemptyTree).
This looks a bit more complicated than a normal binary tree, but clearly distinguishing the different formations and removing the typical "Nil" constructor help with the proof.
From there, you'll want to define what "links" and "nodes" are and how to calculate them given a tree. This is pretty easy given the nonemptyTree definition.
Fixpoint links (t : nonemptyTree) : nat :=
match t with
| Endpoint => 0
| Single l => 1 + links l
| Double l r => 2 + links l + links r
end.
Fixpoint nodes (t : nonemptyTree ) : nat :=
match t with
| Endpoint => 1
| Single l => 1 + nodes l
| Double l r => 1 + nodes l + nodes r
end.
At that point, we just need to prove that for all trees t, nodes t = links t + 1. There are only three cases to consider, and you've already gotten the first one (base case).
| {
"pile_set_name": "StackExchange"
} |
Q:
read json from file upload php
I have a php page where it should be able to upload .json files and my PHP code needs to read the json from the file that is imported.
I tried this:
HTML
<form method="POST">
<input type="file" name="importfile" id="inportfile" onchange="this.form.submit()" accept="application/json" style="display:none"/>
<button id="import">Import</button>
<script>
$('#import').click(function(){ $('#inportfile').trigger('click'); });
</script>
</form>
PHP
if(isset($_POST['importfile'])){
// read json file
$data = file_get_contents($_FILES['importfile']['tmp_name']);
$_SESSION['data'] = $data;
}
But this doesn't work.
Anyone know how to do this in a proper way that works?
A:
You need yo add a new tag in the form enctype :
<form enctype="multipart/form-data">
| {
"pile_set_name": "StackExchange"
} |
Q:
F# function type mismatch
What's wrong with my test function?
let divisorOf(d, n) = n % d = 0
let notDivisible(d, n) = not (divisorOf(d, n))
let rec test(a, b, c) = function
| (a, b, _) when (a > b) -> true
| (a, b, c) -> notDivisible(a, c) && test(a + 1, b, c)
I'm getting a compiler error that the expression on line 7 has function type, not bool.
(7,40): error FS0001: This expression was expected to have type
bool
but here has type
'a * 'a * 'b -> bool
A:
When you use the keyword function you are creating an implict lambda. It is inferred that the input to this is a int*int*int. To fix this just get change
let rec test(a,b,c) =
to
let rec test =
If you want to be explicit with the arguments you could also write it as
let rec test(d, e, f) = match (d,e,f) with //change letters to avoid variable hiding
| (a, b, _) when (a > b) -> true
| (a, b, c) -> notDivisible(a, c) && test(a + 1, b, c)
| {
"pile_set_name": "StackExchange"
} |
Q:
Reconnecting web socket using React Hooks
I want to establish a web socket connection with the server. Reconnenct after 5 seconds if the connection closes. I am using React Hooks and so far achieved this
import React, { useRef, useState, useEffect } from 'react';`
import './App.css';
function App() {
const wsClient = useRef(null);
const [wsState, setWsState] = useState(true)
useEffect(() => {
wsClient.current = new WebSocket(url);
console.log("Trying to open ws");
setWsState(true)
wsClient.current.onopen = () => {
console.log('ws opened');
wsClient.current.send('{"type" : "hello"}')
};
wsClient.current.onclose = (event) => {
// Parse event code and log
setTimeout(() => {setWsState(false)}, 5000)
console.log('ws closed');
}
wsClient.current.onmessage = ((event) => {
// DO YOUR JOB
})
return () => {
console.log('ws closed');
wsClient.current.close();
}
}, [wsState]);
return (
<div className="App">
<Header />
<MainBody />
</div>
);
}
This is creating exponentially increasing number of retries when it is unable to connect with server, if I remove setTimeout and use simple setState it is working normally.
I am unable to understand the issue and also suggest what is the best practice to achieve my goal.
A:
I'm not convinced that an effect is the best place for this. If it's application-level, it may be simpler to implement it in its own module, and bring that in, where needed.
Nevertheless, to get this to work, you should consider that you're managing two separate lifecycles: the component lifecycle, and the websocket lifecycle. To make it work as you want, you have to ensure that each state change in one aligns with a state change in the other.
First, keep in mind that your effect runs every time the dependencies in the array change. So, in your example, your effect runs every time you set wsState.
The other thing to keep in mind is that your cleanup function is called every time wsState changes, which you're doing twice in your effect (setting it to true on open, and false on close). This means that when you create a new socket, and it fails to connect, the close event fires, and it queues up a state change.
Each time it attempts to connect, it sets wsState to true (which queues a re-run of your effect), tries and fails to connect, finally setting another timeout, which updates the state to false. But, not before the effect runs again, trying to set the state to true, etc.
To fix this, start with the effect lifecycle. When should your effect run? When should it be cleaned up? A few thoughts:
The effect should run once during the first render, but not during subsequent renders
The effect should be cleaned up when the WebSocket disconnects
The effect should be re-run after a timeout, triggering a reconnect
What does this mean for the component? You don't want to include the WS state as a dependency. But, you do need state to trigger it to re-run after the timeout.
Here's what this looks like:
import React, { useRef, useState, useEffect } from 'react';
const URL = 'ws://localhost:8888';
export default function App() {
const clientRef = useRef(null);
const [waitingToReconnect, setWaitingToReconnect] = useState(null);
const [messages, setMessages] = useState([]);
const [isOpen, setIsOpen] = useState(false);
function addMessage(message) {
setMessages([...messages, message]);
}
useEffect(() => {
if (waitingToReconnect) {
return;
}
// Only set up the websocket once
if (!clientRef.current) {
const client = new WebSocket(URL);
clientRef.current = client;
window.client = client;
client.onerror = (e) => console.error(e);
client.onopen = () => {
setIsOpen(true);
console.log('ws opened');
client.send('ping');
};
client.onclose = () => {
if (clientRef.current) {
// Connection failed
console.log('ws closed by server');
} else {
// Cleanup initiated from app side, can return here, to not attempt a reconnect
console.log('ws closed by app component unmount');
return;
}
if (waitingToReconnect) {
return;
};
// Parse event code and log
setIsOpen(false);
console.log('ws closed');
// Setting this will trigger a re-run of the effect,
// cleaning up the current websocket, but not setting
// up a new one right away
setWaitingToReconnect(true);
// This will trigger another re-run, and because it is false,
// the socket will be set up again
setTimeout(() => setWaitingToReconnect(null), 5000);
};
client.onmessage = message => {
console.log('received message', message);
addMessage(`received '${message.data}'`);
};
return () => {
console.log('Cleanup');
// Dereference, so it will set up next time
clientRef.current = null;
client.close();
}
}
}, [waitingToReconnect]);
return (
<div>
<h1>Websocket {isOpen ? 'Connected' : 'Disconnected'}</h1>
{waitingToReconnect && <p>Reconnecting momentarily...</p>}
{messages.map(m => <p>{JSON.stringify(m, null, 2)}</p>)}
</div>
);
}
In this example, the connection state is tracked, but not in the useEffect dependencies. waitingForReconnect is, though. And it's set when the connection is closed, and unset a time later, to trigger a reconnection attempt.
The cleanup triggers a close, as well, so we need to differentiate in the onClose, which we do by seeing if the client has been dereferenced.
As you can see, this approach is rather complex, and it ties the WS lifecycle to the component lifecycle (which is technically ok, if you are doing it at the app level).
However, one major caveat is that it's really easy to run into issues with stale closures. For example, the addMessage has access to the local variable messages, but since addMessage is not passed in as a dependency, you can't call it twice per run of the effect, or it will overwrite the last message. (It's not overwriting, per se; it's actually just overwriting the state with the old, "stale" value of messages, concatenated with the new one. Call it ten times and you'll only see the last value.)
So, you could add addMessage to the dependencies, but then you'd be disconnecting and reconnecting the websocket every render. You could get rid of addMessages, and just move that logic into the effect, but then it would re-run every time you update the messages array (less frequently than on every render, but still too often).
So, coming full circle, I'd recommend setting up your client outside of the app lifecycle. You can use custom hooks to handle incoming messages, or just handle them directly in effects.
Here's an example of that:
import React, { useRef, useState, useEffect } from 'react';
const URL = 'ws://localhost:8888';
function reconnectingSocket(url) {
let client;
let isConnected = false;
let reconnectOnClose = true;
let messageListeners = [];
let stateChangeListeners = [];
function on(fn) {
messageListeners.push(fn);
}
function off(fn) {
messageListeners = messageListeners.filter(l => l !== fn);
}
function onStateChange(fn) {
stateChangeListeners.push(fn);
return () => {
stateChangeListeners = stateChangeListeners.filter(l => l !== fn);
};
}
function start() {
client = new WebSocket(URL);
client.onopen = () => {
isConnected = true;
stateChangeListeners.forEach(fn => fn(true));
}
const close = client.close;
// Close without reconnecting;
client.close = () => {
reconnectOnClose = false;
close.call(client);
}
client.onmessage = (event) => {
messageListeners.forEach(fn => fn(event.data));
}
client.onerror = (e) => console.error(e);
client.onclose = () => {
isConnected = false;
stateChangeListeners.forEach(fn => fn(false));
if (!reconnectOnClose) {
console.log('ws closed by app');
return;
}
console.log('ws closed by server');
setTimeout(start, 3000);
}
}
start();
return {
on,
off,
onStateChange,
close: () => client.close(),
getClient: () => client,
isConnected: () => isConnected,
};
}
const client = reconnectingSocket(URL);
function useMessages() {
const [messages, setMessages] = useState([]);
useEffect(() => {
function handleMessage(message) {
setMessages([...messages, message]);
}
client.on(handleMessage);
return () => client.off(handleMessage);
}, [messages, setMessages]);
return messages;
}
export default function App() {
const [message, setMessage] = useState('');
const messages = useMessages();
const [isConnected, setIsConnected] = useState(client.isConnected());
useEffect(() => {
return client.onStateChange(setIsConnected);
}, [setIsConnected]);
useEffect(() => {
if (isConnected) {
client.getClient().send('hi');
}
}, [isConnected]);
function sendMessage(e) {
e.preventDefault();
client.getClient().send(message);
setMessage('');
}
return (
<div>
<h1>Websocket {isConnected ? 'Connected' : 'Disconnected'}</h1>
<form onSubmit={sendMessage}>
<input value={message} onChange={e => setMessage(e.target.value)} />
<button type="submit">Send</button>
</form>
{messages.map(m => <p>{JSON.stringify(m, null, 2)}</p>)}
</div>
);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Inserting character to given places in a string for Python requests
I am trying to use the requests.Session.get method in Python which can take a headers dictionary as an argument. When I copy headers from "Inspect Element" in Mozilla Firefox they look like this:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host: cdn.sstatic.net
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0
But session.get needs them as a dictionary:
{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5)
AppleWebKit 537.36 (KHTML, like Gecko) Chrome",
"Accept":"text/html,application/xhtml+xml,application/xml;
q=0.9,image/webp,*/*;q=0.8"}
Is there a method in Python that takes a string and inserts characters into it at given places (in this example inserting an " to the two sides of every colon, for every new-line character inserting ", to it's left and " to it's right, and a \ character for line breaking before every new-line character) or just automatically converts strings of this form into a dictionary?
A:
headers_as_text = """Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Host: cdn.sstatic.net
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0"""
def get_key_value(text):
colon_position = text.index(":")
if not colon_position:
return text.strip(), ""
return (
text[:colon_position].strip(),
text[colon_position+1:].strip()
)
text_lines = filter(lambda x: x, headers_as_text.split("\n"))
dict_values = dict(map(get_key_value, text_lines))
The final value is a dictionary:
dict_values = {
'Host': 'cdn.sstatic.net',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:59.0) Gecko/20100101 Firefox/59.0',
'Accept-Language': 'en-US,en;q=0.5',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8'
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to reference function more directly?
List directory analyse structure as below:
tree analyse
analyse
├── __init__.py
└── vix.py
The __init__.py is blank,vix.py contains a function draw_vix.
import analyse
analyse.vix.draw_vix()
draw_vix is referenced with analyse.vix.,i want to reference it with vix instead of analyse.vix,that is to say ,to add vix in namespace after import analyse.
Edit __init__.py:
import analyse.vix as vix
from analyse import vix
Have a check:
import analyse
vix.draw_vix()
An error message:
NameError: name 'vix' is not defined
@hl037_,if i add from .vix import vix in __init__.py,
import analyse
vix.draw_vix()
It pose other issue: ImportError: cannot import name 'vix'.
What i want is to write something in __init__.py ,or to write someting in vix.py ,to make vix.draw_vix() take effect.
How to fix it?
A:
You just can't like this.
import analyse
will only make analyse in your global namespace.
At best, you can do :
from analyse import vix
to put vix into the globals.
(Or use star notation)
Bonus : if you don't want to need analyse installed (even if with venv, it's recommended to actually install your app / module inside a venv), to import vix inside __init__.py, you can also do a relative import inside :
from . import vix
https://docs.python.org/3/reference/import.html
[EDIT] Some examples :
File system :
analyse
├─ __init__.py
├─ vix.py
├─ viz.py # another submodule to demonstrate some other points
└─ vit.py # yet another submodule to demonstrate some other points
analyse/__init__.py contains :
import .vit as vit
# from . import vit # works too
vix = 42
viy = 43
analyse/vix.py contains :
def draw_vix():
print('Hello from drax_vix')
analyse/viz.py contains :
def draw_viz():
print('Hello from drax_viz')
analyse/vit.py contains :
def draw_vit():
print('Hello from drax_vit')
If your package is installed (e.g. you created a setup.py and did pip install analyse), or a child of a directory listed in PYTHONPATH env variable, in any script (or the python interpreter) outside the package, these things happen :
1) full import with alias :
import analyse.vix as vix
vix.draw_vix()
# works, and print print('Hello from drax_vix')
analyse
# Error : analyse not defined since you import only symbols from analyse.vix, not the modules themselves
analyse.vix
# Same as previous one
2) Full import
import analyse.vix
analyse.vix.draw_vix()
#Works because python guarantees analyse.vix to be a valid expression
analyse
# analyse module
vix.draw_vix()
# Error : vix undefined. import analyse.vix guarantee analyse.vix to be a valid module, but does not add submodule to global namespace
analyse.vix
# is a module, analyse.vix module has been imported too and set as an attribute of analyse.
analyse.viz
# Error : analyse has no attr viz since viz is a non-imported submodule.
analyse.vit.draw_vit
# Works because analyse is indirectly imported with import analyse.vix, and vit is imported as vit inside analyse/__init__.py and thus an attribute of the module.
3) Import only analyse
import analyse
analyse.vix
# 42 because analyse.vix module is not imported, thus you saw the variable defined vix inside analyse
vix.draw_vix()
# Error : vix undefined, obviously, you never defined it nor imported it
vit.draw_vit()
# Works because vit is imported in __init__.py and set as an attribute of analyse.
4) From analyse import vix, viy, viz, vit
from analyse import vix, viz, vit
analyse.vix
# Error : analyse not define since you imported only symbols
vix
# 42 Because you didn't import analyse.vix and there is a variable vix defined in analyse/__init__.py
viy
# 43
viz
# module viz : viz is not declared as an attribute of analyse, but it falls back to the existing analyse.viz module
vit
# module vit : The one imported inside __init__.py (that is the same as analyse.vit)
5) from analyse import viy
from analyse import viy
# Error : analyse/viy.py does not exist
A:
add vix in namespace after import analyse
By default the top-level scope is not visible in modules. globals function in modules returns module-level scope, not the scope of the importing module (see docs). Therefore some tricks are required to put vix to external scope.
Trick one.
import statement in Python is actually a function call, and the code from __init__.py is executed whithin some stack frame. The trick is to find the stack frame that corresponds to the importing module and pollute it's scope. While this is possible, it is a BAD, BAD practice. It contradics the paradigm of Python, where simple things must be simple. If you need vix in the top-level scope, use import analyse.vix as vix. Scope pollution might result in names conflict and very subtle bugs.
Trick two.
Code from __init__.py is executed only once, during the first load of the package. In all other import analyse statements python interpreter uses the module object cached in sys.modules. The only way that I found is to intercept the calls to the __import__ builtin and add scope polluting hooks.
I strongly recommend avoiding this 'magic'. Nevertheless, if you want to shoot in the foot, here it is.
Place the following code in analyse/__init__.py:
from . import vix # create module "vix" in the current scope
import inspect as _inspect
# Inject `vix` at the first import
_frame = _inspect.currentframe().f_back
while _frame is not None:
# skip Pyhton module loader
if "importlib._bootstrap" in _frame.f_code.co_filename:
_frame = _frame.f_back
continue
#this frame corresponds to the scope, where `import analyse` is specified
_frame.f_globals["vix"] = vix # bind the name 'vix' with the module 'vix' from the current scope
print("DEBUG: injected vix to ", _frame)
break
# remove _frame from the scope
del[_frame]
# overload __import__ function to inject `vix` on every succeeding import of `analyse`
import builtins as _builtins
# save builtin that `import` calls
_builtin_import = _builtins.__import__
def _never_overload_import(name, globals=None, locals=None, fromlist=(), level=0):
"This function injects `vix` in every scope that imports `analyse` module"
global _builtin_import
global vix
result = _builtin_import(name, globals, locals, fromlist, level)
if name == "analyse" and globals is not None and not "vix" in globals:
globals["vix"] = vix
print("DEBUG: injected vix to ", _inspect.currentframe().f_back)
return result
_builtins.__import__ = _never_overload_import
This is how I tested:
file secondary.py just loads the target module.
import analyse
# demonstrate that first import created `vix` at this scope
vix.draw_vix("called from secondary as `vix.draw_vix`")
file test.py loads both secondary.py and analyse
print("***Loading secondary***")
import secondary
print("***Secondary loaded***")
print("***Loading analyse***")
import analyse
print("***Analyse loaded***")
analyse.vix.draw_vix("called as `analyse.vix.draw_vix`")
vix.draw_vix("called as `vix.draw_vix`")
The output:
***Loading secondary***
DEBUG: injected vix to <frame at 0x00909AE8, file 'secondary.py', line 1, code <module>>
draw vix, called from secondary as `vix.draw_vix`
***Secondary loaded***
***Loading analyse***
DEBUG: injected vix to <frame at 0x00911C30, file 'test.py', line 6, code <module>>
***Analyse loaded***
draw vix, called as `analyse.vix.draw_vix`
draw vix, called as `vix.draw_vix`
CHANGELOG
Added overloading __import__ function. The original answer just inserted vix object to the globals of the importing scope, but this is not enough: code in __init__.py is executed only once, during the first load of the package. When the package is imported in another file, it will see no vix module since the injection code is not executed.
| {
"pile_set_name": "StackExchange"
} |
Q:
XML column list specific value
I have an xml column that looks like this:
<document>
<item>
<key>
<string>Michael Burry</string>
</key>
<value>
<string>CDO</string>
</value>
</item>
<item>
<key>
<string>Adam Smith</string>
</key>
<value>
<string>£20</string>
</value>
</item>
<item>
<key>
<string>World Cup 2018</string>
</key>
<value>
<string>football</string>
</value>
</item>......
Instead of listing the entire contents of the column, I want to instead list only the value of <string>football</string> when the first value is <string>World Cup 2018</string>.
Using value('(/document/item/key/string)[7]', 'nvarchar(max)') is not suitable as "World Cup 2018" can appear anywhere.
A:
If you just want a single value then you can just use the value method of the XML datatype with a little bit of XPath that translates to:
Get me the first value of ...key/string which has a sibling element of
...value/string under the same item element with the value "football"
Something like this:
DECLARE @yourTable TABLE ( rowId INT IDENTITY PRIMARY KEY, yourXML XML )
INSERT INTO @yourTable ( yourXML )
SELECT
'<document>
<item>
<key>
<string>Michael Burry</string>
</key>
<value>
<string>CDO</string>
</value>
</item>
<item>
<key>
<string>Adam Smith</string>
</key>
<value>
<string>£20</string>
</value>
</item>
<item>
<key>
<string>World Cup 2018</string>
</key>
<value>
<string>football</string>
</value>
</item>......
</document>'
SELECT *, yt.yourXML.value('(document/item[key/string[.="World Cup 2018"]]/value/string/text())[1]', 'VARCHAR(50)') result
FROM @yourTable yt
| {
"pile_set_name": "StackExchange"
} |
Q:
All tkinter functions run when program starts
I am having a very weird problem that I've never had before when using tkinter. Anywhere that I set a command for a widget such as a button or a menu item, the command runs when the application starts up. Basically the command doesn't wait until the widget is clicked to run. In my code, I know that I did not pack the button, this was to show that widget don't even have to be drawn onto the screen for this problem to occur. Does anybody know what could be causing it? Thanks!
from tkinter import *
class menuItems(object):
def __init__(self):
menubar = Menu(app)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New...", command=self.new())
filemenu.add_command(label="Open...", command=self.open())
filemenu.add_command(label="Save", command=self.save())
filemenu.add_separator()
filemenu.add_command(label="Exit", command=app.quit)
menubar.add_cascade(label="File", menu=filemenu)
app.config(menu=menubar)
def new(self):
pass
def open(self):
pass
def save(self):
print("You have saved the file")
def this_should_not_run():
print("Yay! I didn't run!")
def this_will_run_even_though_it_should_not():
print("You can't stop me!")
def init():
global app, menu
app = Tk()
app.title("Words with Python")
app.geometry("800x500+50+50")
menu = menuItems()
frame = Frame(app)
scrollbar = Scrollbar(frame, orient=VERTICAL)
textbox = Text(frame, yscrollcommand=scrollbar.set)
scrollbar.config(command=textbox.yview)
scrollbar.pack(side=RIGHT, fill=Y)
textbox.pack(side=LEFT, fill=BOTH, expand=1)
frame.pack(fill=BOTH, expand=1)
button = Button(app, text="Nothing", command=this_will_run_even_though_it_should_not())
return
init()
app.mainloop()
A:
Remove the ()s in your command definitions. Right now, you are calling the function and binding the return values to command parameter whereas you need to bind the functions itself so that later on they could be called.
So a line like this:
filemenu.add_command(label="New...", command=self.new())
should actually be this:
filemenu.add_command(label="New...", command=self.new)
(You actually do this in one place correctly: filemenu.add_command(label="Exit", command=app.quit))
A:
filemenu.add_command(label="Open...", command=self.open())
filemenu.add_command(label="New...", command=self.new())
filemenu.add_command(label="Open...", command=self.open())
filemenu.add_command(label="Save", command=self.save())
In these lines, you have to pass the reference to the functions. You are actually calling the functions.
filemenu.add_command(label="Open...", command=self.open)
filemenu.add_command(label="New...", command=self.new)
filemenu.add_command(label="Open...", command=self.open)
filemenu.add_command(label="Save", command=self.save)
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to update a DoubleAnimation.FromProperty without restarting the entire animation?
I'm not hugely familiar with a lot of WPF yet, so if this query betrays some clear misunderstandings I'd appreciate them being pointed out.
What I'm trying to do (for good or ill) is synchronise a DoubleAnimation.FromProperty with the actual width of a StackPanel containing/running the animation.
I originally tried doing this with data binding, e.g.
BindingOperations.SetBinding(anim,
DoubleAnimation.FromProperty,
new Binding {Source = panel, Path = new PropertyPath(ActualWidthProperty)});
But this doesn't seem to work. Although I can bind a text box to the From property and see that it's changing, the animation continues to run from the initial value. Is this anything to do with story board freezing? (which I know nothing about but have just heard of)
Then I thought why not stop and restart the story board (turn it off and on again!), changing the FromProperty in the meantime, by handling the StackPanel.SizeChanged event. Something like this :
void panel_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (myStoryBoard != null && myStoryBoard.GetCurrentState(panel) == ClockState.Active)
{
myStoryBoard.Stop(panel);
foreach(var child in myStoryBoard.Children)
{
var anim = child as DoubleAnimation;
if (anim == null) continue;
anim.From = panel.ActualWidth;
}
myStoryBoard.Begin(panel, true);
}
}
This works, but, of course, it starts the animation from scratch each time the panel is resized. What I'd prefer is to be able to resume the animation from the point it was interrupted but with a new FromProperty. Is this even possible?
A:
It is a lot easier than you think. The cool thing about Animations in WPF and Silverlight is that they can be relative to the current situation. The only thing you need to do to create a relative animation is creating for example the DoubleAnimation with To filled in but do NOT fill in the From.
Example below is to animate the opacity of a stackpanel from the current value to 1:
<DoubleAnimation Duration="0:0: To="1"
Storyboard.TargetName="LayoutRoot"
Storyboard.TargetProperty="StackPanel.Opacity" />
EDIT1:
Make the animation loop back to its original value without using the from and loop forever
<Storyboard AutoReverse="True" RepeatBehavior="Forever">
<DoubleAnimation Duration="0:0:2"
To="1"
Storyboard.TargetName="LayoutRoot"
Storyboard.TargetProperty="StackPanel.Opacity"
/>
</Storyboard>
| {
"pile_set_name": "StackExchange"
} |
Q:
OpenCV C++ Multithreading
I have this opencv image processing function being called 4x on 4 diferent Mat objects.
void processBinary(Mat& binaryMat) {
//image processing
}
I want to multi-thread it so that all 4 method calls complete at the same time, but have the main thread wait until each thread is done.
Ex:
int main() {
Mat m1, m2, m3, m4;
//perform each of these methods simultaneously, but have main thread wait for all processBinary() calls to finish
processBinary(m1);
processBinary(m2);
processBinary(m3);
processsBinary(m4);
}
What I hope to accomplish is to be able to call processBinary() as many times as I need and have the same efficiency as having the method called only once. I have looked up multithreading, but am a little confused on calling threads and then joining / detaching them. I believe I need to instantiate each thread and then call join() on each thread so that the main thread waits for each to execute, but there doesn't seem to be a significant increase in execution time. Can anyone explain how I should go about multi-threading my program? Thanks!
EDIT: What I have tried:
//this does not significantly increase execution time. However, calling processBinary() only once does.4
thread p1(&Detector::processBinary, *this, std::ref(m1));
thread p2(&Detector::processBinary, *this, std::ref(m2));
thread p3(&Detector::processBinary, *this, std::ref(m3));
thread p4(&Detector::processBinary, *this, std::ref(m4));
p1.join();
p2.join();
p3.join();
p4.join();
A:
The slick way to achieve this is not to do the thread housekeeping yourself but use a library that provides micro-parallelization.
OpenCV itself uses Intel Thread Building Blocks (TBB) for exactly this task -- running loops in parallel.
In your case, your loop has just four iterations. With C++11, you can write it down very easily using a lambda expression. In your example:
std::vector<cv::Mat> input = { m1, m2, m3, m4; }
tbb::parallel_for(size_t(0), input.size(), size_t(1), [=](size_t i) {
processBinary(input[i]);
});
For this example I took code from here.
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript - API google marker
I have a very big problem, I've tried to include this javascript on my web-site... but... It doesn't work... and... I don't know why, somebody can help me ??
var map;
var places = [
['ferrara1', 44.831283, 11.617459, 'Ha funzionato ?'],
['ferrara2', 44.833283, 11.617459, 'se vedo tutto siiii !'],
['ferrara3', 44.886283, 11.617459, 'uahahahah'],
['ferrara4', 44.832283, 11.617459, 'è vivo'],
];
function initialize() {
var mapOptions = {
zoom: 15
};
map = new google.maps.Map(document.getElementById('maps'),mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Tu sei Qui.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
point(map,places);
};
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Errore: Geolocalizzazione Fallita.';
} else {
var content = 'Errore: Questo browser non supporta la Geolocalizzazione.';
}
var options = {
map: map,
position: new google.maps.LatLng(44.831283, 11.617459),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
};
function point(map, places){
for (var i = 0; i < places.length; i++ ) {
var azienda = places[i]
var markerLatlng[i] = new google.maps.LatLng(azienda[1], azienda[2]);
var infowindow = new google.maps.InfoWindow({
content: azienda[3]
});
var marker[i] = new google.maps.Marker({
position: markerLatlng[i],
map: map,
title: azienda[0]
});
google.maps.event.addListener(marker[i], 'click', function () {
infowindow.open(map,marker[i])
});
}
};
google.maps.event.addDomListener(window, 'load', initialize);
Edit:
I try to include this javascript on one html page on my web-site to show google maps with some markers (I have commented out one), but it doesn't seem to work and I don't understand why.
The issue seems to be with my function point because if i remove it, the rest of the code works and the google map loads fine (but I don't get the marker I want).
I'm not sure how to proceed debugging the code in javascript with my browser.
A:
You have two instances of improperly declared arrays.
1. var markerLatlng[i] = ...
2. var marker[i] = ...
function point(map, places){
for (var i = 0; i < places.length; i++ ) {
var azienda = places[i];
var markerLatlng[i] = new google.maps.LatLng(azienda[1], azienda[2]);
var infowindow = new google.maps.InfoWindow({
content: azienda[3]
});
var marker[i] = new google.maps.Marker({
position: markerLatlng[i],
map: map,
title: azienda[0]
});
google.maps.event.addListener(marker[i], 'click', function () {
infowindow.open(map,marker[i]);
});
}
};
Either declare those arrays before assigning values or in this case you may not need arrays at all.
Declare first:
var markerLatLng = [], markers = [];
function point(map, places){
for (var i = 0; i < places.length; i++ ) {
var azienda = places[i];
markerLatlng[i] = new google.maps.LatLng(azienda[1], azienda[2]);
var infowindow = new google.maps.InfoWindow({
content: azienda[3]
});
marker[i] = new google.maps.Marker({
position: markerLatlng[i],
map: map,
title: azienda[0]
});
google.maps.event.addListener(marker[i], 'click', function () {
infowindow.open(map,marker[i]);
});
}
};
No arrays:
function point(map, places){
for (var i = 0; i < places.length; i++ ) {
var azienda = places[i];
var markerLatlng = new google.maps.LatLng(azienda[1], azienda[2]);
var infowindow = new google.maps.InfoWindow({
content: azienda[3]
});
var marker = new google.maps.Marker({
position: markerLatlng,
map: map,
title: azienda[0]
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map,marker);
});
}
};
Edit: adding some more semi-colons for consistency :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Нужно ли ставить тире перед вторым «как»?
"Урнакоша" иногда переводится как "прядь волос меж бровями", но чаще (—) как "третий глаз".
Нужно ли ставить тире по правилам или здесь оно может быть исключительно как авторский знак?
A:
Тире ставится в неполном предложении, являющемся частью сложного предложения, когда пропущенный член (обычно сказуемое) восстанавливается из предшествующей части фразы и в месте пропуска делается пауза, например:
Они стояли друг против друга. Олег — растерянный и смущенный, Нина — с выражением вызова на лице (Фадеев); Его деревянные львы были похожи на толстых собак, а нереиды — на торговок рыбой (К. Паустовский).
При отсутствии паузы тире не ставится, например: Егорушка долго оглядывал его, а он Егорушку (Чехов).
Тире в неполном предложении
"Урнакоша" иногда переводится как "прядь волос меж бровями", но чаще [переводится] — как "третий глаз".
Ставить тире или не ставить — это, конечно, дело автора. Я бы поставила, потому что в предложении "куча" кавычек и третий глаз на этом фоне (без тире) совершенно теряется. Я бы его выделила.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to insert data into a String array in postgres stored procedure
I have a pseudo stored procedure as given below:
CREATE OR REPLACE FUNCTION get_data()
RETURNS void AS $$
DECLARE
rec_new RECORD;
querystring TEXT[];
cursor_file CURSOR FOR
select * from tableA;
BEGIN
--open the file cursor
OPEN cursor_file;
LOOP
FETCH cursor_file into rec_new;
EXIT WHEN NOT FOUND;
querystring='{insert into tableB(fileid) values %}',rec_new.fileid;
END LOOP;
CLOSE cursor_file;
END; $$
LANGUAGE plpgsql;
I want to create multiple insert queries with dynamic fileId's being iterated over a loop and put them in a string array ('querstring') seperated by a comma delimiter. The code above is not giving me the exact result. What is the correct way to achieve this?
The expected output is like:
{insert into tableB(fileid) values ('fileA'),
insert into tableB(fileid) values ('fileB'),
insert into tableB(fileid) values ('fileC')}
Then this querystring array needs to be executed also.
A:
You are probably looking for the “array append” operator ||.
But that is an overly complicated way to solve the problem. You can do it simpler and more efficiently with something like
SELECT array_agg(
format(
'insert into tableB(fileid) values (%L)',
fileid
)
) INTO querystring
FROM tablea;
| {
"pile_set_name": "StackExchange"
} |
Q:
JSON to parse data into android application
I am trying JSON parse data into android.
What is my Error i can not understand.
I am beginner of java and android also.
This code is not hard, you will not boring.
My Error and Code show bellow:
04-07 05:19:02.305: E/AndroidRuntime(19599): FATAL EXCEPTION: main
04-07 05:19:02.305: E/AndroidRuntime(19599): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.buet_parsing/com.example.buet_parsing.MainActivity}: java.lang.NullPointerException
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.os.Handler.dispatchMessage(Handler.java:99)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.os.Looper.loop(Looper.java:137)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-07 05:19:02.305: E/AndroidRuntime(19599): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 05:19:02.305: E/AndroidRuntime(19599): at java.lang.reflect.Method.invoke(Method.java:511)
04-07 05:19:02.305: E/AndroidRuntime(19599): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-07 05:19:02.305: E/AndroidRuntime(19599): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-07 05:19:02.305: E/AndroidRuntime(19599): at dalvik.system.NativeStart.main(Native Method)
04-07 05:19:02.305: E/AndroidRuntime(19599): Caused by: java.lang.NullPointerException
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.widget.ListView.setAdapter(ListView.java:462)
04-07 05:19:02.305: E/AndroidRuntime(19599): at com.example.buet_parsing.MainActivity.onCreate(MainActivity.java:46)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.Activity.performCreate(Activity.java:5104)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-07 05:19:02.305: E/AndroidRuntime(19599): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-07 05:19:02.305: E/AndroidRuntime(19599): ... 11 more
04-07 05:19:11.135: I/Process(19599): Sending signal. PID: 19599 SIG: 9
MainAcitivity:
package com.example.buet_parsing;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.ls.LSInput;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ListView lv;
CustomAdapter adapter;
String urlString="http://cricscore-api.appspot.com/csa";
ArrayList<ListIteam> allNews;
AlertDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.list);
adapter=new CustomAdapter(this, allNews);
lv.setAdapter(adapter);
DownloadTask download=new DownloadTask();
Log.v(getClass().getSimpleName(), "Loading data.......");
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setMessage("Loading data..");
builder.setView(new ProgressBar(this));
progressDialog=builder.create();
progressDialog.show();
download.execute();
}
class DownloadTask extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
String result=null;
try {
HttpClient client=new DefaultHttpClient();
HttpGet get=new HttpGet(urlString);
HttpResponse response=client.execute(get);
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
InputStream in=response.getEntity().getContent();
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
String line=reader.readLine();
Log.v(getClass().getSimpleName(), line);
return line;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return result;
}
@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
try {
JSONArray array=new JSONArray(result);
for (int i = 0; i < result.length(); i++) {
JSONObject object=array.getJSONObject(i);
String team1=object.getString("t1");
String team2=object.getString("t2");
ListIteam ls=new ListIteam(team1, team2);
allNews.add(ls);
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
CustomAdapter:
package com.example.buet_parsing;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<ListIteam>{
Activity context;
ArrayList<ListIteam> ls;
public CustomAdapter(Activity context, ArrayList<ListIteam> ls) {
super(context, R.layout.adapter_layout, ls);
this.context=context;
this.ls=ls;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view=convertView;
LayoutInflater inflat=context.getLayoutInflater();
view=inflat.inflate(R.layout.adapter_layout, null, false);
TextView txtTeam1=(TextView)view.findViewById(R.id.team1);
TextView txtTeam2=(TextView)view.findViewById(R.id.team2);
ListIteam l=ls.get(position);
txtTeam1.setText(l.getTeam1());
txtTeam2.setText(l.getTeam2());
return view;
}
}
ListItem:
package com.example.buet_parsing;
public class ListIteam {
String team1;
String team2;
public ListIteam(String team1, String team2) {
super();
this.team1 = team1;
this.team2 = team2;
}
public String getTeam1() {
return team1;
}
public void setTeam1(String team1) {
this.team1 = team1;
}
public String getTeam2() {
return team2;
}
public void setTeam2(String team2) {
this.team2 = team2;
}
@Override
public String toString() {
return "ListIteam [team1=" + team1 + ", team2=" + team2 + "]";
}
}
A:
allNews is null when you set adapter for the listview in oncreate so initialize allNews
replace ArrayList<ListIteam> allNews=new ArrayList<ListIteam>;
| {
"pile_set_name": "StackExchange"
} |
Q:
Where to put "innerShiv" in this .load() code fragment?
I'm trying to insert "innerShiv" into this Code:
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(innerShiv(newHash + " #guts"), function() {
$mainContent.fadeIn(200, function() {
$pageWrap.css({
height: baseHeight + $mainContent.height() + "px"
});
});
});
$("nav a").removeClass("current");
$("nav a[href='"+newHash+"']").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
This doesn't work yet. Where to put the bracket correctly?
Sources:
http://css-tricks.com/6336-dynamic-page-replacing-content
http://jdbartlett.com/innershiv/
Thank you.
A:
Your problems are mostly syntax issues like incorrect number of closing brackets etc. Try using an editor like Aptana which will highlight these sorts of things for you so you can debug before trying it in a browser. In the meantime I've corrected your code.
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(innerShiv(newHash + " #guts"), function() {
$mainContent.fadeIn(200, function() {
$pageWrap.css({
height: baseHeight + $mainContent.height() + "px"
});
});
});
$("nav a").removeClass("current");
$("nav a[href='"+newHash+"']").addClass("current");
});
};
});
$(window).trigger('hashchange');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Netbeans C/C++ 7.2 -std=C++11 not recognized by gcc v4.6 or lower
I left Eclipse to NetBeans for C/C++ development right after release v7 and it all seems a wise choice except that -std=C++11 flag in the current latest release, namely 7.2, is not recognized by gcc 4.6 (-std=C++0x) or the previous. Since Ubuntu 12.04 ships with gcc 4.6 (which should be fair enough to use for my jobs in term of 11 features) and a fresh installation of gcc 4.7 might bring about complexity in maintenance of the system (well...I'm a person extremely simple, neat and clean), is there any work around?
A:
Using the "C++ standard" option from NetBeans does not work. My solution is to do it manually.
Add:
-std=c++0x
To the "Additional Options" in the Project > Settings > Build > C++ Compiler
| {
"pile_set_name": "StackExchange"
} |
Q:
Apply a password group policy seperate from the Default Domain Policy?
Im trying to keep my Default Domain Policy clean and standard and I want to make a GPO for my password policies.
I made it but it still gets the policies from the Default Domain Policy object.
I imagine that it gets that one because it is the most restrictive one but I would enjoy one that I can make a copy of the Default Domain Policy, edit that one, and then apply first that and if something isnt applied/changed/etc, apply the default in the Default Domain Policy.
Is it possible?
A:
Your password policy can be in a group policy you create. There is nothing special about the 'default domain policy' that is created for you.
The Policy you should be applied at the root for the best results. By being linked there directly or inherited from the root, and not be blocked. Password policies are a computer policy and are enforced by the computer with the password database. In the case of your active directory this is your Domain Controllers.
It is likely that you already have password policy settings in existing policies (they are in a default install) So it will be important to make sure the Link order of this new policy is any other policy, though you probably should remove the password settings from any other policies to prevent confusion.
If you look at the Group Policy results for one of your domain controllers you should see what policy and settings are being applied and from what Policy Object if you run into problems.
Separate password policy
Policy Link order
Policy Results.
| {
"pile_set_name": "StackExchange"
} |
Q:
Most efficient way to store a large number of key-value pairs of integers, separated by a delimiter, in a file
I have a system where two programs are concurrently reading and writing a file containing a large number of pairs of unsigned integers. The key can have a value [0,2^16) and the value can have a value [0,2^32). I am currently storing these integers in the file as characters, where each pair is on its own line, the key and value are separated by a single whitespace, and all values have 10 characters.
The reason for the 10 characters is two-fold: 1. the largest unsigned integer, interpreted as characters, is 10 characters long, and 2. I am using mmap to map the file into both programs' memory, using the MAP_SHARED flag. When the program that writes to the file is first run, it will linearly scan the file and construct a hash map mapping the keys to pointers to the values. When the writer wants to put a new key-value pair into the file, it will search for the key in the hash map, and if that key exists, it will overwrite the value stored in the address associated with that key. I ensure that all values are stored as 10 characters in the file, where smaller values are padded on the right with whitespaces, so that the writer can always simply overwrite the value at that address and not have to do some crazy shuffling of memory and munmap and mmap again.
However, storing integers as strings in a file is extremely inefficient, and I would like to know how to more efficiently do three things:
Store the pairs of integers as, well, pairs of integers and not strings. I want the file to be as small as possible.
Not have to use an additional large data structure like the hash map in the writing program.
Allow the reading program to search for and retrieve a key-value pair in log(n) time, instead of what it is doing now, which is reading through the file linearly for a matching string.
In general, can a file be structured to behave like a data structure that can be sorted by something like binary search, and if so, how would I go about doing that?
A:
I ended up implementing a solution that I was looking for, which does the following things:
Key-value pairs are stored in the file in binary format, 4 bytes for the key followed by 4 bytes for the value.
The file contains only key-value pairs, so the file is just a stream of key-value pairs with no delimiters or extra fluff.
Both the reading and writing programs can search for a key and retrieve the corresponding value in log(n) time. This was achieved by reinterpreting the binary as an array of 8 byte chunks, reinterpreting each 8 byte chunk as two 4 byte chunks (key and value), and performing binary search on the mapped file.
The code I came up with is as follows:
struct Pair { uint32_t index[]; };
struct PairArray { uint64_t index[]; };
size_t getFilesize(const char* filename) {
struct stat st;
stat(filename, &st);
return st.st_size;
}
void binarySearch(const PairArray* const pairArray,
uint16_t numElements, uint32_t key, uint32_t*& value) {
int mid = numElements/2;
if (numElements == 0) return;
// interpret the pair as an array of 4 byte key and value
const Pair* pair = reinterpret_cast<const Pair*>(&(pairArray->index[mid]));
// new pointer to pass into recursive call
const PairArray* const newPairArray = reinterpret_cast<const PairArray* const>(
&(pairArray->index[mid + 1]));
// if key is found, point pointer passed by reference to value
if (key == pair->index[0]) {
value = const_cast<uint32_t*>(&pair->index[1]);
return;
}
// if search key is less than current key, binary search on left subarray
else if (key < pair->index[0]) {
binarySearch(pairArray, mid, key, value);
}
// otherwise, binary search on right subarray
else (numElements%2 == 0)
? binarySearch(newPairArray, mid - 1, key, value)
: binarySearch(newPairArray, mid, key, value);
}
int main(int argc, char** argv) {
...
// get size of the file
size_t filesize = getFilesize(argv[1]);
// open file
int fd = open(argv[1], O_RDWR, 0);
if (fd < 0) {
std::cerr << "error: file could not be opened" << std::endl;
exit(EXIT_FAILURE);
}
// execute mmap:
char* mmappedData = static_cast<char*>(
mmap(NULL, filesize, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0));
if (mmappedData == NULL) {
std::cerr << "error: could not memory map file" << std::endl;
exit(EXIT_FAILURE);
}
// interpret the memory mapped file as an array of 8 byte pairs
const PairArray* const pairArray = reinterpret_cast<PairArray*>(mmappedData);
// spin until file is unlocked, and take lock for yourself
while(true) {
int gotLock = flock(fd, LOCK_SH);
if (gotLock == 0) break;
}
// binary search for key value pair
uint32_t* value = nullptr;
binarySearch(pairArray, filesize/8, key, value);
(value == nullptr)
? std::cout << "null" << std::endl
: std::cout << *value << std::endl;
// release lock
flock(fd, LOCK_UN);
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Может стоит убрать кнопки "поднять репутацию" для своих вопросов-ответов?
Сделать это так же как и комментариями. А то поднять/опустить нельзя, а кнопки есть. Не то что бы это мешает (это вообще не заметно), но наверное лучше если бы их вообще не было?
A:
Убирать не надо, а то не органично будет смотреться.
А вот почему их не залочили - это вот интересный вопрос. Немного изменить цвет, чтоб было очевидно, что элементы не активны и залочить. Если уж боятся, что люди могут не понять, почему элементы не активны, то можно хинт при наведении сделать.
На MSE задал вопрос про это: Disable up/down vote arrows on your own posts
A:
Не надо, потому что сообщения без стрелочек выглядят странно. Гораздо лучше, когда сайт единообразен. Я бы и на заблокированных стрелочки вернул.
| {
"pile_set_name": "StackExchange"
} |
Q:
Partial Converse of Holder's Theorem
Holder's Theorem is the following: Let $E\subset \mathbb{R}$ be a measurable set. Suppose $p\ge 1$ and let $q$ be the Holder conjugate of $p$ - that is, $q=\frac{p}{p-1}.$ If $f\in L^p(E)$ and $g\in L^q(E),$ then $$\int_E \vert fg\vert\le \Vert f\Vert _p\cdot\Vert g \Vert_q$$
I am trying to prove the following partial converse is true. Suppose $g$ is integrable, $p>1$ and $$\int_E \vert fg\vert\le M\Vert f\Vert_p$$ when $f\in L^p(E)$ is bounded, for some $M\ge0$. I am trying to prove that this implies that $g\in L^q(E)$, where $q$ is the conjugate of $p$. I am interested in knowing if my proof is correct or if it has any potential.
Attempt: Assuming this is true, I want to show $\int_E \vert g\vert^q<\infty$. Note that $g^{q-1}\in L^p(E)$ since $\int_E \vert g\vert^{pq-p}=\int_E \vert g \vert ^q<\infty$ (I think this is true since $g$ is integrable - I know it holds when $q$ is a natural number). Take $f=g^{q-1}$ and the hypothesis tells us that $$\int_E \vert g \vert^q\le M\Vert g^{q-1}\Vert_P\\<\infty \,\,(\text{since }g^{q-1}\in L^p)$$so $g$ is integrable.
A:
This is not a correct proof. You want to show that $\int_E |g|^q < \infty$, but then you are using this in the proof. So nothing has been shown.
To write a correct proof, you will have to approximate $g$, as you wrote in your last comment. E.g.set $E_k = E \cap B_k(0)$ (so these sets now have finite measure) and
$$
g_k(x) = \begin{cases} g(x) \quad (x \in E_k, |g(x)| \le k) \\ 0 \quad \text{otherwise}
\end{cases}
$$
Clearly $\int_E |g_k|^q < \infty$ for all $k$. Now use the assumption and a suitable limit, e.g. with Lebesgue's Theorem.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nearing Beta Completion Site scores still a worry [Edit: We are doing good Now]
We are nearing out Beta Completion of 90 Days. However we are still some way off from making it to full site.
The scores as of 31st Oct 2010 are;
1,128 Questions: Okay
98% answered: Excellent
Avid Users:Okay
Answer Ratio: Excellent
423 Visit/Day: Worrying
More details at
http://area51.stackexchange.com/proposals/1721/personal-finance-and-money
We have to increase the site visits. Else the site would become a ghost town.
Also if I see the top users (above 500+), there are quite a few users who are no longer logging in for past couple of months. We are loosing followers. We need to do something if we need to make this site a success.
Edit: I am Voting to close this question as its no longer relevant. We are doing good on all aspects for this site.
A:
I'm not too worried about the last metric, Visits/day. The most important metrics are the ones that we're scoring "Okay" or "Excellent" for. Also, refer to:
When Will My Site Graduate? (at blog.stackoverflow.com)
Anyway, Visits/day is mostly a function of how well the site is performing in Google searches. When the site was known as basicallymoney.com, it was getting more traffic from Google. Refer to the comments you'll find here. I think it will simply take more time for the new domain to re-establish, in Google's eyes, what reputation it had previously. When we start ranking better in searches, the visits will go up.
The best thing each of us can do to help money.stackexchange.com rank better is to get quality inbound links to the site. The flair badge is one easy way users can help, for those people who are willing to post it and have a personal web site or blog.
A:
Any everybody should vote for answers that are good or at least reasonable. Voting encourages new users to participate more and probably makes them feel less like outsiders.
You don't need to agree 100%, but if you can concede they have good points, vote. Vote your favorite answer first. Tack on a comment with some clarity if you don't back the answer fully.
Vote up good questions especially! Vote early and vote often.
| {
"pile_set_name": "StackExchange"
} |
Q:
possible to ignore lucene document boost?
I am looking for a way to tell the lucene searcher to ignore document boosting on certain queries?
In our search results we usually work with a dominant boost-factor calculated by the age of a document while indexing (the index is rebuild nightly).
Now, I am looking for a way offer search-functionality which ignores the age, but found yet no way to override/ignore the document boost.
Best regards,
Alex
A:
Instead of storing your calculated-score as boost, you can store it in a new field, and by implementing CustomScoreQuery + CustomScoreProvider you can control which value(default score or your calculated-one in the field) to return
| {
"pile_set_name": "StackExchange"
} |
Q:
How to obtain a percentile ranking for a journal? (i.e., top 30%; 30% to 50%)
My institution ranks scientific achievement according to some criteria when evaluating promotions, positions, etc. for its subjects (students, grad students, personnel, etc.) This is done by a rule book that is specified in the form of a bylaw and is administered by the ministry of science, therefore it is not local to my institution, but applied nationwide.
The passage about SCI journal publications states that journals are divided into three groups:
eminent international journals - a journal that in its subject ranks in the top 30% journals in ISI list publications
outstanding international journals - the same but for <30% and >50%
international journals - the same for <50%
The difference in "points" awarded for publications in each of the categories is rather large. I was wondering how I could determine which journals fall into a criterium from above?
I talked to the administrative service, but got no satisfying answer, i.e. there is no list of journals (which is understandable, as there are far too many subjects). They told me something along the lines: "These things will be evaluated when the time comes", which is, of course, not at least satisfactory to me.
I talked also briefly with the head of the department and he told me that he never really gave it much thought, I should publish in journals that suit me, the higher the impact factor and prestige the better of course, but in the end it isn't that much of an imperative, and that I should let the "politicians" and administrators worry about those tiny matters. I would, however, still like to know which journals I should favorite.
PS: the rule book naturally specifies similar criteria for various scientific publications (conferences, patents, books, etc.), but since I'm working on my first article to be submitted to a journal and I still haven't decided which journal, I would like to take things like this into account
A:
Likely this is not the answer you want to hear, but I assume the administrative service you talked to is correct. If nobody really knows which journals fall under which of these (rather subjective) categories, it will not be feasible to in advance establish for sure way how much any paper you write will count in the end, when you are evaluated.
This is not nearly as strange as it sounds. Formal rules for promotion and the evaluation of research tend to live in the ugly grey area between bureaucrats who like things orderly, well-defined and, most importantly, written down, and the reality of science, where basically no two scientists will ever be able to agree on an absolutely consistent quality ranking of publication outlets. What usually happens is that some sort of nebulous rankings are defined without specifically ranking concrete venues,and then leave it to a commission of academics to decide ad hoc which publications fall into which category.
At my current university, we have similar nebulous requirements for PhD graduation. Essentially, it is required that students need at least one A-ranked publication. However, what is considered A-ranked varies considerably between different faculty, and is basically negotiated when graduation time is near. I assume requirements for tenure etc. are handled similarly.
Note that there are some initiatives that are trying to rank publication venues more formally, for instance CORE for computer science. However, these rankings are also far from perfect (or, for some fields, they are apparently downright terrible).
| {
"pile_set_name": "StackExchange"
} |
Q:
Shell script file, checks if text file is empty or not
I want to check if .todo.txt is empty or not.
If is is empty, I want to add the echo in the file, and if it already has content, I want to do something else.
I tried:
hasData()
{
echo "Hello"
}
isEmpty()
{
echo -e "$n\t$comment\t$dueD/$dueM/$dueY " >> .todo.txt
}
if [ -s $file ] ; then
hasData()
else
isEmpty()
fi
When I run above code, I get the following:
./todo.sh: line 25: syntax error near unexpected token `else'
./todo.sh: line 25: ` else'
A:
when i run my code i get the following ./todo.sh: line 25: syntax error near unexpected token else' ./todo.sh: line 25: else'
You must use parentheses to define a shell function, but they have no part in calling one. A shell function is invoked just like any other command:
if [ -s $file ] ; then
hasData
else
isEmpty
fi
If your functions took arguments, then you would list them after the function name -- again, just like for any other command.
| {
"pile_set_name": "StackExchange"
} |
Q:
TinyMCE stripping HTML
Originally I thought the problem was with the iframe, but now I've realized the problem is with TinyMCE stripping HTML from the Text.
I'm trying to make TinyMCE stop from stripping the iframe tags for me to save into the database. I tried to use the extended_valid_elements, but TinyMCE doesn't obey to the configuration and keep stripping the iframe's tags. I've been looking for 2 days already and I think i've missed something very basic because I just can't seem to find a solution, nor anybody who have the same problem and it's not because they mistyped something...
I copied the full configuration on the TinyMCE documentation and worked from there.
My configuration:
tinymce.init({
selector: "textarea",
theme: "modern",
plugins: [
"advlist autolink lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table contextmenu directionality",
"emoticons template paste"
],
toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
toolbar2: "print preview media | forecolor backcolor emoticons",
templates: [
{title: 'Test template 1', content: 'Test 1'},
{title: 'Test template 2', content: 'Test 2'}
],
language: "pt_BR",
extended_valid_elements: "iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder]",
document_base_url: "<?php echo base_url(); ?>",
relative_urls: true,
});
Thanks in advance.
When I click on the preview button before saving it into the bd it shows the iframe correctly (And all the other stuff too, like alignments for an example).
Now I've realized that the problem is not with iframe, but with everything, because after I save the formatted text into the bd and open it again by editing my post everything is deconfigured and even in the preview button I only see the stripped html.
A:
The problem was that I was treating the text twice. Once to save it, another to show it. When I treat the Text only to show it, there was no problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
A better way to accept multiple request types in a single view method?
I'm trying to expose an API to various request methods (GET, url x-www-form-urlencoded POST, and json POST):
@app.route('/create', methods=['GET', 'POST'])
def create_file():
if request.method == 'GET':
n = request.args.get('n')
t = request.args.get('t')
if request.method == 'POST':
if request.json:
n = request.json['n']
t = request.json['t']
else:
n = request.form['n']
t = request.form['t']
try:
n = int(n)
except:
n = 1
...
The above appears too verbose. Is there a simpler or better way of writing this? Thanks.
A:
Does this look better? It is a bit cleaner in my opinion, if you can accept moving the JSON POST request to a different route (which you really should do anyway).
def _create_file(n, t):
try:
n = int(n)
except:
n = 1
...
@app.route('/create')
def create_file():
n = request.args.get('n')
t = request.args.get('t')
return _create_file(n, t)
@app.route('/create', methods = ['POST'])
def create_file_form():
n = request.form.get('n')
t = request.form.get('t')
return _create_file(n, t)
@app.route('/api/create', methods = ['POST'])
def create_file_json():
if not request.json:
abort(400); # bad request
n = request.json.get('n')
t = request.json.get('t')
return _create_file(n, t)
A:
There is nothing stopping you from rewriting your code into:
@app.route('/create', methods=['GET', 'POST'])
def create_file():
params = None
if request.method == 'GET':
params = request.args
if request.method == 'POST':
if request.json:
params = request.json
else:
params = request.form
n = params.get('n')
t = params.get('t')
try:
n = int(n)
except:
n = 1
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Central division and quaternion algebras
I would like to know if there are some central-simple algebras $D_1$, $D_2$ and $D_3$ over a field $k$ satisfying the following properties :
$ind(D_1)=exp(D_1)=4$ ($ind$ is the Schur index and $exp$ the exponent);
$D_2$ and $D_3$ are two non-isomorphic quaternion algebras;
$ind(D_1^{\otimes2} \otimes D_2)=ind(D_1^{\otimes 2} \otimes D_3)=4$ (recall that $ind(D_1^{\otimes 2})$ is always $2$ in this setting).
To give a little motivation, i'm interested in the existence of "square roots" (in the Brauer group of a field) of quaternion algebras.
A:
You can find such division algebras over $\mathbb{Q}(x_1,x_2,x_3)$ or $k(x_1,x_2,x_3,x_4)$ where $k$ is any field using the results of "Nakayama, T. Über die direkte Zerlegung einer Divisionsalgebra. Japanese J. of Mathematics 12 (1935), 65–70". A simplified proof is given in the book "Associative algebras" by Pierce, Corollary c, p. 381.
In the notation of Pierce, let $r=3$, $n_1 = 4$, $n_2 = 2$, $n_3=2$ and set $D_i$ to be the cyclic algebras denoted as $B_i$ by Pierce. The only thing one needs to observe is that $B_1^{\otimes 2}$ is equivalent to the cyclic algebra associated to the quadratic subfield of $E_1$ (and the element $x_1$) so we may apply the corollary to $D_1^{\otimes 2} \otimes D_2$
and $D_1^{\otimes 2} \otimes D_3$.
(Sorry for not giving more details but the theorem is long to write out in full. If anything is not clear please leave a comment.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't I clone a git repo for readthedocs to build the documentation?
I'm trying to import my project code for readthedocs so that it can generate a documentation for me. However, at the stage of cloning the repo, there is already an error:
checkout
-----
Failed to import project; skipping build.
Error
-----
Failed to get code from 'http://mydomain/myproject.git' (git clone): 128
That error code indicates, that the repository is private, and I cannot access it without logging in, unless I have my SSH key that enables a secure connection between my computer and the server. So I generated my key, then added it to my Deploy Keys in the project.
Any reason you can think of why I still cannot access the project's code?
A:
The reason it happens, is, that despite I provide a public URL for the project, it still cannot be accessed by anyone who is not a project member, a registered user, or someone who owns a SSH key enabling a secure connection between his computer and the project repo. The readthedocs documentation is not hosted on my own server, but on readthedocs servers, so that server would need a SSH key or access to the project, both of which are impossible for me.
So, the only solutions I could think of, is making the project public (which is undesirable, as it is our private company project, and we don't want anyone unwanted to have access to it) or make it available for a certain set of IP addresses, but that only works provided that readthedocs servers have a fixed, constant IP address.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set path to prev directory Python?
I use this function to get current path to directory where is placed Python script:
def get_script_path(self):
return os.path.dirname(os.path.realpath(__file__))
I want to set up path to one directory upper from current catalog to catalog /advs:
I tried:
filename = 'file.txt'
filepath = os.path.join(self.get_script_path(), '../advs', filename)
A:
Try using below it will give the path of previous directory in which running script is present
import os
path_to_prev_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filename = 'file.txt'
filepath = os.path.join(path_to_prev_dir, 'advs', filename)
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Javascript search an email for txt then take the string after into variable
I am trying to write code to search the following and find "Office Location:" and then take whatever the string after it is into a variable, in this case UK-London I write some basic code to find Office Location but don't know how to select the string after. I think this is something simple and I am an idiot (hopefully because I am still new to this) Thanks!
-Alex
Employee Name: Joe Blow Employee ID: 17811 Hire Date: 07/21/2014 Employee Type: Regular Job Title: ATE-0016 - Claims Adjuster Manager: His boss Office Location: UK-London Department: CLM-Administration Cost Center: 03-3002 AEL & AMSL: Claims [not available]
A:
This regex should find the Office Location as long as the text 'Office Location' doesn't appear anywhere else in the text.
var officeLocation = /Office Location: (.+)/.exec(emailContent)[1];
JsFiddle Link
| {
"pile_set_name": "StackExchange"
} |
Q:
How to enable Sticky Session in WSO2 Elastic Load Balancer for Vaadin
wso2 or vaadin people
I follow this guide to setup ELB for WSO2 Application Server
http://docs.wso2.org/wiki/display/ELB203/Setup+ELB+with+WSO2+Application+Server
The ELB works perfectly. However, My vaadin application show this error.
Cookies disabled
This application requires cookies to function.
Please enable cookies in your browser and click here to try again.
Vaadin related commit link.
http://dev.vaadin.com/changeset/11570/svn
It should be some problem related to session/cookie.
I am willing to provide more information if needed
A:
It turns out the bug is fixed in wso2 svn trunk but not in lastest ELB/ESB. I get two JSESSIONID cookie, thats why passthrough proxy fails. Hope it helps someone.
See https://wso2.org/jira/browse/ESBJAVA-1659
| {
"pile_set_name": "StackExchange"
} |
Q:
svn to perforce migration
I am looking at migrating our svn code base to perforce. Looking at google search results,
I did find 2 tools which do the same
P4Convert
ftp://ftp.perforce.com/pub/perforce/tools/p4convert/docs/index.html
SVN2P4
http://public.perforce.com/wiki/SVN2P4
Both these tools seems to be from the Perforce website.
But I couldn't find pros and cons of using one tool vs the other.
We also need to migrate the svn history to perforce. Is this possible using any of these tools ?
A:
I'd recommend trying p4convert-svn. It is very solid.
If you have any problems you should contact Perforce support. There's a new tool in the works but not generally available yet.
| {
"pile_set_name": "StackExchange"
} |
Q:
dynamic display of a running process?
I am writing a script and according to that when I run it certain info will be displayed on the output screen.
for example say the constant data displayed is:
my name is mukesh.
i am 27 years old
unix version 7.2.3.0
but along with the above display something else is also need to be displayed(varying data) I.e
Process A is starting
Process A is running
Process A is completed.
but I don't want the above display.
I want Process A is starting to be cleared from screen
and replaced by Process A is running and then by Process A is completed.
I am not very keen to use clear as it will remove the whole screen containing the constant data also.
and also because the constant data takes a lot of time to process and to be displayed on the screen.
A:
The carriage return character (\r) will return to the beginning of the current line, so you can overwrite text:
printf "%s\r" "Process A is starting "
sleep 5
printf "%s\r" "Process A is running "
sleep 5
printf "%s\n" "Process A is completed."
A:
You can clear a line and use carriage return (\r) to get to the beginning of the line.
clr2eol=`tput el` # capture escape sequence for "clear-to-end-of-line"
echo -n "Process A has started." # display without a newline
sleep 3
echo -n "\r${clr2eol}Process A is running." # move to beginning of line (bol), clear, and display new text
sleep 5
echo -n "\r${clr2eol}Process A has completed." # again, move to bol, clear and display new test
echo # terminating newline you may not want to have this sent right away
Read the manpage on terminfo.
| {
"pile_set_name": "StackExchange"
} |
Q:
#has_content?(String) always returns false
I have my problems with my rspec tests particularly with the has_content method. Here are some of the code snippets. I have been following the Ruby on Rails tutorials from Michael Hartl, in case you don't know.
has_content always returns false even though the microposts have set its respective content.
resulting test
Run options: include {:line_numbers=>[61]}
..FFF
Failures:
1) User pages profile page microposts should have content 0
Failure/Error: it { should have_content(user.microposts.count) }
expected #has_content?(0) to return true, got false
# ./spec/requests/user_pages_spec.rb:72:in `block (4 levels) in <top (required)>'
2) User pages profile page microposts should have content "Foo Bar"
Failure/Error: it { should have_content(m2.content) }
expected #has_content?("Foo Bar") to return true, got false
# ./spec/requests/user_pages_spec.rb:71:in `block (4 levels) in <top (required)>'
3) User pages profile page microposts should have content "Lorem Ipsum"
Failure/Error: it { should have_content(m1.content) }
expected #has_content?("Lorem Ipsum") to return true, got false
# ./spec/requests/user_pages_spec.rb:70:in `block (4 levels) in <top (required)>'
Finished in 0.74407 seconds
5 examples, 3 failures
Failed examples:
rspec ./spec/requests/user_pages_spec.rb:72 # User pages profile page microposts should have content 0
rspec ./spec/requests/user_pages_spec.rb:71 # User pages profile page microposts should have content "Foo Bar"
rspec ./spec/requests/user_pages_spec.rb:70 # User pages profile page microposts should have content "Lorem Ipsum"
Randomized with seed 43497
[Finished in 1.3s with exit code 1]
user_pages_spec.rb
describe "profile page" do
let(:user) { FactoryGirl.create(:user) }
let(:m1) { FactoryGirl.create(:micropost, user: user, content: "Lorem Ipsum") }
let(:m2) { FactoryGirl.create(:micropost, user: user, content: "Foo Bar") }
before { visit user_path(user) }
it { should have_selector('h1', text: user.name) }
it { should have_title(full_title(user.name)) }
describe "microposts" do
it { should have_content(m1.content) }
it { should have_content(m2.content) }
it { should have_content(user.microposts.count) }
end
end
show.hml.erb
<% provide(:title, @user.name) %>
<div class='row'>
<aside class='col-md-4'>
<section>
<h1>
<%= gravatar_for @user, size: 50 %>
<%= @user.name %>
</h1>
</section>
</aside>
<div class="col-md-8">
<% if @user.microposts.any? %>
<h3>Microposts (<%= @user.microposts.count %>)</h3>.
<ol class="microposts">
<%= render @microposts %>
</ol>
<% end %>
</div>
</div>
_micropost.html.erb
<li>
<span class="content">
<%= micropost.content %>
</span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %>
</span>
</li>
micropost.erb
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
validates :user_id, presence: true
validates :content, presence: true, length: { maximum: 140 }
default_scope { order('microposts.created_at DESC') }
end
user.rb
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_secure_password
has_many :microposts, dependent: :destroy
# remaning lines are for validation
end
===EDIT (answer to problem)===
I used let! instead to force the method's invocation before each example.
let!(:m1) { FactoryGirl.create(:micropost, user: user, content: "Lorem Ipsum") }
let!(:m2) { FactoryGirl.create(:micropost, user: user, content: "Foo Bar") }
A:
let method defines a method with given block, so every time you call user you create a new one, and every time you call m1 or m2 you create new micropost with a new user. Instead do:
before(:each) do
@user = FactoryGirl.create(:user)
@m1 = FactoryGirl.create(:micropost, user: user, content: "Lorem Ipsum")
@m2 = FactoryGirl.create(:micropost, user: user, content: "Foo Bar")
visit user_path(@user)
end
// Use the instance variables in your tests, or wrap them in methods:
let(:user) { @user }
let(:m1) { @m2 }
let(:m2) { @m1 }
| {
"pile_set_name": "StackExchange"
} |
Q:
Python distinguish between returned tuple and multiple values
I want to write a wrapper function which call one function and pass the results to another function. The arguments and return types of the functions are the same, but I have problem with returning lists and multiple values.
def foo():
return 1,2
def bar():
return (1,2)
def foo2(a,b):
print(a,b)
def bar2(p):
a,b=p
print(a,b)
def wrapper(func,func2):
a=func()
func2(a)
wrapper(bar,bar2)
wrapper(foo,foo2)
I am searching for a syntax which works with both function pairs to use it in my wrapper code.
EDIT: The definitions of at least foo2 and bar2 should stay this way. Assume that they are from an external library.
A:
There is no distinction. return 1,2 returns a tuple. Parentheses do not define a tuple; the comma does. foo and bar are identical.
As I overlooked until JacobIRR's comment, your problem is that you need to pass an actual tuple, not the unpacked values from a tuple, to bar2:
a = foo()
foo2(*a)
a = bar()
bar2(a)
A:
I don't necessarily agree with the design, but following your requirements in the comments (the function definitions can't change), you can write a wrapper that tries to execute each version (packed vs. unpacked) since it sounds like you might not know what the function expects. The wrapper written below, argfixer, does exactly that.
def argfixer(func):
def wrapper(arg):
try:
return func(arg)
except TypeError:
return func(*arg)
return wrapper
def foo():
return 1,2
def bar():
return (1,2)
@argfixer
def foo2(a,b):
print(a,b)
@argfixer
def bar2(p):
a,b=p
print(a,b)
a = foo()
b = bar()
foo2(a)
foo2(b)
bar2(a)
bar2(b)
However, if you aren't able to put the @argfixer on the line before the function definitions, you could alternatively wrap them like this in your own script before calling them:
foo2 = argfixer(foo2)
bar2 = argfixer(bar2)
And as mentioned in previous comments/answers, return 1,2 and return (1,2) are equivalent and both return a single tuple.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can JSNI Marshal Enums as strings?
I'm trying to use GWT's JSNI to call a Java function through native code. The Java function has an enum in it, and I was curious to know if the enum will marshall in the way I want. I couldn't find anything useful on Google or SO, and the Google basic docs are not very specific. I'm sure I'll find out as I compile and run, but thought I might as well ask.
Given vastly simplified code like this:
package my.example.package;
public class Giant {
public enum GiantWord { FEE, FIE, FO, FUM };
public void sayGiantWord(GiantWord word) { /* ... */ }
public native JavaScriptObject toJS() /*-{
var Giant = function() {
this.sayGiantWord = function(word) {
[email protected]::sayGiantWord(Lmy/example/package/Giant$GiantWord;)(word);
};
};
return new Giant();
}-*/;
}
EDIT - Based on comments, let me give an alternative version of the toJS function, and avoid confusion between this and this.
public static native JavaScriptObject toJS(final Giant g) /*-{
var Giant = function() {
this.sayGiantWord = function(word) {
[email protected]::sayGiantWord(Lmy/example/package/Giant$GiantWord;)(word);
};
};
return new Giant();
}-*/;
will calling sayGiantWord("FEE") from within JavaScript (on the appropriately acquired var from toJS()) work correctly? In other words, will the JSNI marshaller properly convert a String to its matching Java enum?
I expect calling sayGiantWord(1) will be more prone to marshall correctly, since an int can be converted to an enum easily.
Other notes:
The GWT Eclipse plugin is what gave me the syntax for accessing the class member's enum. At least that far, GWT is working with me.
I don't want to pass a number, and if necessary I know I can handle the string with a conversion function in the Java class as follows; I'd just rather not do so.
public void sayGiantWordJS(String word) {
// convert the string to an enum
// call sayGiantWord
}
Thanks for any advice!
A:
I wasn't able to get the Enum to work at all. It seems to not be supported.
When I passed a string or a number through the JavaScript object, JSNI made no attempt to convert the input to an enum. It does convert Enums to special objects that have an "ordinal" value, but it didn't treat the number as the ordinal and didn't try to find the valueOf the input String. I considered adding a constructor to the enum, but everything I've seen says that's for adding extra data fields to the enum.
My answer was the one I said I'd rather avoid. In the end, my code looked similar to this:
package my.example.package;
public class Giant {
public enum GiantWord { FEE, FIE, FO, FUM };
public void sayGiantWord(GiantWord word) { /* ... */ }
public void sayGiantWordJS(String word) {
sayGiantWord(GiantWord.valueOf(word));
}
public static native JavaScriptObject toJS(final Giant g) /*-{
var Giant = function() {
this.sayGiantWord = function(word) {
[email protected]::sayGiantWordJS(Ljava/lang/String;)(word);
};
};
return new Giant();
}-*/;
}
Note - if you pass an invalid value through sayGiantWordJS(), you will get odd behavior in that valueOf throws an exception, but doesn't do so at the point where you invoke it. In my test, I didn't see the exception until the next user interface action that I made.
| {
"pile_set_name": "StackExchange"
} |
Q:
ダイクストラ法で最短経路を見つけるときに負の値を持つ辺があると経路は正しくても誤ったコストが出力される
ダイクストラ法のコード(python)を参考に以下のプログラムを実行しました。
出力として最短ルートは'A->C->B->D'と求められましたが、コストは「5+(-4)+1=2」になるところ、'A->B->D'の「3+1=4」が出力されました。原因がわからないです。
グラフ部分はコードのrouteにあたります。
出力
$ python dijkstra.py
visited to A.
visited to B.
visited to D.
visited to C.
minimal cost is 4.
optimum route is 'A->C->B->D'.
# dijkstra.py
import sys
INF = 10000
VISITED = 1
NOT_VISITED = 0
route = [
[INF, 3, 5, INF],
[INF, INF, INF, 1],
[INF, -4, INF, INF],
[INF, INF, INF, INF]
]
size = len(route)
cost = [INF for _ in range(size)]
visit = [NOT_VISITED for _ in range(size)]
before = [None for _ in range(size)]
cost[0] = 0
while True:
min = INF
for i in range(size):
if visit[i] == NOT_VISITED and cost[i] < min:
x = i
min = cost[x]
if min == INF:
break
visit[x] = VISITED
print("visited to {}.".format(chr(65+x)))
for i in range(size):
if cost[i] > route[x][i] + cost[x]:
cost[i] = route[x][i] + cost[x]
before[i] = x
if cost[size-1] == INF:
print("could not find optimum route.")
sys.exit(1)
i = size - 1
optimum_route = []
while True:
optimum_route.insert(0, chr(65+i))
if i == 0:
break
i = before[i]
print("minimal cost is {}.".format(cost[size-1]))
print("optimum route is '", end="")
for i in range(len(optimum_route)):
print(optimum_route[i], end="")
if i == len(optimum_route) -1:
print("'.")
break
print("->", end="")
A:
一言でいうと、このプログラムは、すべての辺が正であることを仮定したアルゴリズムを使っているため、うまく動きません。以下は、プログラムのwhileループを抜き出したものです。説明のために# for ループ 1と# for ループ 2というコメントを入れています。
while True:
min = INF
# for ループ 1
for i in range(size):
if visit[i] == NOT_VISITED and cost[i] < min:
x = i
min = cost[x]
if min == INF:
break
visit[x] = VISITED
print("visited to {}.".format(chr(65+x)))
# for ループ 2
for i in range(size):
if cost[i] > route[x][i] + cost[x]:
cost[i] = route[x][i] + cost[x]
before[i] = x
visit[i] = NOT_VISITED
# for ループ 1直後のforで何をしているかというと、まだAからの距離が確定していない(NOT_VISITED)ノードのうち、一番距離が短いものを取り出しています。
例えば、whileの一周目が終わった時点のコストは、A==0, B==3, C==5, D==INFとなっています。Aのコストが一番小さいですが、一周目で既にAはVISITEDになっているので、二回目の# for ループ 1で選ばれるのは、Bになります。この後、BをVISITEDと確定し、更にBのコストを元にして、Bから繋がったノードのコストを計算します。
さて、経路のコストがすべて正の場合は、ここでBをVISITEDと確定してしまって構いません。CからBに行く経路があるかもしれませんが、Cのコストが既に5であるため、C経由でBに行く経路のコストは、すべて5より大きくなるからです。
しかし今回の場合は負の経路があります。したがって、C経由でBに行く経路で、コストが小さいものがありえます。実際、C->Bのコストは-4なので、A->C->Bは1となり、コストが小さくなっています。
Bの新しいコストが見つかったので、B以降のコストもすべて再計算しなければなりませんが、すでにBをVISITEDとしてしまっているため、再計算されません。したがって、Dのコストは古いまま、つまりA->B->Dの4になるわけです。
最短ルートが正しいのは、B->Dの経路は一通りしかないため、再計算しなくても同じだから、つまり、たまたま正しくなっているだけです。
変更を最小限にして、正しい結果を求めるには、新しいコストが見つかったときに、VISITEDだったノードをNOT_VISITEDに戻せばいいです。# for ループ 2の後のforを以下のようにすれば良いでしょう。
for i in range(size):
if cost[i] > route[x][i] + cost[x]:
cost[i] = route[x][i] + cost[x]
before[i] = x
visit[i] = NOT_VISITED # この行を追加
| {
"pile_set_name": "StackExchange"
} |
Q:
Uncaught TypeError: Cannot read property 'ready' of null
I know this question has been asked probably too many times before but none of those solutions has been able to help me out.I keep getting the above error even if I have everything in place AFAIK.
I have included the button in the html code but when i try to find them through jquery error: "Cannot read property 'ready' of null" occurs moreover it does not even recognize the document.ready function. Here is my full code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery.js"></script>
<script src="Scripts/jsencrypt.js"></script>
<script src="Scripts/jsencrypt.min.js"></script>
<script src="Scripts/jsencrypt.min.js"></script>
<script src="Scripts/jsencrypt.js"></script>
<script type="text/javascript" src="System.js"></script>
<script type="text/javascript" src="System.IO.js"></script>
<script type="text/javascript" src="System.BigInt.js"></script>
<script type="text/javascript" src="System.BitConverter.js"></script>
<script type="text/javascript" src="System.Convert.js"></script>
<script type="text/javascript" src="System.Security.Cryptography.HMACSHA1.js"></script>
<script type="text/javascript" src="System.Security.Cryptography.js"></script>
<script type="text/javascript" src="System.Security.Cryptography.RSA.js"></script>
<script type="text/javascript" src="System.Security.Cryptography.SHA1.js"></script>
<script type="text/javascript" src="System.Text.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert("button");
});
// debugger;
// var element = document.getElementById("btntest");
//$("#btntest").click(function () {
// alert("button");
//});
</script>
</head>
<body>
<input type="button" id="btntest" value="Test" />
<span>Name:</span>
<input type="text" id="txtName" />
<br />
<br />
<input type="button" id="btnSend" value="Send" />
</body>
</html>
Any suggestions to resolve this would be really appreciated.
A:
Have you tried using a CDN for example -
https://code.jquery.com/jquery-1.11.3.min.js
I don't see any problem with the code as long as $ has been overwritten by any other reference below it. If the code does not work with CDN reference, you can also try adding the jquery reference at the end.
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle <--> SQL Server Reporting ORA-22905 issue
ORA-22905: cannot access rows from a non-nested table item
When calling a function defined in Oracle like:
Function cd_dupe_ck (vdate in Varchar2)
Return cd_dupckrow_t Pipelined
Types:
Type cd_dupckrow_t Is Table Of cd_dupckrow;
Type cd_dupckrow Is Object ( [some columns] );
When calling from the report development tool (VS2012) with a constant it works just fine.
But when trying the non-trivial case (using a parameter) it gets the 22905 error.
e.g.
Select * From Table ( cd_dupe_ck( &date_p ) ) <<< FAILS
but
Select * From Table ( cd_dupe_ck( '20140101' ) ) <<< works fine
The ideal solution would be to find a way to pass the parameter by value, but I would settle for it working.
The @date_p parameter in the report is mapped to &date_p in the dataset.
A:
As I said in my comment above it turns out the answer was simple, but unexpected.
After attempting to replicate the issue in both Crystal Reports and Jasper, having it work fine in both, I was puzzled as to why it only worked with a constant parameter to the table function.
When I came up with another report that utilized a table function that only had a couple of column I realized I had never tried a
Select col1,col2,col3, etc.
format on my select, just a Select *
Upon enumerating all the columns from the table function, it worked without error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Has Firefox become bugless or where are the Firefox CVEs for 2017?
Through 2016 Firefox had about the same number (or same order of magnitude) of new issues listed as every other browser. Around 100-250.
2017 lists only a single issue
https://www.cvedetails.com/product/3264/Mozilla-Firefox.html?vendor_id=452
I'd love to believe it's true but on the surface that basically seems impossible. All software has bugs and especially software as complex as a browser.
Some possibilities:
Vulnerabilities in cvedetails.com not showing the correct data
Vulnerabilities are listed under some other software, not under Firefox
Mozilla discovered of way of having ~0 issues unlike all other software in the history of software.
???
Any idea what's going on?
A:
Canonical Solution
According to Security Advisories for Firefox, there were 182 security vulnerabilities that were fixed in 2017.
List of Firefox CVEs (Fixed) - 2017:
* --------------------------------------------------------------------------------------------------- *
| # | CVE Identifier | Source |
| --------------------------------------------------------------------------------------------------- |
| 1 | CVE-2017-5373 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5373 |
| 2 | CVE-2017-5374 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5374 |
| 3 | CVE-2017-5375 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5375 |
| 4 | CVE-2017-5376 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5376 |
| 5 | CVE-2017-5377 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5377 |
| 6 | CVE-2017-5378 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5378 |
| 7 | CVE-2017-5379 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5379 |
| 8 | CVE-2017-5380 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5380 |
| 9 | CVE-2017-5381 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5381 |
| 10 | CVE-2017-5382 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5382 |
| 11 | CVE-2017-5383 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5383 |
| 12 | CVE-2017-5384 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5384 |
| 13 | CVE-2017-5385 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5385 |
| 14 | CVE-2017-5386 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5386 |
| 15 | CVE-2017-5387 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5387 |
| 16 | CVE-2017-5388 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5388 |
| 17 | CVE-2017-5389 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5389 |
| 18 | CVE-2017-5390 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5390 |
| 19 | CVE-2017-5391 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5391 |
| 20 | CVE-2017-5392 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5392 |
| 21 | CVE-2017-5393 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5393 |
| 22 | CVE-2017-5394 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5394 |
| 23 | CVE-2017-5395 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5395 |
| 24 | CVE-2017-5396 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-01/#CVE-2017-5396 |
| 25 | CVE-2017-5397 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-04/#CVE-2017-5397 |
| 26 | CVE-2017-5398 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5398 |
| 27 | CVE-2017-5399 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5399 |
| 28 | CVE-2017-5400 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5400 |
| 29 | CVE-2017-5401 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5401 |
| 30 | CVE-2017-5402 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5402 |
| 31 | CVE-2017-5403 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5403 |
| 32 | CVE-2017-5404 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5404 |
| 33 | CVE-2017-5405 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5405 |
| 34 | CVE-2017-5406 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5406 |
| 35 | CVE-2017-5407 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5407 |
| 36 | CVE-2017-5408 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5408 |
| 37 | CVE-2017-5409 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5409 |
| 38 | CVE-2017-5410 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5410 |
| 39 | CVE-2017-5411 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5411 |
| 40 | CVE-2017-5412 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5412 |
| 41 | CVE-2017-5413 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5413 |
| 42 | CVE-2017-5414 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5414 |
| 43 | CVE-2017-5415 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5415 |
| 44 | CVE-2017-5416 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5416 |
| 45 | CVE-2017-5417 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5417 |
| 46 | CVE-2017-5418 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5418 |
| 47 | CVE-2017-5419 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5419 |
| 48 | CVE-2017-5420 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5420 |
| 49 | CVE-2017-5421 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5421 |
| 50 | CVE-2017-5422 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5422 |
| 51 | CVE-2017-5425 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5425 |
| 52 | CVE-2017-5426 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5426 |
| 53 | CVE-2017-5427 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-05/#CVE-2017-5427 |
| 54 | CVE-2017-5428 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-08/#CVE-2017-5428 |
| 55 | CVE-2017-5429 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5429 |
| 56 | CVE-2017-5430 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5430 |
| 57 | CVE-2017-5432 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5432 |
| 58 | CVE-2017-5433 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5433 |
| 59 | CVE-2017-5434 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5434 |
| 60 | CVE-2017-5435 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5435 |
| 61 | CVE-2017-5436 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5436 |
| 62 | CVE-2017-5438 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5438 |
| 63 | CVE-2017-5439 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5439 |
| 64 | CVE-2017-5440 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5440 |
| 65 | CVE-2017-5441 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5441 |
| 66 | CVE-2017-5442 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5442 |
| 67 | CVE-2017-5443 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5443 |
| 68 | CVE-2017-5444 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5444 |
| 69 | CVE-2017-5445 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5445 |
| 70 | CVE-2017-5446 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5446 |
| 71 | CVE-2017-5447 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5447 |
| 72 | CVE-2017-5448 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5448 |
| 73 | CVE-2017-5449 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5449 |
| 74 | CVE-2017-5450 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5450 |
| 75 | CVE-2017-5451 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5451 |
| 76 | CVE-2017-5452 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5452 |
| 77 | CVE-2017-5453 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5453 |
| 78 | CVE-2017-5454 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5454 |
| 79 | CVE-2017-5455 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5455 |
| 80 | CVE-2017-5456 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5456 |
| 81 | CVE-2017-5458 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5458 |
| 82 | CVE-2017-5459 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5459 |
| 83 | CVE-2017-5460 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5460 |
| 84 | CVE-2017-5461 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5461 |
| 85 | CVE-2017-5462 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5462 |
| 86 | CVE-2017-5463 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5463 |
| 87 | CVE-2017-5464 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5464 |
| 88 | CVE-2017-5465 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5465 |
| 89 | CVE-2017-5466 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5466 |
| 90 | CVE-2017-5467 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5467 |
| 91 | CVE-2017-5468 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5468 |
| 92 | CVE-2017-5469 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-10/#CVE-2017-5469 |
| 93 | CVE-2017-5031 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-14/#CVE-2017-5031 |
| 94 | CVE-2017-5470 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-5470 |
| 95 | CVE-2017-5471 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-5471 |
| 96 | CVE-2017-5472 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-5472 |
| 97 | CVE-2017-7749 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7749 |
| 98 | CVE-2017-7750 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7750 |
| 99 | CVE-2017-7751 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7751 |
| 100 | CVE-2017-7752 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7752 |
| 101 | CVE-2017-7754 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7754 |
| 102 | CVE-2017-7755 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7755 |
| 103 | CVE-2017-7756 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7756 |
| 104 | CVE-2017-7757 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7757 |
| 105 | CVE-2017-7758 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7758 |
| 106 | CVE-2017-7759 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7759 |
| 107 | CVE-2017-7760 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7760 |
| 108 | CVE-2017-7761 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7761 |
| 109 | CVE-2017-7762 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7762 |
| 110 | CVE-2017-7763 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7763 |
| 111 | CVE-2017-7764 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7764 |
| 112 | CVE-2017-7765 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7765 |
| 113 | CVE-2017-7766 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7766 |
| 114 | CVE-2017-7767 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7767 |
| 115 | CVE-2017-7768 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7768 |
| 116 | CVE-2017-7770 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7770 |
| 117 | CVE-2017-7778 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-15/#CVE-2017-7778 |
| 118 | CVE-2017-7753 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7753 |
| 119 | CVE-2017-7779 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7779 |
| 120 | CVE-2017-7780 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7780 |
| 121 | CVE-2017-7781 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7781 |
| 122 | CVE-2017-7782 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7782 |
| 123 | CVE-2017-7783 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7783 |
| 124 | CVE-2017-7784 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7784 |
| 125 | CVE-2017-7785 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7785 |
| 126 | CVE-2017-7786 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7786 |
| 127 | CVE-2017-7787 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7787 |
| 128 | CVE-2017-7788 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7788 |
| 129 | CVE-2017-7789 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7789 |
| 130 | CVE-2017-7790 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7790 |
| 131 | CVE-2017-7791 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7791 |
| 132 | CVE-2017-7792 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7792 |
| 133 | CVE-2017-7794 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7794 |
| 134 | CVE-2017-7796 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7796 |
| 135 | CVE-2017-7797 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7797 |
| 136 | CVE-2017-7798 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7798 |
| 137 | CVE-2017-7799 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7799 |
| 138 | CVE-2017-7800 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7800 |
| 139 | CVE-2017-7801 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7801 |
| 140 | CVE-2017-7802 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7802 |
| 141 | CVE-2017-7803 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7803 |
| 142 | CVE-2017-7804 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7804 |
| 143 | CVE-2017-7806 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7806 |
| 144 | CVE-2017-7807 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7807 |
| 145 | CVE-2017-7808 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7808 |
| 146 | CVE-2017-7809 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-18/#CVE-2017-7809 |
| 147 | CVE-2017-7793 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7793 |
| 148 | CVE-2017-7805 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7805 |
| 149 | CVE-2017-7810 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7810 |
| 150 | CVE-2017-7811 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7811 |
| 151 | CVE-2017-7812 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7812 |
| 152 | CVE-2017-7813 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7813 |
| 153 | CVE-2017-7814 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7814 |
| 154 | CVE-2017-7815 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7815 |
| 155 | CVE-2017-7816 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7816 |
| 156 | CVE-2017-7817 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7817 |
| 157 | CVE-2017-7818 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7818 |
| 158 | CVE-2017-7819 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7819 |
| 159 | CVE-2017-7820 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7820 |
| 160 | CVE-2017-7821 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7821 |
| 161 | CVE-2017-7822 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7822 |
| 162 | CVE-2017-7823 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7823 |
| 163 | CVE-2017-7824 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7824 |
| 164 | CVE-2017-7825 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-21/#CVE-2017-7825 |
| 165 | CVE-2017-7826 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7826 |
| 166 | CVE-2017-7827 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7827 |
| 167 | CVE-2017-7828 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7828 |
| 168 | CVE-2017-7830 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7830 |
| 169 | CVE-2017-7831 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7831 |
| 170 | CVE-2017-7832 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7832 |
| 171 | CVE-2017-7833 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7833 |
| 172 | CVE-2017-7834 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7834 |
| 173 | CVE-2017-7835 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7835 |
| 174 | CVE-2017-7836 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7836 |
| 175 | CVE-2017-7837 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7837 |
| 176 | CVE-2017-7838 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7838 |
| 177 | CVE-2017-7839 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7839 |
| 178 | CVE-2017-7840 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7840 |
| 179 | CVE-2017-7842 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-24/#CVE-2017-7842 |
| 180 | CVE-2017-7843 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-27/#CVE-2017-7843 |
| 181 | CVE-2017-7844 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-27/#CVE-2017-7844 |
| 182 | CVE-2017-7845 | https://www.mozilla.org/en-US/security/advisories/mfsa2017-29/#CVE-2017-7845 |
* --------------------------------------------------------------------------------------------------- *
| {
"pile_set_name": "StackExchange"
} |
Q:
Recommendations on a backend scheduling app?
We currently use SQL Server, a BPM engine, win services, and even the Windows Task Scheduler to fire off scheduled items. Most are web service invocations, but some are FTP pull downs and whatnot. I know there are good back-end scheduling apps out there that financial companies, and other process heavy industries use for things like this. Are there some decent ones out there that will simply let us call endpoints at regular intervals, and maybe script a bit to decrypt the FTP downloads?
I'm over maintaining all of these different ways we have, and still none are working 100%. some of our business processes are "awesome" where they need to run on a Monday, then Wednesday, then wait for 2 weeks before running again.
Thanks.
A:
Quartz.NET may fit your needs
| {
"pile_set_name": "StackExchange"
} |
Q:
AS3 Trigger event with object on top only
I have a bunch of MovieClips layered on top of each other (the same size), and each one has a MouseEvent.CLICK event associated with it. I only want the one on top (I'll be adding more to the list) to trigger and the rest to do nothing (unless the top gets removed, then the new "top" gets the click event).
How would I accomplish something like this?
A:
There are different ways to try this. The best in my mind is to keep track, such as with an array, of which buttons are there, in order. Deactivate all but the first one in the array, and any time one is removed, remove it from the array and then activate the first button still in the array.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can you extend the list of dummies in pandas.get_dummies?
Suppose I have the following dataset (2 rows, 2 columns, headers are Char0 and Char1):
dataset = [['A', 'B'], ['B', 'C']]
columns = ['Char0', 'Char1']
df = pd.DataFrame(dataset, columns=columns)
I would like to one-hot encode the columns Char0 and Char1, so:
df = pd.concat([df, pd.get_dummies(df["Char0"], prefix='Char0')], axis=1)
df = pd.concat([df, pd.get_dummies(df["Char1"], prefix='Char1')], axis=1)
df.drop(['Char0', "Char1"], axis=1, inplace=True)
which results in a dataframe with column headers Char0_A, Char0_B, Char1_B, Char1_C.
Now, I would like to, for each column, have an indication for both A, B, C, and D (even though, there is currently no 'D' in the dataset). In this case, this would mean 8 columns: Char0_A, Char0_B, Char0_C, Char0_D, Char1_A, Char1_B, Char1_C, Char1_D.
Can somebody help me out?
A:
Use get_dummies with all columns and then add DataFrame.reindex with all possible combinations of columns created by itertools.product:
dataset = [['A', 'B'], ['B', 'C']]
columns = ['Char0', 'Char1']
df = pd.DataFrame(dataset, columns=columns)
vals = ['A','B','C','D']
from itertools import product
cols = ['_'.join(x) for x in product(df.columns, vals)]
print (cols)
['Char0_A', 'Char0_B', 'Char0_C', 'Char0_D', 'Char1_A', 'Char1_B', 'Char1_C', 'Char1_D']
df1 = pd.get_dummies(df).reindex(cols, axis=1, fill_value=0)
print (df1)
Char0_A Char0_B Char0_C Char0_D Char1_A Char1_B Char1_C Char1_D
0 1 0 0 0 0 1 0 0
1 0 1 0 0 0 0 1 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the smallest prime from a substring
In 1946 Erdos and Copeland proved that a certain number is a normal number, i.e. the digits in its decimal expansion are uniformly distributed.
Users will input a sequence of digits and you will find the smallest prime that contains that string in base 10.
Example:
input -> output
"10" -> 101
"03" -> 103
"222" -> 2221
"98765" -> 987659
Shortest code in bytes wins. I do know that some languages (mathematica, sage, pari-gp...) come with built-in functions related to primes. -50 bytes if your program doesn't rely on such functions. Don't try to cheat on this please, if your language already has a huge advantage don't claim the bonus.
Edit
According to a few comments below, the smallest prime that contains "03" is 3. Does this really make a difference? The only thing I can think of is that maybe numbers are easier to handle than strings.
In cases like "03" the preferred output would be 103. However, I don't consider it to be the fundamental part of your program, so you're free to ignore any leading zero if it grants you a lower byte count.
A:
Golfscipt, 33 32 bytes = -18 score
2{:x,2>{x\%!},!!x`3$?)!|}{)}/;;x
Explanation:
2{...}{)}/ - starting with 2, while something is true, increment the top of the stack
;;x - discard the intermediate values collected by {}{}/ and the input, then put the last value tested there
:x,2> - store the value as x, then produce a list from 2 to x-1
{x\%!},!! - keep those that x is divisible by, then coerce to boolean (not empty)
x`3?)! - look up the input in the text form of x (-1 if not found), increment, negate.
| - or
A:
Haskell program, 97 characters = 47 score
main=getLine>>= \i->print$head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x]
Haskell function, 75 characters = 25 score
p i=head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x]
the type of p is (Integral a, Show a) => [Char] -> a. If you supply your own integral type, you can lookup by infix in your own representation of those values. The standard Integer uses the expected decimal notation for integers.
Not very fast. Quadratic in the value (not size) of the output.
ungolfed version:
import Data.List
leastPrime infix = head $ filter prime' [2..]
where prime' x = all (\n-> x`mod`n /= 0) [2..x-1]
&& i `isInfixOf` show x
main = print . leastPrime =<< getLine
example:
Prelude> let p i=head$[x|x<-[2..],all((/=0).mod x)[2..x-1],i`Data.List.isInfixOf`show x]
Prelude> p "0"
101
Prelude> p "00"
1009
Prelude> p "000" -- long pause
10007
A:
Java - 175 characters.
class s{public static void main(String[]a){int i,n=2,p;for(;;){p=1;for(i=3;i<n;i++)if(n%i==0)p=0;if((n==2||p>0)&&(""+n).indexOf(a[0])>=0) {System.out.println(n);break;}n++;}}}
| {
"pile_set_name": "StackExchange"
} |
Q:
Bind a record in Treelist
I'm facing issue in binding single row to the treelist. In my application I have a two forms. first form contains treelist it will contain list of rows.
I need a selected row from the list. Using
public object selectedRow
{
return treelist.GetDataRecordByNode(treelist.FocusedNode)
}
using this code I get the selected row.
In second Form, I'm trying to bind that row.
public void row(selectedRow)
{
treelist2.DataSource=selectedRow; //I get the row value here.
}
But data not able to shown in second treelist. what step I need to do to bind a selectedrow to second treelist.
A:
the DataSource should be an IEnumerable-type.
try something like this (pseudo-code ahead):
public void row(selectedRow)
{
List<yourType> list = new List<yourType>();
list.Add(selectedRow);
treelist2.DataSource=list;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
The graph of Rule 110 and vertices degree
Consider the elementary cellular automaton called Rule 110 (famous for being Turing complete):
It induces a map $R: \mathbb{N} \to \mathbb{N}$ such that the binary representation of $R(n)$ is that of $n$ after the application of Rule 110. For examples, $R(0)=0$, $R(1)=3$, $R(2)=6$ and $R(3)=7$.
See below the illustration for $R(571)=1647$:
There is an OEIS sequence computing $R(n)$ for $n<2^{10}$: A161903.
Definition: Let $\mathcal{G}$ be the graph with $\mathbb{N}$ as set of vertices and $\{\{n,R(n)\}, n \in \mathbb{N} \}$ as set of edges.
The graph $\mathcal{G}$ has infinitely many connected components and its vertices degree is not bounded above.
The proof follows from Lemmas D and E, below.
Question: Is the vertices degree bounded above on each connected component of $\mathcal{G}$?
Lemma A: For $n,r>0$, we have that $2^{r-1}n<R^r(n)<2^{r+1}n$.
Proof: Immediate. $\square$
Lemma B: $R(n)$ is even iff $n$ is even.
Proof: A portion $(\epsilon_1,\epsilon_2,0)$ gives $0$ by applying Rule 110 iff $\epsilon_2=0$. $\square$
Lemma C: For $r,k>0$, $R^r(n) = 2kn$ iff $n=0$.
Proof: If $n>0$ then there is $s \ge 0$ such that $n=2^sm$ and $m$ odd. But $R^r(2^sm) = 2^s R^r(m)$, so $R^r(m)=2km$, it follows by Lemma B that $m$ is even, contradiction. $\square$
Lemma D: For $n,r>0$, $n$ and $2^rn$ are not in the same connected component of $\mathcal{G}$.
Proof: If $n$ and $2^rn$ are in the same connected component then there are $r_1,r_2>0$ such that $R^{r_1}(n) = R^{r_2}(2^rn) = 2^r R^{r_2}(n)$, so by Lemma A, $r_1 = r_2 +r$. Then, $R^{r}(m)=2^rm$ with $m=R^{r_2}(n)$, thus $m=0$ by Lemma C, contradiction. $\square$
Lemma E: For any $n>0$, there is a vertex of $\mathcal{G}$ of (finite) degree $\ge n$.
Proof: The pattern of $r \ge 2$ successive black cells (corresponding to the vertex $2^r-1$) is the image of any pattern of $r-1$ cells without successive white cells, without three successive black cells and whose first and last cells are black, see for example below with $r=27$:
Clearly, for $r$ large enough, the vertex $2^r-1$ has degree $\ge n$. $\square$
Exercise: Show that $|R^{-1} (\{ 2^r-1 \}) | = \sum_{2a+b = r} {a \choose b}$, known as the Padovan sequence.
Bonus question: What is the sequence $\mathcal{S}$ of minimal numbers of the connected components of $\mathcal{G}$?
Note that $\mathcal{S} \subset \mathbb{N} \setminus R(\mathbb{N}^*) = \{0, 1, 2, 4, 5, 8, 9, 10, 11, 16, 17, 18, 19, \dots \}$, so:
$\{0,1,2,4,8\} \subset \mathcal{S}$, by Lemmas B and D.
$5 \in \mathcal{S}$ iff $\forall r_1, r_2>0$ then $R^{r_1}(1) \neq R^{r_2}(5)$.
$11 \not \in \mathcal{S}$ because $R^4(1) = R(11)=31$.
I don't know for the other numbers appearing above.
A search for "$0, 1, 2, 4, 5, 8, 9, 10, 16, 17, 18$" gives one result only, the Fibbinary numbers $\mathcal{F}$, i.e. the integers whose binary representation contains no consecutive ones (the number of such numbers with $n$ bits is the $n$th Fibonacci number). It is related to Zeckendorf's theorem.
Is it true that $\mathcal{F} \subseteq \mathcal{S}$, or even $\mathcal{F} = \mathcal{S}$?
Note that $\mathcal{F} \subset \mathbb{N} \setminus R(\mathbb{N}^*)$ because a portion $(0,0,1,\epsilon)$ gives $(1,1)$ by applying Rule 110.
I don't know whether $19 \in \mathcal{S}$, but $19 \not \in \mathcal{F}$.
A:
I guess I'll indulge in my guilty pleasure a bit. The connected component of the number $1$ has unbounded degree.
Let $X = \{x \in \{0,1\}^{\omega} \;|\; \sum x < \infty\}$, the finite support configurations (which you identified with the naturals) and let $f : X \to X$ be rule $110$ with left and right flipped. After a lot of trial and error I managed to figure out this is called rule 124 in Wolfram's (very convenient and intuitive) naming scheme. This is just so natural numbers go to the right.
We will show that the connected component of the configuration $x = 1000...$ satisfies that for all $k \in \mathbb{N}$ there are infinitely many $n$ such that $f^n(x)$ has at least $k$ preimages in $X$. Let $y \in \{0,1\}^{\omega \times \omega}$ be the spacetime diagram of $x$, so $y_{(i,0)} = x_i$ and $y_{(i,j+1)} = f((y_{(h,j)})_h)_i$. The key to proving it is the following:
The set $\{(m,n) \;|\; y_{(m,n)} = 1\}$ is semilinear.
Semilinear subsets of $\mathbb{Z}^d$ are finite unions of linear sets, which in turn are sets of the form $a + V$ where $V = \langle v_1,v_2,...,v_n \rangle$ where $\langle \cdots \rangle$ denotes the smallest submonoid containing the $v_i$. Equivalently it means definability in Presburger arithmetic.
I won't actually give a precise proof, but this is seen from a simulation of the first ~3000 steps of evolution, and unless I've missed some very subtle period-breaking phenomenon -- which I doubt because eyes usually jump at those --, this should not take long to prove rigorously by pen-and-paper, or by computer. (You could (at least in theory) do it in Walnut, since semilinear implies $k$-automatic, presumably there are also direct implementations of Presburger arithmetic.)
Now, all we need to observe is that in some of the periodic growing areas of $y$ (there are two) you can locate a diamond, i.e. a word $w$ such that the preimage used above it is $u$, and there is another word $v$ with the same image $w$ and the same two left- and rightmost symbols. Then more and more instances of $u$ appear on the line above and you can change any subset of them to $v$.
For all $k$, $y$ has a row with at least $k$ disjoint occurrences of $01011101100 \mapsto 111011111$
any subset of which can be changed to $01100101100 \mapsto 111011111$.
(Those are in terms of the flipped rule. In terms of $110$, these would be $00110111010 \mapsto 111110111$ vs $00110100110 \mapsto 111110111$. Also, I write $u \mapsto w$ for the usual application of the rule to words, so it shortens them by one on both sides.)
Description of spacetime
I will describe what is seen in a non-rigorous fashion, but of course the finite steps are completely proved by just seeing them in the simulator, and given these initial steps, as I've stated above, the final conclusion is something that can be proved by pen and paper (disclaimer: I did not actually write a proof, as it is still a lot of work).
I recommend drawing a spacetime diagram yourself, I used Golly and you can find Golly compatible rule files at the end of this post.
So, the support will grow steadily as a triangle, the leftmost border stays put (as you observed) and the right border moves at speed $1$. After around 100 steps, the roughly 70 rightmost cells of the spacetime diagram form a complicated glider, then there is a slightly denser area, then there is another glider, and the rest is again this denser stuff. (The leftmost "glider" is not really a glider, because it's not moving periodically, but in this informal description I use this term anyway.) We can already observe that the rightmost glider will never change its behavior as it is evolving with a period of 16 and moving at the speed of light. But that is not enough to solve your question.
The pattern looks nice for a few hundred steps, but around 600 steps the glider on the left suddenly blows up!
Fast forward to step 1200 (lots of things happen on the way) and you have two gliders moving to the right. Now the leftmost one suddenly turns into a left-going glider (marked with a green 1 in the figure). Then the central glider suddenly disappears at step 2086 (marked with a green 2), and right after that the leftmost glider hits the left boundary at step 2160 and turns into another glider going to the right.
It takes a few hits from glider gunfire, but then seems to become resistant to it.
Fast-forward a few thousand steps and it is still going strong.
In fact...
there no more surprises!
You can now prove (by induction) that this pattern persists: the glider on the left keeps moving at speed $(18, 213)$, and shoots additional gliders to the left which hit the left boundary every $140$ steps, and the rightmost glider sends additional gliders periodically, which hit the left glider but don't destroy it. The phases match up after some time, which is really the reason why nothing strange happens.
Alternatively, you can prove as I suggested above that $y$ is semilinear: just write the formulas, and check that this semilinear set is closed under rule $110$: it's decidable whether a given semilinear set is the spacetime diagram of a given CA (for example by the Presburger characterization). I'm sure $y$ is semilinear, because all the things that are happening are is periodic, different types of things happen in areas bounded by rational inequalities (or rational lines), and there are only finitely many phenomena (like, four) going on. And then there's about a million bits of garbage at the beginning, which you just code in.
Ok, so now we need to find occurrences of $01011101100 \mapsto 111011111$. Well, that's one of the steps of one of the gliders that are being gunned periodically from right to left.
Golly compatible rules:
Here's rule 110, call it (e.g.) W110.rule and put it in the Rules folder. Then open it in Golly.
@RULE W110
@TABLE
n_states:2
neighborhood:Moore
symmetries:none
var a={0,1}
var b={0,1}
var c={0,1}
var d={0,1}
var e={0,1}
var f={0,1}
var g={0,1}
# C,N,NE,E,SE,S,SW,W,NW,C'
0,0,0,a,b,c,d,e,0,0
0,0,1,a,b,c,d,e,0,1
0,1,0,a,b,c,d,e,0,1
0,1,1,a,b,c,d,e,0,1
0,0,0,a,b,c,d,e,1,0
0,0,1,a,b,c,d,e,1,1
0,1,0,a,b,c,d,e,1,1
0,1,1,a,b,c,d,e,1,0
And here's rule 124:
@RULE W124
@TABLE
n_states:2
neighborhood:Moore
symmetries:none
var a={0,1}
var b={0,1}
var c={0,1}
var d={0,1}
var e={0,1}
var f={0,1}
var g={0,1}
# C,N,NE,E,SE,S,SW,W,NW,C'
0,0,0,a,b,c,d,e,0,0
0,0,1,a,b,c,d,e,0,0
0,1,0,a,b,c,d,e,0,1
0,1,1,a,b,c,d,e,0,1
0,0,0,a,b,c,d,e,1,1
0,0,1,a,b,c,d,e,1,1
0,1,0,a,b,c,d,e,1,1
0,1,1,a,b,c,d,e,1,0
| {
"pile_set_name": "StackExchange"
} |
Q:
What CSS attribute stops my site squidging up?
I am looking at a website on the internet with the standard centered box design (the entire site is centered in a box and has a border each side). As you shrink it, the border gets smaller but the content stays the same size. This is fine.
However on their site, once you get smaller still, you simply get scrollbars. The content remains untouched. On my site if you do this, things like text and links start to scroll onto multiple lines and the whole site gets broken. How can I keep it the same even when the viewport is small?
A:
You can try this:
#box
{
width: 500px;
/* overflow set to scroll will give you your scroll bars */
overflow: scroll;
}
If you are looking to handle the minimum width, it is a little trickier as min-width is not supported by IE.
You can try this:
#container
{
/* IE will ignore min-width */
min-width: 400px;
/* IE will process the expression below to give you your minimum width, other browsers
will ignore it */
width:expression(document.body.clientWidth < 400? "400px": "auto" );
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can I not instantiate this global as a pointer?
My source file appears to give me an error of which I can't quite understand why it is I'm getting this error, as it appears to be somewhat in vain. What I'd also like to understand is what I can do about this to achieve the same effect. I'll leave out the details for now, but as is shown I would like for this to be a global object pointer.
Code
#include "functions.h"
App::Game* game = new Game;
void display_func() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
game->render_objects();
glFlush();
}
void init(int argc, char** argv) {
glutInit(&argc, argv);
game->init_window();
glutDisplayFunc(display_func);
game->init();
glutMainLoop();
}
Compiler Error
functions.cpp:3:23: error: expected type-specifier before ‘Game’
functions.cpp:3:23: error: cannot convert ‘int*’ to ‘App::Game*’ in initialization
I know I can't initialize this in the header file, so what options do I have?
A:
You need to write
App::Game* game = new App::Game;
(with App::Game instead of Game).
Edited to add: Oh, I should probably explain the error-messages, for the sake of other people getting similar messages for a different reason. They're mostly self-explanatory, once you have the following facts:
A "type-specifier" is something that denotes a type, such as int or char* or string or std::string; in this case, the type-specifier that you needed was App::Game.
"Error: expected X before Y" sounds like it means that Y is fine, as long you insert an X before it; but in fact, it actually isn't saying anything about Y, except perhaps that it's not an X. "Before Y" mostly just helps you find where in the line the parse-error occurred. (In many cases it really is that something is needed before Y — for example, if X is a semicolon, then there's a good chance you dropped the semicolon after a statement or declaration — but in many cases it's actually that something is needed instead of Y. That was the case here.)
int gets mentioned just because the compiler, scrambling to come up with a type-specifier in the hopes of continuing parsing, chooses int as a default. (Had you written int *game = new;, you wouldn't have gotten that second error message.)
| {
"pile_set_name": "StackExchange"
} |
Q:
How polite is おっけーです when it is said by the shop staff to a customer?
Let me describe the scenario first so you can get the nuance better.
I was looking for a new apartment from several agents. An agent "A" to which I will refer for the following explanation provided me with services such as searching for several apartments that conforms to my budget, bringing me to look at the apartments, etc. It was on Friday. As no apartments satisfied me, the staff will provide me with other options in the next Monday.
As I have no time to wait, I go to other agents and I found an apartment on Saturday. Sunday afternoon, there was a call from the agent A saying, when you will come tomorrow? My reply is as follows:
大変申し訳ありません。新しいアパートを見つけてしまいましたので・・・
And his respond is
オッケーです
Question
How polite is おっけーです when it is said by the shop staff to a customer?
Is there any feel of disappointment in this context?
A:
オッケーです on its own does not have a feel of disappointment. It's just "I understood" or "okay," which can be said with or without disappointment. (But writing it with hiragana (おっけーです) is only acceptable in a chat with your close friends. You heard it, right?)
オッケーです is relatively colloquial and casual. It's definitely inappropriate if this is said by a receptionist of a luxury hotel you visit for the first time. But some experts like real estate agents and physicians tend to drop keigo (at least very formal ones) fairly quickly once you are familiar with them. Saying オッケーです with a smile is not necessarily a bad word choice.
Another possibility is that he just tried to speak in easy Japanese. We all know keigo is difficult. Depending on how fluent you are, people may avoid using difficult keigo like 承知致しました even in a business setting.
A:
It is not overly formal, but it is not impolite. I'd say it is on the friendly side. So unless there was some hint in the way they said it to indicate that they were disappointed, I'd not think twice about it.
It would be inappropriate if the setting called for very formal language, but I've never found interactions with real estate agents to be that way. They are trying to build rapport with you in general, so it is usually a much less formal setting than customer interactions where no relationship is required.
| {
"pile_set_name": "StackExchange"
} |
Q:
Merge 2 pdf files giving me an empty pdf
I am using the following standard code:
# importing required modules
import PyPDF2
def PDFmerge(pdfs, output):
# creating pdf file merger object
pdfMerger = PyPDF2.PdfFileMerger()
# appending pdfs one by one
for pdf in pdfs:
with open(pdf, 'rb') as f:
pdfMerger.append(f)
# writing combined pdf to output pdf file
with open(output, 'wb') as f:
pdfMerger.write(f)
def main():
# pdf files to merge
pdfs = ['example.pdf', 'rotated_example.pdf']
# output pdf file name
output = 'combined_example.pdf'
# calling pdf merge function
PDFmerge(pdfs = pdfs, output = output)
if __name__ == "__main__":
# calling the main function
main()
But when I call this with my 2 pdf files (which just contain some text), it produces an empty pdf file, I am wondering how this may be caused?
A:
The problem is that you're closing the files before the write.
When you call pdfMerger.append, it doesn't actually read and process the whole file then; it only does so later, when you call pdfMerger.write. Since the files you've appended are closed, it reads no data from each of them, and therefore outputs an empty PDF.
This should actually raise an exception, which would have made the problem and the fix obvious. Apparently this is a bug introduced in version 1.26, and it will be fixed in the next version. Unfortunately, while the fix was implemented in July 2016, there hasn't been a next version since May 2016. (See this issue.)
You could install directly off the github master (and hope there aren't any new bugs), or you could continue to wait for 1.27, or you could work around the bug. How? Simple: just keep the files open until the write is done:
with contextlib.ExitStack() as stack:
pdfMerger = PyPDF2.PdfFileMerger()
files = [stack.enter_context(open(pdf, 'rb')) for pdf in pdfs]
for f in files:
pdfMerger.append(f)
with open(output, 'wb') as f:
pdfMerger.write(f)
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular2: Creating child components programmatically
Question
How to create child components inside a parent component and display them in the view afterwards using Angular2? How to make sure the injectables are injected correctly into the child components?
Example
import {Component, View, bootstrap} from 'angular2/angular2';
import {ChildComponent} from './ChildComponent';
@Component({
selector: 'parent'
})
@View({
template: `
<div>
<h1>the children:</h1>
<!-- ??? three child views shall be inserted here ??? -->
</div>`,
directives: [ChildComponent]
})
class ParentComponent {
children: ChildComponent[];
constructor() {
// when creating the children, their constructors
// shall still be called with the injectables.
// E.g. constructor(childName:string, additionalInjectable:SomeInjectable)
children.push(new ChildComponent("Child A"));
children.push(new ChildComponent("Child B"));
children.push(new ChildComponent("Child C"));
// How to create the components correctly?
}
}
bootstrap(ParentComponent);
Edit
I found the DynamicComponentLoader in the API docs preview. But I get the following error when following the example: There is no dynamic component directive at element 0
A:
This is generally not the approach I would take. Instead I would rely on databinding against an array that will render out more child components as objects are added to the backing array. Essentially child components wrapped in an ng-for
I have an example here that is similar in that it renders a dynamic list of children. Not 100% the same, but seems like the concept is still the same:
http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0
A:
Warning: DynamicComponentLoader has been deprecated in RC.4
In Angular 2.0, loadIntoLocation method of DynamicComponentLoader serve this purpose of creating parent-child relationship. By using this approach you can dynamically create relationship between two components.
Here is the sample code in which paper is my parent and bulletin is my child component.
paper.component.ts
import {Component,DynamicComponentLoader,ElementRef,Inject,OnInit} from 'angular2/core';
import { BulletinComponent } from './bulletin.component';
@Component({
selector: 'paper',
templateUrl: 'app/views/paper.html'
}
})
export class PaperComponent {
constructor(private dynamicComponentLoader:DynamicComponentLoader, private elementRef: ElementRef) {
}
ngOnInit(){
this.dynamicComponentLoader.loadIntoLocation(BulletinComponent, this.elementRef,'child');
}
}
bulletin.component.ts
import {Component} from 'angular2/core';
@Component({
selector: 'bulletin',
template: '<div>Hi!</div>'
}
})
export class BulletinComponent {}
paper.html
<div>
<div #child></div>
</div>
Few things you needs to be take care of are mentioned in this answer
A:
You should use ComponentFactoryResolver and ViewElementRef to add component at runtime.Let's have a look at below code.
let factory = this.componentFactoryResolver.resolveComponentFactory(SpreadSheetComponent);
let res = this.viewContainerRef.createComponent(factory);
Put the above code inside your ngOnInit function and replace "SpreadSheetComponent" by your component name.
Hope this will work.
| {
"pile_set_name": "StackExchange"
} |
Q:
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
I am getting these Warning Msg in my Logger. I am using Log4j and Tiles too. Before using Tiles these were not comming. Below are the Warning logs:
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.info: 31 Detected container provider Struts XML configuration provider (struts.xml) needs to be reloaded. Reloading all providers.
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.info: 31 Parsing configuration file [struts-default.xml]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.info: 31 Parsing configuration file [struts-plugin.xml]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.info: 31 Parsing configuration file [struts.xml]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.info: 31 Overriding property struts.i18n.reload - old value: false new value: true
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.info: 31 Overriding property struts.configuration.xml.reload - old value: false new value: true
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.info: 31 Loading global messages from ApplicationResources
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [struts.actionMapping]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [org.apache.catalina.jsp_file]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [org.apache.catalina.jsp_file]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [struts.valueStack]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 No configuration found for the specified action: 'userLogin.action' in namespace: '/jsp/login'. Form action defaulting to 'action' attribute's literal value.
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [.freemarker.Request]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [.freemarker.RequestParameters]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [templateDir]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [theme]
com.opensymphony.xwork2.util.logging.commons.CommonsLogger.warn: 45 Could not find property [fieldErrors]
Please help me on this. My Logger file size is increasing and it is making my logger not usable..???
A:
For removing these warnings just add below lines of code in your log4j.xml file:
<logger name="com.opensymphony.xwork2.util.logging.commons.CommonsLogger">
<level value="warn"/>
</logger>
| {
"pile_set_name": "StackExchange"
} |
Q:
Credibility of using English in non-English-speaking worlds
In the Magic Tree House series, two ordinary English-speaking kids travel to different faraway lands through a portal. Every character they meet, whether it's ancient Greece or ancient China, speaks English. However, this series was aimed at little kids, and when you're writing for an older audience, do you have to explain away the language barrier conundrum?
More importantly, if your story employs lots of rhyming riddles and 'lost prophecies' from other worlds, would the story instantly lose its credibility if they all happen to be in English? (E.g., main character discovers lost scroll in Egypt. It's a rhyme in English!)
I know suspension of belief is required for all fantasy stories, but at what point do you try to explain the mechanics, and when can you just hand-wave it all under the rug?
A:
The notion of "willing suspension of disbelief" is one of the most misleading phrases in the literature of writing (right up there with "show don't tell"). It is very much worth reading Tolkien's On Fairy Stories, in which he offers an extensive critique of the concept.
Tolkien's argument is essentially this: a story involves immersing a reader in a sub-created world. Their participation and belief in the sub-created world depends on the internal consistency of the world, not on its correspondence to the real world.
Secondly, stories are lenses, not windows. They exist to focus the reader's attention on certain aspects of the human experience and one of the principal devices by which they do this is to simply omit many of the details of ordinary life that real people would have to deal with. Thus characters seldom eat except as something incidental to a meeting or a party. They virtually never have to relieve themselves (except in broad comedy). Virtually no use of computers in all of literature is remotely realistic. Crimes are not really solved in a day. Etc. etc.
A story needs to be self consistent. Whatever it says or suggests about the rules of the story world must be followed consistently within the story. If you decide to ignore language barriers in a story, go for it, but make sure that there is not anything else about the way the story is told that suggests that they matter.
Note that when I say "story world", I don't mean exactly what the folks who indulge in that odd hobby of worldbuilding mean. It is not about creating a world with self-consistent rules and then setting a story in it. It is much more about the conventions of the telling itself than the objective laws of a world, real or imaginary. It is a tacit compact between the writer and the reader that we are not going to concern ourselves with whole classes of practical problems that would otherwise slow down or get in the way of telling the parts of the story that we actually care about. This is not a rare or unusual thing. In fact, it is probably universal. Certainly no contemporary TV show could function without this convention. (In the real world, for instance, all the characters in any cop show would be invalided out with severe PTSD by the end of the first season.)
If you have not noticed that storytelling works this way, well, that just shows how ingrained this feature of storytelling is. We are not consciously aware of it most of the time unless it breaks down. But it is there in everything we read and watch if we only take a moment to look for it.
So, if you want to ignore the language issues, ignore the language issues. Just make sure that you tell the story in a way that people accept (without particularly noticing) that languages issues, like going to the bathroom, are not something we are going to concern ourselves with in this story.
A:
Consider such works as 'Lord of the Rings'. Do you really think that anyone beyond the Shire would speak English, and yet they all do? (Yes there are other languages, but consider how they are introduced and used.)
Then think about sci-fi novels: set in the future and on other worlds and yet the language is still English that we can understand today (consider Shakespeare only died 400 years ago and how much the language has changed). Readers accept English without question.
I don't know the Magic Tree House and so can't comment on it specifically, but I do know that adults accept English speaking as the norm: see Star Trek and Doctor Who.
You just have to make it believable.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set selected Envelope area to MapView in Arcgis Android?
I have loaded an offline .geodatabase esri map. I am drawing an Envelope on top of MapView. Now I want the Envelope area to fit the MapView.
I tried below -
mMapView.setExtent(selectedAreaGraphic.getGeometry());
Am getting the SelectedAreaGraphic from the Graphic layer using the UniqueID at the time of adding the grapic.
It dosen't fill completely the selected Envelope area on MapView.
A:
You can get the Envelope's drawn graphicIDs i.e[the rectangle shape representing Area] from Graphic Layer.
Now you can query the Envelope with Graphic Geometry from these graphicIDs.
Merge all those Envelope point to new Envelope.
Envelope env = new Envelope();
Envelope NewEnv = new Envelope();
for (int i: mGraphicsLayer.getGraphicIDs()) {
try {
Polygon p = (Polygon) mGraphicsLayer.getGraphic(i).getGeometry();
p.queryEnvelope(env);
NewEnv.merge(env);
} catch (Exception e) {
e.printStackTrace();
}
}
Now set MapView extent to new Envelope.
mMapView.setExtent(NewEnv);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to define General deterministic function in PyMC
In my model, I need to obtain the value of my deterministic variable from a set of parent variables using a complicated python function.
Is it possible to do that?
Following is a pyMC3 code which shows what I am trying to do in a simplified case.
import numpy as np
import pymc as pm
#Predefine values on two parameter Grid (x,w) for a set of i values (1,2,3)
idata = np.array([1,2,3])
size= 20
gridlength = size*size
Grid = np.empty((gridlength,2+len(idata)))
for x in range(size):
for w in range(size):
# A silly version of my real model evaluated on grid.
Grid[x*size+w,:]= np.array([x,w]+[(x**i + w**i) for i in idata])
# A function to find the nearest value in Grid and return its product with third variable z
def FindFromGrid(x,w,z):
return Grid[int(x)*size+int(w),2:] * z
#Generate fake Y data with error
yerror = np.random.normal(loc=0.0, scale=9.0, size=len(idata))
ydata = Grid[16*size+12,2:]*3.6 + yerror # ie. True x= 16, w= 12 and z= 3.6
with pm.Model() as model:
#Priors
x = pm.Uniform('x',lower=0,upper= size)
w = pm.Uniform('w',lower=0,upper =size)
z = pm.Uniform('z',lower=-5,upper =10)
#Expected value
y_hat = pm.Deterministic('y_hat',FindFromGrid(x,w,z))
#Data likelihood
ysigmas = np.ones(len(idata))*9.0
y_like = pm.Normal('y_like',mu= y_hat, sd=ysigmas, observed=ydata)
# Inference...
start = pm.find_MAP() # Find starting value by optimization
step = pm.NUTS(state=start) # Instantiate MCMC sampling algorithm
trace = pm.sample(1000, step, start=start, progressbar=False) # draw 1000 posterior samples using NUTS sampling
print('The trace plot')
fig = pm.traceplot(trace, lines={'x': 16, 'w': 12, 'z':3.6})
fig.show()
When I run this code, I get error at the y_hat stage, because the int() function inside the FindFromGrid(x,w,z) function needs integer not FreeRV.
Finding y_hat from a pre calculated grid is important because my real model for y_hat does not have an analytical form to express.
I have earlier tried to use OpenBUGS, but I found out here it is not possible to do this in OpenBUGS. Is it possible in PyMC ?
Update
Based on an example in pyMC github page, I found I need to add the following decorator to my FindFromGrid(x,w,z) function.
@pm.theano.compile.ops.as_op(itypes=[t.dscalar, t.dscalar, t.dscalar],otypes=[t.dvector])
This seems to solve the above mentioned issue. But I cannot use NUTS sampler anymore since it needs gradient.
Metropolis seems to be not converging.
Which step method should I use in a scenario like this?
A:
You found the correct solution with as_op.
Regarding the convergence: Are you using pm.Metropolis() instead of pm.NUTS() by any chance? One reason this could not converge is that Metropolis() by default samples in the joint space while often Gibbs within Metropolis is more effective (and this was the default in pymc2). Having said that, I just merged this: https://github.com/pymc-devs/pymc/pull/587 which changes the default behavior of the Metropolis and Slice sampler to be non-blocked by default (so within Gibbs). Other samplers like NUTS that are primarily designed to sample the joint space still default to blocked. You can always explicitly set this with the kwarg blocked=True.
Anyway, update pymc with the most recent master and see if convergence improves. If not, try the Slice sampler.
| {
"pile_set_name": "StackExchange"
} |
Q:
Autoplay flash in ie8 when using a html5 to flash player fallback
I have a html5 player with flash fallback as follows:
<div class="divVideoWrapper">
<div class="divVideo">
<div class="divVideoContainer">
<div id="videoPlayerChange" class="video_player">
<video class="scrPoster" controls="controls" poster="http://static.e-talemedia.net/content/images/testfirstframe.png" >
<source id="scrVideomp4" class="scrVideomp4" src="http://static.e-talemedia.net/content/video/bosch/testfeaturevideo.mp4" type="video/mp4" />
<source id="scrVideowebm" class="scrVideowebm" src="http://static.e-talemedia.net/content/video/bosch/testfeaturevideo.webm" type="video/webm" />
<source id="scrVideogg" class="scrVideogg" src="http://static.e-talemedia.net/content/video/bosch/testfeaturevideo.ogv" type="video/ogg" />
<object id="objFlash" width="352" height="198">
<param name="movie" value="http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf">
</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="330" height="185" flashvars="src=http://static.e-talemedia.net/content/video/bosch/testfeaturevideo.mp4&poster=http://static.e-talemedia.net/content/images/testfirstframe.png"></embed>
</object>
</video>
<div class="custom_controls">
<div class="divBigButton">
<a class="playBig" title="playBig"></a>
</div>
<a class="play" title="Play"></a><a class="pause" title="Pause"></a>
<div class="volumeWrapper">
<div class="volume">
<div class="volume_slider">
</div>
<a class="mute" title="Mute"></a><a class="unmute" title="Unmute"></a>
</div>
</div>
<div class="timer">
00:00</div>
<div class="time_slider">
</div>
</div>
</div>
<script>
$(function () {
$('.video_player').myPlayer();
});
</script>
When a user clicks on a feature a new video is loaded and in HTML5 it will start playing but in flash it won't. I have tried adding swf&autoStart=true" in the param and autoplay ="yes" and autostart = "true" in the embed part but these don t seem to work - I'm testing it in ie8 as this is the browser that falls back to flash.
Jquery script which changes the video
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$(document).on("click", ".featureLogoText", function () {
var media = $(this).attr('media');
var mediamp4 = media + "mp4";
var mediawebm = media + "webm";
var mediaogv = media + "ogv";
var newPoster = $(this).attr('data-poster');
var html = ' <param name=\"movie\" value=\"http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://fpdownload.adobe.com/strobe/FlashMediaPlayback.swf\" type=\"application/x-shockwave-flash\"allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"330\" height=\"185\" autoplay =\"true\" flashvars=\"src=' + mediamp4 + '&poster=' + newPoster + '\"></embed>';
$("#objFlash").html("");
$("#objFlash").append(html);
var displayText = $(this).text();
$(".divBottomRight .nowPlaying").text("Now Playing: ");
$(".divBottomRight .nowPlayFeature").text(displayText);
var number = $(this).attr('data-number');
});
});
//]]>
</script>
Any help much appreciated!
Thanks
A:
Found the answer b clicking on one of the links to the left!
get embeded flash to autoPlay
so basically i replaced my &poster = in the embed in the flashvars with &autoPlay=true"
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there some limit on files logged through syslog?
I have a Postfix mail server running on Ubuntu 8.10 and when /var/log/mail.log or any other file reaches exactly 2GB of data syslog stops writing any data to the file.
Is there some kind of limit for a file logged through syslog?
I'm discussing with my colleagues if we should be doing an hourly logrotate on the files in question, and hoping that will stop them from hitting this limit. If we have 2-3 hours worth of log files it should be enough when they're this large to find any large problems.
A:
Best answer to this is: The limit is a Linux "problem" and not a syslog problem. See the right answer here: http://linuxmafia.com/faq/VALinux-kb/2gb-filesize-limit.html
And an extra good advise: Update your Ubuntu. It's way too old. And for a production server it is a very high security risk. Upgrade at least to Ubuntu 10.4.
A:
Are you running on 32 bits? If so, take a look at 2GB file size limit.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do i call subclass method from superclass when using class hierarchy in objective c
Here is my code:
@interface RootViewController : UIViewController{
}
-(IBAction)btnDetail1_Clicked:(id)sender;
@end
@implementation RootViewController
-(IBAction)btnDetail1_Clicked:(id)sender{
DetailViewController1 *mvcr = [[DetailViewController1 alloc] initWithNibName:@"DetailViewController1" bundle:nil];
[mvcr setDelegate:self];
[self.navigationController pushViewController:mvcr animated:YES];
[mvcr release];
}
@end
@protocol NotifySubclass
@optional
-(void) serviceCall_done;
@end
@interface MasterViewController : UIViewController{
id<NotifySubclass> delegate;
}
@property (retain) id delegate;
-(void) initCallService;
@end
@implementation MasterViewController
@synthesize delegate;
-(void) initCallService{
"My some other code is here."
[self performSelector:@selector(startLoading) withObject:nil afterDelay:5];
}
-(void) startLoading{
"My some other code is here."
[self performSelectorOnMainThread:@selector(loadComplete) withObject:nil waitUntilDone:YES];
}
-(void) loadComplete{
"I want to call DetailViewController1's "serviceCall_done" method from here.
[delegate serviceCall_done];
}
@end
@interface DetailViewController1 : MasterViewController <NotifySubclass>{
}
@end
@implementation DetailViewController1
- (void)viewDidLoad{
[self initCallService];
}
-(void) serviceCall_done{
}
@end
I want to call DetailViewController1's serviceCall_done method from loadCompete method of MasterViewController.
I had tried creating protocol but not getting where exactly i have to write the protocol as I am calling DetailViewController1 from RootViewController.
Can anyone guide me for this ?
A:
You can use NSNotificationCenter for this Post Notification and add observer in all 3 details class. Read some tutorials about NSNotificationCenter.
Here are some tutorials
Tutorail 1
Tutorial 2
Tutorial 3
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you search for substring in ansible group_names?
For a group name hello, I use the following condition in ansible and it works fine:
when: "'hello' in group_names "
Is there a way to use a regular expression if I want to match for keywords hello in the following group_names:
hello
somewhere_hello
hello123
A:
You can select and count items with filters:
when: group_names | select('search','hello') | list | count > 0
| {
"pile_set_name": "StackExchange"
} |
Q:
Knockout binding with hammer.js
I'm trying to combine Hammer.js and knockout.js, but it seem something doesn't work.
I used this function:
var events = ['tap', 'doubletap', 'hold', 'rotate',
'drag', 'dragstart', 'dragend', 'dragleft', 'dragright', 'dragup',
'dragdown', 'transform', 'transformstart',
'transformend', 'swipe', 'swipeleft', 'swiperight',
'swipeup', 'swipedown', 'pinch', 'pinchin', 'pinchout'];
ko.utils.arrayForEach(events, function (eventName) {
ko.bindingHandlers[eventName] = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var origParams = ko.utils.unwrapObservable(valueAccessor()),
params = typeof(origParams) == 'function' ? {handler: origParams} : origParams,
hammerObj = hammer(element, params.options),
args = params.delegate ? [eventName, params.delegate, params.handler] : [eventName, params.handler]
hammerObj.on.apply(hammerObj, args);
}
}
});
For example I'm trying to get drag event for every image that i have on the page so on my HTML I'm haveing that:
<div class="row-fluid" data-bind="foreach: {data: picturesArray}">
<ul class="thumbnails" >
<li class="img-item" data-bind="
doubletap: img.doubletap.bind(img),
drag: img.drag.bind(img)">
<img class="one-img"
style="width: 100px; height: 100px;" data-bind="attr: { src: img.media.m }"/>
</li>
</ul>
</div>
but it doesn't work. on my JS file, the bind methond doesn't called.
A:
Here's how I solved it.
http://plnkr.co/edit/WJnPNsHQIKbbUu7oaD12?p=preview
Javascript
var events = ['tap', 'doubletap', 'hold', 'rotate',
'drag', 'dragstart', 'dragend', 'dragleft', 'dragright', 'dragup',
'dragdown', 'transform', 'transformstart',
'transformend', 'swipe', 'swipeleft', 'swiperight',
'swipeup', 'swipedown', 'pinch', 'pinchin', 'pinchout'];
ko.utils.arrayForEach(events, function (eventName) {
ko.bindingHandlers[eventName] = {
update: function(element, valueAccessor){
var BindingContext = valueAccessor()[0];
var EventToFire = valueAccessor()[1];
var options = {
dragLockToAxis: true,
dragBlockHorizontal: true
};
var hammerTime = new Hammer(element, options);
hammerTime.on(eventName, function(ev){
//Fire the event with the item it was bound to.
EventToFire(BindingContext);
});
}
}
});
Html
<div data-bind="foreach: Elements">
<!-- send yourself and the binding event to the "drag" handler -->
<div class="square" data-bind="drag: [$data, $parent.Drag]">
<div data-bind="text: Test"></div>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Find the maximum of a real function of $2016$ variables
Find the maximum of the function $$f(\bar x)=\sqrt{x_1^2+2x_2^2+......2016x_{2016}^2}$$ $\bar x=(x_1,x_2,....x_{2016}) \in \mathbb{R}^{2016}$
where the domain of $f$ is $$\bar x=(x_1,x_2,....x_{2016}) \in \mathbb{R}^{2016} :\sum_{n=1}^{2016}x_n^2=1.$$
$f^2(\bar x)={x_1^2+2x_2^2+......2016x_{2016}^2}=\sum_{n=1}^{2016}nx_n^2$
I don't know how to use condition $||\bar x||=1$.
A:
You can work step by step.
First of all, the function obviuously reaches its max at the same $\vec x$ as the function $g_1(x)=f(x)^2$, so you can skip the square root.
Now you have $$g_1(x)=x_1^2 + 2x_2^2+\dots + 2016x^2_{2016} = \\=||x|| + x_2^2+2x_3^2+\dots + 2015x_{2016}^2\\=1 + x_2^2+2x_3^2+\dots + 2015x_{2016}^2$$
Now, notice that $g_1$ reaches its maximum on the same point as $$h_1(x)=x_2^2+2x_3^2+\dots + 2015x_{2016}^2$$
so you can safely say that $x_1=0$.
Now, you can use the same trick to define $g_2$ and notice that $x_2=0$.
Or, another way. Once you have $g_1$, you can see that if $x_i\neq 0$ for any $i<2016$, you can always strictly increase the value of $g_1$ by setting $\bar x_i=0$ and $\bar x_{2016}=\sqrt{x_{2016}^2 - x_i^2}$.
This proves that $x_i=0$ for all $i<2016$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Fix wobbly storage shelf
I just built this storage rack for my basement out of 2x4s and plywood. It is relatively stable but does have some front to back wobble. More than I would like. Is there a way to increase the stability of the unit? I've read something about adding diagonal braces but am unsure how exactly that would work. Any help would be much appreciated.
A:
Most things we build are rectangular, and rectangular structures are prone to racking, which is illustrated in this drawing of a deck, but the same problem affects your rectangular shelves:
As you see a structure can collapse due to racking if the joints flex without tearing apart.
There are various ways to counter racking. Other shapes, like triangles and trapezoids, are not prone to racking. In the picture, by adding knee braces, you attach the rectangle to triangles, which are not prone to racking.
Another way is to make joints that are not as flexible, it looks like the vertical boards in the front of your shelf are attached in a way that won't flex and allow your shelf to rack left to right.
Another way to prevent racking is to attach a sheet over the rectangle. For example, if you attached plywood over the sides of your shelf unit, there's no way it could rack front to back. The sheathing doesn't have to cover the whole side. You could add gussets - just a triangle of plywood in the four corners - and make the shelf nice and solid.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best practice for referring to classes in CSS
If you have an HTML page with a class in an element, for instance <div class="myClass">, would it be best to refer to it in the CSS as .myClass or div.myClass?
A:
div.myClass makes the style declaration more specific. In other words, it takes higher priority. So, it's sometimes a good thing to specify it in order to avoid CSS conflicts when you've got many developers onboard a project and people add classes like there's no tomorrow. In other words, if you've got Bob adding:
.myClass {
color: red;
}
and Sarah adds:
div.myClass {
color: blue;
}
Sarah's class will trump Bob's class when you've got:
<div class="myClass">Sarah FTW</div>
You can get make it even more specific by specifying it with the ID, but that's sort of outside the scope of your question. :)
A:
Unless you're going to give something (a non-div) the class "myClass" and style it differently, you should just go with .myClass.
For example, if all .error are color:red, but div.error are background:red as well, you may set up the file to include styles for both .error and div.error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I need always lock before read even if very occasionally write to the memory?
I have a shared data structure that is read in one thread and modified in another thread. However, its data changes very occasionally. Most of time, it is read by the thread. I now have a Mutex (or RW lock) locked before read/write and unlocked after read/write.
Because the data rarely changes, lock-unlock every time it is read seems inefficient. If no change is made to the data, I can get rid of the lock because only read to the same structure can run simultaneously without lock.
My question is:
Is there a lock-free solution that allows me changes the data without a lock?
Or, the lock-unlock in read (one thread, in other words, no contention) don't take much of time/resources (no enter to the kernel) at all?
A:
If there's no contention, not kernel call is needed, but still atomic lock acquisition is needed. If the resource is occupied for a short period of time, then spinning can be attempted before kernel call.
Mutex and RW lock implementations, such as (an usual quality implementation of) std::mutex / std::shared_mutex in C++ or CRITICAL_SECTION / SRW_LOCK in Windows already employ above mentioned techniques on their own. Linux mutexes are usually based on futex, so they also avoid kernel call when it its not needed. So you don't need to bother about saving a kernel call yourself.
And there are alternatives to locking. There are atomic types that can be accessed using lock-free reads and writes, they can always avoid lock. There are other patterns, such as SeqLock. There is transaction memory.
But before going there, you should make sure that locking is performance problem. Because use of atomics may be not simple (although it is simple for some languages and simple cases), and other alternatives have their own pitfalls.
An uncontrolled data race may be dangerous. Maybe not. And there may be very thin boundary between cases where it is and where it is not. For example, copying a bunch of integer could only result in garbage integers occasionally obtained, if integers are properly sized and aligned, then there may be only a mix up, but not garbage value of a single integer, and if you add some more complex type, say string, you may have a crash. So most of the times uncontrolled data race is treated as Undefined Behavior.
| {
"pile_set_name": "StackExchange"
} |
Q:
Another "cannot find symbol"
I´m getting cannot find symbol error in my code (symbol: method setAr(boolean)).
Here is my Main.java file:
class Vehicle {
protected int marchs;
protected int rode;
public void xydar(int km) { System.out.print("\nxydei "+ km +" km!"); }
}
class Car extends Vehicle {
public Car() { this.rode = 4; }
public void xydar(int km) {
super.xydar(km);
System.out.println(" Estou de car!");
}
}
class CarLux extends Car {
private boolean ar;
public CarLux() { this.ar = true; }
public void setAr(boolean newAr) { this.ar = newAr; }
public void xydar(int km) {
super.xydar(km);
if (this.ar)
System.out.println(" ON!");
else System.out.println(" OFF!");
}
}
public class Main {
public static void main(String []args) {
Vehicle moto = new Vehicle();
moto.xydar(90);
Vehicle car1 = new Car();
car1.xydar(100);
Vehicle car2 = new CarLux();
car2.xydar(400);
car2.setAr(false);
car2.xydar(400);
}
}
How can I call setAr() method correctly? Can anyone help me? I´m new to Java.
Thanks in advance.
A:
You need to declare car2 as a CarLux, not a Vehicle.
CarLux car2 = new CarLux();
That's because your setAr() method is defined on CarLux. car2 is currently held in a variable of type Vehicle, so when you call a method of car2 only the methods declared by Vehicle will be available.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to copy from a set sheet when looping through data
I had an earlier question which was kindly answered and I was given the following code which worked perfectly in a test environment where the code was looping through 3 sheets with only 1 sheet of data and 3 columns.
Below is my ammended code to go through 16 columns. The issue however I believe I am facing is when opening a sheet in the live environment the sub workbooks all contain 4 tabs which are "Lookup", "Detail", "Summary" and "Calls".
The code contains For Each sheet In ActiveWorkbook.Worksheets
I am wanting to only take the data in the below code from each workbook in the loop in the "Calls" tab. Can anyone recommend any change to the existing loop to do this?
Sub Theloopofloops()
Dim wbk As Workbook
Dim Filename As String
Dim path As String
Dim rCell As Range
Dim rRng As Range
Dim wsO As Worksheet
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets(Sheet2)
path = "M:\Documents\Call Logger\"
Filename = Dir(path & "*.xlsm")
Set wsO = ThisWorkbook.Sheets("Master")
Do While Len(Filename) > 0
DoEvents
Set wbk = Workbooks.Open(path & Filename, True, True)
For Each sheet In ActiveWorkbook.Worksheets
Set rRng = sheet.Range("A2:A20000")
For Each rCell In rRng.Cells
If rCell <> "" And rCell.Value <> vbNullString And rCell.Value <> 0 Then
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = rCell
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = rCell.Offset(0, 1)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 2).Value = rCell.Offset(0, 2)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 3).Value = rCell.Offset(0, 3)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 4).Value = rCell.Offset(0, 4)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 5).Value = rCell.Offset(0, 5)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 6).Value = rCell.Offset(0, 6)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 7).Value = rCell.Offset(0, 7)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 8).Value = rCell.Offset(0, 8)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 9).Value = rCell.Offset(0, 9)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 10).Value = rCell.Offset(0, 10)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 11).Value = rCell.Offset(0, 11)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 12).Value = rCell.Offset(0, 12)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 13).Value = rCell.Offset(0, 13)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 14).Value = rCell.Offset(0, 14)
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 15).Value = rCell.Offset(0, 15)
End If
Next rCell
Next sheet
wbk.Close False
Filename = Dir
Loop
End Sub
A:
you may be after what follows:
Option Explicit
Sub Theloopofloops()
Dim wbk As Workbook
Dim Filename As String
Dim path As String
Dim rCell As Range
Dim wsO As Worksheet
path = "M:\Documents\Call Logger\"
Filename = Dir(path & "*.xlsm")
Set wsO = ThisWorkbook.Sheets("Master")
Do While Len(Filename) > 0
DoEvents
Set wbk = Workbooks.Open(path & Filename, True, True)
For Each rCell In ActiveWorkbook.Worksheets("Calls").Range("A2:A20000")
If rCell <> "" And rCell.Value <> vbNullString And rCell.Value <> 0 Then
wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(1, 0).Resize(, 16).Value = rCell.Resize(, 16).Value
End If
Next rCell
wbk.Close False
Filename = Dir
Loop
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio skipping multiple if statements?
I'm making a simple maze program that generates a maze. Currently I was working on making one and only solution to a maze, when I stumbled onto something weird. When I debug this code I see that VS is just skipping my if statements here:
for (i = 0; i <= (col * row) / 200; i++)
{
solution[se[0]][se[1]] = 1;
if (lab[se[0] + 1][se[1]]) se[0] + 1;
else if (lab[se[0]][se[1] + 1]) se[1] + 1;
else if (lab[se[0] - 1][se[1]]) se[0] - 1;
else if (lab[se[0]][se[1] - 1]) se[1] - 1;
solution[se[2]][se[3]] = 1;
if (lab[se[2] - 1][se[3]]) se[2] - 1;
else if (lab[se[2]][se[3] - 1]) se[3] - 1;
else if (lab[se[2] + 1][se[3]]) se[2] + 1;
else if (lab[se[2]][se[3] + 1]) se[3] + 1;
}
I hope it's not a duplicate, but I have no slightest idea what's the problem here, so it could be one.
Here's the full code if someone wants to replicate the problem:
#include <stdio.h>
#include <iostream>
#include <Windows.h>
#include <string>
CONSOLE_SCREEN_BUFFER_INFO csbi;
int **lab, **solution;
int col, row, i, j;
int main() {
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
col = csbi.srWindow.Right - csbi.srWindow.Left; row = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; i = 0; j = 0;
lab = new int* [row];
for (i = 0; i < row; ++i)
lab[i] = new int[col];
solution = new int* [row];
for (i = 0; i < row; ++i)
solution[i] = new int[col];
for (i = 0; i < row; i++) { // Build basic maze
for (j = 0; j < col; j++) {
if (i == 0) lab[i][j] = 0;
else if (i == j == 1) lab[i][j] = 1;
else if (i == 1 && j == col - 1) lab[i][j] = 1;
else if (i == row - 1) lab[i][j] = 0;
else if (j == 0) lab[i][j] = 0;
else if (j == col - 1) lab[i][j] = 0;
else {
if (lab[i - 1][j] == 0) lab[i][j] = rand() % 2;
else {
if (lab[i - 1][j - 1] + lab[i - 1][j + 1] + lab[i - 2][j] <= 1) lab[i][j] = 1;
else {
lab[i][j] = rand() % 2;
}
}
}
}
}
int se[4] = { 1,1,1,col - 1 };
for (i = 0; i <= (col * row) / 200; i++) // Generate a solution
{
solution[se[0]][se[1]] = 1;
if (lab[se[0] + 1][se[1]]) se[0] + 1;
else if (lab[se[0]][se[1] + 1]) se[1] + 1;
else if (lab[se[0] - 1][se[1]]) se[0] - 1;
else if (lab[se[0]][se[1] - 1]) se[1] - 1;
solution[se[2]][se[3]] = 1;
if (lab[se[2] - 1][se[3]]) se[2] - 1;
else if (lab[se[2]][se[3] - 1]) se[3] - 1;
else if (lab[se[2] + 1][se[3]]) se[2] + 1;
else if (lab[se[2]][se[3] + 1]) se[3] + 1;
}
while (se[0] != se[2] || se[1] != se[3])
{
if (se[0] < se[2])
{
if (lab[se[2] - 1][se[3]]) se[2] - 1;
if (lab[se[0] + 1][se[1]]) se[0] + 1;
}
if (se[1] < se[3])
{
if (lab[se[2]][se[3] - 1]) se[3] + 1;
if (lab[se[0]][se[1] + 1]) se[1] + 1;
}
solution[se[0]][se[1]] = 1;
solution[se[2]][se[3]] = 1;
}
std::string out;
for (i = 0; i < row; i++) { // Print maze
for (j = 0; j < col; j++) {
if (solution[i][j]==1) out.append("@");
else if (!lab[i][j]) out.append("#");
else out.append(" ");;
}
std::cout << out << '\n';
out="";
}
system("pause");
for (i = 0; i < row; ++i) delete[] lab[i];
delete[] lab;
}
I'm sorry, this code is a mess, because it's still work in progress.
BTW I'm using VS 2019, didn't try it in another compiler yet. Is it really a compiler's fault?
A:
The reason why the compiler sees fit to 'skip' the if blocks is because there is no code in them that has any effect!
For example, in the statement:
if (lab[se[0] + 1][se[1]]) se[0] + 1;
when the condition in the test is "true" what happens? The statement se[0] + 1 doesn't actually modify anything - it is simply an expression that has the given value.
What you probably want is to add 1 to se[0], so you need this:
if (lab[se[0] + 1][se[1]]) se[0] += 1;
and similarly for the other if and else if lines. (Note the added = character!)
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery - toggleClass with radio
I'm trying to toggleClass the .on / .off class only if the :checked radio so that the CSS animation only happens to the selected radio. The problem is that the else part of my code isn't executing if the input isn't the selected one.
$(function() {
$("#m_clear").on("click", function() {
$("input:checked").each(function() {
$(this).prop("checked", false);
$(this).trigger("change");
});
});
$('input[type=radio]').on("change", function() {
var label = $(this).next("label");
var dot = label.find(".dot");
var tagbox = $(this).closest(".tagbox");
var cancel = label.find(".cancel--tagbox");
var color = label.data("rgb");
var rgb = `rgb(${color})`;
var contrast = darkness(color) ? "#202124" : "#fdfdfd";
if ($('input[type=radio]').is(':checked')) {
cancel.css("color", contrast);
cancel.toggleClass("on off");
dot.toggleClass("off on");
tagbox.css({
"background-color": rgb,
color: contrast,
"border-color": rgb,
color: contrast
});
} else {
dot.toggleClass("off on");
cancel.toggleClass("on off");
tagbox.css({
"background-color": "#fff",
color: "",
"border-color": ""
});
}
});
function darkness(color) {
color.replace(/^\D+|\)/g, "").trim();
//console.log(color);
var rgb = color.split(",");
//console.log(rgb);
var final =
parseInt(rgb[0], 10) + parseInt(rgb[1], 10) + parseInt(rgb[2], 10);
//console.log(final);
if (final < 384) {
return false;
}
return true;
}
});
/*input {
display: none;
}*/
label {
display: flex;
align-items: center;
font: 400 12px/16px Roboto Mono, monospace;
letter-spacing: -0.2px;
padding: 4px 0;
user-select: none;
cursor: pointer;
}
.tagboxes {
display: flex;
padding: 3rem;
list-style: none;
}
.tagbox {
display: flex;
align-items: center;
background-color: #fff;
border: 1px solid #dadce0;
border-radius: 6px;
padding-left: 8px;
padding-right: 8px;
margin: 0.3rem;
transition: 0.1s ease-in-out;
}
.text--tagbox {
margin-right: 3px;
}
.cancel--tagbox {
display: flex;
align-items: center;
justify-content: center;
width: 12px;
height: 12px;
margin-top: 3px;
color: purple;
transition: all 0.25s ease;
}
.dot {
margin-right: 6px;
width: 12px;
height: 12px;
border-radius: 50%;
transition: all 0.25s ease;
}
.dot.off {
transform: scale(0);
}
.dot.on {
transform: scale(1);
}
.dot.off,
.cancel--tagbox.off {
width: 0px;
height: 0px;
opacity: 0;
}
.dot.on,
.cancel--tagbox.on {
width: 12px;
height: 12px;
opacity: 1;
}
#i1+label .dot {
background-color: rgb(49, 231, 182);
}
#i2+label .dot {
background-color: rgb(0, 0, 255);
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<button id="m_clear">Clear All</button>
<div class="tagboxes">
<div class="tagbox">
<input id="i0" type="radio" name="radio">
<label data-rgb="255,64,129" for="i0">
<mark style="background-color: rgb(255, 64, 129);" class="dot on"></mark>
<b class='text--tagbox'>Lobster</b>
<div class="cancel--tagbox off"><i class="fa fa-times"></i></div>
</label>
</div>
<div class="tagbox">
<input id="i1" type="radio" name="radio">
<label data-rgb="49,231,182" for="i1">
<mark class="dot on"></mark>
<b class='text--tagbox'>Tuna</b>
<div class="cancel--tagbox off"><i class="fa fa-times"></i></div>
</label>
</div>
<div class="tagbox">
<input id="i2" type="radio" name="radio">
<label data-rgb="0,0,255" for="i2">
<mark class="dot on"></mark>
<b class='text--tagbox'>Pine</b>
<div class="cancel--tagbox off"><i class="fa fa-times"></i></div>
</label>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
A:
So a few changes.
First I stored the $('input[type=radio]') in a variable $radio to have access to all of them later
Next, rather than checking if any radio button is changed, the if checks against this.checked which will tell us if the radio that was changed is checked or not
If it is checked, we need to see if another radio was checked and needs to be reverted. An unchecked radio does not fire a change event. So we can find all the other radio buttons with the $radios.not(this), and manually trigger a change event on them
After that, both the if and the else are explicitly using addClass and removeClass to make sure that the class state is what we expect them to be when an element is checked or unchecked
$(function() {
$("#m_clear").on("click", function() {
$("input:checked").each(function() {
$(this).prop("checked", false);
$(this).trigger("change");
});
});
var $radios = $('input[type=radio]').on("change", function() {
var label = $(this).next("label");
var dot = label.find(".dot");
var tagbox = $(this).closest(".tagbox");
var cancel = label.find(".cancel--tagbox");
var color = label.data("rgb");
var rgb = `rgb(${color})`;
var contrast = darkness(color) ? "#202124" : "#fdfdfd";
if (this.checked) {
$radios.not(this).trigger("change");
cancel.css("color", contrast);
cancel.removeClass("off").addClass("on");
dot.removeClass("on").addClass("off");
tagbox.css({
"background-color": rgb,
color: contrast,
"border-color": rgb,
color: contrast
});
} else {
cancel.removeClass("on").addClass("off");
dot.removeClass("off").addClass("on");
tagbox.css({
"background-color": "#fff",
color: "",
"border-color": ""
});
}
});
function darkness(color) {
color.replace(/^\D+|\)/g, "").trim();
//console.log(color);
var rgb = color.split(",");
//console.log(rgb);
var final =
parseInt(rgb[0], 10) + parseInt(rgb[1], 10) + parseInt(rgb[2], 10);
//console.log(final);
if (final < 384) {
return false;
}
return true;
}
});
/*input {
display: none;
}*/
label {
display: flex;
align-items: center;
font: 400 12px/16px Roboto Mono, monospace;
letter-spacing: -0.2px;
padding: 4px 0;
user-select: none;
cursor: pointer;
}
.tagboxes {
display: flex;
padding: 3rem;
list-style: none;
}
.tagbox {
display: flex;
align-items: center;
background-color: #fff;
border: 1px solid #dadce0;
border-radius: 6px;
padding-left: 8px;
padding-right: 8px;
margin: 0.3rem;
transition: 0.1s ease-in-out;
}
.text--tagbox {
margin-right: 3px;
}
.cancel--tagbox {
display: flex;
align-items: center;
justify-content: center;
width: 12px;
height: 12px;
margin-top: 3px;
color: purple;
transition: all 0.25s ease;
}
.dot {
margin-right: 6px;
width: 12px;
height: 12px;
border-radius: 50%;
transition: all 0.25s ease;
}
.dot.off {
transform: scale(0);
}
.dot.on {
transform: scale(1);
}
.dot.off,
.cancel--tagbox.off {
width: 0px;
height: 0px;
opacity: 0;
}
.dot.on,
.cancel--tagbox.on {
width: 12px;
height: 12px;
opacity: 1;
}
#i1+label .dot {
background-color: rgb(49, 231, 182);
}
#i2+label .dot {
background-color: rgb(0, 0, 255);
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<button id="m_clear">Clear All</button>
<div class="tagboxes">
<div class="tagbox">
<input id="i0" type="radio" name="radio">
<label data-rgb="255,64,129" for="i0">
<mark style="background-color: rgb(255, 64, 129);" class="dot on"></mark>
<b class='text--tagbox'>Lobster</b>
<div class="cancel--tagbox off"><i class="fa fa-times"></i></div>
</label>
</div>
<div class="tagbox">
<input id="i1" type="radio" name="radio">
<label data-rgb="49,231,182" for="i1">
<mark class="dot on"></mark>
<b class='text--tagbox'>Tuna</b>
<div class="cancel--tagbox off"><i class="fa fa-times"></i></div>
</label>
</div>
<div class="tagbox">
<input id="i2" type="radio" name="radio">
<label data-rgb="0,0,255" for="i2">
<mark class="dot on"></mark>
<b class='text--tagbox'>Pine</b>
<div class="cancel--tagbox off"><i class="fa fa-times"></i></div>
</label>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to use bootstrap and noscript to create an alert
I'm trying to create an alert for if JavaScript is disable in the user's browser. I figured the best way to do this would be to just use a bootstrap dismissible alert like this:
<noscript>
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert"
aria-hidden="true">
×
</button>
Warning! JavaScript is disabled. This site may not work properly without it.
</div>
</noscript>
When I run the code though it just prints out everything inside of the noscript tags as if it were text. How do I correct this? Or is there another way to check if they're using JavaScript or not?
A:
Bootstrap alerts work fine with just html and css so they will work in <noscript> tags.
This happens when you first switch javascript off. Just refresh the page a few times.
| {
"pile_set_name": "StackExchange"
} |
Q:
Calling method from another class
To begin, I would like to apologize for my English :)
I have FirstViewController, which contains scrollView. This is scrolView with enabled paging, and have 2 pages with 2 different view controllers. From one of the view controllers by touching the button the third view controller appears like a modal view. I call a method in FirstViewController that must disable scrolling and hide two labels which is not contained in the scrollView.
Method is executing, but UI not changes, scrolling still enabled and labels still visible.
Now a bit of code:
This is a piece of the FirstViewController.h (not the whole code):
@interface FirstViewController : UIViewController <UIScrollViewDelegate> {
IBOutlet UIScrollView *scrollView;
IBOutlet UILabel *label1;
IBOutlet UILabel *label2;
}
@property (nonatomic, retain) UILabel *label1;
@property (nonatomic, retain) UILabel *label2;
@property (nonatomic, retain) UIScrollView *scrollView;
-(void)prepareToModal;
@end
Now it's -(void)prepareToModal; implementation:
-(void)prepareToModal {
[label1 setHidden:YES];
[label2 setHidden:YES];
scrollView.scrollEnabled = NO;
}
So, from the one of the view controllers, which contained in scrollView, I call prepareToModal
Previously:
#import "FirstViewController.h"
Next:
FirstViewController *vc = [[FirstViewController alloc] init];
[vc prepareToModal];
[vc release];
So, that's all. I put a breakpoint in prepareToModal, and it stopped executing. The method is called, but nothing changes on screen...
What am I doing wrong?
How to do this correctly?
Update:
I solved this problem.
When I present this modal view, I wrote this:
ThirdViewController *tvc = [[ThirdViewControler alloc] init];
tvc.delegate = self;
UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:tvc];
[self presentModalViewController:nc animated:YES];
[tvc release];
[nc release];
Now, insted of [self presentModalViewController:nc animated:YES]; I write this:
[[[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController] presentModalViewController:nc animated:YES];
And It's working very well, I don't need a method -(void)prepareToModal;
Thanks a lot :)
A:
Make sure you have hooked up your IBOutlets in Interface Builder.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I access inserted document's _id within a transaction in ArangoDB
I don't see any examples of accessing inserted/updated documents key's when in a transaction.
var collections = {write: ['foo','bar']};
var action = String(function () {
var doc = params['doc'];
var relatedDoc = params['relatedDoc'];
var db = require('internal').db;
db.foo.save(doc); // how do I access the _id, key etc of the newly inserted doc?
relatedDoc.foos.push(doc._id); // _id does not exist yet
db.bar.save(relatedDoc);
return {success: true};
});
var params = {
doc: doc,
relatedDoc: relatedDoc
};
db.transaction(collections, action, params, function (err, result) {
if (err) {
return dfd.reject(err);
}
return dfd.resolve(result);
});
A:
The collection.save() method will return some meta-data for the saved document:
_rev: document revision id (auto-generated by the server)
_key: document key (either specified by user in _key attribute or auto-generated by the server if not)
_id: same as key, but also including collection name
To use the generated id in your code, you can capture the result of collection.save() in a variable and use it as follows:
var collections = {write: ['foo','bar']};
var action = String(function () {
var doc = params['doc'];
var relatedDoc = params['relatedDoc'];
var db = require('internal').db;
var newDoc = db.foo.save(doc); // capture result of save in newDoc
relatedDoc.foos.push(newDoc._id); // use newDoc._id for
db.bar.save(relatedDoc);
return {success: true};
});
var params = {
doc: doc,
relatedDoc: relatedDoc
};
db.transaction(collections, action, params, function (err, result) {
if (err) {
return dfd.reject(err);
}
return dfd.resolve(result);
});
| {
"pile_set_name": "StackExchange"
} |
Q:
iphone: notification when receiving a call?
I'm developing for a jailbroken device, and I want to create an app that detects a phone call, and presents an alert on top of the call screen. How can I achieve this? What hidden frameworks should I use?
A:
Within CoreTelephony is the CTCallCenter class which includes the callEventHandler property, which is a block that runs upon changes in the call state. As described in the documentation, you could use this to become notified of these states:
CTCallStateDialing;
CTCallStateIncoming;
CTCallStateConnected;
CTCallStateDisconnected;
Docs say you must be in active app state. If you are suspended, then you only get one block state change notification upon waking up. If you are jailbroken and in background state, hopefully you would get your block executed, so you could become aware of this.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I add an admin user to Mongo in 2.6?
I upgraded from 2.4 to 2.6 and authentication broke. This tutorial seems pretty straightforward but I keep getting locked out of my own database. My situation is pretty simple, I have a single Mongo server and need one user/pwd combination to connect.
First I connect via the localhost exception as mentioned. Then I create the admin user as suggested:
use admin
db.createUser(
{
user: "myadmin",
pwd: "mysecret",
roles:
[
{
role: "userAdminAnyDatabase",
db: "admin"
}
]
}
)
Now it's time to add new users so to sanity check myself, I logout of the shell. Now when I type "mongo" it fails. That used to work but OK, it's not seeing a username password and I guess the localhost exception isn't there anymore so I follow the instructions outlined here:
mongo --port 27017 -u myadmin -p mysecret --authenticationDatabase admin
And I get:
MongoDB shell version: 2.6.0
connecting to: 127.0.0.1:27017/test
Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" }
>
Any idea on how to:
Setup Mongo 2.6 so I can easily go in and out of the shell managing the databases (I would think this is the "system user administrator")
Enable a user from a remote client to connect? (Just the mongo side, no help needed with iptables ...)
Thanks!
A:
Apparently the "system user administrator" isn't enough. Create a root user:
> db.createUser({user:"someadmin",pwd:"secret", roles:[{role:"root",db:"admin"}]})
Then add your database user:
> use some_db
> db.createUser(
{
user: "mongouser",
pwd: "someothersecret",
roles: ["readWrite"]
}
)
More details on this gist. Comments on gist and better answers on SO welcome - I'm not a sys admin
| {
"pile_set_name": "StackExchange"
} |
Q:
ElasticSearch search query delimiters
I have a simple record in the index
CharacterId=847
query CharacterId=8 returns the result (it looks like it searches for CharacterId and 8 separately
query CharacterId= returns the result
query CharacterId=* doesn't return anything
query Character* returns the result
query CharacterId=8* doesn't return anything
A:
I will assume that your question is "Why does elasticsearch do that"? In order to answer this question, we need to take a look at how your record was indexed. Assuming that you were using default analyzer, we can see that your record is indexed as two terms characterid and 847:
$ curl "localhost:9200/twitter/_analyze?pretty=true" -d 'CharacterId=847'
{
"tokens" : [ {
"token" : "characterid",
"start_offset" : 0,
"end_offset" : 11,
"type" : "<ALPHANUM>",
"position" : 1
}, {
"token" : "847",
"start_offset" : 12,
"end_offset" : 15,
"type" : "<NUM>",
"position" : 2
} ]
}
Now let's take a look at your queries:
$ curl "localhost:9200/twitter/_validate/query?explain=true&pretty=true" -d '{
"query_string": {"query":"CharacterId=8"}
}'
{
"valid" : true,
"_shards" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"explanations" : [ {
"index" : "twitter",
"valid" : true,
"explanation" : "_all:characterid _all:8"
} ]
}
You are right this query is searching for the term characterid or for the term 8. The term characterid matches the first term of your record and you get the result back.
The second query has similar effect, but it searches only for one term characterid.
$ curl "localhost:9200/twitter/_validate/query?explain=true&pretty=true" -d '{
"query_string": {"query":"CharacterId="}
}'
...
"explanation" : "_all:characterid"
...
The third query is processed as a wildcard query:
$ curl "localhost:9200/twitter/_validate/query?explain=true&pretty=true" -d '{
"query_string": {"query":"CharacterId=*"}
}'
...
"explanation" : "_all:characterid=*"
...
As you can see, it searches for all terms that start with characters characterid=. Your index doesn't have any such terms, therefore it finds nothing.
The fourth query is again processed as a wildcard query:
$ curl "localhost:9200/twitter/_validate/query?explain=true&pretty=true" -d '{
"query_string": {"query":"Character*"}
}'
...
"explanation" : "_all:character*"
...
However, this time, it searches for terms that start with character, so it matches the term characterid.
The last query is similar to the third query:
$ curl "localhost:9200/twitter/_validate/query?explain=true&pretty=true" -d '{
"query_string": {"query":"CharacterId=8*"}
}'
...
"explanation" : "_all:characterid=8*"
...
There are no terms that start with characterid=8, and because of these no records are returned.
If this is not the behavior that you need, you might want to consider not analyzing this field at all, or using just a lowercase analyzer.
| {
"pile_set_name": "StackExchange"
} |
Q:
After building nsmutablearray should i convert it to nsarray for performance benefit?
Wondering, After building nsmutablearray should i convert it to nsarray for performance benefit? If i am going to keep and use that array for quite sometime.
A:
No. The conversion itself will cost time and CPU cycles and you won't gain anything from the conversion.
| {
"pile_set_name": "StackExchange"
} |
Q:
Confused about notation in definition of Fisher Information matrix
In the definition of the Fisher Information matrix:
$$
\begin{align}
I(\theta)_{ij}
&= \mathbb{E}_{x \sim p(x \,;\, \theta)}\left[
\left(\frac{\partial}{\partial \theta_i} \log p(x \,;\, \theta) \right)
\left(\frac{\partial}{\partial \theta_j} \log p(x \,;\, \theta) \right)
\right]
\end{align}
$$
is the expectation on the RHS computed using the same value for "$\theta$" that is passed into $I(\theta)$ ?
Or is the density "$p(x \,;\, \cdot)$" in the expectation computed using the true but unknown parameter value of the parameter, call it $\theta^*$, so that:
$$
\begin{align}
I\left(\bar{\theta}\right)_{ij}
&= {\large \int}
\left(
\frac{\partial}{\partial \theta_i} \log p(x \,;\, \theta)~\Biggr|_{ \theta=\bar{\theta}}
\right)
\left(
\frac{\partial}{\partial \theta_j} \log p(x \,;\, \theta) ~\Biggr|_{ \theta=\bar{\theta}}
\right)
\, p(x \,;\, \theta^*) \, dx
\end{align}
$$
In this second definition, the Fisher information matrix would tell us how much information the true distribution (as specified by $\theta^*$) provides about the value of theta at location $\bar{\theta}$.
Alternatively, if the same value for theta (namely $\bar{\theta}$) is also used in the density "$p(x \; \cdot)$", then the meaning of the Fisher information matrix is something like "how much information does the density specified by $\bar{\theta}$ contain about itself?" And I'm not really sure how that quantity would be useful in practice.
A:
It's the first one: all quantities are evaluated at the true value of $\theta$.
The reason this is the right definition is that $$\frac{\partial}{\partial\theta}\log p(x;\theta)$$
doesn't have mean zero except at the true value, which makes squaring a lot less useful. The information identity (that the variance of the first derivative is equal to the mean of the second derivative) is also only valid at the true value.
Well, strictly speaking, when I say all quantities are evaluated at the true value of $\theta$ what I really mean is evaluated at a $\theta$ we are currently pretending is the true value, whether it is or not. So, the Fisher scoring algorithm modifies the Newton-Raphson algorithm by replacing the actual second-derivative matrix (which might not be positive definite) with the inverse of the information matrix pretending that the current value is the truth (which is guaranteed to be positive semidefinite because it's a variance) .
| {
"pile_set_name": "StackExchange"
} |
Q:
Alternate drivers with test-kitchen
Many cookbooks, such as the mysql cookbook have multiple .kitchen.yml files. For example, mysql has a .kitchen.yml and a .kitchen-cloud.yml. Looking at documentation and code for test-kitchen, I can't see any way to use config files other than .kitchen.yml, .kitchen.local.yml, and ~/.kitchen/config.yml. If I wanted to use the cloud driver from the mysql cookbook, would I:
cp .kitchen-cloud.yml .kitchen.yml
cp .kitchen-cloud.yml .kitchen.local.yml
something else??
It just seems like there should be a cleaner approach to using the alternative config file that a brute force replacement of the default ones.
Thanks
A:
Kitchen provides three environment variables to control where it looks for each of the possible configuration files. To make the default behaviour explicit, you could set them as follows:
KITCHEN_YAML="./.kitchen.yml"
KITCHEN_LOCAL_YAML="./.kitchen.local.yml"
KITCHEN_GLOBAL_YAML="$HOME/.kitchen/config.yml"
You don't need to override all of them, so you could run test-kitchen with your .kitchen-cloud.yml like so:
$ KITCHEN_YAML=".kitchen-cloud.yml" kitchen test
A:
... to add to coderanger, if you want to select drivers or options based on whether your CI tool sets environment variables, you could also do something like this:
---
<%
#--------------------------------------------------------------------------
# the driver_plugin can be overridden with an environment variable:
# $ KITCHEN_DRIVER=docker kitchen test
# if not specified, defaults are used...
# - kitchen_driver_ci if environment variable CI=true or TRAVIS=true are present
# - kitchen_driver_local is used otherwise (which defaults to vagrant)
#--------------------------------------------------------------------------
kitchen_driver_ci = 'ec2'
kitchen_driver_local = 'vagrant'
kitchen_driver_default = kitchen_driver_local
if ENV['KITCHEN_DRIVER']
kitchen_driver = ENV['KITCHEN_DRIVER']
elsif ENV['TRAVIS']=="true"
kitchen_driver = kitchen_driver_ci
elsif ENV['CI']=="true"
kitchen_driver = kitchen_driver_ci
else
kitchen_driver = kitchen_driver_default
end
puts "-----> driver_plugin: #{kitchen_driver.to_s}"
%>
driver_plugin: <%= kitchen_driver %>
driver_config:
require_chef_omnibus: 11.10.4
<% if kitchen_driver == 'ec2' %>
aws_access_key_id: <%= ENV['AWS_ACCESS_KEY_ID'] %>
aws_secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
aws_ssh_key_id: <%= ENV['AWS_SSH_KEY_ID'] || "test-kitchen" %>
ssh_key: <%= ENV['AWS_SSH_KEY_FILE'] || "./test-kitchen.pem" %>
region: <%= ENV['AWS_REGION'] || "us-east-1" %>
availability_zone: <%= ENV['AWS_AVAILABILITY_ZONE'] || "us-east-1c" %>
flavor_id: "t2.small"
groups: ["test-kitchen"]
<% end %>
<% if kitchen_driver == 'vagrant' %>
customize:
memory: 2048
<% end %>
platforms:
- name: ubuntu-14.04
<% if kitchen_driver == 'ec2' %>
driver_config:
image_id: ami-6ab2a702
username: ubuntu
tags: { "Name": "Test Kitchen" }
<% end %>
busser:
sudo: true
suites:
- name: default
run_list: [
]
attributes: {
}
This way you maintain a single file and avoid divergent platform tests (making a change in one file and forgetting to in another). There are also cases where options provided in .kitchen.local.yml might conflict with those in .kitchen.yml.
A:
In addition to what zts said, remember that you can use ERb in kitchen files, so your driver config can look like this:
driver:
name: <%= ENV['KITCHEN_DRIVER'] || 'vagrant' %>
| {
"pile_set_name": "StackExchange"
} |
Q:
Create Jquery Plugin with dynamic parameters for MULTIPLE usage
I creating jquery plugin, looks like this :
(function ( $ ) {
// -- This is Person Object used for plugin
var PersonObject = function(elem, options)
{
this.elem = elem;
this.options = options;
this.run();
};
PersonObject.prototype = {
run: function()
{
// console.log(this.options.person_name);
self = this;
tpl = '<a class="btn btn-link btncok">one</a>';
self.elem.after(tpl);
$('.content').on('click', '.btncok', function(e) {
e.stopImmediatePropagation();
self.show();
});
return self.options.person_name;
},
show: function()
{
console.log(this.options.person_name);
}
};
// -- end Person Object
// -- This is my jquery fn function
$.fn.myPlugin = function(options) {
// here is default options
var default_options = {person_name: 'father'};
options = $.extend({}, default_options, options);
return this.each(function() {
new PersonObject($(this), options);
});
};
// -- end jquery plugin
}( jQuery ));
.
.
so then, when the above plugin are used by many elements with different situation like this :
<div class="jumbotron content">
<p class="something-one">one</p>
<p class="something-two">two</p>
</div>
<script>
// call the plugin WITH parameters
$('.something-one').myPlugin({person_name: 'mother'});
// result wrong : father (should be mother)
// call the plugin WITHOUT parameters
$('.something-two').myPlugin();
// result correct : father
</script>
the parameters is not work expected.
all the element that using the plugin will receive same parameters by last element call
how to fix this problem :(
A:
You are seeing the same value because of the below click handler
$('.content').on('click', '.btncok', function(e) {
e.stopImmediatePropagation();
self.show();
});
$('.content').on('click', '.btncok', .... is does not delegate event as expected. Instead attach an event to tpl directly. Something like this
this.appendedEl = $('<a class="btn btn-link btncok">'+this.options.person_name+'</a>');
this.elem.after(this.appendedEl);
this.appendedEl.on('click', function(e) { // <--- this way the event is attached to the right element
e.stopImmediatePropagation();
this.show();
}.bind(this)); // <--- I used bind instead of self
Here is a demo http://jsbin.com/jafulo/edit?js,output
| {
"pile_set_name": "StackExchange"
} |
Q:
File size of 0 when trying to upload file through selenium with ng-file-upload
I'm using version 12.01 of the excellent ng-file-upload and attempting to create an e2e test with protractor using Chrome 49. I'm using sendKeys to path the file path, and I'm able to see the upload being triggered, but the file size in the
<button
class="avatar-upload__button"
ngf-select="uploadFiles($file, $invalidFiles)"
ng-model='ngfFile'
accept="image/*"
ngf-max-size="14.5MB">
</button>
I'm able to see the file upload being called in this function:
$scope.uploadFiles = (file, errFiles) => {
}
But at this point file.size is 0, where when I run this manually, i get the correct size. I wouldn't be too fussed about this except that the upload seems to be getting choked off/is not happening (presumably because the file information is bad).
My guess at this point is it is related to using this on a button rather than an input[type="file"]. I'm going to start digging into ng-file-upload, but any suggestions/ideas appreciated.
A:
I knew something smelled bad here because nobody else was having this problem. I assembled the path incorrectly and the file did not exist.
| {
"pile_set_name": "StackExchange"
} |
Q:
SonarQube - Is there an API to grab a part of analysis for all projects you have?
I want to be able to extract, for example, just the Technical Debt numbers out of my sonar instance for all the projects I have, and display them on a page.
Does Sonar provide an api that I can utilize and achieve this?
A:
SonarQube lets you get exhaustive data using its Web API. Taking your example of project's measures:
Since SonarQube 5.4
Use api/measures Web API (see parameters in documentation). Example for project postgresql:
Get the component ID:
https://nemo.sonarqube.org/api/components/show?key=postgresql
Get the desired metrics:
https://nemo.sonarqube.org/api/measures/component?componentId=6d75286c-42bb-4377-a0a1-bfe88169cffb&metricKeys=sqale_debt_ratio&additionalFields=metrics,periods
Before SonarQube 5.4
Use api/resources Web API:
http://sonarqube_url/api/resources?resource=your_resource&metrics=metric_key
Listing metric keys
Use api/metrics/search (documented here), see also Metric Definitions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cinlar, Probability and Stochastic, Ch.2 ex. 4.14
I have this exercise (Cinlar, Ch.2 ex. 4.14 ):
Let $T$ be a positive random variable and define a stochastic process $X = (X_t)_{t \in \mathbb{R}_+}$ by setting, for each $\omega$ $$ X_t(\omega) = \begin{cases}
0 & t< T(\omega) \\
1 & t\ge T(\omega)
\end{cases}
$$
Show that $X$ and $T$ determine each other.
So I have to find two measurable functions $f,g$ such that \begin{align*}
X &= f \circ T \\
T &= g \circ X
\end{align*}
the first one is easy. I have some problems with the second:
\begin{align*}
\varphi: 2^{\mathbb{R}_+} &\longrightarrow \mathbb{R}_+ \\
x &\longmapsto \inf\{t \in \mathbb{R}_+ : x_t = 1\}
\end{align*}
I have that $T = \varphi \circ X$, so I'd like to say that $\varphi$ is measurable. I have that $$\varphi^{-1}(\alpha,+\infty) = \{x \in 2^{\mathbb{R}_+} : x_t = 0 \; \forall t\in[0, \alpha] \}$$
If what I've said till now is right, how can I show that this set is measurable in the product space? Thanks
EDIT: as pointed out in the comments this set is not measurable in $2^{\mathbb{R}_+}$. But the deterministic function $\varphi$ needs to have as domain the measurable space associated to the stochastic process $X$, which is $2^{\mathbb{R}_+}$ with its product $\sigma$-algebra... How can I solve this?
A:
It can be shown that $T$ is determined by $(X_t)_{t \in \mathbb{Q}_+}$ (and a fortiori by $(X_t)_{t \in \mathbb{R}_+}$). I take the same function $\varphi$, but now I define it over $2^{\mathbb{Q}_+}$
\begin{align*}
\varphi: 2^{\mathbb{Q}_+} &\longrightarrow \mathbb{R}_+ \\
x &\longmapsto \inf\{t \in \mathbb{Q}_+ : x_t = 1\}
\end{align*}
Now, it is evident that $T = \varphi \circ (X_t)_{t \in \mathbb{Q}_+}$, since $\mathbb{Q}_+$ is dense in $\mathbb{R}_+$, it remains to show that $\varphi$ is $\mathscr{P}(\{0,1\})^{\mathbb{Q}_+}$-measurable.
But this is true because, in fact, since $\mathbb{Q}_+$ is countable, we have that $\mathscr{P}(\{0,1\})^{\mathbb{Q}_+} = \mathscr{P}(\{0,1\}^{\mathbb{Q}_+})$, and therefore every numerical function over $2^{\mathbb{Q}_+}$ is measurable.
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.