text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Add space before question mark and exclamation mark
My client wants to have a space before exclamation marks and question marks. To ensure this always is done correctly I use the following script in php. This script removes any existing spaces and then puts a non-breaking space before all question marks and exclamation marks:
$text = str_replace(' ?', '?', $text);
$text = str_replace('?', ' ?', $text);
$text = str_replace(' !', '!', $text);
$text = str_replace('!', ' !', $text);
return $text;
This all works fine but I was wondering if there's a better way with Regex?
A:
You may use
$text = "No? Oh ? And ! and!";
$text = preg_replace('~\s*([?!])~', ' $1', $text);
echo $text;
See the PHP demo
Details:
\s* - 0+ whitespace symbols
([?!]) - Group 1 capturing ? or !
The replacement pattern only contains and the backreference to Group 1 contents to insert the captured text.
A:
Use preg_replace
With regex it would look like this:
preg_replace('/(\S)([?!])/', '$1 $2', $text);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
vba excel listobject HeaderRowRange
I am having some problem to understand how HeaderRowRange works.
Lets see:
According to the documentation:
headersRowrange is a Range
so this should work:
Dim ftsTbl As ListObject
Set ftsTbl = ThisWorkbook.Sheets(1).ListObjects(1)
MsgBox ("ftsTbl.HeaderRowRangeD1:" & ftsTbl.HeaderRowRange("D1").Address)
but it doesnt. (invalid procedure call or argument)
Why?
nor does the following work:
MsgBox ("ftsTbl.HeaderRowRangeD1:" & ftsTbl.HeaderRowRange("D1").item(1).Address)
What I really need to do is getting the following range in this listObject:
I need the range of the header of the listobject from D1 to D6 columns.
I thought that I could use Range( cell1 ,cellX) like this:
Dim ftsTbl As ListObject
Set ftsTbl = ThisWorkbook.Sheets(1).ListObjects(1)
Dim DocsHeadersRange As Range
'Set DocsHeadersRange = ThisWorkbook.Sheets(1).Range(ftsTbl.HeaderRowRange("D1"), ftsTbl.ListColumns("D6").DataBodyRange.iTem(ftsTbl.ListRows))
But it does not work.
Why?
I am defining a bunch of ranges in sheet(1) in order to use in
Sub Worksheet_SelectionChange(ByVal Target As Range)
Set Overlap = Intersect(***defined range of listobject***, Selection)
If Not Overlap Is Nothing Then
If Overlap.Areas.Count = 1 And Selection.Count = Overlap.Count Then
...etc
Thanks
Cheers
A:
D1 is already a valid range address so don't name it that if you want to refer to it with any Range object (not sure about your use here as I don't think it is valid anyway. You can use Find. Also, why do you have D1 on the end of ftsTbl?
Public Sub TEST()
Dim ftsTbl As ListObject
Set ftsTbl = ThisWorkbook.Sheets(1).ListObjects(1)
Debug.Print ftsTbl.HeaderRowRange.Find("D1").Address
End Sub
You can also use ListColumns:
Debug.Print ftsTbl.ListColumns("D1").Range.Cells(1, 1).Address
You can then use something like
Debug.Print ThisWorkbook.Worksheets("Sheet1").Range(ftsTbl.ListColumns("D1").Range.Cells(1, 1), ftsTbl.ListColumns("D6").Range.Cells(1, 1)).Address
or
Debug.Print ThisWorkbook.Worksheets(ftsTbl.Parent.Name).Range(ftsTbl.ListColumns("D1").Range.Cells(1, 1), ftsTbl.ListColumns("D6").Range.Cells(1, 1)).Address
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to list the folders at a specific path from an Amazon S3 bucket, in Objective C?
After I've read the Amazon documentation and I didn't seem to find how to list the folders name at a specific path from my Amazon S3 bucket, I also looked around on StackOverflow with no luck I answered my own question.
I will post it here and hope that it will also help others :)
A:
And here is my code:
// pass path as: @"backup/"
- (void)listAmazonFoldersAtPath:(NSString *)path
completion:(void (^)(BOOL success, NSMutableArray *filesArray))completionBlock
{
NSMutableArray *collection = [[NSMutableArray alloc] init];
AWSS3 *s3 = [AWSS3 defaultS3];
AWSS3ListObjectsRequest *listObjectsRequest = [AWSS3ListObjectsRequest new];
listObjectsRequest.prefix = path;
listObjectsRequest.delimiter = @"/";
listObjectsRequest.bucket = kAmazonS3Bucket;
[[s3 listObjects:listObjectsRequest] continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(@"listObjects failed: [%@]", task.error);
completionBlock(NO, collection);
} else {
AWSS3ListObjectsOutput *listObjectsOutput = task.result;
for (AWSS3CommonPrefix *s3ObjectPrefix in listObjectsOutput.commonPrefixes) {
if(s3ObjectPrefix.prefix && s3ObjectPrefix.prefix.length > 0){
NSString *fileName = [[s3ObjectPrefix.prefix componentsSeparatedByString:@"/"] lastObject];
if (fileName && fileName.length > 0) {
[collection addObject:s3ObjectPrefix.prefix];
}
}
}
completionBlock(YES, collection);
NSLog(@"Current folders: %@", collection);
}
return nil;
}];
}
I hope it will help others.
NOTE: If you also want to list the subfolder please feel free to comment the line:
listObjectsRequest.delimiter = @"/";
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to stop a flink streaming job from program
I am trying to create a JUnit test for a Flink streaming job which writes data to a kafka topic and read data from the same kafka topic using FlinkKafkaProducer09 and FlinkKafkaConsumer09 respectively. I am passing a test data in the produce:
DataStream<String> stream = env.fromElements("tom", "jerry", "bill");
And checking whether same data is coming from the consumer as:
List<String> expected = Arrays.asList("tom", "jerry", "bill");
List<String> result = resultSink.getResult();
assertEquals(expected, result);
using TestListResultSink.
I am able to see the data coming from the consumer as expected by printing the stream. But could not get the Junit test result as the consumer will keep on running even after the message finished. So it did not come to test part.
Is thre any way in Flink or FlinkKafkaConsumer09 to stop the process or to run for specific time?
A:
The underlying problem is that streaming programs are usually not finite and run indefinitely.
The best way, at least for the moment, is to insert a special control message into your stream which lets the source properly terminate (simply stop reading more data by leaving the reading loop). That way Flink will tell all down-stream operators that they can stop after they have consumed all data.
Alternatively, you can throw a special exception in your source (e.g. after some time) such that you can distinguish a "proper" termination from a failure case (by checking the error cause). Throwing an exception in the source will fail the program.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gradle test dependencies not loaded in Spring Boot test
I am trying to work with p6spy in Spring Boot tests. I have a test class annotated with
@RunWith(SpringRunner.class)
@SpringBootTest
My gradle.build looks like this
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
runtime('com.h2database:h2')
testCompile 'p6spy:p6spy:3.0.0'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
As for the application itself (which runs fine), I added the new datasource to the test-application-context.
spring:
application:
name: persistence
datasource:
url: jdbc:p6spy:h2:mem:persistence;DB_CLOSE_ON_EXIT=FALSE
username: sa
password:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
jpa:
database: H2
But when I run my test I get this error
java.lang.IllegalStateException: Cannot load driver class: com.p6spy.engine.spy.P6SpyDriver
To me this looks like my dependencies are not loaded. At first, I was using the @DataJpaTest annotation, but this one ignored even my new test-application-context.
Any help appreciated.
EDIT: I got it working bei adding the p6spy dependency manually to the test using IntelliJ. Now I'm sure that my classpath is wrong, but I don't know how to fix it to make it work in Gradle.
A:
The problem is located in my version of IntelliJ. I will file a bug report.
If anyone should have this problem, I added the missing dependencies manually in the project settings. Then it works also from the IDE.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
python Regular expression application (replace output which has(parentheses).)
As I had not explained my question clearly.I will try to explain what I wanna do in my program.
I have created a sqlite database which is build in the python . I have devided table into three kinds of field.A. commandkey B.command C. function[the function of command]
2.To select a sequence of commands from my program, I need to write a function readciscodevice(without regular expression).
This function can print a sequence of commands such as
OUTPUT A:
enable
conf t
interface fa(1)/(2)
ip address (1) (2)
or
OUTPUT B:
enable
conf t
router ospf (1)
network (1) (2)
As you know, the parentheses(1), (2) should have some string inside, hence the command will work after i put ip address and subnet mask in to the first output(A).
Now I am trying to use regular expression to input some string into (1) and (2) in the output A.
this is my expected result after adding regular expression:
interface fa0/1
ip adress 192.168.1.1 255.255.255.0
I should write some raw_input for (1) and (2) but how should I fix the regular expression. Am I writing a wrong way in finditer or use other method. As my english is bad, It is difficult for me to fully understand the website tut to learn Regular expression but at lease I tried to write this re.
Please provide some suggestion for me to do this thx.
I have written a function to printout output and some of the output has a (parentheses) that I preferred to re-intput some string into the (parentheses).
Now I am trying to use python and regular expression .replace and finditer.
But it seems not my cup of tea. So thank you for your help.
This is my output in my database:
interface fa(1)/(2)
ip address (1) (2)
This is my function
def readciscodevice(function, device)://here are some sqlite3 statement
conn = sqlite3.connect('server.db')
cur = conn.cursor()
if device == "switch":
cur.execute(
"SELECT DISTINCT command FROM switch WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read
elif device == "router":
cur.execute(
"SELECT DISTINCT command FROM router WHERE function =? or function='configure terminal' or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read;
elif device == "showcommand":
cur.execute(
"SELECT DISTINCT command FROM showcommand WHERE function =? or function='enable' ORDER BY key ASC",
(function,))
read = cur.fetchall()
return read;
a = input("function:") //First, I input function field from database
b = input("device:") //I need to input the name of my elif =="name"
p = re.compile('\(.*?\)') //I am not sure what it is doing...
s = "1"
iterator = p.finditer(s) //finditer is suitable to replace parentheses?
for match in iterator:
s = s[:match.start()] + s[match.start():match.end()].replace(match.group(), dict[match.group()]) + s[match.end()]
for result in readciscodevice(a,b):
print(result[0])
A:
Try using re.sub(pattern, repl, string) instead of re.compile and finditer, to replace (1) and (2).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to extend definition of n-tuple to the case $n=0$?
The classical definition of n-tuple $(x_i)_{i < n}$ starts at $n=2$. In this case $$(x_0,x_1) := \{\{x_0\},\{x_0,x_1\}\}$$(1).
For $2<n=k+1$, $(x_i)_{i < n}:=((x_i)_{i < k},x_k)=\{\{(x_i)_{i < k}\},\{(x_i)_{i < k},x_k\}\}$(2).
Hence it well defined on $2 \le n \in \mathbb N$.
One would tend to extend this definition to every natural number.
In the case $n=1$, if we let $(x_0)=x_0$, then (2) can be extended to $1 \le n \in \mathbb N$, so $(x_0,x_1)=\{\{(x_0)\},\{(x_0),x_1\}\}=\{\{x_0\},\{x_0,x_1\}\}$, which also compatible with (1).
However, if we go on do this to $n=0$, we will get a trouble.
That is, $()=?$ If $()=\emptyset$, then $(x_0)=((),x_0)=\{\{()\},\{(),x_0\}\}=\{\{\emptyset\},\{\emptyset,x_0\}\}$, but it contradict to $(x_0)=x_0$ as defined. Similar, if we let $()$ remains blank, then $(x_0)=((),x_0)=\{\{()\},\{(),x_0\}\}=\{\{\},\{ ,x_0\}\}=\{\emptyset,\{x_0\}\}$, which also contradict to $(x_0)=x_0$.
So my question: Is there any methodology to climb over this barrier?
A:
There is no way to define a $0$-tuple to that $1$-tuples are ordered pairs (without contradicting Foundation): Suppose that there were such a definition of a $0$-tuple $\langle\;\rangle$ so that $$a = \langle a \rangle = \langle \langle \; \rangle , a \rangle = \{ \{ \langle \; \rangle \} , \{ \langle \; \rangle , a \} \}$$ then $a \in \{ \langle \; \rangle , a \} \in a$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scraping hidden product details on a webpage using Selenium
Sorry I am a Selenium noob and have done a lot of reading but am still having trouble getting the product price (£0.55) from this page:
https://groceries.asda.com/product/spaghetti-tagliatelle/asda-spaghetti/36628. Product details are not visible when parsing the html using bs4. Using Selenium I can get a string of the entire page and can see the price in there (using the following code). I should be able to extract the price from this somehow but would prefer a less hacky solution.
browser = webdriver.Firefox(executable_path=r'C:\Users\Paul\geckodriver.exe')
browser.get('https://groceries.asda.com/product/tinned-tomatoes/asda-smart-price-chopped-tomatoes-in-tomato-juice/19560')
content = browser.page_source
If I run something like this:
elem = driver.find_element_by_id("bodyContainerTemplate")
print(elem)
It just returns: selenium.webdriver.firefox.webelement.FirefoxWebElement (session="df23fae6-e99c-403c-a992-a1adf1cb8010", element="6d9aac0b-2e98-4bb5-b8af-fcbe443af906")
The price is the text associated with this element: p class="prod-price" but I cannot seem to get this working. How should I go about getting this text (the product price)?
A:
The type of elem is WebElement. If you need to extract text value of web-element you might use below code:
elem = driver.find_element_by_class_name("prod-price-inner")
print(elem.text)
A:
Try this solution, it works with selenium and beautifulsoup
from bs4 import BeautifulSoup
from selenium import webdriver
url='https://groceries.asda.com/product/spaghetti-tagliatelle/asda-spaghetti/36628'
driver = webdriver.PhantomJS()
driver.get(url)
data = driver.page_source
soup = BeautifulSoup(data, 'html.parser')
ele = soup.find('span',{'class':'prod-price-inner'})
print ele.text
driver.quit()
It will print :
£0.55
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Computer hangs at BIOS screen. Cannot enter setup
I have an HP Pavilion a6500f (it's a year out of warranty) and it's hanging on the blue HP BIOS screen. If I mash F10 while it's starting up, it will say "Entering Setup..." but I will see no results. It will hang there and not do anything.
If I actually wait until I can see the screen and then hit F10, there's no response at all and the computer will sit at the BIOS menu.
I've dusted and cleaned it out, reseated the memory, switched the RAM slots, and reset the CMOS battery using the reset jumper. I'm out of ideas. I'm pretty sure it's not a hard drive issue, since my problem is at the BIOS. After this post, I'll disconnect the hard drive and try to just boot without it.
Anyone have any other ideas?
Edit:
Okay, so I tried disconnecting the hard drive and now I can get back into the BIOS. I reconnected it and I'm locked out again. So the problem is my hard drive.. I guess I should delete this post unless someone has any ideas as to what's wrong with the drive?
A:
After the edit, it sounds like a device enumeration issue, something wrong with the hard drive probably. If you try swapping it out for another hard drive you know functions well elsewhere does it again stall?
Original reply:
If it hangs at POST it probably indicates a defect with a critical component (ie. not a component like the hard drive, but a component like the memory/mainboard/CPU). It sounds like you've done everything you can to try and alleviate simple issues with CMOS corruption/bad seating, so I would suggest there is an actual defect on the mainboard or a problem with device enumeration, there nothing to speculate any further than that.
Hope you get it fixed.
A:
Sounds like a device isn't being detected properly and it's hanging trying to enumerate it. Probably, if you wait long enough (potentially 30+ minutes) it may eventually go past. That said, since you unplugged the hard drive and it quit, it's almost certainly the hard drive. It could well be a motherboard fault or something but it's unlikely. The easiest test, of course, is to try another drive or try this drive in another machine (although note, other machines may be more lenient about their timeouts)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Parsing dynamic JSON to POJO with Retrofit
Hi I have json which has some dynamic field names:
{
"status": {
"rcode": 200,
"message": "OK"
},
"data": {
"0": {
"SubFranchiseID": "0",
"OutletID": "607",
"OutletName": "Spill "
},
"1": {
"SubFranchiseID": "0",
"OutletID": "32",
"OutletName": "PizzaRoma"
}
},
"hash": "b262c62ea3c8c693ad35210289a487d6963434d7"
}
"0" and "1" are dynamic String values.
From here How to parse Dynamic lists with Gson annotations?
I created my Data class as :
public class Data {
public Map<String, Restaurant> restaurants = new HashMap<>();;
public Map<String, Restaurant> getRestaurants() {
return restaurants;
}
}
But I am getting zero value when i use getRestaurants().size() in Retrofit.
How should change my Data class ?
Edit :
My main class :
public class MyClass{
private Status status;
private Data data;
private String hash;
public Data getData() {
return data;
}
// other getter and setters
}
Retrofit and RxJava :
RetrofitService service1 = ServiceFactory.createRetrofitService(RetrofitService.class, RetrofitService.API_ENDPOINT);
service1.data()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<MyClass>() {
@Override
public final void onNext(MyClass response) {
if(response.getData().getRestaurants().size() == 0)
Log.d("1", "size is ZERO ");
}
});
A:
The solution was to not use the Data class , instead I changed my MyClass as:
public class MyClass{
private Status status;
@SerializedName("data")
private Map<String, Restaurant> data;
private String hash;
public Map<String, Restaurant> getData() {
return data;
}
// other getter and setters
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Solution for passing tokens from iframe HTML
I'm in a bit of a pickle. Using Java and Tomcat 7 container as a webapp. We pass around tokens everywhere in our application (for security when in session a user is assigned a token and appended to the end of the URL).
However we currently have a window (which contains the token in the URL) that opens another html in an iframe. Within this html is a link to another section of the website, how can I retrieve the token from the HTML if it's unavailable at the time? What might be the least messiest solution, JavaScript in the HTML to get the token from the browser and then append it to the end of the link?
A:
Save the token as a cookie. The cookie is sent along with each request to the server. Once set, it is available on the server side and can be accessed with javascript on the client side.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
perl how to extract #define'd number from C header file
I am looking for a Perl snippet to print the number 100, contained in a C header, to the terminal.
#ifndef VERSIONS_H
#define VERSIONS_H
#define __SOFTWARE_REVISION__ 100
#endif
I am able to extract the #define line, but the number.
#!perl -w
use warnings;
use strict;
my $line;
my $file = shift @ARGV;
open my $fh, "<", $file or die $!;
while (<$fh>) {
print if /__SOFTWARE_REVISION__/;
}
close ($fh);
A:
The regex matches for any line that contains that literal phrase, not only where it is defined. You need to specify the line far more precisely, and to capture the needed number.
The code also proceeds to loop through the file needlessly.
With a few more adjustments
use warnings;
use strict;
use feature qw(say);
my $file = shift @ARGV;
die "Usage: $0 filename\n" if not $file or not -f $file;
open my $fh, '<', $file or die "Can't open $file: $!";
while (<$fh>) {
if (/^\s*#\s*define\s+__SOFTWARE_REVISION__\s+([0-9]+)/) {
say "Software revision: $1";
last;
}
}
close $fh;
If the software revision can be other than integer replace [0-9]+ with \S+.
I'd suggest to work through the tutorial perlretut with reference perlre on hand.
I assume that this need comes up in a Perl program (and not that Perl is the chosen tool for this).
Still, note that there are other, more systemic, ways to retrieve this information using the compiler (see a comment on gcc by rici for example).
While it is better to use Perl in a Perl script rather than go out to the system, this case may be one of exceptions: it may be better to use an external command rather than parse source files, a task well known to be treacherous.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can anyone please help me in reading and writing annotation in the PDF using IOS
Can anyone please help me with reading and writing annotations in a PDF using iOS? This is the sample code that I have tried. Can anyone please tell me where I am going wrong? I am able to load The Annotation Array, but when I try to get the dictionary for A (line below) I am not able to parse it.
CGPDFDictionaryRef aDict;
if(!CGPDFDictionaryGetDictionary(annotDict, "A", &aDict))
The code that I've tried is as follows:
CGPDFPageRef pageAd = CGPDFDocumentGetPage(pdf, index+1);
CGPDFDictionaryRef pageDictionary = CGPDFPageGetDictionary(pageAd);
CGPDFArrayRef outputArray;
if(!CGPDFDictionaryGetArray(pageDictionary, "Annots", &outputArray)) {
return;
}
int arrayCount = CGPDFArrayGetCount( outputArray );
for( int j = 0; j < arrayCount; ++j ) {
CGPDFObjectRef aDictObj;
if(!CGPDFArrayGetObject(outputArray, j, &aDictObj)) {
return;
}
CGPDFDictionaryRef annotDict;
if(!CGPDFObjectGetValue(aDictObj, kCGPDFObjectTypeDictionary, &annotDict)) {
return;
}
CGPDFDictionaryRef aDict;
if(!CGPDFDictionaryGetDictionary(annotDict, "A", &aDict)) {
return;
}
CGPDFStringRef uriStringRef;
if(!CGPDFDictionaryGetString(aDict, "URI", &uriStringRef)) {
return;
}
CGPDFArrayRef rectArray;
if(!CGPDFDictionaryGetArray(annotDict, "Rect", &rectArray)) {
return;
}
int arrayCount = CGPDFArrayGetCount( rectArray );
CGPDFReal coords[4];
for( int k = 0; k < arrayCount; ++k ) {
CGPDFObjectRef rectObj;
if(!CGPDFArrayGetObject(rectArray, k, &rectObj)) {
return;
}
CGPDFReal coord;
if(!CGPDFObjectGetValue(rectObj, kCGPDFObjectTypeReal, &coord)) {
return;
}
coords[k] = coord;
}
char *uriString = (char *)CGPDFStringGetBytePtr(uriStringRef);
NSString *uri = [NSString stringWithCString:uriString encoding:NSUTF8StringEncoding];
CGRect rect = CGRectMake(coords[0],coords[1],coords[2],coords[3]);
CGPDFInteger pageRotate = 0;
CGPDFDictionaryGetInteger( pageDictionary, "Rotate", &pageRotate );
CGRect pageRect = CGRectIntegral( CGPDFPageGetBoxRect( page, kCGPDFMediaBox ));
if( pageRotate == 90 || pageRotate == 270 ) {
CGFloat temp = pageRect.size.width;
pageRect.size.width = pageRect.size.height;
pageRect.size.height = temp;
}
rect.size.width -= rect.origin.x;
rect.size.height -= rect.origin.y;
CGAffineTransform trans = CGAffineTransformIdentity;
trans = CGAffineTransformTranslate(trans, 0, pageRect.size.height);
trans = CGAffineTransformScale(trans, 1.0, -1.0);
rect = CGRectApplyAffineTransform(rect, trans);
// do whatever you need with the coordinates.
// e.g. you could create a button and put it on top of your page
// and use it to open the URL with UIApplication's openURL
NSURL *url = [NSURL URLWithString:uri];
NSLog(@"URL: %@", url);
// CGPDFContextSetURLForRect(ctx, (CFURLRef)url, rect);
UIButton *button = [[UIButton alloc] initWithFrame:rect];
[button setTitle:@"LINK" forState:UIControlStateNormal];
[button addTarget:self action:@selector(openLink:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
A:
The A key is optional in an annotation dictionary. If the annotation is a link to another page, it might use the Dest key. Or it might use the U key in the additional actions dictionary. If the A dictionary cannot be retrieved, try loading the AA key. If it does not exist, the annotation does not have an action. If it exists, then load the U key from the AA dictionary.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the relationship between government expenditure and the quality of life?
Can we say, in general, what is the relationship between relative government expenditure (or the total taxation) and the average quality of life?
A:
Triggered by the somewhat arbitrary selection of countries in the OECD graph in Bobson's answer, I found that data are easily available for much more countries than just the OECD countries.
Summary: there is some positive correlation between tax : GDP ratio and happiness score, but the correlation is too low to allow meaningful conclusions about happiness score from known tax : GDP ratio for a generic country.
Putting together with Wikipedia List of countries by tax revenue to GDP ratio
the [World Happiness Report 2017 table also from Wikipedia]https://en.wikipedia.org/wiki/World_Happiness_Report#2017_report) (the 2017 report is on happiness data 2014-2106 which matches better than the 2018 report with the age of the tax revenue data)
I find:
blue: OECD countries (to ease comparison with @Bobson's answer)
red: countries where happiness (+) or tax revenue : GDP ratio (x) is missing
With the unaided eye, I'd say that there's a maybe lower line of very roughly 1.75 happiness points + 9 ⋅ total tax revenue/GDP. Very few countries are below that:
There may or may not be a similar upper limit as well at roughly 5.25 happiness points + 12 ⋅ total tax revenue/GDP (dark green line).
The five (dark green dots) countries above are the United Arab Emirates, Bahrain, Qatar, Kuwait and Saudi Arabia, i.e. the rich Arab oil countries that probably use lots of oil sales revenue instead of taxes.
And, anyways, even the most happy countries so far do not manage to get a happiness score of more than 7.6 (red line).
If I do a linear regression of happiness score over Tax revenue : GDP ratio for all countries where both happiness and tax revenue are available, I get the following picture:
Regression formula is 4.425 happiness score + 4.36 ⋅ total tax revenue/GDP. Both intercept and slope are highly significant*, and the corresponding 95 % confidence interval for the regression line is the reddish shaded area in the graph. However, knowing that on average over almost 150 countries happiness correlates with tax revenue to GDP ratio (correlation coefficient is, btw, 0.49) doesn't help us saying anything about a single country. For that, we'd need to look at the prediction intervals (blue shaded area).
That tells us that for a generic country with 25 % of GDP going into taxes, we'd expect a happiness score somewhere between 3.5 and 7.4 (95 % prediction interval). Happiness score of 3.5 is what Guinea, Liberia and Togo in West Africa have (Syria is 3.46). 7.4 basically scatches the very top we actually have anywhere worldwide, it is between the Netherlands and Finland (topmost was Norway with 7.54). In other words, we'd expect it to avoid being one of the 6 most miserable countries, and also not to make it into the top 5 countries. Seeing that this is the 95 % prediction interval, so we'd expect about 5 % of such countries to be outside that range we just calculated. In summary, the variation between countries with similar tax to GDP ratio dominates.
A few more things to consider / thoughts:
Particular social insurance varies across countries not only in quality and costs, but also in how it is organized. And that latter can vary from 100% in government hand (and tax paid) over mandatory but separate from taxes and available if the individual wants to informal (family + friends) to basically unavailable for normal people. The first 2 possiblities can vary from 0 to 100 % tax money - even for the same percentage of GDP going into health care. For example, health care in Germany is to a large extent not by tax (i.e. government budget), but by compulsory health insurance fees. The extent of this is another 0.07 of GDP. Compare to Italy, where health care is financed by taxes. That is, the Italian tax : GDP ratio includes health care, whereas for Germany that comes on top.
So we do have a correlation. As we all know, that doesn't make a causation. And IMHO we can have plausible causation stories in both directions:
paying taxes makes people unhappy - they have less money which they can spend on what they need most.
That is, unless they perceive that they get back a sensible value of their taxes: if taxes are spent on things people in fact think important.
This is something I've anecdotally heard e.g. Italians complain about: at 43.5 % of GDP they are taxed about as heavily as Germany - but they don't feel they get as much for their taxes (but see the health care difference above), in particular, they perceive that their government/administration is inefficient (we Germans do complain about that as well, but after spending some years in Italy I think we're in fact much better off)
low taxes can be a sign of various situations a country can be in, ranging from efficiency (Switzerland), i.e. being able to supply service without needing too much taxes to governments that are unable to collect taxes which may be a symptom of general inefficiency.
Maybe the lower line of happines vs. tax : GDP ratio indicates that if the heavy taxation doesn't lead to happiness, people are unwilling to pay those taxes...
Even if you look at high tax high happiness countries, you could have either:
taxes paid making people happy or
happiness making people pay more taxes (being OK with being taxed)
* regression for the OECD countries only does not yield a significant slope, and the same is also true for the non-OECD countries. But non-OECD countries have on average lower happiness scores and lower tax to GDP ratios.
A:
Analyzing comparative government policies is hard, since there's no way to have a control group or rigorous studies. All political scientists can do is analyze reported data and try to tease out correlations.
On this subject (as would be expected) there is no definitive answer, but it has been researched. For example, here is one article which discusses it, based on The Political Economy of Human Happiness by Benjamin Radcliff.
The article states:
Indeed, the evidence assessed by Radcliff suggests [a link between government spending and happiness]. His data shows that for one of the metrics, linked to welfare spending, countries scoring high on this indicator, happiness levels are above one point higher than low-scoring countries. He suggests that this contribution to happiness is double that of being married (being married is positively correlated with happiness), and three times the negative drag of unemployment.
However, it also includes this graph, which shows a very weak correlation:
The graph here compares taxation levels (tax revenue as % of GDP) with happiness levels (life satisfaction), based on data from the OECD and the World Happiness Report quoted above. It shows an increasing trendline, associating a level of taxation of 20% in this group of OECD countries with a happiness level of around 6.5. All others thing equal, a level of 50% is correlated with a happiness level of around 6.8: some one thirds of a point higher across the trendline.
But not all others things are equal: the distribution is broad and the effects are very diverse. Denmark is on the top right with a happiness level of 7.526 and the very highest tax level of 50,9. On the far left, we find Switzerland with a marginally lower happiness level of 7.509 and only half the tax rate at 26.6%. On the lowest part of the graph, with happiness levels just above 5 points, we find Portugal, Greece and Hungary, with taxation levels around 34-38%.
So there is research on the subject, but no definitive relationship.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Garbage being printed when using strcpy
I have a function that will parse some data coming in. My problem is that after using strncpy I get some garbage when I try to print it. I try using malloc to make the char array the exact size.
Code:
void parse_data(char *unparsed_data)
{
char *temp_str;
char *pos;
char *pos2;
char *key;
char *data;
const char newline = '\n';
int timestamp = 0;
temp_str = (char*)malloc(strlen(unparsed_data));
g_print("\nThe original string is: \n%s\n",unparsed_data);
//Ignore the first two lines
pos = strchr(unparsed_data, newline);
strcpy(temp_str, pos+1);
pos = strchr(temp_str, newline);
strcpy(temp_str, pos+1);
//Split the line in two; The key name and the value
pos = strchr(temp_str, ':'); // ':' divides the name from the value
pos2 = strchr(temp_str, '\n'); //end of the line
key = (char*)malloc((size_t)(pos-temp_str)-1); //allocate enough memory
data = (char*)malloc((size_t)(pos2-pos)-1);
strncpy(key, temp_str, (size_t)(pos-temp_str));
strncpy(data, pos + 2, (size_t)(pos2-pos));
timestamp = atoi(data);
g_print("size of the variable \"key\" = %d or %d\n", (size_t)(pos-temp_str), strlen(key));
g_print("size of the variable \"data\" = %d or %d\n", (size_t)(pos2-pos), strlen(data));
g_print("The key name is %s\n",key);
g_print("The value is %s\n",data);
g_print("End of Parser\n");
}
Output:
The original string is:
NEW_DATAa_PACKET
Local Data Set 16-byte Universal Key
Time Stamp (microsec): 1319639501097446
Frame Number: 0
Version: 3
Angle (deg): 10.228428
size of the variable "key" = 21 or 22
size of the variable "data" = 18 or 21
The key name is Time Stamp (microsec)
The value is 1319639501097446
F32
End of Parser
Run it again:
The original string is:
NEW_DATAa_PACKET
Local Data Set 16-byte Universal Key
Time Stamp (microsec): 1319639501097446
Frame Number: 0
Version: 3
Angle (deg): 10.228428
size of the variable "key" = 21 or 25
size of the variable "data" = 18 or 18
The key name is Time Stamp (microsec)ipe
The value is 1319639501097446
F
End of Parser
A:
Your results are because strncpy does not put a null character at the end of the string.
A:
Your strncpy(data, pos + 2, (size_t)(pos2-pos)); doesn't add a terminating \0 character at the end of the string. Therefore when you try to print it later, printf() prints your whole data string and whatever is in the memory right after it, until it reaches zero - that's the garbate you're getting. You need to explicitly append zero at the end of your data. It's also needed for atoi().
Edit:
You need to allocate one more byte for your data, and write a terminating character there. data[len_of_data] = '\0'. Only after that it becomes a valid C string and you can use it for atoi() and printf().
|
{
"pile_set_name": "StackExchange"
}
|
Q:
$\left| (4 \mathbb{N} -1) \cap \mathbb{P} \right| \ = \ \infty$ where $\mathbb{P}$ is the set of prime numbers.
I try to show that there are infinitely many prime numbers in the set $
\{ 4n-1 \ : \ n \in \mathbb{N} \}$. I've been told that I needed to adjust Euclid's proof a bit so that it would work for numbers of this kind, so I did, but without finding something useful.
My attempts
First, I supposed that there are there are only finitely many prime numbers of the shape $4n-1$, lets say $S \ = \ \{n_1,n_2, \cdots n_t \}$. Then I took a look at this, hoping that it would be prime.
$$
\prod_{1 \leq j \leq t}(4n_j -1)+1
$$
But, if $n$ is odd, the ones cancel out and $2$ would divide everything if I'm not mistaking. If $n$ is even, I guess everything would be even as well.
It seems that I misunderstood the hint. Could you give me a sketch about how this really works? You can make use of rings and groups if you need to, and you can use easy analytic stuff, but please don't use very advanced knowledge.
A:
Suppose $p_1,\cdots,p_n$ are all of them.
Then consider $4p_1\cdots p_n-1$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Building a GNOME 3 based distribution from scratch?
Possible Duplicate:
Installing ubuntu desktop without all the bloat
I have this idea of installing Ubuntu using the minimal cd, and then installing GNOME 3 using the ppa. How viable is this? And how will my remix compare with distro's that already ship with GNOME 3 like Fedora or openSUSE?
A:
This is a very similar question as this AU question and answer.
You should note, adding Gnome3 onto Ubuntu 11.04 is not as "clean" as the new Fedora 15 - since this has been built with Gnome3 from the beginning. Building ontop of Ubuntu means upgrading most of the Gnome-2 libraries.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
unhandled exception Handler in .Net 3.5 SP1
I'm converting my own web browser use WPF from Windows XP to Windows 7.
when I test on Windows XP, It has no error and exceptions.
But I convert and test on Windows 7 with Multi-touch Library, My Browser occurred unhandled exception.
Source: PresentationCore
Message: An unspecified error occurred on the render thread.
StackTrace:
at System.Windows.Media.MediaContext.**NotifyPartitionIsZombie**(Int32 failureCode)
at System.Windows.Media.MediaContext.NotifyChannelMessage()
at System.Windows.Interop.HwndTarget.HandleMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
InnerException: null
I want to know where the bug occurred. That Trace Message are garbage information for me.
I already googling to know that message, but i never found any information.
How do I get exactly function where the bug occurred? please tell me something.
A:
I encountered a similar problem myself so I thought I should document it here for others too.
My WPF application runs fine in .net 3.0 / 3.5 or 4.0. However, using a multi-touch screen would cause crashes due to multiple stylus inputs being unhandled:
System.ArgumentException was unhandled
Message="StylusPointDescription cannot contain duplicate StylusPointPropertyInfos.\r\nParameter name: stylusPointPropertyInfos"
Source="PresentationCore"
ParamName="stylusPointPropertyInfos"
It turns out this is a debug in .net 3.0 / 3.5 that is addressed (in theory) with this hotfix from MS:
http://thehotfixshare.net/board/index.php?showtopic=14251
However, that actually never worked for me.
Currently the only work around I have found for this multi-touch crash is to upgrade to VS2010 and use .NET 4.0. (as this bug was fixed in WPF 4 and back ported to 3.5 I believe)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scroll Views in storyboarding iphone
I'm trying to set up a scrollView in an app using storyboarding. I have done everything correctly but the scrollview won't scroll in simulator or on iPhone.
MoreViewController.h
@property(nonatomic, retain) IBOutlet UIScrollView *moreScroll;
MoreViewController.m
-(void)viewDidLoad{
[moreScroll setScrollEnabled:YES];
[moreScroll setContentSize:CGSizeMake(1220, 354)];
}
I have connected the scrollView to the files owner, can someone help please
Thanks in Advance
A:
With autolayout is there a new method - (void)viewDidLayoutSubviews
Here is a quick info:
Notifies the view controller that its view just laid out its subviews.
When a view’s bounds change, the view adjusts the position of its subviews. Your view controller can override this method to make changes after the view lays out its subviews. The default implementation of this method does nothing.
You should be fine if you add this:
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubViews];
[moreScroll setContentSize:CGSizeMake(1220, 354)];
}
A:
Setting an scroll view’s scroller style sets the style of both the horizontal and vertical scrollers. If the scroll view subsequently creates or is assigned a new horizontal or vertical scroller, they will be assigned the same scroller style that was assigned to the scroll view..
You should be if you add this lines in your code:
This line in .h file
@interface Shout_RouteView : UIViewController<UIScrollViewDelegate>
{
}
@property (retain, nonatomic) IBOutlet UIScrollView *scrollViewMain;
This lines copy in .m file
-(void)viewWillAppear:(BOOL)animated {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
scrollViewMain.frame = CGRectMake(0, 0, 768, 815);
[scrollViewMain setContentSize:CGSizeMake(768, 1040)];
}else {
scrollViewMain.frame = CGRectMake(0, 0, 320, 370);
[scrollViewMain setContentSize:CGSizeMake(320, 510)];
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why LastModifiedbyid in Trigger.new gives old value
I have noticed the strange behaviour of salesforce due to which even my code broke down in production.
I was trying to stop the user from updating some field..I used before udpate trigger and code like Trigger.new[i].LastModifiedbyId..
Ideally it should give the current user in Trigger.new[i].LastModifiedbyId in but it gives oldrecordLastModifiedbyId..
Although userinfo.getuserid resolves the problem later.
Any idea about this behaviour of salesforce.
A:
System audit fields like LastModifiedById, LastModifiedDate, and SystemModStamp are not updated until later in the transaction. You shouldn't rely on any of those values being set, especially in a "before" trigger; even OwnerId might have the wrong value during a trigger, especially if assignment rules are going to be evaluated. Using UserInfo.getUserId() is the most accurate way to determine the current user modifying a record.
Edit: The fields LastModifiedById and LastModifiedDate, at least, appear to be set during step 6 (temporary save to database) in the Triggers and Order of Execution document. This means that an after trigger should, in theory, be able to perform the validations you're looking. Validation rules and before triggers are executed before this temporary record save, and will definitely see the wrong values.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
play-framework 2 how to escape colon in routes
in my play2 routes file, I am trying to use a colon as a literal:
GET /:search controllers.SearchController.index()
but play complains, that a parameter is missing. How do I escape the colon (I tried backslashing it)?
thanks
A:
You must introduce a dummy regex parameter, as such:
GET /$colon<\:>search controllers.SearchController.index(colon)
You must then also redefine your controller method:
public static Result index(String colon) {
....
The parser is built in such a way that path expressions cannot be escaped, save for this method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How many banner ads that must be placed in the application
I have application for photos in The main facade I put one ads banner and one at the entrance to the image I want to put two units Is this allowed and you can use the same ads code for that
A:
Take a look at this Banner ad guidance from Google. There are instructions and examples with best practices.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Search matrix for blocks with upcoming dates
I have a matrix field with one "event" block type that contains several fields. One of those fields is a date field. Is there a way to get just blocks with upcoming dates?
A:
Here’s how you would do that:
{% set futureEvents = entry.myMatrixField.myDateField('>= '~now) %}
{% for event in futureEvents %}
{{ event.description }}
{% endfor %}
Update:
This actually hadn’t worked as I expected to, but it does as of Craft 2.3.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
filesharing from 2 computers.
Well, I have this program, the download option is working fine. I can access the other computer and download the file from it to my desktop, but the upload is a problem. When I choose the file, the program tries to get the file from the other computer and not mine so the path is wrong. Is there somehow I can use JFileChooser (as I do in download) and put in my computer name or IP address? Before I started to try the access to another computer I did make it work with JFilChooser, but the path messes it up now. Some tips or tricks?
public void upload(String username) throws RemoteException, NullPointerException{
try {
System.out.println(getProperty);
String lol = "/hei/hei.txt";
String ServerDirectory=("//" + "JOAKIM-PC"+ "/Users/Public/Server/");
byte[] filedata = cf.downloadFile2(getProperty + lol);
File file = new File(getProperty + lol);
BufferedOutputStream output = new BufferedOutputStream
(new FileOutputStream(ServerDirectory + file.getName()));
output.write(filedata,0,filedata.length);
output.flush();
output.close();
} catch(Exception e) {
System.err.println("FileServer exception: "+ e.getMessage());
e.printStackTrace();
}
}
public void download(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser("//" + "JOAKIM-PC" + "/Users/Joakim/Server/");
chooser.setFileView(new FileView() {
@Override
public Boolean isTraversable(File f) {
return (f.isDirectory() && f.getName().equals("Server"));
}
});
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
File selectedFile = chooser.getSelectedFile();
String clientDirectory = getProperty + "/desktop/";
byte[] filedata = cf.downloadFile(selectedFile);
System.out.println("Byte[] fildata: " + selectedFile);
File file = new File(fileName);
System.out.println("fileName: " + fileName);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(clientDirectory + file.getName()));
output.write(filedata, 0, filedata.length);
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}
A:
If I understood well, you want to use on your upload method this code:
JFileChooser chooser = new JFileChooser("./hei/");
int returnval = chooser.showOpenDialog(this);
String ServerDirectory=("//" + "JOAKIM-PC"+ "/Users/Public/Server/");
if(returnval == JFileChooser.APPROVE_OPTION){
File file = chooser.getSelectedFile();
try{
byte[] filedata = cf.downloadFile2(file.getAbsolutePath());
BufferedOutputStream output = new BufferedOutputStream
(new FileOutputStream(ServerDirectory + file.getName()));
output.write(filedata,0,filedata.length);
output.flush();
output.close();
}
catch(Exception e){
e.printStackTrace();
}
}
Is it right for you?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Firing Projectiles in Unity
Im trying to build a weapon in a game using Unity. My bullets spawn but i cant seem to get the force to apply on instantiation to get them to actually fire.
My weapon script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour {
public Rigidbody2D projectile;
public float forceMultiplier;
public Vector2 direction;
public Transform firePoint;
private float timeBtwShots;
public float startTimeBtwShots;
public void Fire(float force, Vector2 direction)
{
Instantiate(projectile, firePoint.position, transform.rotation);
projectile.AddForce(direction * force);
}
// Update is called once per frame
void Update () {
if (timeBtwShots <= 0)
{
if (Input.GetKeyDown(KeyCode.Return))
{
Fire(forceMultiplier, direction);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
A:
You need to add the force to the spawned object and not the prefab.
Your code should be something like this:
public void Fire(float force, Vector2 direction)
{
Rigidbody2D proj = Instantiate(projectile, firePoint.position, transform.rotation);
proj.AddForce(direction * force);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
print - Background or main thread operation
This might sound quite basic and stupid but it has been bothering me for a while. How can print be classified in terms of operation - main or background ?
As a small test, on putting print in a background task - web service call :
Webservice().loadHeadlinesForSource(source: source) { headlines in
print("background print")
self.headlineViewModels = headlines.map(HeadlineViewModel.init)
DispatchQueue.main.async {
print("main thread print")
completion()
}
}
Both the print statements get printed. From previous experience, if print was a main thread task, Xcode would have given me a warning saying that I need to put that in main thread. This is an evidence that print is not a main thread operation. Note that I am not saying print is a background task.
However, I have this understanding that since print displays output on Console, it is not a background operation. As a matter of fact all logging operations are not.
How would one justify the classification ?
A:
It seems what you consider to be a main thread operation is a call that needs to be performed on the main thread. From that perspective you are correct and have found an evidence of this call not being a main thread operation.
But does this have anything to do with anything else? Internally if needed this method may still execute its real operation on the main thread or any other thread for what we care. So in this sense a main thread operation is a restriction that call needs to be performed on main thread but has nothing to do with its execution or multithreading.
Without looking into what print does in terms of coding we can see that it works across multiple "computers". You can run your app on your device (iPhone) while plugged and Xcode on your computer will print out logs. This makes a suspicion that print is much like call to the remote server in which case the server is responsible for serializing the events so it makes no difference what thread the client is on. There are other possibilities such as dropping logs into file and then sending it which really makes little difference.
So How can print be classified in terms of operation - main or background? The answer is probably none. The call is not restricted to any thread so it is not main. It will probably lock whatever thread it is on until the operation is complete so it is not background either. Think of it like Data(contentsOf: <#T##URL#>) which will block the thread until data from given URL is retrieved (or exception is thrown).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
java.lang.NumberFormatException when trying to connect to HBase
I am setting HBase configuration new HBaseGraphConfiguration().set("hbase.zookeeper.quorum", ZOOKEPER_QORUM_NODE) where
ZOOKEPER_QORUM_NODE = "172.31.17.251:2181,172.31.17.252:2181,172.31.17.253:2181";
However it throws an java.lang.NumberFormatException, the part of the error is
Caused by: java.lang.NumberFormatException: For input string: "2181]"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at org.apache.zookeeper.client.ConnectStringParser.<init>(ConnectStringParser.java:72)
The console output before the error line is
2018-05-30 14:40:52 INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=[172.31.17.251:2181, 172.31.17.252:2181, 172.31.17.253:2181] sessionTimeout=180000 watcher=hconnection-0x25a65b770x0, quorum=[172.31.17.251:2181, 172.31.17.252:2181, 172.31.17.253:2181], baseZNode=/hbase
2018-05-30 14:40:52 INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=[172.31.17.251:2181, 172.31.17.252:2181, 172.31.17.253:2181] sessionTimeout=180000 watcher=hconnection-0x25a65b770x0, quorum=[172.31.17.251:2181, 172.31.17.252:2181, 172.31.17.253:2181], baseZNode=/hbase
How to solve it?
A:
Thanks for the answer of @VS_FF, I have found the issue and also now posting the whole answer
The short solution of this problem is just set conf.setDelimiterParsingDisabled(true);
First it is suggested to set the hbase.zookeeper.quorum = "ip1,ip2,ip3" (host ip) and hbase.zookeeper.property.clientPort = 2181 (port) separately.
The string of ip addresses are inputted to HBase configuration . Then, it has two sorts of parsing method, controlled by
conf = new PropertiesConfiguration();
conf.setDelimiterParsingDisabled(true);
if this setDelimiterParsingDisabled(true) is applied, then configuration will input the origin string to zookeeper, saying "ip1,ip2,ip3", otherwise setDelimiterParsingDisabled(false) (this is the default setting), in this condition, it will input an array to zookeeper, saying [ip1,ip2,ip3].
However, zookeeper need to get a String variable, so if setDelimiterParsingDisabled(false), it will first convert the array to String, adding the brackets [].
Finally, zookeeper parse the String variable by using split of notation ,, that is why it finally gets ip1 = "[ip1", ip2 = "ip2", ip3 = "ip3]" and throws an NumberFormatException
|
{
"pile_set_name": "StackExchange"
}
|
Q:
KeyCode_Enter to next edittext
In edittext, after typing 'Enter' key, system make a new line inside it. I'd like to focus on next edittext, no new line. how to code? my code in xml is below
<EditText
android:id="@+id/txtNPCode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_alignLeft="@+id/lblNPCode"
android:layout_below="@+id/lblNPCode"
android:layout_centerHorizontal="true"/>
<EditText
android:id="@+id/txtCNPCode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_alignLeft="@+id/lblCNPCode"
android:layout_below="@+id/lblCNPCode"
android:layout_centerHorizontal="true"/>
I also caputer key code in setOnKeyListener
tCNPCode.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == 66) {
Toast.makeText(S_PCode.this, "Enter Key", Toast.LENGTH_LONG).show();
//tNPCode.setFocusable(true);
}
return false;
}
});
A:
You don't even have to use OnKeyListener. Simply add line android:singleLine="true" to your EditText. After this operation EditText behaves exactly like you want. So, in your particular case:
<EditText
android:id="@+id/txtNPCode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_alignLeft="@+id/lblNPCode"
android:layout_below="@+id/lblNPCode"
android:layout_centerHorizontal="true"
android:singleLine="true"
/>
<EditText
android:id="@+id/txtCNPCode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_alignLeft="@+id/lblCNPCode"
android:layout_below="@+id/lblCNPCode"
android:layout_centerHorizontal="true"
/>
solves the problem.
A:
You have to use the requestFocus method. In your case it will be something like:
tCNPCode.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode == 66) {
txtCNPCode.requestFocus();
}
return false;
}
});
A:
The best way is to use one of the options for inputType, for example: android:inputType="textPersonName"
This will achieve the wanted effect. Check out the other options too, it'll save you some time in future :)
You shouldn't use android:singleLine="true", since it's deprecated. Here's what the documentations says about it:
This attribute is deprecated and is replaced by the textMultiLine
flag in the inputType attribute. Use caution when altering existing
layouts, as the default value of singeLine is false (multi-line
mode), but if you specify any value for inputType, the default is
single-line mode. (If both singleLine and inputType attributes are
found, the inputType flags will override the value of singleLine.).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Derive a 2D recurrence from a set of linear recurrences
Given a set of high-order linear recurrences:
$A(1, n): 0, 1, 0, 1, 0, ...$
$A(2, n): a_{n} = 2a_{n-2} - a_{n-4}$
$A(3, n): b_{n} = 3b_{n-2} - 3b_{n-4} + b_{n-6}$
$A(4, n): c_{n} = 4c_{n-2} - 6c_{n-4} + 4c_{a-6} - c_{n-8}$
ans so on.
I want to derive 2D recurrence for $A(m, n)$.
Obviously, each of linear recurrences has a characteristic polynomial $(x^2 - 1)^m$ (due to coefficients representing terms of row $m$ of Pascal's triangle). Moreover, each of that recurrences has more or less "nice" explicit formula.
So:
Is it possible to derive 2D recurrence?
If not, is it possible to derive general explicit formula for that recurrences?
EDIT:
Initial values (offset starts from $1$) are:
$A(2, n): 0,3,0,7$
$A(3, n): 0,6,3,31,10,76$
$A(4, n): 0,10,21,117,122,448,367,1131$
$A(5, n): 0,16,89,439,906,2630,3907,9037,11380,23196$
The main problem is that I don't know which initial values would be for $A(m, n)$. So I need a way to generalize it.
A:
The ordinary generating function (OGF for short) of $A(m,n)$, for fixed $m$, is $$F_m(x):=\frac{P_m(x)}{(x^2-1)^m},$$ where $P_m(x)$ is a polynomial of degree $\leq m$.
Since you are interested in $2D$ recursion of $A(m, n)$, we also want to consider the OGF of $A(m+1, n)$, that is $$F_{m+1}(x) := \frac{P_{m+1}(x)}{(x^2-1)^{m+1}}.$$
We obtain $$F_{m+1}(x) = \frac{P_{m+1}(x)F_m(x)}{P_m(x)(x^2-1)}.$$
Suppose $Q(x) = \frac{P_{m+1}(x)}{P_m(x)(x^2-1)} = q_0 + q_1x + q_2x^2 + \dots$. Then $$A(m+1, n) = [x^n]F_{m+1}(x) = [x^n]Q(x)F_m(x) = q_0A(m,n)+q_1A(m,n-1) + \dots + q_nA(m,0).$$
Example: The OGF of $A(1,n): 0, 1, \dots$ is $\frac{x}{1-x^2}$ and the OGF of $A(2,n): 0,3,0,7,\dots$ is $\frac{3x+x^3}{(1-x^2)^2}$. Then $Q(x)=\frac{3+x^2}{1-x^2}=3+4x^2+4x^4+4x^6+\dots$ and so $$A(2,n) = 3A(1,n) + 4A(1,n-2) + 4A(1,n-4) + 4A(1,n-6) + \dots,$$ and so $A(2,6)=3A(1,6)+4A(1,4)+4A(1,2)+4A(1,0) = 0$ as $A(1,0)=A(1,2)=A(1,4)=A(1,6)=0$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
asp.net user controls binds inside gridview
Hello fellow programmers, got a few problem here. I am adding a user control inside a gridview.
Now my question is how can bind it cause inside the user control is a gridviewthat needs the CourseCatID so that it could bind the datas. And by the way I cannot use nested griview cause I need the render of the nested usercontrol for another purpose. Any tutorial/help will be gladly appreciated.
<asp:GridView ID="grdCategory" runat="server" AutoGenerateColumns="False" Width="1100px"
DataKeyNames="CourseCatID" Font-Names="verdana,arial,helvetica,sans-serif" Font-Size="8pt"
CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False" />
<asp:BoundField HeaderText="CourseCatID" Visible = "false" DataField="CourseCatID" />
<asp:TemplateField HeaderText="Course Category">
<ItemTemplate>
<asp:Label ID="lblCourseCatID" runat="server" Visible="false" Text='<%# Eval("CourseCatID")%>'></asp:Label>
<a href="javascript:toggleDiv('mydiv<%# Eval("CourseCatID")%>')">
<asp:TextBox ID="txtCourseCatName" runat="server" Text='<%# Eval("CourseCatName") %>' Font-Size="XX-Small"
Font-Names="Verdana" Width="300px" Visible="false"></asp:TextBox>
<asp:Image ID="img" onclick="javascript:Toggle(this);" runat="server" ImageUrl="~/Images/minus.gif"
ToolTip="Collapse" Width="7px" Height="7px" ImageAlign="AbsMiddle" /></a>
<asp:Label ID="lbllastname" Height="15px" runat="server" Text='<%# Eval("CourseCatName")%>'> </asp:Label>
<div id="mydiv<%# Eval("CourseCatID")%>">
<br />
      <%--OnClick="ImageAdd_click" --%>
<asp:ImageButton ID="ImageAdd" Height="17px" ImageUrl="Images/addCourse.png" runat="server"
CommandName="cmdAdd" CommandArgument='<%# Eval("CourseCatID") %>' />
<br />
<br />
      
<asp:Panel ID="pnlCourse" runat="server"></asp:Panel>
<b><cuc1:CourseUserControl ID="CourseUserControl1" runat="server" /></b>
<br />
<br />
<br />
<br />
</div>
</ItemTemplate>
</asp:TemplateField>
Thank you for your time
A:
You have a couple of options.
The easiest one is to expose a public property on the user control that will let you do this:
<cuc1:CourseUserControl ID="CourseUserControl1" runat="server" CourseCategoryID='<%# (int)Eval("CourseCatID") %>' />
Then databind in the user control as soon as that property is assigned to. Note that I'm assuming the category is an Int32. For example (note that the CourseCategoryID stores its value in a private field, not in ViewState):
private int _courseCategoryID;
public int CourseCategoryID
{
get { return _courseCategoryID; }
set
{
_courseCategoryID = value;
// TODO: code that initializes the GridView in user control.
this.DataBind();
}
}
Your other option is to expose the same property and handle the RowDataBound event and do this:
if (e.Row.RowType == DataControlType.DataRow)
{
CourseUserControl courseDetails;
courseDetails = (CourseUserControl)e.Row.FindItem("CourseUserControl1");
// Assuming category ID is Int32
courseDetails.CourseCategoryID = (int)grdCategory.DataKeys[e.Row.RowIndex].Value;
courseDetails.DataBind();
}
Note that I'm databinding manually instead of immediately after assigning a new category to the user control in the current row.
For more information, see:
GridView.RowDataBound Event (ASP.NET 3.5)
or
GridView.RowDataBound Event (ASP.NET 4.0)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Any way to remove the yellow duck (help tooltip)?
Is there any way to close the help tooltip that appears at the bottom-right corner of the screen ?
As I usually zoom in to make the text more readable, that yellow duck becomes bigger and bigger, and I find it more annoying than helpfull.
A:
Yes, wait a bit and then choose "I hate this duck"
From the Meta StackExchange question Stack Exchange has been taken over by a rubber duck!:
You can then either go for "I have another problem" which repeats the same thing over again or you could select "I hate this duck" so make the duck sorry to hear that and bid Goodbye,duck.
I tried it myself. You have to choose for example "No" when it asks you whether you have a microphone or not. Then it goes through some text like "Quack Overflow is listening" and "The duck is thinking about your problem". After "The duck is typing" you will hear a "Quack". Wait a second or two and it will give you the option to choose "I hate this duck", after which the duck disappears.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Interpreter ignores elif clause entirely
The code in question is this:
age = input("How old are you?")
if ( int(age) ):
print ( "Congratulations! Some people die before they get to be %s years old!" % (age) )
elif ( age < 12 ):
print ( "You're way too young to hear all this swearin'. Get out." )
else:
print ( "That's not how this works. That's not how any of this works." )
raise SystemExit
print ( "You probably shouldn't brag, but that's quite a feat!" )
The if clause, seems to trigger fine, as does the "else" clause, which, if working as intended, ought to print the given message and close the program if the given input is anything other than a number. The problem is the elif clause, which the interpreter seems to just completely ignore. Even when I put 1, 2, 3 or 4 into the program - which is indisputably lower than 12 - it just continues on to print the "Congratulations!" line. I'm very confused and new to this - any insight would be highly appreciated. Thanks in advance!
A:
if int(age). What is this doing? It's just checking for a boolean value which is true. If it's true then it will always go into the if statement. In Python everything has a "truthiness" so any number which isn't equal to zero will result in the if being entered.
Here's something closer to what you're trying to achieve (I think?). You could edit to re-prompt for input, raise an error, whatever else.
age = input("How old are you? ")
if not age.isdigit():
print("Invalid age, must be numeric")
elif int(age) < 12:
print("You're way too young to hear all this swearin'. Get out.")
else:
print("Congratulations! Some people die before they get to be %s years old!" % (age))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is mysql load file data charset handling environment dependent?
I called DATA INFILE from java.sql.Statement.executeUpdate(String sql) to load UTF-8 CSV file into table.
When I use
LOAD DATA INFILE '/var/lib/mysql-files/upload/utf8table.csv' INTO TABLE temp.utf8table CHARACTER SET utf8 FIELDS TERMINATED BY ';' LINES TERMINATED BY '\r\n' (@vC1, @vC2) set C1=@vC1, C2=nullif(@vC2,'');
, without specifying CHARACTER SET utf8, non ASCII characters were corrupted. But the same query imported all characters correctly when was executed in Mysql Workbench. Query with charset specified works well in both cases. What can be the difference in the execution environments that leaded to such behavior?
A:
According to the docs:
The server uses the character set indicated by the character_set_database system variable to interpret the information in the file. SET NAMES and the setting of character_set_client do not affect interpretation of input. If the contents of the input file use a character set that differs from the default, it is usually preferable to specify the character set of the file by using the CHARACTER SET clause. A character set of binary specifies “no conversion.”
See also sysvar_character_set_client. The default is latin1 if not specified.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Share configuration file at CakePHP between Config files (routles.php, mail.php...)
I have a site running in localhost as a development environment and in a server for production.
There are some differences in some configuration files between both and I every time I have to update the changes in the server I have to be careful not to overwrite some files which are different.
I would like to be able to simplify this process by creating just one single file with the correct configuration for each environment.
I need to read that file currently in this Config files:
app/Config/email.php
app/Config/routes.php
And ideally, if possible in:
app/Vendor/Vendor_name/vendor_file.php
Is it possible somehow?
I have tried to use Configure::read and Configure::write but it seems it can not be done inside email settings such as public $smtp or in the routes file.
Thaks.
A:
The routes file is simply a php file with calls to the router. You could very simply split it up into multiple files and load them yourself:
app/Config/
routes.php
routes_dev.php
routes_production.php
routes.php would then load the proper routes file.
<?php
if ($env == 'dev') {
include 'routes_dev.php';
} else {
include 'routes_production.php';
}
The email config is also just a php file. You could write a function to set the proper default config based on the environment.
class EmailConfig {
public function __construct() {
if ($env == 'dev') {
$this->default = $this->dev;
}
}
public $default = array(
'host' => 'mail.example.com',
'transport' => 'Smtp'
);
public $dev = array(
'host' => 'mail2.example.com',
'transport' => 'Smtp'
);
}
As for vendor files, that's a case by case basis.
If you have a deployment system, it might be better to actually have separate files for each environment (maybe even a full config directory) and rename them after the deployment build is complete, making Cake and your code none the wiser.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Autorotating ViewController after dismissing MPMoviePlayerViewController
Before you vote this question down, note, that I've already tried to implement all the solutions available on stackoverflow. Here is the issue:
My application runs only in portrait mode. The only thing which needs to be in landscape is video player. When a user taps on my TableViewCell this block of code is called:
MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:videoUrl];
[self presentMoviePlayerViewControllerAnimated:moviePlayer];
After that, I need to give the user the ability to watch video both in portrait and landscape mode. After he is done, everything should get back into portrait mode. I've tried to call this block of code in my AppDelegate.m:
- (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
NSUInteger orientations = UIInterfaceOrientationMaskPortrait;
if ([[self.window.rootViewController presentedViewController] isKindOfClass:[MPMoviePlayerViewController class]]) {
orientations = UIInterfaceOrientationMaskAllButUpsideDown;
}
return orientations;
}
With it everything is fine except one thing - when the video is over or when the user taps "Done" button while in landscape mode, my view controller appears in landscape mode too.
Besides it, I've tried a lot of other methods - but nothing seems to work.
I'll be glad for any help!
A:
Thanks @Shubham - Systematix for the answer.
All that I had to do was to remove every code related to autorotating except this method in AppDelegate:
- (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if ([[window.rootViewController presentedViewController] isKindOfClass: [MPMoviePlayerViewController class]])
{
//NSLog(@"in if part");
return UIInterfaceOrientationMaskAllButUpsideDown;
}
else
{
//NSLog(@"in else part");
return UIInterfaceOrientationMaskPortrait;
}
}
When I did it everything worked like a magic!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a term for a made-up synonym or analogy to describe a forgotten word?
(I'm not a linguist, just generally interested in languages, so forgive me if I lack the appropriate vocabulary.)
There are some examples here, but the general gist is that someone forgets a word (in my case, "shovel") and substitutes a usually multi-word, often inaccurate or outright wrong synonym ("dirt spoon"). This obviously isn't a common synonym for shovel, but gets the point across, especially when there's a shovel visually present to cement the impression. Other examples include "sea pancake" for manta ray and "cereal water" for milk.
There usually seems to be some kind of analogy going on, if not always clear. The speaker tends to default to a similar item and attach an adjective or other descriptor. Not all examples in the link do so, but I'm more interested in the ones that do.
I don't know if this is a frequent linguistic phenomenon or if it's just somewhat prevalent on the internet.
A:
Yep, these are called circumlocutions. Someone who is frequently unable to remember the right words could be diagnosed with anomic aphasia.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GetPixel always return 0 on png image
When i read image with GetPixel() color value is always black. My image is a png image.
I tried convert the image to bitmap before, but don't had success.
I believe which the problem isn't my code, because whether I open png image in Paint and only save it. The code read image correctly.
I load image like bellow
myImage = new Bitmap(fileName);
I need read image here
private void LoadImageMap(Bitmap value){
for (int col = 0; col < value.Width; col++)
{
for (int row = 0; row < value.Height; row++)
{
var color = value.GetPixel(col, row);
var color is black, always.
Sample of the image...
A:
PNG image there is transparency and when pixel is full transparency GetPixel() result with zero value to RGB colors.
Then my code needed of the one if to validate this case.
the solution was like bellow:
var color = value.GetPixel(x, y);
if(color.A.Equals(0))
{
color = Color.White;
}
PNG use ARGB colors where A represent the alpha channel and whether alpha is zero this pixel has full transparence.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select the count of entries that have Max value in a range
I need to get the count of myIndex which it has the max Value per hour, for example:
MyIndex f_hour maxi
8187 10 70** ++1 for 10h and 8187
8178 10 50
8184 10 46
8190 10 46
8180 10 40
8179 10 33
8185 10 30
8183 10 26
8181 10 23
8182 10 20
8186 10 20
8177 10 13
8189 10 6
8188 10 3
**8188 11 80** ++1 for 11h and index 8188
8187 11 60
8180 11 53
8186 11 50
8179 11 46
8190 11 46
8178 11 43
8181 11 33
8184 11 33
8189 11 33
8183 11 26
8185 11 23
8182 11 16
8177 11 13
**8187 12 73** now 8187 has at 10h the max value and now at 12h too, so 2 !!
8188 12 66
8179 12 60
8190 12 56
the result will be like
MyIndex Count
8187 2 (times)
8188 1 (time)
How can I do this?
A:
This is a histogram of histogram query. You seem to want to count the number of hours that each value appears as a maximum. This ends up being a double group by:
select maxvalue, count(*) as numhours
from (select hour, max(value) as maxvalue
from table t
group by hour
) t
group by maxvalue
order by maxvalue;
EDIT:
I see, you don't want the histogram of values but of indexes. You can do that with window functions, which are ANSI standard and available in most (but not all) databases:
select myindex, count(*) as numhours
from (select t.*, row_number() over (partition by hour order by value desc) as seqnum
from table t
group by hour
) t
where seqnum = 1
group by myindex
order by myindex;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Você come direito!
Eu ouvi esse frase em lugares diferentes:
No escritório do médico:
Estava doente e o médico perguntou: Você come direito?
Pareceu para mim que: você tem apetite?
No texto li:
Ele fuma demais e não faz nenhum exercício físico e não come direito.
Parece para mim que: Não tem uma diate saudavél.
Sim? Qual é significado desse frase?
A:
"Comer direito" é uma expressão vaga e ampla, mas essencialmente significa ter uma dieta saudável, incluindo aí a qualidade, quantidade e regularidade das refeições.
No exemplo do médico, esse era quase certamente o sentido na pergunta. Para perguntar sobre o apetite especificamente, ou se menciona a palavra, ou se pergunta sobre "comer bem".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Isn't this HTML5 date input supposed to have a spinner in Fx4 and Safari5?
Loading
http://diveintohtml5.ep.io/examples/input-type-date.html
<form>
<input name="birthday" type="date">
<input type="submit" value="Go">
</form>
into Fx4 and Safari5 on XPsp3, I expected to see some kind of enhancement like the up/down on type="number".
Do you?
Update: A date picker appears in Opera - nothing in Safari5 or FX4 on XP
A:
"Up" and "down" is for type="number", not type="date", isn't it? This page suggests, that the UIs for the new types are not yet supported in anything but Opera.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clone private git repo with dockerfile
I have copied this code from what seems to be various working dockerfiles around, here is mine:
FROM ubuntu
MAINTAINER Luke Crooks "[email protected]"
# Update aptitude with new repo
RUN apt-get update
# Install software
RUN apt-get install -y git python-virtualenv
# Make ssh dir
RUN mkdir /root/.ssh/
# Copy over private key, and set permissions
ADD id_rsa /root/.ssh/id_rsa
RUN chmod 700 /root/.ssh/id_rsa
RUN chown -R root:root /root/.ssh
# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Remove host checking
RUN echo "Host bitbucket.org\n\tStrictHostKeyChecking no\n" >> /root/.ssh/config
# Clone the conf files into the docker container
RUN git clone [email protected]:Pumalo/docker-conf.git /home/docker-conf
This gives me the error
Step 10 : RUN git clone [email protected]:Pumalo/docker-conf.git /home/docker-conf
---> Running in 0d244d812a54
Cloning into '/home/docker-conf'...
Warning: Permanently added 'bitbucket.org,131.103.20.167' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
2014/04/30 16:07:28 The command [/bin/sh -c git clone [email protected]:Pumalo/docker-conf.git /home/docker-conf] returned a non-zero code: 128
This is my first time using dockerfiles, but from what I have read (and taken from working configs) I cannot see why this doesn't work.
My id_rsa is in the same folder as my dockerfile and is a copy of my local key which can clone this repo no problem.
Edit:
In my dockerfile I can add:
RUN cat /root/.ssh/id_rsa
And it prints out the correct key, so I know its being copied correctly.
I have also tried to do as noah advised and ran:
RUN echo "Host bitbucket.org\n\tIdentityFile /root/.ssh/id_rsa\n\tStrictHostKeyChecking no" >> /etc/ssh/ssh_config
This sadly also doesn't work.
A:
My key was password protected which was causing the problem, a working file is now listed below (for help of future googlers)
FROM ubuntu
MAINTAINER Luke Crooks "[email protected]"
# Update aptitude with new repo
RUN apt-get update
# Install software
RUN apt-get install -y git
# Make ssh dir
RUN mkdir /root/.ssh/
# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
ADD id_rsa /root/.ssh/id_rsa
# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts
# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git
A:
You should create new SSH key set for that Docker image, as you probably don't want to embed there your own private key. To make it work, you'll have to add that key to deployment keys in your git repository. Here's complete recipe:
Generate ssh keys with ssh-keygen -q -t rsa -N '' -f repo-key which will give you repo-key and repo-key.pub files.
Add repo-key.pub to your repository deployment keys.
On GitHub, go to [your repository] -> Settings -> Deploy keys
Add something like this to your Dockerfile:
ADD repo-key /
RUN \
chmod 600 /repo-key && \
echo "IdentityFile /repo-key" >> /etc/ssh/ssh_config && \
echo -e "StrictHostKeyChecking no" >> /etc/ssh/ssh_config && \
// your git clone commands here...
Note that above switches off StrictHostKeyChecking, so you don't need .ssh/known_hosts. Although I probably like more the solution with ssh-keyscan in one of the answers above.
A:
There's no need to fiddle around with ssh configurations. Use a configuration file (not a Dockerfile) that contains environment variables, and have a shell script update your docker file at runtime. You keep tokens out of your Dockerfiles and you can clone over https (no need to generate or pass around ssh keys).
Go to Settings > Personal Access Tokens
Generate a personal access token with repo scope enabled.
Clone like this: git clone https://[email protected]/user-or-org/repo
Some commenters have noted that if you use a shared Dockerfile, this could expose your access key to other people on your project. While this may or may not be a concern for your specific use case, here are some ways you can deal with that:
Use a shell script to accept arguments which could contain your key as a variable. Replace a variable in your Dockerfile with sed or similar, i.e. calling the script with sh rundocker.sh MYTOKEN=foo which would replace on https://{{MY_TOKEN}}@github.com/user-or-org/repo. Note that you could also use a configuration file (in .yml or whatever format you want) to do the same thing but with environment variables.
Create a github user (and generate an access token for) for that project only
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to estimate (predict) the half life of a quantitative trading system?
Usually even good performing quant trading strategies work for a while and then return start to shrink. I see two reasons for that which would probably give rise to different analysis:
The Strategy got known by too many traders and has been arbitraged away.
Market conditions have changed (will or will not revert).
A:
I go out on a limb and say No.
You can of course observe how it does, but making a prediction about how and when it decays is difficult to impossible with any degree of precision. You'd need a meta-model of the market as a whole. And, well, if you had that, wouldn't you use that knowledge to make your model better?
That said, you can of course measure pnl and other return characteristics and extrapolate, but that isn't a proper predictive model in my book.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Table Row Toggle in jQuery
I have been stuck with this problem for a while now. I know that for table rows to animate smoothly you need divs. And I came over this solution where I can hide the tablerow I want, but I cannot make it appear again.
I need some if solution or maybe some toggle solution.
HTML:
<table>
<tbody>
<tr>
<td class="clickme">
Sample text
</td>
<td class="clickme">$10</td>
<td class="clickme">$100</td>
<td class="clickme">$0</td>
</tr>
<tr class="hideme">
<td colspan="4">
<div>
Sample text, sample text, sample text, sample text, sample text, sample text
</div>
</td>
</tr>
<tr>
<td class="clickme">
Sample text
</td>
<td class="clickme">$10</td>
<td class="clickme">$100</td>
<td class="clickme">$0</td>
</tr>
<tr class="hideme">
<td colspan="4">
<div>
Sample text, sample text, sample text, sample text, sample text, sample text
</div>
</td>
</tr>
<tr>
<td class="clickme">
Sample text
</td>
<td class="clickme">$10</td>
<td class="clickme">$100</td>
<td class="clickme">$0</td>
</tr>
<tr class="hideme">
<td colspan="4">
<div>
Sample text, sample text, sample text, sample text, sample text, sample text
</div>
</td>
</tr>
<tr>
<td class="clickme">
Sample text
</td>
<td class="clickme">$10</td>
<td class="clickme">$100</td>
<td class="clickme">$0</td>
</tr>
<tr class="hideme">
<td colspan="4">
<div>
Sample text, sample text, sample text, sample text, sample text, sample text
</div>
</td>
</tr>
</tbody>
</table>
Jquery:
$('.hideme').find('div').hide();
$('.clickme').click(function() {
$(this).parent().next('.hideme').find('div').slideToggle(500);
return false;
});
The right markup and Jquery is updated. Final JSFiddle: http://jsfiddle.net/NVx4S/21/
A:
<table>
<tbody>
<tr>
<td id="content-1" class="clickme">
Sample text
<!-- <a href="#content-1" class="clickme">Sample text</a> -->
</td>
<td>$10</td>
<td>$100</td>
<td>$0</td>
</tr>
<tr>
<td colspan="4">
<div id="slide-content-1">
Sample text, sample text, sample text, sample text, sample text, sample text
</div>
</td>
</tr>
</tbody>
</table>
$('.clickme').click(function() {
//$(this.hash).slideToggle(500);
$('#slide-'+this.id).slideToggle(500);
return false;
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Any event to detect when the "Class" attribute is changed for a control
I have a "div" control with some id="myDiv" class="myClass"
var var1=10;
in Javascript. Based on user action I will change the class for this control from "myClass" to "newClass" so when this has happened I want to change the value of var1 to 20.
So how would I recognize that change in Class?
A:
You may use onpropertychange(IE) and DOMAttrModified (others)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Android Firestore, How to set multiple timestamp in one document
According to the official documentation doc I am using FieldValue to set the document field as timestamp value, my question is:
How can I add multiple timestamp value to the same document, like I need to set the startDate and the endDate and docTimpStamp
I am using the following code:
@ServerTimestamp Date time;
and on adding the document:
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("startDate", FieldValue.serverTimestamp());
time.setTime (...); // here change the date to be the endDate
dataMap.put("endDate", FieldValue.serverTimestamp());
time.setTime (...); // here change the date to be the docTimeStamp
dataMap.put("docTimeStamp",FieldValue.serverTimestamp());
and this solution is not working, the data not found getting with the same values and not real time.
How can I implement this process?
A:
I think you are mixing the use of the ServerTimestamp annotation with the use of the static serverTimestamp() method
The ServerTimestamp annotation is "used to mark a timestamp field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp."
In your code there is no POJO containing null for the time Date object.
On the other hand, when you do dataMap.put("endDate", FieldValue.serverTimestamp()); you tell to Firestore to "include a server-generated timestamp" for the value of endDate.
So it is normal that you find the same time for the three values, as they are written to the database (quasi) simultaneously.
In addition, note that there is no link between (e.g.) the two following lines.
time.setTime (...); // here change the date to be the endDate
dataMap.put("endDate", FieldValue.serverTimestamp());
In the first line you set a new value for time but time is not used in the 2nd line. And FieldValue.serverTimestamp() is not linked to the time object, as explained above.
So, in conclusion, you will probably have to take the full control on the values you want to write (with time.setTime(...); as you do) and avoid using the serverTimestamp() method but use the time object.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is Timezone offset added to Time undesirably (03:00 to 08:00)
In Android application I am adding events to user's calendar.
My problem is that, the time I save is changed, when it is stored in Google calendar (means 03:00 to 08:00 offset of +0500 added to time which is my time-zone +0500)
Kindly guide me what I am doing wrong..
I am using this code to set time and date for calendar Event
calendar.set(year, monthOfYear, dayOfMonth);
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime startDateTime = new DateTime(sdf.format(calendar.getTime()));
EventDateTime start = new EventDateTime().setDateTime(startDateTime);
event.setStart(start);
Detail Reference to original code:
https://developers.google.com/google-apps/calendar/create-events
A:
The problem is likely related to your SimpleDateFormat and can be simplified as:
calendar.set(year, monthOfYear, dayOfMonth);
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
DateTime startDateTime = new DateTime(calendar.getTime())
EventDateTime start = new EventDateTime().setDateTime(startDateTime);
event.setStart(start);
The Calendar exposes the underlying Date and the DateTime has a constructor that takes Date so there should be no need to parse it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery Datatables - Access Row ID when binding data
I'm using jQuery DataTables and some of my rows have select boxes defined in the columns option array:
ddlOptions = '<option value="val">Text</option>'
"columns": [
{ data: "DateOfService", defaultContent: "" },
{"defaultContent": "<select id=\"TimeIn1\" class=\"timeDDL\">" + ddlOptions + "</select>"},
{"defaultContent": "<select id=\"TimeOut1\" class=\"timeDDL\">" + ddlOptions + "</select>"}
]
When I create the select boxes, all the id's are going to be the same, so I need to give them all individual id's. I was thinking I can just use the RowId property from my dataset, but how would I go about doing so?
A:
After more digging I found this page: http://datatables.net/reference/option/columns.render
On it, it has the following example:
$('#example').dataTable( {
"columnDefs": [ {
"targets": 0,
"data": "download_link",
"render": function ( data, type, full, meta ) {
return '<a href="'+data+'">Download</a>';
}
} ]
});
The full parameter contains all of my Row data, which is just what I needed. Hope this helps someone else...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
If the homomorphic image of a polynomial is irreducible, does it imply polynomial is irreducible
If the homomorphic image of a polynomial is irreducible, then is the original polynomial irreducible?
let $\phi: R[x]\rightarrow S[x]$ be a ring homomorphism. Let $f(x)\in R[x]$ be a polynomial and $g(x)\in S[x]$ be the polynomial obtained by applying $\phi$ to $f(x)$.
If $g(x)$ is irreducible, does it imply $f(x)$ is irreducible in $R[x]$
A:
Not necessarily: consider the quotient projection $\pi:\Bbb Z[x]\to \Bbb F_2[x]$. Then $\pi((2x+1)(x^2+x+1))=x^2+x+1$
An example of a UFD $R$ and a map $f:R[x]\to R[x]$ that maps a reducible element to an irreducible one is $R=\Bbb Z[T_n\,:\, n\in\Bbb N]$ and $f(p(T;x))=p(T_0,T_0,T_1,T_2,\cdots; x)$. In fact, $f((T_0-T_1+1)(x^2+1))=x^2+1$.
However, if in addition to $R$ being a domain we require that $f:R[x]\to R[x]$ is a $R$-algebra homomorphism and $f(x)\notin R$, indeed we'll have that preimage of irreducible polynomials will be irreducible. This is because $R[x]^*=R^*$ and $f(p)=p\circ [f(x)]$, with $\deg f(p)=\deg p\deg f(x)\ge \deg p$. Therefore, if $p=qr$, then $f(p)=(q\circ [f(x)])\cdot (r\circ [f(x)])$. The only way one of these factors could be in $R^*$ is that one of $r$ or $q$ has degree $0$ in the first place (and thus that it is equal to its image by $f$).
The previous observation applies to ring-homomorphisms $f:\Bbb Z[x]\to \Bbb Z[x]$, since they must be $\Bbb Z$-algebra homomorphisms. Of course, if you allow $f(x)\in\Bbb Z$, there are some reducible polynomials that take prime values in a couple of integers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why twitter OAUTH not redirecting me back to application in CustomWebView in Android?
I am trying to open twitter integration inside a custom webview beacuse,
I am using this example
ctx.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
If I user above code, it give a problem on pressback button. After redirection and posting status. When I press back button it goes to browser not to my application. I decide to user custom webview to avoide this by handling back event.
I am using following example. But now after authuntication browser not redirecting me back to my application but give an error, that page not found.?
Can anyone help?
A:
I finally modify my CustomeWebView class method to check if the redirecting URL is start with "----" then parse tokens from URL and finish this activity and start new activity.
I am also find some good examples to use twitter in android
https://github.com/brione/Brion-Learns-OAuth
https://github.com/marakana/OAuthDemo
http://automateddeveloper.blogspot.com/2011/06/android-twitter-oauth-authentication.html
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I use HP:s HTML config on macOs Sierra somehow?
I've bought a HP Laserjet Pro M12 (M11-M13 series). I'm trying to setup the wireless part. No firmware has been released for Sierra yet. I have installed the drivers 10.11 instead. When I click open HTML config, I get sent to http://localhost:5050/SSI/index.htm, it seems to be a webhost provided by the printer via USB.
The first page I visit renders fine, but when I click any link the page breaks and it says safari can't connect to the server "localhost".
Is there some way to get this working? I've tried other browsers.
A:
I just solved this by replacing localhost:5050 with 0.0.0.0:5050 in the domain name, ie http://0.0.0.0:5050/SSI/index.htm
Not sure why it worked but it did :P
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MS Access VBA SQL SELECT * INTO tempTbl WHERE Stuff="" AND OtherStuff BETWEEN Date Range
I have a form with one text box, two combo boxes (dropdowns), and two text boxes with input masks for mm/dd/yyyy 99/99/0000;0;_
I am attempting to use all of these fields as filters for a subform.
I have the controls set to fire after update and run a sub that builds a SELECT * INTO sql string for a temp Table that is then sourceobject'ed back to the subform.
In code I have for each control I have code building a snippet of the Where statement for the final sql. the snippet grows as needed, is labeled "Filter"
Some other non-Finished Code....
If Not IsNull(txtDateFrom) Then
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= " & Me.txtDateFrom & ")" & " And " & "([Date_LastSaved] <= " & Me.txtDateTo & ")"
End If
Dim sql As String
sql = "SELECT * INTO tmpTable FROM tblReview"
If Not IsNull(Filter) Then
sql = sql & " WHERE " & Filter
End If
My issue and question is that I am testing this one specific situation where there will be Filter = Filter & " AND " & "DATE_STUFF"
where the final sql looks like...
SELECT * INTO tmpTable FROM tblReview WHERE ReviewStatus = 'Quoted' AND ([Date_LastSaved] >= 09/12/2018) And ([Date_LastSaved] <= 10/16/2018)
which should have some result with the test data. Yet, the tmpTable is empty.
This is only happening when I apply a date range criteria.
I tried BETWEEN but could not nail down the syntax.
Any insight is greatly appreciated, Thanks!
UPDATE:
Answer:
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= #" & Me.txtDateFrom & "#)" & " And " & "([Date_LastSaved] <= #" & Me.txtDateTo & "#)"
A:
If you want to use dates then they must be quoted. If you just say 10/16/2018 then you are dividing the integer 10 by 16 by 2018 which will yield an integer zero. It will then convert the dates to an integer to do the compare, which will yield a much bigger number, and thus you get no rows.
Any date testing should always be done using date types rather than strings. I think in msaccess you can surround it in #, but not sure. Just research this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Finding all solutions of a system of linear equations in $\mathbb{R}$
So I have to find all solutions of the following equations:
$$
a+2b+c-3d=3;
$$
$$
-2a+b-2c+d=-1;
$$
$$
2a+2c-2d=2;
$$
$$
a+3b+c-4d=4
$$
so I found out using the Gauss elimination, that the equation has no solutions,
but after solving it the normal way, I found that one possible solution could be:
$d=0, b=1, a=1-c$ and $c$ can be anything. But I am not sure if that's really a solution or if it doesn't count, because than there would be an unlimited amount of solutions.
A:
Your question is:
$$\mathbf Ax=\small\begin{bmatrix}1&2&1&-3\\-2&1&-2&1\\2&0&2&-2\\1&3&1&-4\end{bmatrix}\begin{bmatrix}x_1\\x_2\\x_3\\x_4\end{bmatrix}=\begin{bmatrix}3\\-1\\2\\4\end{bmatrix}$$
The reduced row echelon form of $\mathbf A$ is:
$$\text{rref(A)}=\tiny\begin{bmatrix}1&0&1&-1\\0&1&0&-1\\0&0&0&0\\0&0&0&0\end{bmatrix}$$
So you have two linearly dependent rows (only two pivot columns). Therefore the $\text{rank(A)}=2$, which implies that the cardinality of the column space is $2.$ We know that by the rank-nullity theorem that $\text{rank(A)+ ker(A) = number of columns(A)}$. Therefore the nullity is $2.$ The matrix is rank deficient, and you have two free variables.
Solving the system:
Find the reduced row echelon form of the augmented matrix (pivots boxed):
$$\small\begin{bmatrix}1&2&1&-3&\vert&3\\-2&1&-2&1&\vert&-1\\2&0&2&-2&\vert&2\\1&3&1&-4&\vert&4\end{bmatrix}\underset{\text{Rref}}{\rightarrow}\begin{bmatrix}\boxed{1}&0&\color{blue}{1}&\color{blue}{-1}&\vert&1\\0&\boxed{1}&\color{blue}{0}&\color{blue}{-1}&\vert&1\\0&0&\color{blue}{0}&\color{blue}{0}&\vert&0\\0&0&\color{blue}{0}&\color{blue}{0}&\vert&0\end{bmatrix}$$
The free variables correspond to the column vectors without a pivot row (in blue). They will be multiplied by $x_3$ and $x_4$ after solving the system, and the choice of $x_3$ and $x_4$ will make no difference, because they will be scalars in front of a vector in the null space of $\mathbf A.$ So we can even give them different names to identify them as free variables - for example, $x_3=s$ and $x_4=t.$ With this, we want to solve $x_1$ and $x_2,$ keeping in mind:
$$x_1\begin{bmatrix}1\\0\\0\\0\end{bmatrix}+x_2\begin{bmatrix}0\\1\\0\\0\end{bmatrix}+s\begin{bmatrix}1\\0\\0\\0\end{bmatrix}+t\begin{bmatrix}-1\\-1\\0\\0\end{bmatrix}=\begin{bmatrix}1\\1\\0\\0\end{bmatrix}$$
The reduced echelon spells out:
\begin{align}1\,x_1 + 0\,x_2 +1s\,-1\,t&=1;\quad x_1=1+0-1s+1t\\
0\,x_1 + 1\,x_2 +0\,s-1t&=1; \quad x_2 =0 + 1 +0\,s+1t\\
&x_3=s\\
&x_4=t
\end{align}
We end up with
$$\underset{\text{vectors }\in\text{ Col(A)}}{\underbrace{\begin{bmatrix}1\\0\\0\\0\end{bmatrix}+\begin{bmatrix}0\\1\\0\\0\end{bmatrix}}}+\underset{\text{null space of A}}{\underbrace{s\begin{bmatrix}-1\\0\\1\\0\end{bmatrix}+t\begin{bmatrix}1\\1\\0\\1\end{bmatrix}}}$$
$s$ and $t$ are free variables. Scalars in $\mathbb R.$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Switching Wiris http to https
We have implemented the Wiris tool into an application, but when you open the editor in Chrome for example you need to click the shield and select 'Load unsafe script' each time. As a note the application it is integrated with is https.
I know that when you inspect the tool there are three links in the markup:
http://www.wiris.net/demo/editor/editor?lang=en
http://www.wiris.com/editor3/docs/manual/latex-support
http://www.wiris.com/editor3/docs/manual
I can only assume that because these are http they are triggering the security option each time the editor is opened. Does anyone know if it is possible to launch the editor with https so that it can be used more efficiently.
A:
In the configuration.ini file for WIRIS there is a variable called wirisimageserviceprotocol.
You could try setting the value of that to https like this:
wirisimageserviceprotocol = https
Reference: WIRIS Configuration
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gaining root privileges in SCO
I am learning Linux for work, so am still a bit rusty on the edges.
I need to change the folder permission of the directory /opt, and I know in Linux, you do the following:
chmod 775 /opt
I get a message under that saying:
chmod: WARNING: cannot change /opt/: Operation not permitted (error 1).
Does that mean I need sudo permissions? But the sudo command is not recognized.
But in SCO, it is different, as SCO is a little older than Ubuntu.
I have found this link on the net, but don't quite understand what they mean by "memo": Changing file permissions.
Is there an easier way of doing this, like something similar to Linux?
A:
That message means you don't have sufficient privileges on the system to change the mode of the directory. If sudo is not installed on the system, you will need to gain elevated privileges using su (you'll need the root password), when you will be able to use chmod in exactly the way you would on Linux - using either absolute or symbolic permissions.
If you don't have the root password, you will need to ask someone who has sufficient privileges to make the change for you. Depending on local policy, a request to have sudo installed and configured may or may not work.
EDIT
From an answer to your other open thread, it seems that SCO has a command called asroot, which serves a similar purpose to sudo elsewhere.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Out of memory error with bitmap and a image in full screen
I'm making an app gallery. It's worked but so slow and after I click in some images it's get an out of memory error.
FullScreenImageAdapter.java
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
@Override
public int getCount() {
return this._imagePaths.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
Button btnClose;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//BitmapFactory.decodeFile(pathToImage, bmOptions);
int photoW = options.outWidth;
int photoH = options.outHeight;
int scaleFactor = Math.min(photoW/50, photoH/50);
options.inJustDecodeBounds = false;
options.inSampleSize = 8;
options.inPurgeable = true;
// options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
imgDisplay.setImageBitmap(bitmap);
// close button click event
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
public class FullScreenViewActivity extends Activity{
private Utils utils;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view);
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,
utils.getFilePaths());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
//adapter.destroyItem(viewPager,position,i);
}
}
GridViewActivity
public class GridViewActivity extends Activity {
private Utils utils;
private ArrayList<String> imagePaths = new ArrayList<String>();
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils(this);
// Initilizing Grid View
InitilizeGridLayout();
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
AppConstant.GRID_PADDING, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth() - ((AppConstant.NUM_OF_COLUMNS + 1) * padding)) / AppConstant.NUM_OF_COLUMNS);
gridView.setNumColumns(AppConstant.NUM_OF_COLUMNS);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setPadding((int) padding, (int) padding, (int) padding,
(int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
}
}
--
public class GridViewImageAdapter extends BaseAdapter {
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
}
@Override
public int getCount() {
return this._filePaths.size();
}
@Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
// get screen dimensions
Bitmap image = decodeFile(_filePaths.get(position), imageWidth,
imageWidth);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
imageView.setImageBitmap(image);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
@Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
_activity.startActivity(i);
}
}
/*
* Resizing image size
*/
public static Bitmap decodeFile(String filePath, int WIDTH, int HIGHT) {
try {
File f = new File(filePath);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_WIDTH = WIDTH;
final int REQUIRED_HIGHT = HIGHT;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
So the gridview is so slow and after click some images the fullsecreenImageView
I get out of memory error
A:
Consider switching to using glide for image loading - https://github.com/bumptech/glide
It will handle caching and memory for you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Render plotly plots asynchronously in shiny app
In shiny app I render couple plotly plots at once, but they render only after all of them are calculated. For example, if rendering 8 of 9 plots takes 8 seconds and rendering 9th takes 15 seconds, the first 8 plots will appear only after 9th is rendered (after 15 seconds instead of 8). See example below.
box_plot1 appears only when box_plot2 is rendered. I played a bit with shiny promises, but didn't find solution so far.
MWE:
library(shinydashboard)
library(plotly)
header <- dashboardHeader(
title = ""
)
body <- dashboardBody(
fluidRow(
column(width = 6,
box(width = NULL, solidHeader = TRUE,
plotly::plotlyOutput("box_plot1")
)
),
column(width = 6,
box(width = NULL, solidHeader = TRUE,
plotly::plotlyOutput("box_plot2")
)
)
)
)
ui <- dashboardPage(
header,
dashboardSidebar(disable = TRUE),
body
)
server <- function(input, output, session) {
output$box_plot1 <- plotly::renderPlotly({
p <- plot_ly(ggplot2::diamonds, x = ~cut, y = ~price, color = ~clarity, type = "box") %>%
layout(boxmode = "group")
p
})
output$box_plot2 <- plotly::renderPlotly({
for (i in 1:3) {
print(i)
Sys.sleep(1)
}
plot_ly(ggplot2::diamonds, y = ~price, color = ~cut, type = "box")
})
}
shinyApp(ui = ui, server = server)
A:
You can use renderUI in combination with reactiveValues which keep track of the order of the calculations.
library(shinydashboard)
library(plotly)
header <- dashboardHeader(
title = ""
)
body <- dashboardBody(
fluidRow(
column(width = 6,
uiOutput("plot1")
),
column(width = 6,
uiOutput("plot2")
)
)
)
ui <- dashboardPage(
header,
dashboardSidebar(disable = TRUE),
body
)
server <- function(input, output, session) {
rv <- reactiveValues(val = 0)
output$plot1 <- renderUI({
output$box_plot1 <- plotly::renderPlotly({
for (i in 3:5) {
print(i)
Sys.sleep(1)
}
p <- plot_ly(ggplot2::diamonds, x = ~cut, y = ~price, color = ~clarity, type = "box") %>%
layout(boxmode = "group")
rv$val <- 1
p
})
return(
tagList(
box(width = NULL, solidHeader = TRUE,
plotly::plotlyOutput("box_plot1")
)
)
)
})
output$plot2 <- renderUI({
if(rv$val == 0) {
return(NULL)
}
output$box_plot2 <- plotly::renderPlotly({
for (i in 1:3) {
print(i)
Sys.sleep(1)
}
plot_ly(ggplot2::diamonds, y = ~price, color = ~cut, type = "box")
})
return(
tagList(
box(width = NULL, solidHeader = TRUE,
plotly::plotlyOutput("box_plot2")
)
)
)
})
}
shinyApp(ui = ui, server = server)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Javascript function fails return value
I am a little baffled by this, but I have written a function that counts the number of dimensions in an array. This code executed just fine in my work environment, but now that I am in my personal environment, the function (countDims()) no longer returns a value. It appears to execute all the way up to the return statement. Here is the jsfiddle. Thoughts on why this might be?
And a snippet.
function constantArray(val,...dim){
// Function returns an nd-array of the given constant value. Note that the ellipsis in
// the function definition enables a variable number of arguments. Note that at least one
// dimension value must be given, and all desired dimension extents must be defined as
// integer lengths.
arr_out = [];
// The initial value forms the kernel of the array
for (i = 0; i < dim[dim.length - 1]; i++) {
arr_out.push(val);
}
// Reducing the dimension list on each pass provides a natural stopping point for recursion
dim.pop(dim[dim.length - 1]);
if (dim.length == 0) {
return arr_out;
}
else {
// Note that the ellipsis in the function call allows us to pass the remaining dimensions
// as a list. In this context, the ellipsis is the "spread" operator.
return constantArray(arr_out, ...dim);
}
}
function countDims(arr, dim_cnt){
// Function returns the number of dimensions in an array. Note that we keep the dimension
// count in the function arguments to ease updating during recursive calls.
if (dim_cnt == undefined) {dim_cnt = 0};
if (Array.isArray(arr)) {
dim_cnt++;
countDims(arr[0], dim_cnt);
}
else {
console.log("The dimension count of this array is "+dim_cnt);
console.log("I am in the return space!")
return dim_cnt;
}
}
x = constantArray(0, 4, 5)
console.log(x)
x_dims = countDims(x)
console.log(x_dims)
A:
Did you forgot to return in the first condition of countDims?
if (Array.isArray(arr)) {
dim_cnt++;
return countDims(arr[0], dim_cnt);
function constantArray(val, ...dim) {
// Function returns an nd-array of the given constant value. Note that the ellipsis in
// the function definition enables a variable number of arguments. Note that at least one
// dimension value must be given, and all desired dimension extents must be defined as
// integer lengths.
var arr_out = [];
// The initial value forms the kernel of the array
for (let i = 0; i < dim[dim.length - 1]; i++) {
arr_out.push(val);
}
// Reducing the dimension list on each pass provides a natural stopping point for recursion
dim.pop(dim[dim.length - 1]);
if (dim.length == 0) {
return arr_out;
} else {
// Note that the ellipsis in the function call allows us to pass the remaining dimensions
// as a list. In this context, the ellipsis is the "spread" operator.
return constantArray(arr_out, ...dim);
}
}
function countDims(arr, dim_cnt = 0) {
// Function returns the number of dimensions in an array. Note that we keep the dimension
// count in the function arguments to ease updating during recursive calls.
//if (dim_cnt == undefined) {dim_cnt = 0};
if (Array.isArray(arr)) {
dim_cnt++;
return countDims(arr[0], dim_cnt);
} else {
console.log("The dimension count of this array is " + dim_cnt);
console.log("I am in the return space!")
debugger
return dim_cnt;
}
}
var x = constantArray(0, 4, 5)
console.log(x)
var x_dims = countDims(x)
console.log(x_dims)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Return current web path in PHP
Currently developing a PHP framework and have ran into my first problem. I need to be able to drop the framework into any folder on a server, no matter how many folders deep, and need to find that directory to use as a base URL.
For example, it currently works if I put the framework in the root of the server (http://cms.dev/), but if I were to put it in http://cms.dev/folder/ it does not work.
A:
__FILE__ is a magic constant that returns the entire path of the current script. Combine with dirname and add ".." appropriately. It's more reliable than getcwd, since it cannot change during execution.
You can then strip off the web root, to get the relative path to your script (should map to URL). There are many $_SERVER variables that have this information. I suggest using the file system to determine:
If your script is publicly accessible?
At which depth / URL prefix?
Then combine with your base URL. If your script's path ==
/home/public/foo_1/script.php
... and your $_SERVER['DOCUMENT_ROOT'] ==
/home/public
Then you can rewrite your URL as /foo_1/script.php. You don't need the fully qualified URL, unless you want it. This technique works best if you execute it from a central location, like an autoloader.
A:
There are four existing answers, but they all seem to deal with file paths, and you're asking about a base URL for web requests.
Given any web request, you get a bunch of keys in $_SERVER that may be helpful. For example, in your mock example, you might have the following:
http://cms.dev/folder/ — $_SERVER['REQUEST_URI'] == /folder/
http://cms.dev/folder/index.php — $_SERVER['REQUEST_URI'] == /folder/index.php
http://cms.dev/folder/index.php/some/pathinfo — $_SERVER['REQUEST_URI'] == /folder/index.php/some/pathinfo
http://cms.dev/folder/some/modrewrite — $_SERVER['REQUEST_URI'] == /folder/some/modrewrite
Thinking critically, how would you pull out the base URL for any given subrequest? In certain cases you can look at $_SERVER['REQUEST_URI'] and strip off trailing elements if you know how deep in your hierarchy the request is. (For example, if your script is two folders deep, strip off the last two path elements.) When PATH_INFO or mod_rewrite are in use, things become less clear: as longer and longer URLs are provided, there is no clear indication where the paths end and the dynamic URL begins.
This is why WordPress, MediaWiki, phpBB, phpMyAdmin, and every application I've ever written has the user manually specify a base URL as part of the application configuration.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Delphi: SendMessage don't send to FMX
I successfully send message cross apps. But the code doesn't work in FMX. I can find the FMX form but no message receive at dest.
Sender code:
CDS.dwData:= 0; //Identify message
CDS.cbData:= ByteLength(Str);
CDS.lpData:= PChar(Str);
if DstHandle=0 then
DstHandle := Winapi.Windows.FindWindow(nil, PChar(TargetFormCaption));
if DstHandle<>0 then
begin
Res := SendMessage(DstHandle, WM_COPYDATA, Handle, NativeInt(@CDS));
Result:= True;
end
else
Result:= False;
Result is true but WMGetData is not triggered.
Receiver code:
procedure WMGetData(var Msg : TWMCopyData) ; message WM_COPYDATA;
...
procedure TForm3.WMGetData(var Msg: TWMCopyData);
begin
Caption:= 'Got something !';
end;
A:
Forms in FMX are not able to receive messages in the same way as VCL forms. FMX does not dispatch window messages that FMX does not use itself.
The clean way to approach this is to use AllocateHWnd to create a window that can receive your messages. Even for VCL apps that is the right approach because such a window is not subject to re-creation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SimpleDateFormat cannot parse milliseconds with more than 4 digits
I want to parse a timestamp, like this - "2016-03-16 01:14:21.6739". But when I use the SimpleDateFormat to parse it, I find that it outputs an incorrect parsed value. It will covert 6739 milliseconds to 6 seconds with 739 millseconds left. It converted the date to this format - Wed Mar 16 01:14:27 PDT 2016. Why the seconds part has changed from 21 seconds to 27 seconds(an addition of 6 seconds?). The following is my code snippet:
final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
String parsedate="2016-03-16 01:14:21.6739";
try {
Date outputdate = sf.parse(parsedate);
String newdate = outputdate.toString(); //==output date is: Wed Mar 16 01:14:27 PDT 2016
System.out.println(newdate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
A:
SS in SimpleDateFormat is milliseconds. You have 6739 milliseconds, which means you are adding an extra 6.7 seconds onto your time. Perhaps you can truncate the 6739 to 673 (or if you prefer, round it to 674) so it can be parsed correctly as milliseconds.
A:
It seems that is not possible to use SimpleDateFormat to express times with a finer grain than the millisecond.
What is happening is that as you put 6739, Java understands it as 6739 milliseconds i.e. 6 seconds and 739 milliseconds hence the 6 seconds difference observed.
Check these ones, it is explained quite well:
String-Date conversion with nanoseconds
Java date parsing with microsecond or nanosecond accuracy
A:
tl;dr
LocalDateTime.parse(
"2016-03-16 01:14:21.6739".replace( " " , "T" ) // Comply with ISO 8601 standard format.
)
Milliseconds versus Microseconds
As others noted, java.util.Date has millisecond resolution. That means up to 3 digits of a decimal fraction of second.
You have 4 digits in your input string, one too many. Your input value demands finer resolution such as microseconds or nanoseconds.
java.time
Instead of using the flawed, confusing, and troublesome java.util.Date/.Calendar classes, move on to their replacement: the java.time framework built into Java 8 and later.
The java.time classes have a resolution of nanosecond, up to nine digits of decimal fraction of a second. For example:
2016-03-17T05:19:24.123456789Z
ISO 8601
Your string input is almost in standard ISO 8601 format used by default in java.time when parsing/generating textual representations of date-time values. Replace that space in the middle with a T to comply with ISO 8601.
String input = "2016-03-16 01:14:21.6739".replace( " " , "T" );
Unzoned
A LocalDateTime is an approximation of a date-time, without any time zone context. Not a moment on the timeline.
LocalDateTime ldt = LocalDateTime.parse( input );
UTC
Make that LocalDateTime an actual moment on the timeline by applying the intended time zone. If meant for UTC, make an Instant.
Instant instant = ldt.toInstant( ZoneOffset.UTC );
Zoned
If meant for a particular time zone, specify a ZoneId to get a ZoneDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone( zoneId );
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unexpected string in JSON at position 608 while parsing
I'm trying to host my react website to GitHub, but when I try to use:
npm install --save gh-pages
I get the following error:
Failed to parse json
npm ERR! JSON.parse Unexpected string in JSON at position 608 while parsing '{
npm ERR! JSON.parse "name": "myportfoliosite",
npm ERR! JSON.parse "versio'
The repository is at: https://github.com/InquisitiveDev2016/React-Developer-Portfolio2
Here is the package.json file:
{
"name": "myportfoliosite",
"version": "0.1.0",
"private": true,
"homepage": "https://github.com/InquisitiveDev2016/React-Developer-Portfolio2",
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-mdl": "^1.11.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.0.1"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
}
}
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I am trying to follow the instructions under the GitHub pages folder at:
https://facebook.github.io/create-react-app/docs/deployment
But I am stuck, can someone please check what's wrong with the file?
A:
This package.json was not a valid JSON you can try to fix the JSON structure, using online tools like and validate the JSON
https://jsoneditoronline.org/
https://jsonformatter.org/
below JSON should work for you:
{
"name": "myportfoliosite",
"version": "0.1.0",
"private": true,
"homepage": "https://github.com/InquisitiveDev2016/React-Developer-Portfolio2",
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-mdl": "^1.11.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.0.1"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
merge [shortcut], [shortcuts] and [keyboard-shortcuts] on superuser
On superuser we have
[keyboard-shortcuts] x 34
[shortcuts] x 4
[shortcut] x 2
I was thinking of changing the 6 ones labeled shortcuts and shortcut to keyboard-shortcuts as this would be the least work and only take a minute (retagging 4 questions). But I'm not sure. I think shortcuts is maybe better (are there other than 'keyboard-' shortcuts?).
So I'm asking the community... how should this be retagged?
Edit: Apparently (thanks Shog9) there is a difference in meaning between 'keyboard-shortcut' and 'shortcut' tout-court (the latter being e.g. a shorthand for instance to type into the Firefox address bar). So the only problem that remains now: should we take 'shortcut' or 'shortcuts' for that last meaning? This question doesn't give a decisive answer towards tags being plural or singular.
Another Edit: Ok, I've updated the tags, so now there's only 'keyboard-shortcuts' and 'shortcuts'. But I like Jeff Yates' idea of separating 'keyboard-shortcuts' in 'keyboard' and 'shortcuts'. Can this be done with the moderator tools?
A:
shortcut is not currently used for questions related to keyboard shortcuts.
One question tagged [shortcuts] also refers to a different meaning for that word.
Proceed carefully...
A:
I favor [keyboard-shortcuts], too. It's more descriptive, it contains the other terms (so it will show up in the suggestion box), and it is most frequently used. Seems like a clear winner to me.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Updating multiple selected INofityPropertyChange objects in DataGridView
I'm working with a DataGridView (Windows Forms) with MultiSelect enabled which is placed in a User Control. I'd like to update all selected rows from outside the User Control by calling a public method that implements the following code:
foreach(DataGridViewRow dr in dataGridView.SelectedRows)
{
MyBusiness business = (MyBusiness)dr.DataBoundItem;
business.Rating = 5;
}
Unfortunately, when multiple rows are selected, only one DataGridViewRow is immediately refreshed, namely the one that was last selected. The underlying objects are changed, and the NotifyPropertyChange-event is fired. Moreover, when I change the selection after update, I see all rows updated exactly as I'd like them to be immediately.
Second thing, very strange: When I set a breakpoint in the Setter of the Rating-property where NotifyPropertyChange is fired and wait there a few seconds before continuing code execution, everything works well (all rows are immediately updated). If I don't wait but press F5 very quickly each time the breakpoint is passed, I get the effect described above.
My business object looks like this (significantly shortened of course):
public class MyBusiness : INotifyPropertyChanged
{
private int _rating;
public int Rating
{
get { return _rating; }
set
{
if(_rating != value)
{
_rating = value;
NotifyPropertyChanged("Rating");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Has anybody already noticed this behavior too, or even knows a solution (or a workaround)?
A:
If your DGV is bound to a regular List, it only subscribes to the PropertyChanged event for the currently-selected row. Try using a BindingList instead, or calling BindingSource.ResetItem(n) for each item changed.
MSDN gives an example which uses a BindingList and also (pointlessly) calls ResetItem. Play with their example, and you can see that either removing the call to ResetItem, or replacing the BindingList with a regualr List<> will operate as intended.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Visual Studio Express - Simple build configuration error
I've switched to a new computer but copied all my project files to it. I am getting this error when I try to run:
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppBuild.targets(806,5): error MSB3191: Unable to create directory "C:\Users\MyUser\StarFall\StarFall_build\CMakeFiles\". Access to the path 'C:\Users\MyUser\StarFall\StarFall_build\CMakeFiles\' is denied.
The path has changed, but I don't know where I can change this setting. I realise that this may be specific to what my project settings are, but if you need more details I will post them!
A:
Like Arun mentioned, this kind of an error happens when there is a macro in your project which is pointing to a wrong location. You shouldn't change the microsoft.cppbuild.targets file. Instead, go to your project properties and change the directory paths that are erroneous.
You can see macro expansions when you click on the dropdown arrow beside a macro, click edit and click Macros>>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use fopen() in php?
I am trying to make my code able to log any kind of errors on opening a database. What i am trying to do is , create a .txt file that all the logs will be saved in there in case of error.
What i ve done so far is :
bla bla bla
} catch(PDOException $e) {
//in case of error , we create a log file with the error
//$PDOException_file = 'PDOException_file_' . date('Y_m_d-H-i-s') . '.txt' ;
$PDOException_file = 'PDOException_file' . '.txt' ;
$fh = fopen($PDOException_file, 'w') or die();
fwrite($fh, date('Y_m_d-H-i-s') . ' PDOException Error: ' . $e->getMessage() . "\n\n" );
fclose($fh);
echo 'Error: ' . $e->getMessage();
}
What i expected from the code i wrote would be to create one .txt file "PDOException" file and inside get the logs like this :
2013_05_02-12-40-02 PDOException Error: bla bla bla
2013_05_02-12-43-02 PDOException Error: bla bla bla
2013_05_02-13-45-02 PDOException Error: bla bla bla
That means every time i have an error , open the file , write the error make 2 new lines close the file. Then the next time i get an error , i write to the end of this file the error etc etc.
What happens though is that i rewrite in the beginning of my file on the old data. How can i avoid that?
A:
In your code where you have:
$fh = fopen($PDOException_file, 'w') or die()
You should use:
$fh = fopen($PDOException_file, 'a') or die()
The w open's the file for writing only and places the file pointer at the beginning of the file and truncate the file to zero length (deleting all contents). If the file does not exist, it will attempt to create it. The a will open the file for writing only and place the file pointer at the end of the file. If the file does not exist it will attempt to create it.
You can find more information on fopen() here: http://php.net/manual/en/function.fopen.php
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Use Variables for key in Jinja Render method
I am trying to iterate over a dictionary and then use the dictionary items to render the template using Jinja.
for key,value in dict.values()
out = template.render(key=value)
I am using undefined=DebugUndefined so that i can use multiple template renders without overwriting the placeholders.
The issue i am facing is that Jinja expects the exact string being passed to the render and i am not able to use the dictionary key. Jinja is trying to find the text {{ key }} for replacement.
Is there a a way I can pass in a variable as the key?
A:
You have to build the dictionary and pass it as a kwargs:
out = template.render(**{key: value})
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using Persistent Header with Show/Hide Content
I have a page that I would like to be able to use a persistent header, along with clicking on a div and having it work like an accordion. I am able to work the 2 parts when I use them separately, but the code won't work when I put them together
HTML
<div class="main">
<div>
<section>
<h2 class="actog">Header</h2>
<div class="accon">
<!--Content Here-->
</div>
</section>
<section>
<h2 class="actog">Different Header</h2>
<div class="accon">
<!--Content Here-->
</div>
</section>
<section>
<h2 class="actog">Another Header</h2>
<div class="accon">
<!--Content Here-->
</div>
</section>
</div>
</div>
CSS
.actog {
color:black;
margin:5px 0;
padding:5px;
width:100%;
height:auto;
background-color:green;
/* Transitions */
}
.actog:hover, .active{
cursor:pointer;
text-decoration:underline;
color:#ff385b;
background-color:pink;
}
.accon{padding:5px 0;}
.floatingHeader {
position: fixed;
margin-top: 0;
top:0;
visibility: hidden;
}
And these two snippets of jQuery
jQuery(document).ready(function() {
jQuery(".actog").next(".accon").hide();
jQuery(".actog").click(function(){
$('.active').not(this).toggleClass('active').next('.accon').slideToggle(500);
$(this).toggleClass('active').next().slideToggle(400);
});
});
function UpdateTableHeaders() {
$(".main div section").each(function() {
var el = $(this),
offset = el.offset(),
scrollTop = $(window).scrollTop(),
floatingHeader = $(".floatingHeader", this)
if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
floatingHeader.css({
"visibility": "visible"
});
} else {
floatingHeader.css({
"visibility": "hidden"
});
};
});
}
// DOM Ready
$(function() {
var clonedHeaderRow;
$(".main div section").each(function() {
clonedHeaderRow = $(".actog", this);
clonedHeaderRow
.before(clonedHeaderRow.clone())
.css("width", clonedHeaderRow.width())
.addClass("floatingHeader");
});
$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");
});
Here is A Fiddle
A:
I came up with the final solution
CSS
.actog {
color: black;
margin: 5px 0;
padding: 5px;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
background-color: green;
-webkit-transition: .25s;
-moz-transition: .25s;
-o-transition: .25s;
-ms-transition: .25s;
transition: .25s;
}
.actog:hover,.active,.activeClone {
cursor: pointer;
text-decoration: underline;
color: #ff385b;
background-color: pink;
}
.accon {padding: 5px 0; width: 100%;}
.floatingHeader {
position: fixed;
margin-top: 0;
top: 0;
visibility: hidden;
display: none;
}
HTML
<div>
<section>
<h2 id="1-clone" class="actog">Header</h2>
<div class="accon">
04/01/13<b></b>
04/02/13<b></b>
04/03/13<b></b>
04/04/13<b></b>
04/05/13<b></b>
04/06/13<b></b>
04/07/13<b></b>
04/08/13<b></b>
04/09/13<b></b>
04/10/13<b></b>
04/11/13<b></b>
04/12/13<b></b>
04/13/13<b></b>
04/14/13<b></b>
04/15/13<b></b>
04/16/13<b></b>
04/17/13<b></b>
04/18/13<b></b>
04/19/13<b></b>
04/20/13<b></b>
04/21/13<b></b>
04/22/13<b></b>
</div>
</section>
<section>
<h2id="2-clone" class="actog">Different Header</h2>
<div class="accon">
04/01/13<b></b>
04/02/13<b></b>
04/03/13<b></b>
04/04/13<b></b>
04/05/13<b></b>
04/06/13<b></b>
04/07/13<b></b>
04/08/13<b></b>
04/09/13<b></b>
04/10/13<b></b>
04/11/13<b></b>
04/12/13<b></b>
04/13/13<b></b>
04/14/13<b></b>
04/15/13<b></b>
04/16/13<b></b>
04/17/13<b></b>
04/18/13<b></b>
04/19/13<b></b>
04/20/13<b></b>
04/21/13<b></b>
04/22/13<b></b>
</div>
</section>
<section>
<h2 id="3-clone" class="actog">Another Header</h2>
<div class="accon">
04/01/13<b></b>
04/02/13<b></b>
04/03/13<b></b>
04/04/13<b></b>
04/05/13<b></b>
04/06/13<b></b>
04/07/13<b></b>
04/08/13<b></b>
04/09/13<b></b>
04/10/13<b></b>
04/11/13<b></b>
04/12/13<b></b>
04/13/13<b></b>
04/14/13<b></b>
04/15/13<b></b>
04/16/13<b></b>
04/17/13<b></b>
04/18/13<b></b>
04/19/13<b></b>
04/20/13<b></b>
04/21/13<b></b>
04/22/13<b></b>
</div>
</section>
Jquery
function UpdateTableHeaders() {
$(".main div section").each(function() {//select each section in a div in a container with class main
var el = $(this),
offset = el.offset(),
scrollTop = $(window).scrollTop();
floatingHeader = $(".floatingHeader", this);
var shadow = '#' + floatingHeader.attr('id').replace('-clone','-orig');
if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height()) && ($(shadow).hasClass('active'))) { //if the header has scrolled past visibility and it has the class of active, then target it
floatingHeader.css({
"visibility": "visible", "display":"block" //show header
})
.addClass('activeClone') //add class once has scrolled down
.unbind('click') //remove the action of the first click
.click(function(){
$(shadow).click();
});
} else {
floatingHeader.css({
"visibility": "hidden", "display":"none" //hide header
})
.removeClass('activeClone'); //remove the class once scrolled back up
};
});
}
$(function() {
var clonedHeaderRow;
$(".main div section").each(function() {
clonedHeaderRow = $(".actog", this);
var newId = clonedHeaderRow.attr('id').replace('-clone','-orig');
clonedHeaderRow
.before(clonedHeaderRow.clone().attr('id',newId))
.css("width", clonedHeaderRow.width())
.addClass("floatingHeader"); //add class
});
$(window).scroll(UpdateTableHeaders);
});
jQuery(document).ready(function() {
jQuery(".actog").siblings(".accon").hide();
jQuery(".actog").not('.floatingHeader').click(function() {
$('.active').not(this).toggleClass('active').siblings('.accon').slideToggle(500);
$(this).toggleClass('active').siblings('.accon').slideToggle(400);
});
});
http://codepen.io/burn123/pen/dsbpI
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Display toast when observable returns an error in IONIC 3 ASP.NET WEB API
I am developing an IONIC 3 app that consumes Asp.NET web API services, for the authentication am using Token based auth, so when the user enters valid credentials he gets back a token that will be saved in FireBase db and if he enters wrong credentials he gets a toast that displays a simple error text.
I am getting the response successfully whatever its the Token or the error from the Observable, but I want to show a toast in case of bad credentials.
I am new to Rxjs and reactive programming. So my question is How to chain the code showing the toast to the subscribe method in the code below:
logUser(){
this.loginService.login(this.loginModel.userName,this.loginModel.password,this.loginModel.grant_type)
.subscribe(token => {this.Token= token ,
console.log(this.Token.access_token)},
error => this.errorMessage = <any>error);
//<any>this.toast.create(this.toastOptions).present()
}
A:
I've indented your code in a different way to show you where you should open the toast message for both scenarios (success and error):
logUser(){
this.loginService.login(this.loginModel.userName,this.loginModel.password,this.loginModel.grant_type)
.subscribe(
token => {
this.Token = token;
console.log(this.Token.access_token);
// Here you can show a toast when the user was able to get the token!
// ...
},
error => {
this.errorMessage = (<any>error);
// Here you can show a toast when an error has ocurred!
// ...
});
}
So basically since the subscribe is async, you'd need to put all the code that handles the success scenario inside of the token => { ... } callback, and all the code that handles an error in the error => { ...} callback.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
to find and replace the string in php
I have got a number of values by a foreach loop. Now I want to check each the values with a string.
My string is "http://www.example.com/TantraProjects/Ranjit/nt_plugin"
I have the values like written below:
http://blogsearch.google.com/blogsearch?scoring=d&partner=wordpress&q=link:http://www.example.com/TantraProjects/Ranjit/nt_plugin/
http://blogsearch.google.com/blogsearch_feeds?scoring=d&ie=utf-8&num=10&output=rss&partner=wordpress&q=link:http://www.example.com/TantraProjects/Ranjit/nt_plugin/
link:http://www.example.com/TantraProjects/Ranjit/nt_plugin/ - Google Blog Search
Now I want to change all the values, replacing http://www.example.com/TantraProjects/Ranjit/nt_plugin with MY NEW PATH.
How can I replace the string using php?
A:
str_replace
And please, use google, there are thousands of answers for that question online. :)
Also if you want to embed a links in URLs like that:
http://blogsearch.google.com/blogsearch?scoring=d&partner=wordpress&q=link:http://www.example.com/TantraProjects/Ranjit/nt_plugin/
You need to use urlencode on the URL you pass after &q=.
So basically:
$string = "http://blogsearch.google.com/blogsearch?scoring=d&partner=wordpress&q=MY_NEW_PATH";
$output = str_replace('MY_NEW_PATH', "link:".urlencode('http://www.example.com/TantraProjects/Ranjit/nt_plugin'), $string); //$search , $replace, $subject
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Looping array from input and getting all matches
I'm trying to loop through an array of items and see if any of those match then show them. Well if I type in any character they all show.
(sensitive == false ? RegExp('^'+this.value,'i').test(source[i]) : RegExp('^'+this.value).test(source[i]) )
this is my condition, though if the this.value = a every single item in the array (source[i]) shows up. Is there a way to make this more strict?
EXAMPLE
if array is (using jquery autocomplete example array)
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
element.addEventListener('keypress', function (e) {
var dd = document.getElementById('fake_dropdown');
for (i = 0; i < availableTags.length; i++) {
var li;
if ((sensitive == false ? RegExp('^' + this.value, 'i').test(availableTags[i]) : RegExp('^' + this.value).test(availableTags[i]))) {
li = document.getElementById('auto_id_' + (i + 1));
li.style.display = "block";
} else {
li = document.getElementById('auto_id_' + (i + 1));
li.style.display = "none";
}
var liLoop = dd.getElementsByTagName('li');
for (var j = 0; j < liLoop.length; j++) {
if (liLoop[j].style.display == "block") break;
else dd.style.display = "none";
}
}
}, false);
UPDATED MORE CODE
All these show up. Why is this? Also why is BACKSPACE not considered to be a keypress, for it doesn't reevaluate the condition if I click backspace.
A:
See
el.addEventListener('focus', function (e) {
lastIndex = this;
if (typeof focus == 'function') focus.call(this, this);
}, false);
//use keyup handler since keypress will not be fired for unprintable characters
//don't register the handler inside the focus handler since it can cause multiple event registrations
el.addEventListener('keyup', function (e) {
var dd = document.getElementById('fake_dropdown'),
items = 0;
var top, left, height, width, bottom;
var term = this.value,
//move this out out the for loop
regex = (sensitive == false ? new RegExp('^' + this.value, 'i') : new RegExp('^' + this.value));
for (i = 0; i < source.length; i++) {
var li = document.getElementById('auto_id_' + (i + 1));
if (regex.test(availableTags[i])) {
li.style.display = "block";
items++;
} else {
li.style.display = "none";
}
}
if (items == 0) {
dd.style.display = "none";
} else {
top = el.offsetTop
left = el.offsetLeft;
height = el.offsetHeight;
width = el.offsetWidth;
bottom = top + height;
dd.style.left = left + 'px';
dd.style.top = bottom + 'px';
dd.style.width = width + 'px';
dd.style.display = "block";
}
}, false);
Demo: Fiddle
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I import a .dmp file into Oracle?
I have a .dmp file that I would like to import into Oracle 9i. How do I do that?
A:
Presuming you have a .dmp file created by oracle exp then
imp help=y
will be your friend. It will lead you to
imp file=<file>.dmp show=y
to see the contents of the dump and then something like
imp scott/tiger@example file=<file>.dmp fromuser=<source> touser=<dest>
to import from one user to another. Be prepared for a long haul though if it is a complicated schema as you will need to precreate all referenced schema users, and tablespaces to make the imp work correctly
A:
I am Using Oracle Database Express Edition 11g Release 2.
Follow the Steps:
Open run SQl Command Line
Step 1: Login as system user
SQL> connect system/tiger
Step 2 : SQL> CREATE USER UserName IDENTIFIED BY Password;
Step 3 : SQL> grant dba to UserName ;
Step 4 : SQL> GRANT UNLIMITED TABLESPACE TO UserName;
Step 5:
SQL> CREATE BIGFILE TABLESPACE TSD_UserName
DATAFILE 'tbs_perm_03.dat'
SIZE 8G
AUTOEXTEND ON;
Open Command Prompt in Windows or Terminal in Ubuntu. Then Type:
Note : if you Use Ubuntu then replace " \" to " /" in path.
Step 6: C:\> imp UserName/password@localhost file=D:\abc\xyz.dmp log=D:\abc\abc_1.log full=y;
Done....
I hope you Find Right solution here.
Thanks.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Gulp Watch JS loop infinito
Sou novo estudante de Gulp, e eu fiz esse watch para se os meus arquivos javascripts sofrerem alteração, ele executar o build-js. Mas quando eu executo o Gulp, ele compila tudo certo mas ele fica executando o build-js num loop infinito. O que fiz de errado?
Obrigado!
gulp.task('build-js', function (cb) {
pump([
gulp.src('lib/*.js'),
uglify(),
gulp.dest('dist')
],
cb
);
});
gulp.task('watch-js', function () {
gulp.watch('lib/*.js', ['build-js']);
})
gulp.task('default', ['build-js', 'watch-js']);
A:
O problema pode ser por estar aplicando o watch em todos os js, onde dispara se qualquer um deles alterar. Tente aplicar dessa forma:
gulp.watch(['lib/*.js', '!lib/bundle.js'], ['build-js']);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Value error when plotting list in list with matplotlib
I'm trying to plot lists in list where x axis is one list and y is a number of lists that are plotted as different lines.
My code can plot lists in list but only as long as the lists have same dimension. For example if I were to plot following it would work
x = np.array(["00:00:02.56","00:00:05.12","00:00:07.68"])
y = np.array([[1171.1,878.1,954.6],[806.7,870.4,1171.1],[954.6,870.4,954.6]])
But if y has one more list ie 4 like below
y = np.array([[1171.1,878.1,954.6],[806.7,870.4,1171.1],[954.6,870.4,954.6],[959.6,980.4,999.6]])
Then I will bet a Value error "ValueError: x and y must have same first dimension"
Error looks like this:
Traceback (most recent call last):
File "./list_in_list.py", line 137, in <module>
if __name__ == "__main__": main()
File "./list_in_list.py", line 26, in main
multiplot()
File "./list_in_list.py", line 131, in multiplot
plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i)
File "/usr/lib/python3/dist-packages/matplotlib/pyplot.py", line 3154, in plot
ret = ax.plot(*args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/__init__.py", line 1814, in inner
return func(ax, *args, **kwargs)
File "/usr/lib/python3/dist-packages/matplotlib/axes/_axes.py", line 1424, in plot
for line in self._get_lines(*args, **kwargs):
File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 386, in _grab_next_args
for seg in self._plot_args(remaining, kwargs):
File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 364, in _plot_args
x, y = self._xy_from_xy(x, y)
File "/usr/lib/python3/dist-packages/matplotlib/axes/_base.py", line 223, in _xy_from_xy
raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension
My code looks like this
#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
import datetime
x = np.array(["00:00:02.56","00:00:05.12","00:00:07.68"])
y = np.array([[1171.1,878.1,954.6],[806.7,870.4,1171.1],[954.6,870.4,954.6],[959.6,980.4,999.6]])
x = [datetime.datetime.strptime(elem, '%H:%M:%S.%f') for elem in x]
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("A test graph")
for i in range(len(y)):
plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i)
plt.legend()
plt.show()
How do I plot y in one plot regardless of how many lists y contains.
A:
The plotting loop does not make much sense to me.
Instead try to simply plot each row of y like so
for i, pt in enumerate(y):
plt.plot(x,pt,label = 'id %s'%i)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using table or div
What is the best practice when building our web page div or table?
Someone says the div is recommended, but I found it is not easy to control the size and alignment with div.
What is your opinion?
A:
It depends entirely on what you're wanting to display:
<DIV> and <SPAN> is for page layout
<Table> is for displaying tabular data (such as data points etc)
The days of using <table> for whole page layouts is gone - and you should be discouraged for using them for this reason.
HTML tags are meant to be semantic. This means describing the data it contains - not how to display it (this is for stylesheets to handle)
A:
There's nothing fundamentally wrong with TABLE - it's just that it was historically overused for the wrong thing. In general, try to use TABLE for true tables of data, use DIV and SPAN for logical block or inline containers of content.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
XSLT:Generic way to move child node to parent node in XML
I have this following xml structure:
<root>
<p1>
<a>1</a>
<b>2</b>
<_timestamp>20160928201109</_timestamp>
<c>
<_c_timestamp>20160928201056</_c_timestamp>Tmp</c>
</p1>
<p2>
<a>1</a>
<b>2</b>
<_timestamp>20160928201109</_timestamp>
<d>
<_d_timestamp>20160928201056</_d_timestamp>Tmp1</d>
</p2>
</root>
and want to convert to this structure using XSLT:
<root>
<p1>
<a>1</a>
<b>2</b>
<_timestamp>20160928201109</_timestamp>
<_c_timestamp>20160928201056</_c_timestamp>
<c>Tmp</c>
</p1>
<p2>
<a>1</a>
<b>2</b>
<_timestamp>20160928201109</_timestamp>
<_d_timestamp>20160928201056</_d_timestamp>
<d>Tmp1</d>
</p2>
</root>
i.e., any occurrence of tag with structure <_anyName_timestamp> should be moved to parent node.
Any pointers to the XSLT structure would be helpful.
A:
any occurrence of tag with structure <_anyName_timestamp> should be
moved to parent node.
Moving is the easy part here. The difficult part is to identify the elements to move. Try:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:apply-templates select="*[starts-with(name(), '_') and contains(substring(name(), 2), '_timestamp')]"/>
<xsl:copy>
<xsl:apply-templates select="node()[not(starts-with(name(), '_') and contains(substring(name(), 2), '_timestamp'))]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Or perhaps a bit more elegant:
<xsl:template match="*">
<xsl:variable name="ts" select="*[starts-with(name(), '_') and contains(substring(name(), 2), '_timestamp')]" />
<xsl:apply-templates select="$ts"/>
<xsl:copy>
<xsl:apply-templates select="node()[count(.|$ts) > count($ts)]"/>
</xsl:copy>
</xsl:template>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python: concatenate arrays stored in a dictionary
I have a large dictionary which stores following arrays:
Store = dict()
Store['A'] = A #size 500x30
Store['B'] = B #size 500x20
I am having only A and B for illustration. In my current real life situation I have about 500 keys and values in the dictionary I am using.
I want to concatenate the arrays in an elegant way to get an array C.
For illustration this is what I aim to achieve:
A = np.random.normal( 0, 1, ( 500, 20 ) )
B = np.random.normal( 0, 1, ( 500, 30 ) )
C = np.concatenate((A,B),1)
A:
np.concatenate([Store[x] for x in Store], 1)
np.concatenate([Store[x] for x in sorted(Store)], 1) if order matters.
A:
If the order does not matter, pass the values of your dictionary to numpy.concatenate:
>>> store = {'A':np.array([1,2,3]), 'B':np.array([3,4,5])}
>>> np.concatenate(store.values(),1)
array([1, 2, 3, 3, 4, 5])
If the order does matter, you can use
np.concatenate([v for k,v in sorted(store.items(), key=...)], 1)
Pass in any key function you like, or just leave the key argument out if you want to sort lexicographically. Sadly, concatenate does not seem to take a generator object.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTTP 502, different browsers have different redirect location in response header
Our applications are sitting on two servers which has a load balancer in front of it. The load balancer is over SSL (https) while the server are not. We do SSL offloading. When the user clicks on the load balancer URL, the first HTTP GET response is 502 with a location tag in the response header. This location consists of the URL of the actual page.
The problem is, we are somehow getting the different (possibly wrong?) path in the Location header in Chrome and Firefox (both latest version of today). In IE it is working fine.
Example:
LB URL: https://mywebapp.com/dashboard
Chrome Firefox Response header location tag:
http://mywebapp.com/dashboardonserverxyz
IE Response header location tag:
/dashboardonserverxyz
The question: Why is IE giving relative path whereas chrome, firefox gives absolute redirect path in location. Also, which one is the actual one sent by the application server? Since the URL given by Chrome, firefox has http, the users are not able to access the application. I tried clearing cache, resetting browser, uninstalling and reinstalling. Someone the location value is still coming as absolute.
Any help will be much appreciated. FYI: Application is TIBCO Spotfire, Load balancer is F5.
A:
Putting the solution in case anyone else faces the same issue.
So this got nothing to do with the browser. It was the cache at the load balancer level (F5). Once we disabled the load balancer caching, the http redirect access came with a relative path.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Short symmetric formula for 'at most one of P, Q, and R is true'?
Just now I discovered that
$$
\text{at most one of } P, Q, R \text{ is true}
$$
is equivalent to
$$
((P \equiv Q) \land (Q \not\equiv R)) \:\:\equiv\:\: R
$$
I like this, but I don't like the loss of symmetry. Is there perhaps another fairly short, but more symmetric, equivalent formula?
(As inspiration, note that
$$
\text{exactly one of } P,Q,R \text{ is true}
$$
is equivalent to
$$
(P \equiv Q \equiv R) \;\land\; \lnot(P \land Q \land R)
$$
which is nicely symmetric, since both $\;\equiv\;$ and $\;\land\;$ are symmetric and associative.)
A:
$$
\lnot[(P\land Q)\lor(Q\land R)\lor(R\land P)]
$$
$$
(\lnot P\lor\lnot Q)\land(\lnot Q\lor\lnot R)\land(\lnot R\lor\lnot P)
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I get input without declaring a variable type or declare multiple type for same variable in c++?
I want to get a input that can be integer or string and want to pass it to overloaded function, so that candidate function can be automatically detected and output generated. Is there a way to do that?
A:
There's no way to do it automatically, but you can certainly do it programmatically.
Read in a string.
Check if the string is a valid number.
If it is a number, get its value (via atoi() or similar) and pass it to the integer version of your function.
Otherwise, pass the string to the string version of your function.
There is no way to get this "for free" since the compiler can't know at compile time whether the input is going to be a number or not.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
issue while posting data using spring and AngularJS :: The request sent by the client was syntactically incorrect
I am getting below error while POSTING to a rest service. Please help me understanding what I am missing here?
The request sent by the client was syntactically incorrect.
My Controller Code is:
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody String addUser(@RequestBody UserDomain userDomain, BindingResult result) {
System.out.println("UserDomain :: " + userDomain);
userService.addUser(userDomain);
return "redirect:/";
}
Services.js
services.factory('UserFactory', ['$resource', function ($resource) {
return {
usercreation: $resource('/ngdemo/web/users', {}, {
query: {method: 'GET', isArray: true },
create: {method: 'POST'}
})
};
}]);
Controller.js
app.controller('DemoCtrl', ['$scope', 'UserFactory', '$facebook', 'NotificationFactory', '$location', function ($scope, UserFactory, $facebook, NotificationFactory, $location) {
$scope.UserDomain = { firstname: null };
$scope.isLoggedIn = false;
$scope.login = function () {
$facebook.login().then(function () {
refresh();
});
}
function refresh() {
$facebook.api("/me").then(
function (response, Userfactory) {
$scope.welcomeMsg = "Welcome " + response.name;
$scope.result = response;
console.log("console ctrl demo12 - " + $scope.welcomeMsg);
alert($scope.result);
$scope.isLoggedIn = true;
//$scope.UserDomain.id = $scope.result.id;
$scope.UserDomain.socialId = $scope.result.id;
$scope.UserDomain.gender = $scope.result.gender;
$scope.UserDomain.firstname = $scope.result.first_name;
$scope.UserDomain.hometown = $scope.result.hometown.name;
$scope.UserDomain.currentLocation = $scope.result.location.name;
$scope.UserDomain.lastname = $scope.result.last_name;
$scope.UserDomain.email = $scope.result.email;
$scope.UserDomain.username = $scope.result.username;
$scope.UserDomain.link = $scope.result.link;
$scope.UserDomain.relationshipStatus = $scope.result.relationship_status;
console.log("$scope.result - " + $scope.result.relationship_status);
console.log("$scope.UserDomain - " + $scope.UserDomain.relationshipStatus);
//making call to add user
UserFactory.usercreation.create($scope.UserDomain);
},
function (err) {
$scope.welcomeMsg = "Please log in";
});
}
}]);
JSON formed and checked in mozilla console::
{"firstname":"Naveuuuin","socialId":"7048797897728972","gender":"male","hometown":"Udaipur, Rajasthan","currentLocation":"Bangalore, India","lastname":"Vyas","email":"[email protected]","username":"vyas","link":"https://www.facebook.com/vyas","relationshipStatus":"Single"}
UserDomain Class is:
package ngdemo.domain;
import javax.persistence.*;
@Entity
@Table(name = "P_USER")
public class UserDomain {
@Id
@Column(name = "USER_ID")
@GeneratedValue
private Integer id;
@Column(name = "SOCIAL_ID")
private String socialId;
@Column(name = "FIRSTNAME")
private String firstname;
@Column(name = "LASTNAME")
private String lastname;
@Column(name = "EMAIL")
private String email;
/* @Column(name = "PHONENUMBER")
private String telephone;*/
@Column(name = "HOMETOWN")
private String homeTown;
@Column(name = "GENDER")
private String gender;
@Column(name = "LINK")
private String link;
@Column(name = "CURRENT_LOCATION")
private String currentLocation;
@Column(name = "RELATIONSHIP_STATUS")
private String relationshipStatus;
@Column(name = "USERNAME")
private String username;
public String getSocialId() {
return socialId;
}
public void setSocialId(String socialId) {
this.socialId = socialId;
}
public String getCurrentLocation() {
return currentLocation;
}
public void setCurrentLocation(String currentLocation) {
this.currentLocation = currentLocation;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHomeTown() {
return homeTown;
}
public void setHomeTown(String homeTown) {
this.homeTown = homeTown;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getRelationshipStatus() {
return relationshipStatus;
}
public void setRelationshipStatus(String relationshipStatus) {
this.relationshipStatus = relationshipStatus;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
/* public String getTelephone() {
return telephone;
}*/
public void setEmail(String email) {
this.email = email;
}
/* public void setTelephone(String telephone) {
this.telephone = telephone;
}*/
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "UserDomain{" +
"currentLocation='" + currentLocation + '\'' +
", id=" + id +
", socialId=" + socialId +
", firstname='" + firstname + '\'' +
", lastname='" + lastname + '\'' +
", email='" + email + '\'' +
", homeTown='" + homeTown + '\'' +
", gender='" + gender + '\'' +
", link='" + link + '\'' +
", relationshipStatus='" + relationshipStatus + '\'' +
", username='" + username + '\'' +
'}';
}
}
A:
Thanks all anyways!
Everything was right, only problem was with casing in my JSON returned and domain model.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My name is akin to my size
My name is akin to my size
Each can be complex or concise
I remain within gaze
In front of your face
Observable under the right eyes
My true prefix is one of a kind
My infixes are aplenty you'll find
Even if one knew
What they attempt to construe
It would take them a very long time
Considering freedom and span
I am not a favourable fan
Yet I still do support you
Will continue to guide you
Hold heavy loads as much as I can
In multiple forms I exist
In strenuous times I assist
With so much potential
I am quintessential
Attempt to unveil me, I insist!
Hint:
I am organic in nature.
Hint:
I am a specific substance.
Hint:
I am named after a god.
Hint:
I am a macromolecule.
Hint:
I lie beneath the skin.
A:
I wonder if you might be a:
MEDIUM
My name is akin to my size
Medium is a word that can describe the magnitude or size of some property (e.g. a steak can be cooked 'medium rare', a T-shirt can be 'medium size'...).
Each can be complex or concise
A 'complex medium' is a form of growth medium which is used in a laboratory for culturing bacteria. With regards to 'concise', this might be inferred as a synonym for 'compact' - a compact disk (CD) is a form of storage medium...
I remain within gaze
In front of your face
Observable under the right eyes
In the case of a growth medium, bacteria will culture within it 'right before your eyes', but can only be seen (or observed) using the right eyes, i.e. a microscope.
In multiple forms I exist
In strenuous times I assist
There are other meanings to the word 'medium', one of which is a person who acts as a conduit for the voices of the dead, or a way to connect to 'the other side'. In such 'strenuous times' as shortly after the death of a loved one, somebody may attempt to communicate with their dearly departed through the use of such a medium.
With so much potential
I am quintessential
Attempt to unveil me, I insist!
These lines simply refer to the word 'medium' having multiple meanings, although the use of 'unveil' here further conjures up the image of the heavily curtained (veiled) and perfumed room usually used in the work of a talking-to-the-dead medium...
A:
I think the answer might be
Microbe (or even microorganism)
My name is akin to my size
The name contains "micro" which indicates its size.
Each can be complex or concise
These organisms can vary vastly in complexity depending on the size of the genome.
I remain within gaze
In front of your face
Observable under the right eyes
Microbes are present everywhere but can often only be viewed using a microscope
Considering freedom and span
I am not a favourable fan
Bacteria and viruses are often seen in a bad light.
Yet I still do support you
Will continue to guide you
Hold heavy loads as much as I can
Microorganisms often help with bodily function and to protect the human body.
In multiple forms I exist
In strenuous times I assist
There are many, many forms of microorganism which provide a vast array of functions.
With so much potential
I am quintessential
A:
I think you are:
Eyeglasses
Verse 1:
My name is akin to my size
Each can be complex or concise
I remain within gaze
In front of your face
Observable under the right eyes
Explanation:
"Eyeglasses" are akin to their size in that they contain the word "eye" and are the right size for your eyes. Other kinds of "glasses" (eg drinking glasses) could be any size. Prescriptions vary, meaning the lens can be "complex" or "simple" (concise). They are literally right in front of your gaze, but only under the "right" eyes (of those who require them).
Verse 2:
In multiple forms I exist
In strenuous times I assist
With so much potential
I am quintessential
Attempt to unveil me, I insist!
Explanation:
Glasses are available in many forms (spectacles, monacles, pince-nez, contact lenses etc). They assist with eye strain and are essential to those who need them. "Unveil" means to allow something to be viewed, and eyeglasses help you to see things which otherwise you could not.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Scroll To End of ListView After Data Added - WPF
I tried adding the following in a button click handler:
ListView listView = MyListView;
int lastItemIndex = listView.Items.Count - 1;
listView.ScrollIntoView(listView.Items[lastItemIndex]);
listView.UpdateLayout();
The button click is also associated with a command handler that adds an item to the ObservableCollection associated with the ListView.
The problem is that the button click handler is called before my command handler so it is too early. In the button click handler, the ListView does not yet see the updated ObservableCollection with the added item. What event or better yet, what can I do without changing the code behind to get the ListView to scroll to the end after my item is added to the ObservableCollection? I have looked but nothing yet in stackoverflow for answers. Thanks!
A:
If you ItemSource is ObservableCollection, you can hook to CollectionChanged event in your Window/UserControl constructor and scroll last item into view whenever item gets added in a collection.
Assuming your underlying class is TesClass, this is how you will do it:
((INotifyCollectionChanged)listView.ItemsSource).CollectionChanged +=
(s, e) =>
{
if (e.Action ==
System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
listView.ScrollIntoView(listView.Items[listView.Items.Count - 1]);
}
};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove Alpha numeric from string in MS Access or SQL
I have a column with street addresses in MS Access. I need to remove the "st", "nd", "rd", and "th" from the e.g., 21st, 32nd, 33rd, 44th... and keep the numbers...
Any ideas how can I do this?
Thanks!
A:
The Val() function could be useful here. It will read digits from a string until it encounters a character which it doesn't recognize as part of a number. See the help topic for more details.
? Val("21st")
21
? Val("32nd")
32
? Val("33rd")
33
? Val("44th")
44
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to position elements in a div such that they move where the div moves
I am trying to build a simple div based popup which can be used to display messages and other stuff. I am using jqueryui position function to position the div in the appropriate place in the page.
The issue is that the while the div is positioned correctly, the elements inside it are not. That is the div is at the center of the screen, whereas the select elements within the div are at the bottom of the page.
What is the best way to make the div behave like a box such that the elements inside it also move where the div moves?
-- Edit - Adding sample markup below --
<div class="divpopupsmall" id="ctl00_cp1_JobCategoryCitySelect" style="position: relative; top: 93.2px; left: 278.5px;">
<div>
<select class="popupboxelement" id="ctl00_cp1_ddlJobCategory" name="ctl00$cp1$ddlJobCategory">
<option value="0">Driver</option>
<option value="1">Maid</option>
<option value="2">Cook</option>
<option value="3">Nanny</option>
<option value="4">Gardener</option>
<option value="5">Guard</option>
<option value="6">Laborer</option>
<option value="7">Garment Worker</option>
<option value="8">Office Helper</option>
<option value="9">Delivery Helper</option>
<option value="10">Receptionist</option>
<option value="11">Other</option>
<option value="12">Maid cum Cook</option>
<option value="13">Data Entry</option>
<option value="14">Cashier</option>
<option value="15">Nurse-maid</option>
<option value="16">IT Pro</option>
<option value="17">Machinist</option>
<option value="18">Sales Rep</option>
<option value="19">BPO Call Center</option>
<option value="20">Management</option>
<option value="21">Teacher</option>
<option value="22">Finance</option>
<option value="23">Engineer</option>
</select>
</div>
</div>
CSS :
.divpopupsmall{border: 7px solid rgba(150,150,150,0.2); width:400px; height:200px;z-index:700;background-color:#fff;-moz-box-shadow:0px 0px 10px #aaaaaa;-webkit-box-shadow:0px 0px 10px #aaaaaa;
box-shadow:0px 0px 10px #aaaaaa;-moz-border-radius:2px;-webkit-border-radius:2px;border-radius:2px;}
.popupboxelement{position:absolute;}
This is the markup from the actual HTML source taken via Firebug. The style attribute for the .divpopupsmall is added by the jqueryui.position function.
A:
The issue was that there is an intermediate div which was the container to the .popupboxelement and the positioning for this intermediate div was not set (i.e. it was the default value which is 'static') (see markup in question)
I changed the positioning of the intermediate div and it works as expected.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proving an Inequality (terms won't cancel out)
Problem: If $x$ and $y$ are real numbers such that $y \geq 0$ and $y(y+1) \leq (x+1)^2$, prove that $y(y-1) \leq x^2$.
This is what I tried:
\begin{align}
y(y+1) \leq (x+1)^2 &\implies y^2 + y \leq x^2 + 2x + 1 \\
&\implies x^2 \geq y^2 + y - 2x - 1 \\
&\implies x^2 \geq y^2 - y - 2x - 1 \tag{because $y \geq 0$}\\
&\implies x^2 \geq y(y-1) -2x - 1
\end{align}
I think I'm approaching this wrong, because if I start with the inequality $y(y+1) \leq (x+1)^2$, then the $2x + 1$ that results from the expansion of the RHS will never cancel out.
So, I tried this instead:
\begin{align}
y(y+1) \leq (x+1)^2 &\implies y^2 + y \leq x^2 + 2x + 1 \\
&\implies x^2 \geq y^2 + y - 2x - 1 \\
&\implies x^2 \geq y^2 - y - 2x - 1 \tag{same as before}
\end{align}
Then, I supposed that $y(y-1) \leq x^2$ is true. Consequently, because $y^2 - y - 2x - 1 \leq x^2$ (the last line), it is sufficient to show that $y(y-1) \leq y^2 - y - 2x - 1$. Again, this doesn't work because $-2x - 1$ doesn't cancel out.
Now I'm very much stuck and don't know how to proceed. If anyone can give me a hint, it'll be very much appreciated. Thanks!
A:
Consider two cases: $2x+1 \leq 2y$, and $2x+1 > 2y$. Note that we can assume $y > 1$ since if $y < 1$ the inequality is true trivially.
Specifically, if $2x+1 \leq 2y \to y(y-1) = y(y+1) - 2y \leq (x+1)^2 - 2y = x^2 + (2x+1-2y) \leq x^2 + 0 = x^2$, and if $2x+1 > 2y \to x > \dfrac{2y-1}{2} \to x^2 > \dfrac{(2y-1)^2}{4} = \dfrac{4y^2-4y+1}{4} = y(y-1) + \dfrac{1}{4} > y(y-1)$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Different syntax for nodes with pos=x on a path with (A) -- (B) and (A) to (B)
I wonder why we need a different syntax for specifying nodes (and coordinates) on a path when using the simple -- and the .. controls … system or the to operation.
Here’s an example to illustrate the problem:
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\tikzset{every node/.style={fill=white,inner sep=2pt}}
\begin{document}
\begin{tikzpicture}
\draw [thick] (0,0) -- (5,2)
node [pos=0.2] {A}
node [midway] {B};
\end{tikzpicture}
\begin{tikzpicture}
\draw [thick] (0,0) .. controls +(1,2) and +(-2,-1) .. (5,2)
node [pos=0.2] {A}
node [midway] {B};
\end{tikzpicture}
\begin{tikzpicture}% with wrong result
\draw[line width=1pt](0,0) to[out=40, in=160] (5,2)
node [pos=0.2] {A}
node [midway] {B};
\end{tikzpicture}
\begin{tikzpicture}
\draw[line width=1pt](0,0) to[out=40, in=160]
node [pos=0.2] {A}
node [midway] {B} (5,2);
\end{tikzpicture}
\end{document}
When using -- or controls it is possible to position the node after the second coordinate.
But with to[in=x, out=y] this won’t work
all nodes go to (0,0) (not the first coordinate it’s always (0,0)) an we must gove the nodes before the second coordinate right after the to operation
I guess this has to do with the way to works but I wonder why …?
A:
The to path mechanism is extremely powerful. Essentially, using a to path one can put anything on the path at the current stage in its construction. When constructing a path segment, the to path machine needs to know the starting coordinate, the target, and any nodes to be placed on the path. The latter is because the to path should have complete control, including deciding how to interpret the various ways of positioning a node on a path segment.
TikZ's path constructor works like a parser. So it eats the input line, spewing out PGF commands as it goes along. A to path constructor is invoked when the target coordinate is reached (but before it is processed). Therefore any nodes that are to be involved in the to path construction have to be read before the target is specified. It may be possible to specify nodes after the target, but whether or not this works will depend vastly on what the to path actually does. In some simple cases, it simply inserts a more normal segment into the current path specification, in which case putting the nodes afterwards ought to work. But if it does something more complicated then it will not.
With more simply path specifications, such as --, -|, or .. controls .., then TikZ knows how the path will look so when handling nodes it can be a little more flexible as to when they are specified: there's no potential for surprises.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to show image from api call in Angular?
HI I have a api call and want to show the image from the property: welcomePopupImage: string;
A:
Your file path is incorrect. You have ./Resource/ but above you have /resources/ . The s is missing in your img src.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Where is the race condition in this code snippet? (from C# 5.0 in a Nutshell)
This is from Joseph Albahari's excellent C# 5.0 in a Nutshell book
In one of his chapters, he mentions a race-condition in this code block ..my guess is it's meant to be pretty self-evident, as he didn't bother to specify where it was but running the code multiple times I was unable to produce the said-race condition
_button.Click += (sender, args) =>
{
_button.IsEnabled = false;
Task.Run (() => Go());
};
void Go()
{
for (int i = 1; i < 5; i++)
{
int result = GetPrimesCount (i * 1000000, 1000000);
Dispatcher.BeginInvoke (new Action (() =>
_results.Text += result + " primes between " + (i*1000000) + " and " +
((i+1)*1000000-1) + Environment.NewLine));
}
Dispatcher.BeginInvoke (new Action (() => _button.IsEnabled = true));
}
A:
I don't agree with @Serge's answer. You don't even need multiple threads to see the problem. Try to run your code in its original form and notice the output. For me it's the following and is sometimes random (I fixed the first value):
1000000 primes between 5000000 and 5999999
1000000 primes between 5000000 and 5999999
1000000 primes between 5000000 and 5999999
1000000 primes between 5000000 and 5999999
Notice the last 2 values. They're all the same, but they should depend on i. The problem is not that the operation is not atomic, because the GUI thread will execute the actions sequentially anyway.
The reason for this occurring is that the lambda function passed to BeginInvoke takes the value of i at the moment of execution, not at the moment of initialization, so they will all see the last value of i by the time they get executed. The solution is to explicitly pass i as a parameter to the lambda like so:
for (int i = 1; i < 5; i++)
{
int result = 1000000;
Dispatcher.BeginInvoke(new Action<int>(j =>
results.Text += result + " primes between " + (j * 1000000) + " and " +
((j + 1) * 1000000 - 1) + Environment.NewLine), i);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What component of the payload appears on the cross member?
I have a set of DIY steps; I've modelled it as the steps themselves "s", a short vertical support "a", a long vertical support "b" and a cross-member "c". Here's a picture:
Just to be sure I modelled it correctly, here is also a photo of the actual structure (it was built separately from the tree fort, please assume it's not connected to it).
I know that if you have a step-ladder in the shape of an 'A' then the cross piece of the 'A' shape carries a part of the load as the sides try to splay apart. But what of this case, where the supports A and B are vertical? If someone is standing on the steps, what component of their weight would find itself on the cross piece 'C'? How would you calculate it from the angles and lengths?
A:
TL;DR: We don't have enough information to say, but almost certainly less than 50% of the load placed on the ladder.
A simple model:
We can model the setup as a triangle:
Each length (beam) is made of wood and I'll assume they have a Young's modulus of $E=15$ GPa (typical of wood) and cross-sectional area of around $A_0=0.001$ m$^2$, which looks the right order of magnitude.
I'll also assume that the beams are connected together in a way that the angles can all be approximated as being fixed by harmonic potentials with a spring constant $k_\alpha$.
The initial (equilibrium) dimensions are $l_1^0=1.5$ m and $l_2^0=3.0$ and $\alpha_2^0=90^\circ$. And a weight $W$ is suspended from a length $rl_3$ along the ladder.
The potential energy of this system is then:
$$ U=Wrl_3\cos\alpha_1+\frac{EA_0}{2}\sum_i\frac{1}{l_i^0}(l_i-l_i^0)^2+\frac{k_\alpha}{2}\sum_i(\alpha_i-\alpha_i^0)^2 $$
The stable configuration is found by minimising $U$ with respect to the lengths $l_1,l_2,l_3$ (note that the three angles are uniquely determined by these lengths). And the resultant force experienced by the cross beam, expressed as a fraction of the load $W$, is
$$ f=\frac{1}{W}\frac{EA_0|l_1-l_1^0|}{l_1^0} $$
The results:
I numerically solved this equation to find the dependence of $f$ on $k_\alpha$ (how stiff the angle connections are) half-way up the ladder ($r=0.5$) and at the very top ($r=1.0$):
It's interesting to see that a maximum peak is obtained. Here's why: when the stiffness $k_\alpha$ is very small, there are no moments acting and therefore no weight is transferred to the cross beam. As you increase the angle stiffness, more weight is transferred to the cross beam. However, if the angle stiffness is extremely large, then the angle connections absorb more and more of the strain and therefore the force experienced by the cross beam decreases.
The result, according to this model, is that less than 50% of the load is transferred to the cross beam, and quite plausibly <1%, depending on the angle stiffness.
Caveats:
The stiffness of the individual angles will be different to each other in which case it may be possible to distribute more than 50% of the load to the cross beam (e.g. if $\alpha_3$ is very stiff but $\alpha_1$ and $\alpha_2$ are not). But this seems unlikely.
Also, some of the load will be absorbed by the wood bending but I've neglected this from my model. It wouldn't be difficult to modify the equations to account for this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IBM Watson Conversation - Python: Make chat bot jump to some intent & get back to previous intent
I am working on a chat-box. I am using IBM Watson Conversation to make a conversation bot. My query is:
Suppose the user is talking to the bot in some specific node, and suddenly the user asks a random question, like "what is the weather?", my bot should be able to connect to few Internet websites, search the content and come with a relevant reply, and after that as the user inputs to get back to the previous topic, the bot should be able to resume from where it left.
Summary: How to code in Python to make the bot jump to some intent and
then get back to previous intent. Thanks!
A:
Search for a "request response". This is a way to redirect the conversation / dialog flow to your app, and then forward it back to watson.
Hope it helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Creating a user configurable UI in ios
I'm writing an app in which there will be user defined "categories" which will consist of a label and each category will have a user defined list of "items" which will be UIButtons. I want a user to be able to layout the user interface to their choosing. What's the best way to implement this? Any example code out there?
Edit: Just to make myself clear, I have groups of buttons with a group "heading". I'd like users to be able to move these buttons around inside a group and also to arrange the groups as a whole. It's okay if they have to enter some sort of "edit mode" to move things around.
A:
Probably the easiest way is to use editable UITableViews with UITableViewStyleGrouped style (just like Settings.app). Then you can add, remove and arrange items inside groups. You can show it as "edit mode" view.
Here are some useful posts about it:
iOS 5: Drag and Drop Between UITableViews
Tutorial on How to drag and drop item from UITableView to UITableView
iPhone UITableView Tutorial: Grouped Table
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cannot insert duplicate key. Composite Primary key. ASP.NET Entity Framework
I'm trying to create application using Entity Framework.
There's what I want to do (every entity has Id as well):
I want to use composite primary key in this case (PatientId + DiagnosisId).
There's a collection of Diagnoses in Patient model class:
public ICollection<Diagnosis> Diagnoses { get; set; }
public class Diagnosis
{
[Required]
[MaxLength(200)]
public String Type { get; set; }
public String Complications { get; set; }
public String Details { get; set; }
public Int32 DiagnosisId { get; set; }
public Patient Patient { get; set; }
public Int32 PatientId { get; set; }
}
Also in the database context I defined
public DbSet<Diagnosis> Diagnoses { get; set; }
and
modelBuilder.Entity<Diagnosis>().HasKey(x => new { x.DiagnosisId, x.PatientId });
in OnModelCreating method to create the composite primary key.
In an ASP.NET MVC CRUD controller I create Diagnosis and every time DiagnosisId is the same = 0. And I can't paste new data to database because it's like duplicate. That's my create post method on Pastebin if it could help
A:
The parent key goes first:
modelBuilder.Entity<Diagnosis>().HasKey(x => new { x.PatientId, x.DiagnosisId });
Because you want all the Diagnoses for a particular Patent to be stored together.
And you need to request that the key is generated by the database. For EF Core its:
modelBuilder.Entity<Diagnosis>().Property(r => r.DiagnosisId).ValueGeneratedOnAdd();
for EF6 it's:
modelBuilder.Entity<Diagnosis>().Property(r => r.DiagnosisId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
update(add) dynamodb with lambda function
I have done a lot of research and the topic does not have enough source for juniors like me. Everything I could find was case specific that was making it impossible to understand. Therefore for myself and for the people who will read this in the future I will not make my question too case specific.
I have created a table record on DynamoDB with the following lambda function:
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-2', apiVersion: '2012-08-10'})
exports.handler = (event, context, callback) => {
console.log(event)
const params = {
Item: {
"UserId": {
S: "global"
},
"search": {
SS: [
"" + event.hashtag
]
}
},
TableName: "crypto-app"
};
dynamodb.putItem(params, function(err, data) {
if (err) {
callback(err)
} else {
callback(null, data)
}
});
};
this is creating a simple string set
{
"search": {
"SS": [
"london"
]
},
"UserId": {
"S": "global"
}
}
how can I add more strings to my string set with a lambda function to make it like this?
{
"search": {
"SS": [
"london", "tokyo", "moskow"
]
},
"UserId": {
"S": "global"
}
}
A:
You can update the item and add additional string set values.
Here's how you would do it if you had named the attribute xxx rather than search, which is a reserved word.
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-2'});
const params = {
Key: {
UserId: {
S: 'global',
},
},
UpdateExpression: 'ADD xxx :avals',
ExpressionAttributeValues: {
':avals': {
SS: ['tokyo', 'moskow'],
},
},
TableName: 'crypto-app',
};
dynamodb.updateItem(params, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
However, because you named the attribute search, which is reserved, you need to essentially escape that reserved name using an expression attribute name, which is a placeholder that you use in an expression, as an alternative to an actual attribute name.
Here's an example of how you do that:
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB({region: 'us-east-2'});
const params = {
Key: {
UserId: {
S: 'global',
},
},
UpdateExpression: 'ADD #a :avals',
ExpressionAttributeValues: {
':avals': {
SS: ['tokyo', 'moskow'],
},
},
ExpressionAttributeNames: {
'#a': 'search',
},
TableName: 'crypto-app',
};
dynamodb.updateItem(paramse, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
Another, probably better, way to do this is to use the DynamoDB DocumentClient. It's a higher level client interface and it simplifies working with items by abstracting away the notion of attribute values, and instead using native JavaScript types.
With the DocumentClient, rather than explicitly writing UserId: { 'S': 'global' }, you can simply use UserId: 'global' and the string type ('S') will be inferred.
Here's an example of the item update using DocumentClient:
const AWS = require('aws-sdk');
const dc = new AWS.DynamoDB.DocumentClient({region: 'us-east-2'});
const params = {
Key: {
UserId: 'global',
},
UpdateExpression: 'ADD #a :avals',
ExpressionAttributeValues: {
':avals': dc.createSet(['tokyo', 'moskow']),
},
ExpressionAttributeNames: {
'#a': 'search',
},
TableName: 'crypto-app',
};
dc.update(params, (err, data) => {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IOEerror in python "No such file or directory"
I am writing a django project that involves retrieving data from a table. I have a module that has the line to retrieve some data (snp_data.txt is a file on the same directory of the module):
data = file("snp_data.txt")
While the module works well when I call it separately outside the django project; I keep getting the error below, when I call with other module within the django app.
no such file or directory as 'snp_data.txt'
Any idea what's going on?
A:
You are trying to open the file in the current working directory, because you didn't specify a path. You need to use an absolute path instead:
import os.path
BASE = os.path.dirname(os.path.abspath(__file__))
data = open(os.path.join(BASE, "snp_data.txt"))
because the current working directory is rarely the same as the module directory.
Note that I used open() instead of file(); the former is the recommended method.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Optimizing Listview in C# for large files
I have a C# program that is pulling in a .csv file that is approx. 42,000 lines long. All data in the file is stored as follows:
Zipcode,City,State
I am pulling all the information into three different columns in a listview.
Currently this data takes about 30 - 50 seconds to be brought into my program. My question is how can I better optimize my code to get this time down?
The following is a snippet of my code. The commented code is code I previously tried, but had no success in reducing the time, therefore I rewrote it in a way that was easier to read.
//These are globally declared.
lvZip.Columns.Add("Zipcode", 150, HorizontalAlignment.Left);
lvZip.Columns.Add("City", 150, HorizontalAlignment.Left);
lvZip.Columns.Add("State", 150, HorizontalAlignment.Left);
lvZip.View = View.Details;
lvZip.Items.Clear();
//string dir = System.IO.Path.GetDirectoryName(
// System.Reflection.Assembly.GetExecutingAssembly().Location);
//string path = dir + @"\zip_code_database_edited.csv";
//var open = new StreamReader(File.OpenRead(path));
//foreach (String s in File.ReadAllLines(path))
//{
// Zipinfo = s.Split(',');
// Zipinfo[0] = Zipinfo[0].Trim();
// Zipinfo[1] = Zipinfo[1].Trim();
// Zipinfo[2] = Zipinfo[2].Trim();
// lvItem = new ListViewItem(Zipinfo);
// lvZip.Items.Add(lvItem);
//}
//open.Close();
StreamReader myreader = File.OpenText(path);
aLine = myreader.ReadLine();
while (aLine != null)
{
Zipinfo = aLine.Split(',');
Zipinfo[0] = Zipinfo[0].Trim();
Zipinfo[1] = Zipinfo[1].Trim();
Zipinfo[2] = Zipinfo[2].Trim();
lvItem = new ListViewItem(Zipinfo);
lvZip.Items.Add(lvItem);
aLine = myreader.ReadLine();
}
myreader.Close();
A:
What you should be doing is using the ListView.BeginUpdate() and the ListView.EndUpdate() before and after you add anything into the ListView. The second thing would be to use the ListView.AddRange() instead of ListView.Add(). By using the Add method, you will redraw the ListView every time you use it. However, using ListView.AddRange() you will only redraw it once. That should optimize it a little for you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python difflib: highlighting differences inline?
When comparing similar lines, I want to highlight the differences on the same line:
a) lorem ipsum dolor sit amet
b) lorem foo ipsum dolor amet
lorem <ins>foo</ins> ipsum dolor <del>sit</del> amet
While difflib.HtmlDiff appears to do this sort of inline highlighting, it produces very verbose markup.
Unfortunately, I have not been able to find another class/method which does not operate on a line-by-line basis.
Am I missing anything?
Any pointers would be appreciated!
A:
For your simple example:
import difflib
def show_diff(seqm):
"""Unify operations between two compared strings
seqm is a difflib.SequenceMatcher instance whose a & b are strings"""
output= []
for opcode, a0, a1, b0, b1 in seqm.get_opcodes():
if opcode == 'equal':
output.append(seqm.a[a0:a1])
elif opcode == 'insert':
output.append("<ins>" + seqm.b[b0:b1] + "</ins>")
elif opcode == 'delete':
output.append("<del>" + seqm.a[a0:a1] + "</del>")
elif opcode == 'replace':
raise NotImplementedError, "what to do with 'replace' opcode?"
else:
raise RuntimeError, "unexpected opcode"
return ''.join(output)
>>> sm= difflib.SequenceMatcher(None, "lorem ipsum dolor sit amet", "lorem foo ipsum dolor amet")
>>> show_diff(sm)
'lorem<ins> foo</ins> ipsum dolor <del>sit </del>amet'
This works with strings. You should decide what to do with "replace" opcodes.
A:
Here's an inline differ inspired by @tzot's answer above (also Python 3 compatible):
def inline_diff(a, b):
import difflib
matcher = difflib.SequenceMatcher(None, a, b)
def process_tag(tag, i1, i2, j1, j2):
if tag == 'replace':
return '{' + matcher.a[i1:i2] + ' -> ' + matcher.b[j1:j2] + '}'
if tag == 'delete':
return '{- ' + matcher.a[i1:i2] + '}'
if tag == 'equal':
return matcher.a[i1:i2]
if tag == 'insert':
return '{+ ' + matcher.b[j1:j2] + '}'
assert False, "Unknown tag %r"%tag
return ''.join(process_tag(*t) for t in matcher.get_opcodes())
It's not perfect, for example, it would be nice to expand 'replace' opcodes to recognize the full word replaced instead of just the few different letters, but it's a good place to start.
Sample output:
>>> a='Lorem ipsum dolor sit amet consectetur adipiscing'
>>> b='Lorem bananas ipsum cabbage sit amet adipiscing'
>>> print(inline_diff(a, b))
Lorem{+ bananas} ipsum {dolor -> cabbage} sit amet{- consectetur} adipiscing
A:
difflib.SequenceMatcher will operate on single lines. You can use the "opcodes" to determine how to change the first line to make it the second line.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OpenCv: How to set a marker at a certain coordinate in a video stream open cv
I'm working with NITE/OPENNI and opencv in xcode 4 to work with the kinect. I'm able to get the coordinates of the head for example this is done by :
In the main, outside the wile(true):
IplImage *rgbimg = cvCreateImageHeader(cvSize(640,480), 8, 3);
Then in the wile(true)
XnSkeletonJointPosition Head;
g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition( aUsers[i], XN_SKEL_HEAD, Head);
printf("%d: (%f,%f,%f) [%f]\n", aUsers[i], Head.position.X, Head.position.Y, Head.position.Z, Head.fConfidence); }
I also have a video stream :
// Take current image
const XnRGB24Pixel* pImage = Xn_image.GetRGB24ImageMap();
//process image data
XnRGB24Pixel* ucpImage = const_cast<XnRGB24Pixel*> (pImage);
cvSetData(rgbimg,ucpImage, 640*3);
cvCvtColor(rgbimg,rgbimg,CV_RGB2BGR);
cvShowImage("RGB",rgbimg);
This is all done in the main in a while(true).
Now my question is how can i set some kind of marker (e.g.: *,cross-hair, X ) at the position of the coordinates of the hand in the video stream ?
EDIT
i tried:
XnRGB24Pixel* ucpImage = const_cast<XnRGB24Pixel*> (pImage);
cvSetData(rgbimg,ucpImage, 640*3);
cvCvtColor(rgbimg,rgbimg,CV_RGB2BGR);
cvCircle(rgbimg, cvPoint(Head.position.X,Head.position.Y), 20, cvScalar(0,255,0), 1);
cvShowImage("RGB",rgbimg);
and i get :
as you can see the circle stays in the top left corner for some reason. Any ideas how to change this ?
A:
Try the display functions in OpenCV:
line(), circle(), drawPoly() and apply them to every frame in your video
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Recursively removing `nil` and empty values from hash
I have a hash that starts out as:
{"request"=>{
"security"=>{"username"=>{"type"=>nil}, "password"=>{"type"=>nil}},
"order_i_d"=>{"type"=>nil, "description"=>nil},
"order_number"=>{"type"=>nil},
"show_kit_as_individual_s_k_us"=>false,
"website_i_d"=>{"type"=>nil, "description"=>nil}
}}
And I'd like to recursively remove all values that are nil? and empty? but leave the falsey values in place. The final result should look like:
{"request"=>{
"show_kit_as_individual_s_k_us"=>false
}}
How can I accomplish this?
A:
Just another implementation, written for fun & practice.
No monkey patching
Works on Hashes and Arrays
Can be used as a module function like: DeepCompact.deep_compact(hash)
Also a destructive target modifying variant: DeepCompact.deep_compact!(hash)
Can be used by extending on an existing object: { foo: nil }.extend(DeepCompact).deep_compact
Can be used via refinements: adding using DeepCompact to a file/class will bring deep_compact and deep_compact! to Hashes and Arrays for all code in that file/class.
Here's the module:
module DeepCompact
[Hash, Array].each do |klass|
refine klass do
def deep_compact
DeepCompact.deep_compact(self)
end
def deep_compact!
DeepCompact.deep_compact!(self)
end
end
end
def self.extended(where)
where.instance_exec do
def deep_compact
DeepCompact.deep_compact(self)
end
def deep_compact!
DeepCompact.deep_compact!(self)
end
end
end
def deep_compact(obj)
case obj
when Hash
obj.each_with_object({}) do |(key, val), obj|
new_val = DeepCompact.deep_compact(val)
next if new_val.nil? || (new_val.respond_to?(:empty?) && new_val.empty?)
obj[key] = new_val
end
when Array
obj.each_with_object([]) do |val, obj|
new_val = DeepCompact.deep_compact(val)
next if new_val.nil? || (new_val.respond_to?(:empty?) && new_val.empty?)
obj << val
end
else
obj
end
end
module_function :deep_compact
def deep_compact!(obj)
case obj
when Hash
obj.delete_if do |_, val|
val.nil? || (val.respond_to?(:empty?) && val.empty?) || DeepCompact.deep_compact!(val)
end
obj.empty?
when Array
obj.delete_if do |val|
val.nil? || (val.respond_to?(:empty?) && val.empty?) || DeepCompact.deep_compact!(val)
end
obj.empty?
else
false
end
end
module_function :deep_compact!
end
And then some examples on how to use it:
hsh = {
'hello' => [
'world',
{ 'and' => nil }
],
'greetings' => nil,
'salutations' => {
'to' => { 'you' => true, 'him' => 'yes', 'her' => nil },
'but_not_to' => nil
}
}
puts "Original:"
pp hsh
puts
puts "Non-destructive module function:"
pp DeepCompact.deep_compact(hsh)
puts
hsh.extend(DeepCompact)
puts "Non-destructive after hash extended:"
pp hsh.deep_compact
puts
puts "Destructive refinement for array:"
array = [hsh]
using DeepCompact
array.deep_compact!
pp array
And the output:
Original:
{"hello"=>["world", {"and"=>nil}],
"greetings"=>nil,
"salutations"=>
{"to"=>{"you"=>true, "him"=>"yes", "her"=>nil}, "but_not_to"=>nil}}
Non-destructive module function:
{"hello"=>["world"], "salutations"=>{"to"=>{"you"=>true, "him"=>"yes"}}}
Non-destructive after hash extended:
{"hello"=>["world"], "salutations"=>{"to"=>{"you"=>true, "him"=>"yes"}}}
Destructive refinement for array:
[{"hello"=>["world"], "salutations"=>{"to"=>{"you"=>true, "him"=>"yes"}}}]
Or just use one of the multiple gems that provide this for you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding 1,15,30 or 45 minutes to currentTimeMillis()
does anyone know how to add minutes to currentTimeMillis. i am passing an integer t, which is how many minutes users would like to add to the currentTimeMillis() time_int. Is this possible in java? can anyone show me?
public void radioStartTime(int t)
{
time_int =(int)System.currentTimeMillis(); //casting long into int.
System.out.println(time_int);
}
A:
Well, given that there are 1,000 milliseconds in a second and 60 seconds in a minute, you need to add 60,000 for each minute.
Hence:
Add n minutes, n = Add
1 60,000
15 900,000
30 1,800,000
45 2,700,000
I'd also be a little wary of converting the return value from currentTimeMillis() back to an int data type, you may want to keep it as a long so there's less chance of losing range.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Application launcher is missing
I have 13.04 installed from a DVD that I got on eBay but the application launcher is missing. I've tried CCSM but it won't work!
A:
If you can't download the CD, you could buy from the Canonical Shop here: http://shop.canonical.com/product_info.php?products_id=976
We don't offer support to variations of Ubuntu, forks, unofficial variants and derivatives are not controlled or guided by Canonical Ltd. (list on Wikipedia) and generally have different goals in mind. You should ALWAYS download/buy Ubuntu from trusted sources, preferable directly from the makers. You should verify your CD, so it won't include defects or modifications.
Insert your Ubuntu CD into the drive of the computer that you want
to run/install Ubuntu onto.
Turn the computer on, or restart the computer.
While booting from the CD, hold any key to access the CD menu.
At the CD menu, choose 'Check CD for Defects' (if you never get to
the menu, try BootFromCD)
You can also order CD's from a third party at http://www.osdisc.com/cgi-bin/view.cgi/products/linux/ubuntu
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.