INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to calculate probability based on 2 cases?
I feel that this is an easy one, but I want to make sure I understand it properly.
So, let's say that I want to calculate the probability of an event B and I know that if event A happens than B's probability to happen is p1 and if event A doesn't happen than B's probability is p2. I also know the probability of event A to happen.
So what is the probability of B to happen? How do I combine the two probabilities from the two possible outcomes of A?
|
$$P(B)=P(B|A)P(A)+P(B|\bar{A})P(\bar{A})$$ ... and $P(\bar{A})=1-P(A)$.
In your example $P(B|A) =p_1$ and $P(B|\bar{A})=p_2$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability"
}
|
How to draw KDE over Histogram Plot
I just plotted a histogram on R for some data, following:
hist(Y1, breaks=30)
I don't know how to draw a Kernel density estimate plot smoothly over the histogram plot.
All suggestion appreciated
|
You need `freq = FALSE` in `hist`.
set.seed(1)
Y1 <- rgamma(100, 10, 3)
hist(Y1, breaks = 30, freq = FALSE)
dens <- density(Y1)
lines(dens)
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "r, statistics"
}
|
Number format in VBA
I want to set my array to 0 decimal place. I know that it has to be some `number.format=0`. But I do not know where to place it. And sorry for the format of my code, it is not in gray because I do not know to use it.
Option Explicit
Option Base 1
Function arraydemo(r As Range)
Dim cell As Range, i As Integer, x(40, 1) As Double
i = 1
For Each cell In r
x(i, 1) = Rnd * 40
i = i + 1
Next cell
arraydemo = x
End Function
|
Your array is in Double, so when you store random result to array, it will in decimal automatically, you can delete the decimal with change declaration of array from decimal to integer, but this will delete decimal value from random result.
I think the best way is: modify the decimal from the result of your function. Example :
Sub test()
Dim r As Range
Dim A As Variant
Set r = Range("A1:A40")
A = arraydemo(r)
For i = 1 To UBound(A)
Range("A1").Offset(i) = A(i, 1)
Range("A1").Offset(i).NumberFormat = "0"
Next
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, vba"
}
|
Can I use .Contains for Integer list?
I have a list of integer and I want to check whether it contains several values, but it does not work and always return true in if statement. The code is here:
if(IntegerList.Contains(1 | 2 |3 | 4))
{ //do something }
|
The way you're doing it checks whether the list contains `1 | 2 | 3 | 4` which is equal to `7` (bitwise OR). If your `IntegerList` does contain the value `7` then your query will indeed return `true`.
If you want to check whether `IntegerList` contains **ALL** of the items in `SearchList`, you can use the following LINQ query:
bool containsAll = SearchList.All(x => IntegerList.Contains(x));
If you want to know whether `IntegerList` contains **ANY** of the items in `SearchList`, just swap `All` with `Any`, like so:
bool containsAny = SearchList.Any(x => IntegerList.Contains(x));
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": -2,
"tags": "c#"
}
|
Own version of strncpy shouldn't work, but it does
so here's the code.
#include <stdio.h>
#define MAXOUTPUT 10
void copy_n(char des[], char src[], int n);
int main(void)
{
int i;
char output[MAXOUTPUT];
copy_n(output, "SomeTestInputHere", 26);
printf("%s\n", output);
for(i=0;output[i]!='\0';i++)
printf("%c\n", output[i]);
return 0;
}
void copy_n(char des[], char src[], int n)
{
int i;
for(i=0;i<MAXOUTPUT;i++)
{
if(i<n)
des[i]=src[i];
else
des[i]='\0';
}
}
Why won't it crush when printing a string or char by char? Where does the terminating NUL come from here? It's for Reek's Pointers on C, and is supposed to copy n characters, filling with NUL when, des>=src.But when src>des it should copy all chars without terminating NUL.
|
Your `copy_n` function `for` loop uses the constant `MAXOUTPUT` as the guard in the loop; and `MAXOUTPUT` has a value 10.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c, arrays, character"
}
|
Count substring occurrences within a cell
How can I count the number of occurrences of a substring within a cell?
For example:
| | A |
| 1 |John,John,Tom,David|
What formula would I use if I want to return the number of occurrences of "John" in cell A1 (=2)?
|
Wow, after searching around for a month on this problem, I stumbled upon the answer after posting this question. Here is what I came up with in case anyone else has this problem.
=SUM(IF(ISNUMBER(FIND("John"; SPLIT(A1; ",")));1;0))
This is an array formula so will need to be entered using `Ctrl`+`Shift`+`Enter`.
If anyone thinks of a better way to solve this problem, please let me know!
|
stackexchange-superuser
|
{
"answer_score": 7,
"question_score": 7,
"tags": "microsoft excel, google spreadsheets"
}
|
C言語のポインタ変数を含む構造体初期化について
`struct S v={0};`
`NULL`0100
0
`NULL`
struct S {
int val;
void *ptr;
int val2;
}
int main(int argc,char *argv[]){
struct S v={0};
printf("%d\n%d\n",v.val,v.val2);
if( v.ptr == NULL) {
// NULL
}
}
|
c JIS X 3010:2003 6.7.8 Yes
*
a)
b)
* ()
`val` `0`
>
No
> NULL0100
`memset` `0`
`NULL`
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 10,
"question_score": 5,
"tags": "c"
}
|
Need to generate files based on the value available in a variable in shell
In my script I have a variable `$var` which will hold a value "00135 00136 00137". I want to generate three files based on the values available in `$var` \- if possible without using a loop.
For example, I need touch files with these names:
test.00136.txt
test.00137.txt
test.00138.txt
|
Avioding a while loop is possible with xargs.
First split the var into lines, use the string num as a placeholder and touch the files:
var="000135 00136 00137 00138 00139"
echo "${var}" | tr " " "\n" | xargs -I num touch test.num.txt
Edit:
Avoid tr with
echo -n "$var" | xargs -d' ' -n1 -Inum echo test.num.txt
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "shell, unix, ksh"
}
|
how to print this array in reverse
i just started learning java and i'm trying to print this array in reverse not sure what i'm doing wrong but it doesn't return the second loop, no errors
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner red = new Scanner(System.in);
int[] arr;
arr = new int[3];
for (int i=0;i<arr.length;i++)
{
System.out.println("enter number");
arr[i]=red.nextInt();
}
for (int j=2;j<0;j--) {
System.out.println(arr[j]);
}
}
}
|
Try this
for (int j = arr.length-1; j >= 0; j--) {
System.out.println(arr[j]);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "java"
}
|
Log user IP with PHP
Currently I'm using this script to log my users IP adresses:
$userip = $_SERVER['REMOTE_ADDR'];
However, after I bought a Anti-DDoS HTTP Proxy, it returns the proxy IP instead.
$_SERVER['REMOTE_ADDR'] -> 198.12.12.102
I'm using Cloudflare with the proxy, so I've entered the Proxy's IP inside the IP field in Cloudflare and then selected 'Bypass the Cloudflare network'.
|
Well, yes, if the request is proxied, all PHP sees is the proxy's address. In this case, **and only in this case** , should you look at alternative HTTP headers. The proxy may, _should_ , add the original IP address as an extra HTTP header, like `X-Forwarded-For`, which will be available in `$_SERVER['HTTP_X_FORWARDED_FOR']`.
Usually it's a security risk to pay attention to these headers; only if you know that _your_ proxy that _you_ control explicitly adds this header on _your behalf_ should you use it.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "php"
}
|
Can't extract time from timestamp Postgres
Hi im trying to extract time from a timestamp in Postgres
SELECT extract(time from '2000-01-01 01:12:00'::timestamp)
Result should be: 01:12:00
It looks like that time is not a valid argument for extract. Is that right?
|
Try this:
s=# SELECT cast ('2000-01-01 01:12:00'::timestamp as time);
time
----------
01:12:00
(1 row)
doesn't extract - then, you might want to use `cast`.
and yes - <
`time` is not a valid aprt
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 9,
"tags": "postgresql, datetime, time, timestamp"
}
|
how do set border radius for google map infowindow
I have google map infowindow,i want to set border radius to infowindow. so how do it.
and this is my code
var latlng = new google.maps.LatLng(lat,lng);
var myOptions = {
zoom : 8,
center : latlng,
mapTypeId : google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvass"),
myOptions);
var infowindow = new google.maps.InfoWindow();
infowindow.open(map, marker);
|
I think you have to create a custom infobox overlay to change anything other than the content, the google maps infoWindow is if I'm not mistaken just a scaled image.
Go custom! Example here: <
and here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, ajax, google maps, google maps api 3"
}
|
Numpy attributes not recognized in Numba
Numba offers JIT for Python. In its documentation it says "One objective of Numba is having a seamless integration with NumPy."
So why including some of the simplest features from numpy isn't possible:
import numpy as np
from numba import *
@jit(nopython=True)
def testfun(x):
y = np.size(x)
return y
x=np.array([1 ,2, 3],dtype=float)
testfun(x)
When I run this code, I get the error "Unknown attribute 'size' of type Module."
Numba understands calls to NumPy ufuncs. I assume simple numpy functions such as size, shape, sum, reshape, etc are ufuncs.
|
Not sure why it is not supported, but this works:
import numpy as np
from numba import *
@jit(nopython=True)
def testfun(x):
y = x.size
return y
x=np.array([1 ,2, 3],dtype=float)
testfun(x)
You might want to have a look at the Supported NumPy features on their web-site.
|
stackexchange-scicomp
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, numpy"
}
|
Why two requests are displayed in Fiddler2 when first request sent to BlazeDS using RemoteObject of Flex
Why are two requests displayed in Fiddler2 when first request sent to BlazeDS using RemoteObject of Flex.
I use this enviroment:
* Flex SDK 3.5
* BlazeDS 4.0.1
* Spring 3.0.5
* Spring BlazeDS Integration 1.0.3
|
Is the first request an OPTIONS or HEAD request?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "apache flex, spring, blazeds, fiddler, remoteobject"
}
|
Using AA(A) batteries to power a 3.3V SoC
I have a 3.3V SoC that could draw up to around 250mA - 300mA. Is it a good idea to power it using 2x AA(A) batteries? Is it supposed to be an unstable setup without decoupling capacitors?
Thanks
|
Contrary to one reply, decoupling caps are still needed regardless of the cleanliness of the power supply. Digital logic draws most of its power consumption in millions/billions of short spikes per second, and the physics (inductance, mainly) of copper tracks and power-planes sees to it that this spiky power draw results in the power supply rail (Vcc, Vdd) going up & down at those millions/billions of spikes per second - not what you want for reliable running of whatever's going on in the chip. It's the job of decoupling caps to supply this power to the chip, because they're deliberately places as close to the power supply pins as possible. <
|
stackexchange-electronics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "power supply, batteries, 3.3v"
}
|
Force multipeer connection to close
Is there a way to end a (ios 7) multipeer connection? As in, not completely disconnect the local peer but instead just disable the connection with a specific peer?
|
The only peer that you can disconnect from an `MCSession` is yourself, so you'd need to create a new session for each peer you connect to. You can keep those sessions in a dictionary with the connected peer's `displayName` property as a key, and when you want to disconnect a given peer, grab the relevant `MCSession` and send that session a `disconnect` message.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ios, p2p, multipeer connectivity"
}
|
Loss due to impedance matching in a filter
I have a quite basic question, after starting to re-read some RF theory. If a voltage source has a resistance of 50 ohms, and the equivalent impedance of a connected bandpass filter and its load are 50 ohms for a perfect match, won't there be significant loss - so much so that the passband will disappear entirely? If the bandwidth of a filter is defined as the portion where the gain is above 1/sqrt2 ~ 0.707 V, and the highest the output can ever get is 0.5 V due to the voltage divider rule, is it impossible to have an impedance matched band pass filter? Why would someone want to have a matched preselection filter between an antenna and an LNA if matching losses might cause the weak signal to be out of amplification range?
|
The \$\frac{1}{\sqrt{2}}\$ point is defined relative to the magnitude, so if your magnitude in the passband is 0.5, then the -3dB point is at \$\frac{0.5}{\sqrt{2}}\approx0.354\$.
|
stackexchange-electronics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "filter, impedance matching, band pass, loss"
}
|
How to hide user-passwords in SQL Server database
To improve the security for my users I wish to hide all user-passwords in my MSSQL database. The webapplication is in ASP Classic and the SQL-field is a varchar(max).
I have heard about hashing the codes, but how does this work? Is it something to be done in the SQL string or making an ASP function?
My current users tabel setup are:
id username password
1 jersey plaintextpassword
2 timber plaintextpassword
....
|
i prefer to store user password as with md5
save passwords after md5sum when user trying to login
user variables from form
var_username = jersey
var_password = 123456
// dont forget to escape for sql injection
// generate md5sum for password
var_md5password = md5(password)
SELECT * FROM users WHERE username = 'var_username' AND password = 'var_md5password'
for example
|- id -|- username -|- password -|
|- 1 -|- jersey -|- 123456 -|
|- 2 -|- timber -|- 1234567 -|
table with md5
|- id -|- username -|- password -|
|- 1 -|- jersey -|- e10adc3949ba59abbe56e057f20f883e -|
|- 2 -|- timber -|- fcea920f7412b5da7be0cf42b8c93759 -|
more secure way
secret_key = topsecretkey
password: 123456
md5(password+secretkey)
it will generate a better md5
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "sql, sql server, asp classic"
}
|
MySQl Trigger help needed
using MySQL 5.1.36, I am trying to write trigger which drops scratch tables form "scratch" database.
CREATE DEFINER=`root`@`localhost` TRIGGER
`jobq`.`DropScratch`
BEFORE DELETE ON jobq.jobq FOR EACH ROW
BEGIN
DECLARE tblname VARCHAR(128);
set tblname=concat('scratch.',OLD.jobname);
DROP TABLE IF EXISTS tblname;
END;
I am always getting an error:
Explicit or implicit commit is not allowed in stored function or trigger.
Can I somehow overcome this restriction?
Thank you beforehand
Arman
|
The primary problem here is that you are not allowed to drop a table within a trigger. That's what the error message is getting at when it says "implicit commit" is not allowed. The drop table does an implicit commit.
So you will need to figure out a different way to do this other than a trigger. One way would be to set up a cron job which compares the data in information_schema.tables to the jobq table to look for tables in the scratch DB that can be dropped, and then drop them.
I should also point out that the way you are trying to dynamically create a drop table statement will not work. That is going to drop a table named literally "tblname", not "scratch.jobname". If you want to drop a table dynamically you will need to build the drop table statement in a separate scripting language, such as python, perl, shell, etc.
Good luck!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, triggers"
}
|
RESTful web server library for iOS
I am trying to create a Rest web service running on iPhone; I've done my initial research and found CocoaHttpServer and TouchCode json parser, is there any library / sample code which binds these together into a Rest endpoint?
If it does not exist, how do I go about writing one? Any reference to some kind of design document etc. will really help.
|
I'm using CocoaHTTPServer and the iOS builtin JSON libraray to have a RESTful service in iVocabulary. First I wrote a lengthy Connection class (the core for handling requests in CocoaHTTPServer) myself. But parsing the URL was kind of complicated.
So I wrote a more generic Connection class that routes HTTP requests to different blocks for different URLs and different HTTP methods. The URL can contain parameters (with : as prefix), that get parsed. That's not a generic REST service per se, but I added (for example) a block for the url "/rest/:entityname" that fetches all Core Data objects of the given entity.
You can find that router implementation in my fork of CocoaHTTPServer on github: <
Another router implementation: <
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "iphone, ios, json, cocoa, rest"
}
|
Using projections to obtain perspective views
I understand that a perspective view is essentially a type of projection. Is it possible to create projection definitions for a typical GIS system that will mimic a perspective view from a particular location? If so, how feasible would it be to use common 2D GIS tools to create perspective renderings of data, similar to what can be achieved in 3D tools such as Arc Scene and Google Earth?
|
Perspective isn't just a "type" of projection to be "mimiced": it _is_ a projection. _E.g._ , ArcGIS supports it (but note that the illustration on its help page is terrible). So all you have to do is tell your GIS to use an aspect of this projection. ("Aspects" vary by how much of the earth they show, the angle they look at it from, and where the viewpoint is located in 3D.)
|
stackexchange-gis
|
{
"answer_score": 2,
"question_score": 4,
"tags": "coordinate system, 3d"
}
|
I set time to wrong time zone, how do I change it? (Debian)
I am on Debian and have used the dpkg-reconfigure tzdata command, however it changed the universal time and not the local time. My clock on xfce still displays the wrong time. Right after setting the right time it displays this:
Current default time zone: 'America/Los_Angeles' Local time is now: Sun Jan 17 04:50:23 PST 2016. Universal Time is now: Sun Jan 17 12:50:23 UTC 2016.
My time is 4:50 am
It seems to have the correct timezone, but it is eight hours off :(
|
You need to set your clock to the correct time. Right now it's 2100 UTC, so in Los Angeles it should be 1pm (1300 hours).
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 1,
"tags": "debian, timezone"
}
|
Using different infinitive forms for the "unreal past" and "future"
I assume these three sentences below have the same meaning. Only the first one conveys the message that the action of sitting happens for a longer period. Am I right?
* I'd like to have been sitting there when she walked in.
* I'd like to be sitting there when she walked in.
* I'd like to be there, sitting when she walked in.
These sentences are refereeing to the unreal past. My second question is that weather it would be alright to just change
> when she walked in >
to
> when she walks in
and keep the rest of the sentences unchanged, to talk about a **wish**?
|
Only **to have been** is correct in the first part of your sentence when used with _when she walked in_. We need to use _have been_ because we are referring to an event in the past; saying _I'd like to be_ expresses a wish about the present or future.
If you change _when she walked in_ to _when she **walks** in_, you change the meaning of the sentence, from the past to the present tense. The present tense can refer to a general truth (like _she walks in every day_ ) or a planned future event (like _she walks in at 8 o'clock tonight_ ). If you use _she walks in_ , then you have to wish _to be (sitting) there_ to match.
|
stackexchange-ell
|
{
"answer_score": 2,
"question_score": 0,
"tags": "adjectives, infinitives"
}
|
Given n elements, each with m possibilities, what is the probability of seeing certain elements at least once?
Say there are m different objects I can pick from, and I have n objects. Each has an equal probability of being any of the m possibilities. Each object is determined independent of the others.
Say two of the possibilities are A and B. What is the probability I see both A and B at least once? How is this extended for more than two elements?
For a concrete example: I'm rolling n m-sided dice. I want to know the probability I see all of the numbers 1 through k at least once?
|
Let: $A_i$=see Ai object at least once,
so $A_i'$=not see Ai object at all. Suppose we have a m-sided dice, which I roll it n times.
An example for 3 objects A1,A2,A3
$P(A_1 \cap A_2 \cap A_3)=1-P((A_1 \cap A_2 \cap A_3)')=1- P(A_1' \cup A_2' \cup A_3')=1-[P(A_1')+ P(A_2')+P(A_3')-P(A_1'\cap A_2') -P(A_3'\cap A_2') -P(A_1'\cap A_3')+P(A_1'\cap A_2'\cap A_3')]$
where
$P(A_i')=\frac{(m-1)^n}{m^n}$
$P(A_i'\cap A_j')=\frac{(m-2)^n}{m^n}$
$P(A_i'\cap A_j'\cap A_l')=\frac{(m-3)^n}{m^n}$
For 4 objects work the same with the use of \begin{align*} P(A \cup B \cup C \cup D) & = P(A) + P(B) + P(C) + P(D) - P(A \cap B) - P(A \cap C)\\\ & \quad - P(A \cap D)- P(B \cap C) - P(B \cap D) - P(C \cap D)\\\ & \quad + P(A \cap B \cap C) + P(A \cap B \cap D) + P(A \cap C \cap D)\\\ & \quad + P(B \cap C \cap D) - P(A \cap B \cap C \cap D) \end{align*} and for k object the same way
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "probability"
}
|
Pentaho- How do I view the backend sql of reports?
I have currently managed to get access to the Pentaho User console and have 4 reports that I plan to migrate to an alternate BI platform ( say Power BI or SSRS)
Within Pentaho user console, I can view the reports, my home page also shows me option to create new report/ Manage data sources.
However, I am unable to view the dataset/ query behind any of these 4 reports. I would like to know which are the tables being referred to in these reports and the basically want to reuse the SQL query.
NOTE- My user console does not show an option to EDIT an existing report.
Any pointers would be really appreciated!
|
1. You can't edit Pentaho Reports(.prpt) in pentaho CDE(BI Server), you have to open the files in pentaho report designer itself.
2. For dashboards we do have option, every dashboard file will create two other files along with CDE, you can edit the CDA file by going into browse files and execute the query and see the result.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "pentaho, pentaho data integration, pentaho cde, pentaho report designer, pentaho design studio"
}
|
php redirect and google analytics
Hi I see there are some topics on this but can't really relate them to my question. I have a domaina.com that I use for an email campaign.
This domain only has one page (index.php) and it redirects to my real website that is domainb.com
When I go into analytics I want to be able to see under referals that they came from domaina.com
There are so many ways of redirecting and I cant really figure out the right way to do it to make sure its looked at as a refereal by google analytics so I can use the data to analyse the outcome.
Can anyone give me a hint on how to do this?
Thanks
|
I frankly do not think it's possible to set a referrer with a PHP redirect (AFAIK the referrer header is set by the browser, not by PHP).
However you can use campaign parameters and set the medium to "referrer", the source to domaina.com and campaign to "(not set)". So you would set your redirect url to:
After GA evaluated the campaign paramters this should produce the result you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "php, google analytics, redirect"
}
|
Why does non-lenient SimpleDateFormat parse dates with letters in?
When I run the following code I would expect a stacktrace, but instead it looks like it ignores the faulty part of my _value_ , why does this happen?
package test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(final String[] args) {
final String format = "dd-MM-yyyy";
final String value = "07-02-201f";
Date date = null;
final SimpleDateFormat df = new SimpleDateFormat(format);
try {
df.setLenient(false);
date = df.parse(value.toString());
} catch (final ParseException e) {
e.printStackTrace();
}
System.out.println(df.format(date));
}
}
The output is:
> 07-02-0201
|
The documentation of DateFormat.parse (which is inherited by SimpleDateFormat) says:
>
> The method may not use the entire text of the given string.
>
final String value = "07-02-201f";
In your case (201f) it was able to parse the valid string till 201, that's why its not giving you any errors.
The "Throws" section of the same method has defined as below:
>
> ParseException - if the beginning of the specified string cannot be parsed
>
So if you try changing your string to
final String value = "07-02-f201";
you will get the parse exception, since the beginning of the specified string cannot be parsed.
|
stackexchange-stackoverflow
|
{
"answer_score": 12,
"question_score": 14,
"tags": "java, simpledateformat"
}
|
Pass a multidimensional keyed array into javascript via html
I have this in my html...
<button onclick="myFunction(array['foo':['bar', 'pub']])">Click Me</button>
However, the browser complains, "SyntaxError: missing ] in index expression".
I've checked for missing brackets and am pretty sure it's all good, as well as making sure the receiving function worked (switched out original for one that just prented the array to test with.)
|
String-associative objects are called, just as hinted, `Objects`. `Arrays` are a specific _type_ of object that access their elements by numerical index. Objects also use a different literal syntax, and neither uses a keyword to instantiate them.
<button onclick="myFunction({'foo':['bar', 'pub']})">Click Me</button>
That said, have you looked into "data-... attributes"?
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, arrays, html, multidimensional array"
}
|
Dropwizard not logging to file
I have logging configured in my dropwizard yml file to log to a file and not to the console, however some logs are still being logged to the console.
service.yml
logging:
level: INFO
appenders:
- type: file
threshold: DEBUG
logFormat: "%-6level [%d{HH:mm:ss.SSS}] [%t] %logger{5} - %X{code} %msg %n"
currentLogFilename: /tmp/application.log
archivedLogFilenamePattern: /tmp/application-%d{yyyy-MM-dd}.log
archivedFileCount: 7
timeZone: UTC
When I execute I get my service logs in my log file but i get request logs on the console and not in the log file
127.0.0.1 - - [11/Nov/2015:22:31:52 +0000] "GET /api/v1/hello HTTP/1.1" 200 - "-" "curl/7.15.3 (x86_64-unknown-linux-gnu) libcurl/7.15.3 OpenSSL/0.9.8w" 1
Im using Dropwizard 0.7.1
|
You will need to configure an appender for request logs. The default appender is console.
Reference: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "dropwizard"
}
|
Geometric centre of a simplex
Let be $S_n(1)=$$\\{(x_1, x_2, ... ,x_n)\in \mathbb R^n : x_j\geq 0, x_1 + x_2 + ... + x_n \leq 1\\}$ the standard simplex. My task is to calculate the geometric centre C with Lebesgue integration. I know $C=\frac{1}{\lambda(S_n(1))}\int_{S_n(1)} x \,d\lambda$. I have already shown that $\lambda(S_n(1))=\frac{1}{n!}$. But I don´t know how to solve the integral..
Any help or hints is greatly appreciated!
|
When you cut through the simplex with a hyperplane at coordinate $x$, you get a cross-section that:
* is a simplex of dimensionality $n-1$
* has lengths $u=1-x$ times those of the standard simplex with that dimensionality.
You conclude that the integral is
$\int_0^1(1-u)u^{n-1}\lambda(S_{n-1}(1))du$
where I have substituted $u=1-x$ and you already know $\lambda(S_{n-1}(1))$ according to the problem statement. Can you continue from there?
From standard geometric considerations, you should get $1/3$ for $n=2$, $1/4$ for $n=3$, ... .
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "lebesgue integral, simplex"
}
|
Is it possible to add markdown to the OS X Server blog editor?
I recently installed OS X Server and have enabled the wiki/blog functionality.
Is it possible to add markdown to the blog editor?
If not, is there software that integrated with the blog functionality and provides a markdown editor as part of a native OS X application?
|
I reviewed an edition of the server guide and see no markdown support anywhere, so I think you may have to go with another tool that easily exports into other formats.
I'd recommend running with Markdown Service Tools to start. It's all you need to stick to markdown on a mac. If you like GUIs like I do, you may also like using MacDown to write in markdown and export however you need it. It's a great open-source solution to the problem.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 3,
"tags": "macos, osx server"
}
|
Are Drasilian coins only for selling?
NPCs in _Dragon Quest XI S_ say that Drasilian coins are the only item I don’t need to hold onto, I can sell them all. Is this correct or do I need them for a quest or crafting later?
|
Just as the NPCs say, Drasilian coins are never useful for anything besides selling for money. No quest or exchange requires them, and they are used in no forging recipes. Sell them to your heart's content.
|
stackexchange-gaming
|
{
"answer_score": 2,
"question_score": 5,
"tags": "dragon quest xi"
}
|
How to make wysiwyg using Flutter?
I want to make wysiwyg like 
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python, selenium, get"
}
|
How to check in PowerShell if the script was run in background (e.g. Windows Task Scheduler) or in user session
How to check in PowerShell if the script was run in background (e.g. via Windows Task Scheduler) or in user session
|
Inside the script (When the script is running) you can use $host.name
if ($host.name -match 'ise') {"Do not send mail.."}
if ($host.name -match 'console') {Send-mail...}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "windows, powershell, windows task scheduler"
}
|
Transformations of sinusoidal functions
We have 2 sinusoidal functions:
$f(x)= 0,30+2\sin (3x-\frac{1}{2}\pi$) and $g(x)=0,30+2\sin(3(x-\frac{1}{2}\pi))$.
What would happen to both functions if you performed a translation of let's say $(3\pi;0,10)$?
What would happen if you multiply with reference to the y-axis (I believe in English it's called a horizontal stretch) of f(x) and g(x) with $\frac{1}{5}$?
I have to do this in a test in 2 hours but nowhere in the book do they explain transformations of already 'complete' sinusoids (of the form a+sinb (c(x-d)) ) , I understand transformations, however this is the last thing I must know, you guys on mstackexchange have helped me a lot, since I've missed every single lessson this past month I had you guys as my 'teachers' and I'm sorry for some of my boring questions.. this is the last one, after that my questions will be better , I promiss.
|
I'm going to write $.3$ instead of $0,30$ as I'm more comfortable with that notation.
Translating $f(x)=.3+2\sin(3x-(\pi/2))$ by $(3\pi,.1)$, following the example given in the comments, gives you $$f(x)=.1+.3+2\sin(3(x-3\pi)-(\pi/2))=.4+2\sin(3x-(19\pi/2))$$ which you could also write as $$f(x)=.4+2\sin(3x-(3\pi/2))$$ Can you do $g(x)$ now?
I'm not sure what's meant by "multiply with reference to the $y$-axis" but a plausible interpretation yields $$(1/5)(.3+2\sin(3x-(\pi/2)))$$ which you might write as $$.06+(.4)\sin(3x-(\pi/2))$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "trigonometry"
}
|
Does multiple updates on single document in a transaction incur write cost for each update separately in Firestore
For example will `update(sfDocRef, "population", newPopulation)` and `update(sfDocRef, "count", newCount)` be counted as separate document write. Or should i use set() method
db.runTransaction { transaction ->
val snapshot = transaction.get(sfDocRef)
val newPopulation = snapshot.getDouble("population")!! + 1
val newCount = snapshot.getLong("count")!! + 1
it.apply {
update(sfDocRef, "population", newPopulation)
update(sfDocRef, "count", newCount)
}
}
|
It is considered as a seperate write operation. It is better to combine those. I think this will help you. Link
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 1,
"tags": "firebase, google cloud firestore, transactions"
}
|
How does a redux thunk function operate? What happens when a redux thunk function gets called?
I am struggling to wrap my head around the syntax/ understanding how the thunk function flow...
i.e. the following function:
function incrementAsync() {
return dispatch => {
setTimeout(() => {
dispatch(increment());
}, 1000);
};
}
I think I mostly am confused by the passing in `dispatch` as an argument part. What exactly happens when `incrementAsync` is called?
|
A normal Redux action is a plain JS object, as illustrated in the tutorial: <
What Thunk does is to extend Redux so that actions can also be a function. When `incrementAsync` is called, it returns a new function that takes an argument `dispatch`. That function is then called by Redux (via Thunk), passing in the `dispatch()` function from Redux as an argument, enabling you to dispatch more actions (a)synchronously.
This is all taking advantage of the fact that JS functions are first-class members of the language and can be assigned to a variable, and passed around.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, reactjs, function, redux thunk, dispatch"
}
|
Request a 2nd url with the same HttpWebRequest obj
I want to do something like this
{
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("
WebRequestObject.KeepAlive = true;
//do stuff
WebRequestObject.Something("
//more here
}
How do i keep the connection alive and go to multiple urls using that same alive connection?
|
You simply use another `HttpWebRequest` object and provided that you set `KeepAlive` to `true` in both cases the internal HTTP connection manager in the .NET Framework should handle things for you. See the MSDN documentation for the `KeepAlive` property for more info on this.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "c#, .net, httpwebrequest"
}
|
Scan table in stored procedure
I want to put in an array some columns of a table in sql server.
for example
att1 att2 att3 att4 att5
-------------------------
1 2 3 4 5
5 6 7 8 9
10 11 12 13 14
I want to have it into an array only the first 3 columns
like
`[1,2,3,5,6,7,10,11,12]`
so i am skipping columns att4 and att5
|
var dataList = new List<object>();
while (reader.Read())
{
var values = new object[reader.FieldCount];
var fieldCount = reader.GetValues(values);
dataList.AddRange(values);
}
//var arrayData = dataList.ToArray()
var arrayData = dataList.ConvertAll<double>(o => (double) o).ToArray();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "c#, sql server 2008, stored procedures"
}
|
Is there a word for major software developers?
Is there a word for major software developers? There are amateur developers who work alone, there are indie developers who work for small companies and then you have Adobe who is a major developer. Is there a word or adjective that's used to refer to them? I am wondering, for instance, how Microsoft refer to those major developers in their internal memos. There has to be some kind of word or phrase.
|
Sure "Major software developers". You sometimes call a publishing company a "house" so "Major software houses" is also possible.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 0,
"tags": "word request, phrase request"
}
|
Identify html form or its encoding (text or file) in servlet
How do I recognize in a servlet whether the request sent using HTML form has enctype `multipart/form-data` or the default `application/x-www-form-urlencoded`?
Alternatively: is there any other way to recognize which form was used? `request.getParameter("some_param")` works only with default encoding.
|
> _I'm using Apache Commons FileUpload for multipart, but wasn't sure how to switch between handling multipart and default forms_
Use Apache Commons FileUpload's own `ServletFileUpload#isMultipartContent()` to check it.
if (ServletFileUpload.isMultipartContent(request)) {
// Parse with FileUpload.
}
else {
// Use normal getParameter().
}
### See also:
* Apache Commons FileUpload User's Guide
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, forms, servlets, apache commons fileupload, enctype"
}
|
Which is better in terms of performance? To test whether a boolean is true or set it all the times?
For example in a very long loop:
(`bool x;`)
To test it always:
if (!x) x = true;
or just set it to true all the time:
x = true;
|
The unconditional assignment is, more importantly, easier to read. It is highly unlikely that such code would be executed often enough to affect overall performance of any program.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "performance, language agnostic"
}
|
How do I programmatically redirect an unauthenticated request to an STS?
I need unauthenticated users to first be redirected to a login page on an ASP.NET website, then I'll do some business logic to determine one of three authentication types:
1. the user will manually log in with a username and password
2. the user will get redirected to an STS for a federated login
3. or (in some cases) the user does not require a login at all and the system will just set their IsAuthenticated=true so they can continue on in their process.
My question is, if it's option #2, how do I programmatically redirect a request to an STS like if I had checked the option in the image below to "Redirect all unauthenticated requests to the STS"?
!enter image description here
|
What we had to do what set it to "Redirect all unauthenticated requests to the STS" and then look in the ISS logs on the receiving Active Directory server to see what the URL looked like that is was redirecting to. Then we were able to build the URL on the fly from the Login.aspx page and redirect manually when necessary.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "asp.net, wif, claims based identity"
}
|
How can I eliminate the errors in SQL
I wrote a simple code to create a table in SQL. It is generating errors I am unable to understand even though I am sure the syntax are correct. Here is the output of my problem in the image: ,
email varchar(128)
)
I highly recommend you to avoid using reserved words like Users.
A guide to help you creating tables.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "mysql, sql"
}
|
Copy a Geopackage to another folder using PYQGIS
I try to copy a GPKG to another folder. The result is the correct named copied GPKG but there is only one layer in the copy. It’s the layer with the same name as the GPKG. The other features (1x polygon, 1x no geometry) from the original are not copied. The original GPKG is open with QGIS when I start the copy-process. Is there another simple way to copy the whole GPKG or do I have to create a new GPKG and copy the layers of the original GPKG to it?
from shutil import copy
inputgpkg = r'C:\Testfolder\original.gpkg'
outputgpkg = r'C:\Testfolder2\copy.gpkg'
copy(inputgpkg,outputgpkg)
|
As user30184 stated, one needs to copy the -wal and -shm file as well:
from shutil import copy
inputgpkg = r'C:\Testfolder\original.gpkg'
outputgpkg = r'C:\Testfolder2\copy.gpkg'
copy(inputgpkg,outputgpkg)
copy(inputgpkg+'-wal',outputgpkg+'-wal')
copy(inputgpkg+'-shm',outputgpkg+'-shm')
|
stackexchange-gis
|
{
"answer_score": 2,
"question_score": 0,
"tags": "pyqgis, geopackage"
}
|
Storing and loading str:func Python dictionaries
Alright so I want to know if doing this would affect the code, and if I'm doing it correctly.
So basically, let's say in one file I have a dictionary called commands (inside a class), and in another an object of the other class is made, and the dictionary is used. During run-time, I edit the dictionary and add new functions. Now I need to reload the dictionary without having to restart the whole script (because this would affect a lot of people using my services). If I send a signal to the script (it's a socket server) that indicates that the dictionary should be reloaded. How would I re-import the module after it's already imported mid-code? and would re-importing it affect the objects made of it, or do I have to somehow reload the objects? (note that the objects contain an active socket, and I do not wish to kill that socket).
|
It is better to store the data in a database, like Redis which supports dictionary-like data. This way you can avoid the problem of reloading altogether, as the database process makes sure the fetched data is always up-to-date.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 3,
"tags": "python, sockets, dictionary, import, module"
}
|
Merge 2 columns with priority
I have a pandas df with 2 columns A and B. What I need is a new merged column 'result', in which A is preferred to B. I really thought it would be easy but still no solution. How would you guys do that? Thanks for your help.
A B result
go for go
go go
go go
for for
for for
|
Use `combine_first` or `fillna`:
df['result'] = df['A'].combine_first(df['B'])
print (df)
A B result
0 go for go
1 go NaN go
2 go NaN go
3 NaN for for
4 NaN for for
Or:
df['result'] = df['A'].fillna(df['B'])
print (df)
A B result
0 go for go
1 go NaN go
2 go NaN go
3 NaN for for
4 NaN for for
EDIT:
For replace empty space to `NaN`s use:
df = df.replace('', np.nan)
Or:
df = df.mask(df == '')
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "python, pandas, merge"
}
|
Putting icon in a textbox in XAML (WPF)
I want to put a small icon (a png file) in to the corner of a textbox. A sketch of what I mean is at <
So far I've got (in my main xaml file)
<TextBox Style="{StaticResource IconTextBox"} ...
and in my resources area:
<Style x:Key="IconTextBox" TargetType="TextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Image Source="icon.png" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Obviously this isn't working (I'm losing the textbox for a start!). Ideally when the user is typing into the textbox, the text doesn't overlap the image - but for the time being I'll just be happy getting the image in the textbox.
Thanks
|
Instead of overwriting the template, I would create a new simple UserControl:
//pseudocode, does not compile!
<UserControl x:Class="MyUserControl" x:Name="root">
<Grid>
<!-- put some effort in aligning the items so it looks nice -->
<TextBox Text="{Binding ElementName=root, Path=Text}" />
<Image Source="{Binding ElementName=root, Path=IconSource}" />
</Grid>
</UserControl>
public class MyUserControl : UserControl{
dependencyproperty string Text;
dependencyproperty string IconSource;
}
so you can use it as follows:
<my:MyUserControl Text="{Binding MyText}" IconSource="{Binding MyIcon}"/>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "wpf, textbox, icons"
}
|
How to use codecs to convert from one language to a utf-8 encoded document?
So basically I am still pretty new to Python and I have a problem where I have a document in Japanese that I am trying to convert to a utf-8 encoded document. I don't really know what I should be getting in return when I do this. When i run the program I currently have, it just deletes everything and leaves me with a blank utf-8 encoded document. Here is what I have, any help is greatly appreciated.
EDIT: I'm sorry it was a typo, I fixed the original encoding. It is Shift-jis.
import codecs
codecs.open("rshmn10j.txt", 'r', encoding='shift-jis')
newfile = codecs.open("rshmn10j.txt", 'w', encoding='utf-8')
newfile.write(u'\ufeff')
newfile.close()
|
if you're trying to convert a document from encoding "x" to encoding "utf8", you first have to read the document using the encoding it is encoded in.
import codecs
original_document_encoding = "shift-jis" # common japanese encoding.
with codecs.open("rshmn10j.txt", 'r', encoding=original_document_encoding) as in_f:
unicode_content = in_f.read()
with codecs.open("rshmn10j.out.txt", 'w', encoding='utf-8') as out_f:
out_f.write(unicode_content)
`with` is used here to auto-close the file when the block is exited.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, codec"
}
|
Script to stop/restart local SQL services
Does anyone have a simple script (powershell or command line) that would enable to me to shutdown local SQL Services (SQL Server, Integration services, etc ..) when I don't need them and then perhaps another script to turn them all back on when I do need them?
Currently I am going to Services and then stopping/starting them manually.
|
We had a need to stop and disable and then enable and start on multiple remote servers, so this is how I handled it:
Stopping:
function stopdisable ($compnam, $svc)
{
(get-service -computername $compnam -name $svc).stop()
set-service -computername $compnam -name $svc -startuptype disabled
}
stopdisable "server1" "servicename1"
stopdisable "server2" "servicename2"
Starting:
function enablestart ($compnam, $svc)
{
set-service -computername $compnam -name $svc -startuptype automatic
(get-service -computername $compnam -name $svc).start()
}
enablestart "server1" "servicename1"
enablestart "server2" "servicename2"
Of course, this is dependent upon you having the appropriate permissions on the remote servers.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql server, powershell"
}
|
Google Maps API - Create Offset for Overlays dynamical for every zoom level
I have a `balloon` which pops up when clicking on a `Marker`. Sometimes the balloon exeeds the bounds of the map and is not fully shown.
I can't center the map to the coordinates of the marker, because the ballon is sometimes too high and would still be outside the bounds. So I need an `offset` which moves the center of the map slightly down so the balloon is always nicly in the middle of my map.
The problem is that Google maps doesn't work with pixels but with `LatLng`. Therefore I need a dynamically scalable function to keep the offset in every zoomlevel the same!
|
Alright, I found an algorithmic solution!
map.setCenter(
new google.maps.LatLng(
marker.getPosition().lat()+(X/Math.pow(2,map.getZoom())),
marker.getPosition().lng()
)
);
Each zoom level nearly doubles the LatLng which is shown on the map. So just find an `X` which is the perfect offset for you (in my case it was 128) and everything works great!
PS: The position of the marker is the same as the balloon.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, google maps api 3, google maps markers"
}
|
Which to use: OneToOne vs ForeignKey?
My understanding is that OneToOneField is used for just 1 row of data from **_Table2_** (Favorite fruit) linked to one row of data in _Table1_ (Person's name), and ForeignKey is for multiple rows of data in **_Table2_** (Car models) to 1 row of data in **_Table1_** (Brand/Manufacturer).
My question is what should I use if I have multiple tables but only one row of data from each table that links back to **_Table1_**. For example: I have Table1 as "Cars", my other tables are "Insurance Info", "Car Info", "Repair History". Should I use ForeignKey or OneToOne?
|
You just need to ask yourself "Can object A have many object B, or object B many object A's"?
Those table relations each could be different:
1. A Car could have 1 or many insurance policies, and an insurance policy only applies to one car. If the car can only have one, then it could be a one-to-one.
2. A Car can have many repair history rows, so this would be a foreign key on the repair history, with a back relation to the Car as a set.
3. Car Info is similar to the UserProfile concept in django. If it is truly unique information, then it too would be a one-to-one. But if you define Car Info as a general description that could apply to similar Car models, then it would be a foreign key on the Car Table to refer to the Car Info
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 7,
"tags": "python, django"
}
|
Can I keep a REST web service in the same codebase as a regular web app
I am working to create a web app. Simultaneously I am also developing a REST web service that will use the same codebase...What I want to know is, can I make the same codebase on a server function as base for both the web app and the web service. (In the web app a user can log in and perform operations while the web service is like an API).
Or do I need to keep 2 distinct code bases for the web app and the web service?
Also, I want the same web app to act as both producer and consumer of the web services...Is this possible?
|
Yes you can. Technical a REST API is the same thing as the server side of a web application.
But if your REST API is accessed by third parties you might want to have a different versioning strategy then for your web app, so for anything of serious size I would probably separate those.
Sorry can't speak about the producer/consumer part of the question. Don't understand that part of the question.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, rest"
}
|
Facebook ID change
im developing a web with Facebook Login. When the user login, i store the facebook id.
**The problem is that i change the AppID and AppSecret (because i create a new app in facebook) and the user id return by facebook is different than my old app**
Im using PHP v4.0 Facebook SDK and this is my code:
$facebook = new Facebook(array(
'appId' => '***********',
'secret' => '**********************',
'cookie' => true,
'oauth' => true,
));
$user = $facebook->getUser();
$me = null;
if ($user) {
try {
$me = $facebook->api('/me');
$this->facebook_id = $me['id'];
Then i store it in a database..
**Thanks!**
|
That is intentionally.
Facebook does that for privacy reasons.
There is no way to obtain the same user id from different applications.
> The id of this person's user account. This ID is unique to each app and cannot be used across different apps.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "php, facebook, facebook graph api, facebook php sdk"
}
|
API server not function ["The connection has been reset"]
I'm having some troubles with one of my servers. I've done an application with two servers, one the frontend that grabs the data of server API (Ubuntu server).
Well, yesterday had a lot of visits and the API server stop functioning but:
-I can do stuff in MySQL by SSH.
-The memory usage is ok.
-The logs are ok.
-The bandwitch usage is ok.
-If i restart the server or Apache2, function by some time (3-4 minutes).
And the most important i think if i tries to access to API (Is rest-style with http) it puts me the Firefox error "The connection has been reset".
I'd tried:
-Restart the server
-Restart Apache2
-Restart MySQL
-Viewed the logs of Apache2/MySQL
I don't know too much about systems so i don't know what to do more.
|
Conection-resets for HTTP connections like you're doing are usually the result of the web-server hanging up or outright refusing to connect. There are a couple of possible causes of this:
* The web-server is not listening on the port you think it is.
* The Front-end is trying to talk to the API server on a port you're not expecting.
* The web-server didn't actually start
* You can verify this through `netstat -an` and looking for a listening service on the port you're expecting.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linux, apache 2.2, ubuntu, timeout"
}
|
What does it mean to do/determine something "programmatically"?
Programmatically. (alt. programmically)
I've never used it, but I see it in questions a lot, i.e. "How to programmatically determine [insert task here]". Firefox immediately tells me that neither of these two words are real (at least, it doesn't recognize them). I've also never seen them used anywhere but here.
1) What does it mean to do/determine something "programmatically"?
2) Why do so many people ask how to do/determine something "programmatically"? Isn't it _assumed_ that, if you're asking how to do something on a programming help board, you're asking how to do it "programmatically"?
3) Why is it that I've never seen the word "programmatically" anywhere else?
|
Doing something programatically generally means that you can do it using source code, rather than via direct user interaction or a macro.
For example, consider the problem of resizing columns to fit in Excel.
You could do it manually by double clicking between the columns, but that requires user interaction.
You could use the excel macro recorder, but that is fairly complicated.
Or, you could use VBA to write code that would do it.
I doubt it's actually in the dictionary.
|
stackexchange-stackoverflow
|
{
"answer_score": 64,
"question_score": 44,
"tags": "computer science, terminology"
}
|
Is powerline communication secure for a shared building?
I have been looking at Ethernet over power to provide network access in another room, as this is on the electrical grid of my building what/are there any security risks with someone sniffing my data? if so are there devices that encrypt the content.
any advise on security issue would be great
Lee
|
I think you're looking for ethernet over power lines, not PoE (power-over-ethernet which mean using a pair of wires from the ethernet cable to power the device). I'm using a pair of Devolo at home and they are working well and the traffic is encrypted.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "networking, ethernet"
}
|
Appdomain refresh / restart
I am writing a webservice and have the following observation: Even if I simply add a text file to the directory (bin) where all the dlls referred by the webservice is stored, the appdomain refreshes.
This causes all the user sessions stored in a Dictionary (in one of the dlls) to be erased.
For example, if the dictionary above is contained in a dll, say, sessiondict.dll and I am replacing another dll that has no dependancy whatsoever with sessiondict.dll, then why should this data be lost?
Am I missing anything?
**EDIT:**
Though I am reading more on AppDomain restarts, however, have not been yet able to figure out as to why the design is such that even adding a text file in the bin folder causes the appdomain to restart.
|
This is standard behaviour - any time anything in the bin directory is touched (as well as other locations such as web.config) then your appdomain will recycle.
You shouldn't be storing data inside the bin directory. You also should be aware that IIS by default will recycle the appdomain at regular intervals unless you've told it not to (once per day by default I believe).
As you can't replace one part of an application anyway, I'm not sure what the valid reasons for doing this are?
This post is a good explanation of what can cause AppDomain recycles.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, .net"
}
|
Why do some apps require a password when I move them to the trash?
Some applications located in `/Applications` require a password in order to move them to the trash, others don't. Then there are also apps which cannot be deleted because they are required by OS X (a warning pops up).
Upon further inspection, I've come to the conclusion that **Apps installed via the Mac App Store** require a password in order to be moved to the trash. Why?
|
This is a permissions effect. Most Application installed on Lion by default, via the App Store, and some installers are installed as `system` a.k.a Root and root only by default has Read and Write access to the Applications installed as root, while everyone else including your user is read only or custom for each Application. Applications that you drag and drop are owned by you, and you can delete them at will usually with out a password.
Verify in the Finder or Terminal what the permissions are on Apps that require a password to move to the trash, its likely that those Apps that are set to **read only** access for your current user are the ones asking for a password and a temporary privilege to delete something owned by the system.
In terminal try:
ls -la /Applications
|
stackexchange-apple
|
{
"answer_score": 2,
"question_score": 2,
"tags": "applications, mac appstore, macos"
}
|
App Engine authentication to access google cloud resources
1. I'm building an app using which the users registered(from the IAM page) for the project can access the resources of that project. I need the authentication when the URL is hit. Is there a way to achieve this?
2. Is it possible to provide IAM roles specific for a user request (assuming that the user will login using his email id) to access the resources based on IAM level permissions?
|
In the early days of AppEngine it was pretty easy to do some basic auth/access-control, but lately they're moving it to something called IAP.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "google app engine, google cloud platform, google authentication, google iam"
}
|
How do I write a query with a negative boost?
The ElasticSearch API indicates that you can create negative boosts to demote results. How does one do this in Searchkick? Do I need to use the advanced query tools? Or is there an option somewhere I'm missing?
|
It's worth noting that `function_weight` takes a float, so you can using a negative floating point number for a negative boost.
This means that you can use `boost_where` with a negative value to demote a result based on a field.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "elasticsearch, searchkick"
}
|
Which is the correct relative error?
Which is the correct relative error?
$$ r_1=\frac{|p_n-p|}{|p_n|} $$ or $$ r_2=\frac{|p-p_n|}{|p|} $$
|
Assuming $p$ is the exact solution and $p_n$ is a numerical approximation, the absolute and relative errors are defined as $$\text{err}_\text{abs} := |p_n-p|$$ and $$\text{err}_\text{rel} := \frac{\text{err}_\text{abs}}{|p|} = \frac{|p_n-p|}{|p|}$$ So $r_2$ is correct.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "numerical methods"
}
|
Highcharts max interval for dateTime in x-axis?
I have a daily graph, spanning across 00:00 to 23:59. but for live data, let's say currently is 9AM, by default it will stretch the graph from 00:00 - 09:00, which doesn't look nice to me. What I want is the x-axis max at 23:59 of the same day, so it will show 09:00 - 23:59 as blank. I tried `$graph["xAxis"]["max"] = (time()+86400)*1000` but without avail. any suggestion? thanks!
|
Highcharts will only show the last data point that is specified. If you want to force it to show the 0900 - 23:59 you will have to pass it all the data points for the those times you want displayed, **but for the value pass null**. Here is an example: jsfiddle example.
Once the data points go over the hour range it will automatically format the datatime labels differently. You may want to control the formatting of the data labels via dateTimeLabelFormats.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 6,
"tags": "javascript, highcharts"
}
|
How to give space between two cells in tableview?
I want a space between two cell in table view,
I want cell like this,
!enter image description here
How can i do that?
|
You can create a Sections of TableView also in the UITableView... This methods are compulsory so create sections and in each section you can create single cell as in your picture..
|
stackexchange-stackoverflow
|
{
"answer_score": 23,
"question_score": 50,
"tags": "iphone, objective c, cocoa touch, uitableview, ios4"
}
|
Find the pattern in these numbers
> 3, 3, 5, 4, 4, 3, 5, 5, 4, 3
How did I get those numbers and how do I get more that fit the pattern?
|
the pattern comes from:
> the letter count of the names of the numbers 1 to 10
Because
> one has 3 letters, two has 3 letters, and so on.
|
stackexchange-puzzling
|
{
"answer_score": 6,
"question_score": -4,
"tags": "pattern, english"
}
|
No data showing when adding delimited text layer with lat/long
See screenshot of Data Source Manager of Delimited Text input. Sample data look fine.
 to check it. If they are there, setting Geometry CRS to EPSG:4326 should solve the problem.
EDIT: Your coordinates are treated as text fields because of the ° characters. Delete them and it will work fine.
|
stackexchange-gis
|
{
"answer_score": 4,
"question_score": 0,
"tags": "qgis, coordinate system, qgis 3, csv"
}
|
Back to "initramfs" on Debian by systemd "shutdown to initramfs" feature
I need to go back to initramfs during shutdown in order to do a clean unmount of the loopback devices which host my linux installation.
To achieve that goal I have read a lot of documentation and source code about the shutdown to initramfs feature.
Unfortunately it seems unsupported on Debian.
I believe it maybe quite simple to implement by writing shutdown services like the dracut ones, but to avoid a waste of time I would ask you if yet exists a pre-built solution for that.
Thank you so much, Antonio
|
After a lot of experiments I have stated that hacking initramfs tools would not be a stable solution, so I have chosen to rely directly on Dracut.
The complete solution is hosted on GitHub at this URL.
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 4,
"tags": "linux, debian, ubuntu, systemd, initramfs"
}
|
Tools for Debugging ThreadPool Issues in Visual Studio 2010
I have never spent much time debugging multithreaded .NET apps (or others), and have quite a simple one to solve very quickly. Ideally I would imagined and would lurve to be able to intercept thread creation and use by worker objects, so that nothing unexpected happens while I'm on a breakpoint in my thread. Is that realistic?
What else is there in VS 2010?
|
You could freeze all threads except the thread you're currently working with. This should stop all work being done on all other thread pool threads and should prevent new work from getting queued unless the thread you're working with also queues work.
See John Robbins' blog on freezing threads.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": ".net, visual studio, debugging, visual studio 2010"
}
|
Must then A ∩ B also have a maximum?
Let $\sup(A) = \max\\{A\\}$ and $\sup(B) = \max\\{B\\}$ hold,
that is, that the suprema are contained in the respective amount and thus maxima.
**Must then $A \cap B$ also have a maximum?**
If so, prove it. If not, give a counterexample.
I literally have no clue what to do. Please help, I'd appreciate it.
|
Assuming further that $A\cap B \neq \emptyset$ otherwise this could already be a good case for a counterexample.
Take $A= (0,1)\cup \\{2\\}$ and $B=(0,1)\cup\\{3\\}$ then $A\cap B = (0,1)$ has no maximum.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "maxima minima, supremum and infimum"
}
|
Creating a Python list comprehension with an if and break
Is it possible to turn this code into a list comprehension?
for i in userInput:
if i in wordsTask:
a = i
break
I know how to convert part of it:
[i for i in userInput if i in wordsTask]
But I don't know how to add the break, and the documentation hasn't been much help.
Any help would be appreciated.
|
a = next(i for i in userInput if i in wordsTask)
To break it down somewhat:
[i for i in userInput if i in wordsTask]
Will produce a list. What you want is the first item in the list. One way to do this is with the next function:
next([i for i in userInput if i in wordsTask])
Next returns the next item from an iterator. In the case of iterable like a list, it ends up taking the first item.
But there is no reason to actually build the list, so we can use a generator expression instead:
a = next(i for i in userInput if i in wordsTask)
Also, note that if the generator expression is empty, this will result in an exception: `StopIteration`. You may want to handle that situation. Or you can add a default
a = next((i for i in userInput if i in wordsTask), 42)
|
stackexchange-stackoverflow
|
{
"answer_score": 59,
"question_score": 19,
"tags": "python, if statement, for loop, list comprehension"
}
|
Why "p" in pmatrix?
I am using the command `\begin{pmatrix} [...] \end{pmatrix}`. I wonder why this command is not just called `\begin{matrix} [...] \end{matrix}` and why a "p" before "matrix".
|
The `amsmath` package provides a number of options. The leading letter before `matrix` indicates the delimiter that is used:
`p` for parens, `b` for brackets, `v` for verts, `B` for braces, `V` for double verts.
\documentclass{article}
\usepackage{amsmath,tabstackengine}
\begin{document}
\[
\begin{matrix}
1&2&3\\
4&5&6\\
7&8&9
\end{matrix}
\quad
\begin{pmatrix}
1&2&3\\
4&5&6\\
7&8&9
\end{pmatrix}
\quad
\begin{bmatrix}
1&2&3\\
4&5&6\\
7&8&9
\end{bmatrix}
\quad
\begin{vmatrix}
1&2&3\\
4&5&6\\
7&8&9
\end{vmatrix}
\]
\[
\begin{Bmatrix}
1&2&3\\
4&5&6\\
7&8&9
\end{Bmatrix}
\quad
\begin{Vmatrix}
1&2&3\\
4&5&6\\
7&8&9
\end{Vmatrix}
\]
\end{document}
 text inside a div.label?
I can add innerHTML if necessary but I can't change the container (class="label").
< (now working example)
|
You can use something along the lines of
<div class="label"
style="position: absolute; top: 70px; left: 20px; width: 200px; height: 120px; display: table; vertical-align: middle; border:1px solid #000">
<span style="display: table-cell;vertical-align: middle;">
Also several lines of
Label Text
may be included
</span>
please see <
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "html, css, vertical alignment"
}
|
Using Serial as boolean function argument
The following program compiles in the Arduino IDE.
void doSomething(bool) {}
void setup() {
doSomething(Serial);
}
void loop() {}
But, as expected, this one doesn't:
class MyClass {};
void doSomething(bool) {}
void setup() {
MyClass myClass;
doSomething(myClass);
}
void loop() {}
The compiler returns the error `cannot convert 'MyClass' to 'bool' for argument '1' to 'void doSomething(bool)'`
* * *
Why is it possible to compile the former? Isn't Serial a normal class instance (of `HardwareSerial`)? Does it makes any sense to interpret `Serial` as a bool?
|
`HardwareSerial` defines `operator bool()`, which allows it to be used in a boolean context.
|
stackexchange-arduino
|
{
"answer_score": 4,
"question_score": 1,
"tags": "serial"
}
|
MomentJs only returning dates within the last week in Meteor
I have a load of dates in a collection in Meteor. At the moment I am just returning them with a limit of 10, but I need to return them up to the last week (7 Days). My problem is there isn't the same number of items in in each day, so I can't just grab the same number for each day. I am using Meteor with moment js. Here is an example of some data and the code I am using to return it:
{
_id: "a68JFTrCFabQe5qQ2",
createdAt: Tue Dec 15 2015 09:32:36 GMT+1100 (AUS Eastern Summer Time),
user: "7uXThqXFkjkMpDrcb"
}
//This data gets to the client with the following:
getDay: function(day){
return Time.find({today: day}, {limit: 10}).fetch();
}
//Instead of limiting it by 10 I need items from the last 7 days only.
Thanks!
|
You need to search for records with a createAt that is greater than today's date - 7 days. Assuming you are using a normal javascript Date() object when creating these objects in the collection, you would use the following code to get all records within the last week:
Time.find({
createdAt: {
$gte: new moment().subtract(1, 'week').toDate(),
$lte: new Date()
}
});
This is if you're using moment. If you aren't, just use regular Date() and subtract a week and put it in the $gt field.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript, meteor, time, momentjs"
}
|
why does running `which` in a node child process result in different results?
when running the `which` command in terminal (for example, `which yarn`), I get a different result from when I'm running a node script (from the same location) which calls `execSync('which yarn')`
can someone explain why?
tldr;
// in terminal
which yarn
// results in
/Users/xxx/.nvm/versions/node/v17.1.0/bin/yarn
// in node
execSync('which yarn')
// results in
/var/folders/0j/xxx/T/yarn--xxx/yarn
|
It looks like the Node.js process is running as a different user (not as you), and that user has a different path from your account (or at least, it isn't running any `.bashrc` or similar specific to your user account that might add to the path). That makes sense given that your result refers to a folder specific to you (`/Users/xxx/`), but the one from Node.js refers to a central location shared by all users.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "node.js, terminal"
}
|
ido-completing-read - How is the history list supposed to behave?
Including the history list makes no difference at all. The colors still appear in the original order.
(setq foo '("blue" "green" "red"))
(ido-completing-read "Pick: " '("red" "green" "blue") nil t nil 'foo)
What is the function of the history list then? Is there an alternative way to change the order of elements based on history, like smex?
|
History list is used when we press up/down while in minibuffer. It doesn't change the order of elements.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "emacs, elisp, ido"
}
|
Ctrl + Alt + V: Disable auto-generation of the keyword "final"
It was not like this in version 1.5, but now that I updated my Android Studio to 2.1.1 whenever I generate a local variable with the Ctrl + Alt + V shortcut, the variable is generated with the keyword "final".
For example, let's say I have the following statements:
Object o = new Object();
o.toString();
Let's highlight the second line and press Ctrl + Alt + V and voila:
final String s = o.toString();
// ^ I'm talking about this.
How do I disable the auto-generaion of the keyword "final"?
This auto-insertion of final is highly annoying as I use this shortcut like every other minute and I have to delete the keyword because most of the time I don't need the variable to be final and would not like to keep my code unnecessarily wordy.
|
I don't know why you want to turn it off since it is good practice.
Here is how you can do that: `, but this function needs a maximum number of elements to be written to the file. I can use `strlen(1)` here but I'd like to know if there is any better way to do this.
|
Use fputs instead:
FILE * f = fopen( "myfile.txt", "w" );
fputs( "Hello world\n", f );
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "c, windows, string, file io"
}
|
Como transformar String de hora para um inteiro?
Exemplo, recebo uma String com a hora do dia "16:20". O dia tem 1440 minutos. Como saber em qual intervalo de zero a 1440 está esta hora? Num valor inteiro(integer).
|
Creio que não precise de uma classe como `Calendar` para resolver, basta um `split` e fazer uma operação matemática, assim:
String horacompleta = "12:39";
String[] horamin = horacompleta.split(":");
int hora = Integer.parseInt(horamin[0]);
int min = Integer.parseInt(horamin[1]);
int minutos = (hora * 60) + min; //Pega o total
Pode colocar em uma função assim:
public static int hour2minutes(String fullhour)
{
String[] parts = fullhour.split(":");
int hour = Integer.parseInt(parts[0]);
int min = Integer.parseInt(parts[1]);
return (hour * 60) + min;
}
E para usar, faça assim:
hour2minutes("12:39"); //759
hour2minutes("16:20"); //980
hour2minutes("23:59"); //1439
Veja um teste no IDEONE: <
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "java, android"
}
|
A way to refresh Firefox in the background?
I'm happily typing HTML in Notepad++ on my Windows machine with 2 monitors, one has Notepad++ and the other has Firefox.
After I finished typing the HTML I would like to see the updated result in Firefox, so I click the Firefox window to highlight it (or `Alt` \+ `Tab` to it when I only have a few windows open), and then press F5, and I see my updated page.
What I want is to have some keyboard shortcut to refresh Firefox while I'm still working in Notepad++, so that I don't have to `Alt` \+ `Tab` all the time.
How could this be done?
|
ended up using this: <
and this: <
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 2,
"tags": "windows 7, firefox, keyboard shortcuts, browser"
}
|
meteor - unexpected token error when using arrow notation
I'm implementing some routing groups, based on post I found which uses arrow notation.
I'm using the latest version of meteor and all top level dependencies are up to date too.
When I save my routes.js, I get an unexpected token error which fails on the arrow notation in the code. I'm missing something obvious I'm sure, any clues?
loggedIn = FlowRouter.group
triggersEnter: [ ->
unless Meteor.loggingIn() or Meteor.userId()
route = FlowRouter.current()
unless route.route.name is 'login'
Session.set 'redirectAfterLogin', route.path
FlowRouter.go ‘loginLayout’
]
Error:
> While building for web.browser: imports/startup/client/routes.js:10:18: Unexpected token (10:18)
|
The tutorial is in coffeescript not js and you are loading it in a .js file which should be .coffee however if you have other js code in routes.js then you need to convert coffee to js. The snippet above would become:
var loggedIn = FlowRouter.group({
triggersEnter: [ function() {
var route;
if (!(Meteor.loggingIn() || Meteor.userId())) {
route = FlowRouter.current();
if (route.route.name !== 'login') {
Session.set('redirectAfterLogin', route.path);
}
return FlowRouter.go(‘loginLayout’);
}
}]
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, meteor, flow router"
}
|
How to show breadcrumbs on Visual studio Code?
I made this window disappear. How do I recover it? , breadcrumbs are enabled by default in VSCode. They can still be toggled using the steps outlined above.
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 12,
"tags": "visual studio code"
}
|
create new folder while saving the file (not before...)
The option to create new folder while saving a file seem to have disappeared in Odin?
Am I missing something? or is it another "improvement" in Odin?
|
This is a consequence of Flatpak packaging and sandboxing, I think. You do not say which apps you find are affected but I suspect they are Flatpak'd or using the FileChooser portal rather than directly. It may depend on what filesystem permissions they request and are granted.
|
stackexchange-elementaryos
|
{
"answer_score": 0,
"question_score": 0,
"tags": "pantheon files, files"
}
|
How are netlink sockets in the Linux kernel different from polling from userland?
I have doubt about the functioning of netlink socket in kernel-application interaction context. As I have read that netlink socket is used for event based notification from kernel to application. The benefit of this is Application is not required to poll.
But as in case of netlink socket also, it will also be polling finally to check whether some data has been sent from kernel. So my question is, how this functioning of netlink socket is different from Polling of file decriptor? I refered this but it tells how to use netlink, not the difference between netlink socket and polling.
|
For applications, the behaviour of netlink sockets and other device files is mostly similar (i.e., calling `poll` and `read`).
You would use netlink if you need one of netlink's features (such as multicast) or if your driver becomes easier to implement (the kernel-side API is more similar to a socket and has built-in buffering) because you don't you have to write the file operations yourself.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "linux, linux kernel, embedded linux, netlink"
}
|
Purpose of this hinge component found on the pinch-bolt of front brake?
I'm thinking that it provides extra tension to the brake line. Would this hinge be set in it's "down" position when installed (as seen in the picture)? If so, wouldn't that be considered a risk in the case that if the hinge flips up during rides, the cable gains slack, thus losing brake-pulling capability?
, tension on the brake cable will further lock the mechanism in place as it is on a slight angle causing the lever to be further pulled closed under braking tension.
The lever in the up position opens the caliper arms up wider to facilitate wheel changes.
Some people flip up the lever as a lazy way to get extra brake pad clearance when the rim gets out of true, but it isn't the best idea. That said, the brakes will still work, but are generally less effective with the lever positioned up.
|
stackexchange-bicycles
|
{
"answer_score": 6,
"question_score": 5,
"tags": "brakes, front"
}
|
Create copy of list and remove element
I would like to write something like this
S = [ 0, 1, 2 ]
F = [ S.without(i) for i in range(0,len(S)) ]
print F
and Python putting out
[ [0,1], [0,2] ,[1,2] ]
and have not found something like this in the online reference. Can you help me?
|
>>> S = [0, 1, 2]
>>> F = [S[0:i] + S[i+1:] for i in range(len(S))]
>>> print F
[[1, 2], [0, 2], [0, 1]]
>>>
If you don't need the elements to be in any order -- that is, if you can use sets -- and if you want to remove items by _value_ rather than by _index_ , then this is a more elegant solution:
>>> S = set(range(3))
>>> F = [S - set((i,)) for i in S]
>>> F
[set([1, 2]), set([0, 2]), set([0, 1])]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, list"
}
|
Como obter a data da próxima sexta-feira
Gostaria de informar que dia cai toda sexta que vem, como faço? Aí quando chegar na próxima sexta informa a outra sexta e assim por diante.
|
A função `strtotime` permite gerar datas a partir de strings como "próxima sexta" (em inglês):
echo date('Y-m-d', strtotime('next Friday'));
Veja funcionando.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php"
}
|
“Paragraph ended before \verbatim@ was complete.” when trying to use verbatim in tabular
I have the following code in my Beamer slide code:
\begin{frame}
\frametitle{selections}
\begin{tabular}{ll}
sample 1 &
\begin{minipage}{3in}
\begin{verbatim}
sample 2
\end{verbatim}
\end{minipage}\\
\end{tabular}
\end{frame}
When I try to compile, it breaks with the following error:
Runaway argument?
sample 2 \end {verbatim} \end {minipage}\\ \end {tabular}
! Paragraph ended before \verbatim@ was complete.
<to be read again>
\par
l.965 \end{frame}
?
I'm not sure what's wrong. Could anyone offer me guidance?
|
Use `\begin{frame}[fragile]`. This option is needed when the content contains verbatim.
|
stackexchange-tex
|
{
"answer_score": 36,
"question_score": 22,
"tags": "tables, verbatim"
}
|
Include related entities with WebAPI OData request
Is there any way to include related entities in an OData request?
For example, I have a Person entity and a Task entity. The relationship is one-to-many, with a Person having many Tasks. If I query the data with the OData request:
/odata/Person
to get all the Person entities, the json returned does not include a Tasks property for each Person.
However, if I query the data with the OData request:
/odata/Person(14)/Tasks
I get the collection of Tasks that belong to that Person.
What I'm hoping to be able to do is get ALL of the Tasks for all of the Person entities when I make my /odata/Person request.
|
Try
/odata/Person?$expand=Tasks
it will expand the navigation property "Tasks" in each entity person. If you want to only query Tasks, do not need other properties, you can try:
/odata/Person?$select=Tasks&$expand=Tasks
PS: Your service need to support `$expand` and `$select`.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c#, .net, entity framework, odata"
}
|
Zip code highlighting in Google Maps?
When we search for a zip code in Google Maps we get the area highlighted in the map with a dotted border.
How is this calculated?
How do they know how to draw the polygon?
I'm looking at implementing something equivalent, an overlay on each zip code of the visible area of the map.
|
I am not entirely sure if you are asking about implementation hints (I can't help you there) or more specifically about the zip code boundaries.
In any case, the Census Bureau provides so-called zip code tabulation areas which are polygonic approximations of zip codes. I say approximations because zip codes are really points on a map and may not conform to neat boundaries as typically seen on a map. Nonetheless, they provide the approximation, pretending they are areas. So, to your question, Google presumably translates the address to lat/longs, then checks for spatial membership in any number of 'neighborhood' layers, including neighborhood proper, zip code, probably others. If you searched for a specific zip code, their parser recognizes that as such and returns the corresponding feature from the tabulation area shapefile, and returns the corresponding polygon.
Zip code tabulation areas can be fetched here: <ftp://ftp2.census.gov/geo/tiger/TIGER2014/ZCTA5/tl_2014_us_zcta510.zip>
|
stackexchange-gis
|
{
"answer_score": 1,
"question_score": 0,
"tags": "polygon, google maps, google maps api, zip codes"
}
|
Xcode 4.2: What steps to ensure I'm targeting iOS 4.3 rather than 5?
When I look at the build settings for my new project in Xcode 4.2, I can change the "Deployment > iOS Deployment Target" to iOS 4.3, but under "Architecture > Base SDK", I am strictly limited to iOS 5.
Are there any other steps I need to take to ensure that my new app will run on iOS 4.3? How do I change the Base SDK?
|
When you install the iOS SDK, it removes any previously installed SDKs. That's why iOS 5 is your only SDK choice.
Setting the deployment target to iOS 4.3 is the way to ensure your app runs on 4.3. The deployment target is the earliest version of iOS that can run your app. You must make sure not to use any new iOS 5 technologies and methods or else the app won't run on 4.3.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "xcode, xcode4, target, xcode4.2, base sdk"
}
|
How to get public array In HTML file which is initialize in .cs file of web app?
Рow to get the array in HTML file added from some side initialize in .cs file? Hope for your reply.
|
Your question does not provide enough info. I will assume you mean the codebehind file (c#) when you say .cs file (what else is there to assume?) and your array is added in c#, which you want to access in js
Register your array as a string literal as script block
something like:
string myArr = "; var myArr = [ 1, 2, 3, 4 ]; "; //putting your array in a string
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), myArr, true);
now in your html file, you can access them with javascript.
<script type="text/javascript">
alert(myArr[2]); //will alert 3
</script>
For 2D arrays,
var myArr = [[0,0],[1,1],[2,2]]; //2D array
alert(myArr[0]); // to access 1st row: [0,0]
alert(myArr[0][0]); // to access 1st row 1st column: 0
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, asp.net, html"
}
|
Hide "www" text in URL bar (firefox)
I was wondering if it is possible to hide the "www" text in the URL bar (only in Firefox) using CSS in Stylish addon or/and Java in Greasemonkey.
I want this to make Firefox even more compact.
* * *
This is some CSS code that i found for URL bar in firefox that will modify the text size using Stylish. Hope it can help.
@namespace url("
.urlbar-input-box,
.searchbar-textbox {
font-size: 11px !important;
}
### Update
I don't want to remove the "www", I just want to hide it from the url bar.
|
`www.example.com` and `example.com` are two different things. Typically they are considered the same, but `www.` is in fact a subdomain.
Therefore, hiding it would be misleading to the user.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "css, firefox, url, text, hide"
}
|
In Django, how do I generate the CSRF input element while in a view?
In a Django template, I can use `{% csrf_token %}` to generate a hidden input element with the CSRF token as the value.
How do I do the same in a view? For instance,
def my_view(request):
csrf_input = somehow_generate_csrf_token_input()
return HttpResponse(csrf_input)
|
Follow the doc, use the processor to generate the CSRF token:
from django.core.context_processors import csrf
def my_view(request):
# csrf(request) returns a dict like {'csrf_token': 'xxx'}
csrf_token = csrf(request)['csrf_token']
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "django"
}
|
Declaring constant with no value
If I declare a constant like `static final double PI;` I'll get `The blank final field PI may not have been initialized` error. Why can't I declare it this way first and initialize it later?
**UPDATE** : I might not know the initial constant value and have to initialize it after some logic so that I can have a value for it. That's why I need to initialize it later.
|
Java has to make sure that a final field is only initialized once and never changes. This can only happen during initialization.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java"
}
|
Run Craft Find and Replace via Console
I'm trying to streamline my deployments for local, staging and production and would like to know if it's possible to invoke the Find and Replace method via Console. I have a multi-config in place, but I'd like to ensure that any hardcoded urls are replaced in the database.
|
You can write a plugin that does this.
Use < and check the "Console Command" checkbox and it will generate the boilerplate for you.
Your "Find and Replace" command would follow similar logic to what the FindAndReplaceTask's `runStep()` method does.
|
stackexchange-craftcms
|
{
"answer_score": 2,
"question_score": 2,
"tags": "craft features, console"
}
|
cannot unlock login screen 14.04
When my computer boots, entering the correct password won't start my session. I found out the problem is /home/user/.Xauthority ownership. root owns this folder and giving the ownership to the user will solve the problem... for a while. I don't know how or when, but the ownership will go back to root pretty often; It can happen just after one boot or ten.
Is there a definitive solution to this problem?
|
The solution is to change your behaviour. **Don't** run GUI apps (like _nautilus_ for instance) by calling them from terminal with `sudo ...`.
|
stackexchange-askubuntu
|
{
"answer_score": -1,
"question_score": 1,
"tags": "14.04, login screen"
}
|
How to extract year and change format to mm-dd-yyyy from yyyy/mm/dd in BigQuery
Not able to extract year from this format(yyyy/mm/dd) and not able to change the format to mm-dd-yyyy . I have tried the following but failed.
with table1 as(
select "2017/1/1" as doj union all
select "2017/2/3" as doj union all
select "2017/3/5" as doj union all
select "2017/4/7" as doj union all
select "2017/6/9" as doj
)
select format_date("%m-%d-%Y",doj)doj from table1
Error: No matching signature for function FORMAT_DATE for argument types: STRING, STRING. Supported signature: FORMAT_DATE(STRING, DATE)
|
Below is for BigQuery Standard SQL
#standardSQL
WITH `project.dataset.table1` AS(
SELECT "2017/1/1" AS doj UNION ALL
SELECT "2017/2/3" AS doj UNION ALL
SELECT "2017/3/5" AS doj UNION ALL
SELECT "2017/4/7" AS doj UNION ALL
SELECT "2017/6/9" AS doj
)
SELECT
PARSE_DATE("%Y/%m/%d", doj) doj_as_date,
EXTRACT(YEAR FROM PARSE_DATE("%Y/%m/%d", doj)) year
FROM `project.dataset.table1`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "google bigquery"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.