text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Export from Query to Excel, while defining Row to export to I have seen a bunch of ways to export data into excel worksheets form queries, yet I cannot find one that I can define the starting row I would like the insertion of the query data to begin.
For example, I would like the first 5 columns of my query to go into columns A8-F8, and the rest of the columns from my query to go into columns H8-Y8.
Is there a way to specify where my data from the query should start pasting, and the starting row as well?
A: You could add a null value for the 6th position of your query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery: how do I trigger an event after a click-hold-release action? I want to show a menu after a click, drag, and release action.
How do I trigger that with jQuery?
A: *
*Listen for a mousedown event on whatever should be clicked on.
*Add a mousemove and mouseup event handler to the window
*In the mouseup event handler call trigger('yourcustomeventhere') on whatever element you please. Also, remove the mouseup and mousemove event handlers from window
*...?
*profit.
jQuery is the library that will do this for you. I thought I explained the code well enough, but apparantly not:
$(anElement).mousedown(foodown);
function foodown(){
$(window).mousemove(foomove).mouseup(fooup);
//stuff
}
function foomove(){
//stuff
}
function fooup(){
$(someElement).trigger('yourcustomevent');
$(window).unbind('mousemove', foomove).unbind('mouseup', fooup);
}
/**
* Dragondrop jQuery plugin by zzzzBov
*/
(function ($) {
"use strict";
var $window;
function begin(e) {
var event;
$window.mousemove(drag).mouseup(end);
event = $.Event('beginDragon');
$(e.target).trigger(event);
if (event.isDefaultPrevented()) {
e.preventDefault();
}
}
function drag(e) {
var event;
event = $.Event('dragDragon');
$(e.target).trigger(event);
if (event.isDefaultPrevented()) {
e.preventDefault();
}
}
function end(e) {
var event;
event = $.Event('endDragon');
$(e.target).trigger(event);
$window.unbind('mousemove', drag).unbind('mouseup', end);
if (event.isDefaultPrevented()) {
e.preventDefault();
}
}
$.each('beginDragon dragDragon endDragon'.split(' '), function (i, name) {
$.fn[name] = function(data,fn) {
if (fn == null) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind(name, data, fn) :
this.trigger(name);
};
});
$window = $(window);
$window.mousedown(begin);
}(jQuery));
A: You could use the jQueryUI and let it do a lot for you. It also comes with a create UI (of course, because it's jQuery UI)
Take a look at this: http://jqueryui.com/demos/droppable/
edit:
Or take a look here: http://jqueryui.com/demos/draggable/
Take a close look to the events used here.
A: jQuery UI has a drag and drop implementation. If that doesn't do what you do, you'll have to roll your own implementation by tracking the mouseup and mousedown events on the element yourself. (And possibly mouseleave to detect if the mouse left the area you want to track the gesture in.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.NET MVC: Putting application logic in models This may sound like a stupid or unconstructive question but I'm a fan of not creating so many layers to reduce the amount of code that has to be written and maintained. In a classic scenario, the application logic would be in one class which calls the business layer. However, if the application logic is simple enough, would it be a crime if I were to put application logic in view models? In my case, this would entail calling the business layer in my view models.
A: yes, it would be a crime and completely destroy the mvc nature of... mvc.
if you have to, put application logic in your controller.
A: Surely it is not a crime. But it is good to understand why the Application Logic is "Normally" (what is normal) separated from the User Interface layer. The most important reason that is usually given for this separation is the ability to re-use the application logic when you application gets another User Interface implementation. This can be another technology, or another deployment model. Also for maintenance and readability this is often a best practice.
The fact that you are talking about a viewmodel probably means that you are creating a controller class that has no dependency on the view, according to MVC. This is already a separation in some sense from your user interface.
So my opinion: If you have the need / requirement / wish to modernize your user interface in the future or have multiple user interfaces target the same application logic, put some effort in a separate application logic component. Otherwise, you are not commiting a crime by implementing your application logic in your controller.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: chrome won't load swf files I was asked by a family member to fix their site, but since I don't work in Flash I'm not certain how to target the problem.
The site is in Wordpress 3.2.1 and uses two small .swf files created in CS5 - neither of which will load in Chrome 11 or 13. They test ok in Firefox/Safari/IE for all modern versions. I've been digging for an answer but it seems this problem may be both pervasive and unique to each local environment. Maybe someone here has a fix?
here is the site: www.countdowntoday.com
here is the code from the index page:
<object width="400" height="320">
<param name="movie" value="countdown.swf">
<embed src="<?php bloginfo('template_directory'); ?>/flash/countdown.swf" width="400" height="320">
</embed>
</object>
Any advice would be greatly appreciated.
A: I think that the problem is that value="countdown.swf" and src="<?php bloginfo('template_directory'); ?>/flash/countdown.swf" points to differents places.
Change the value property to the same as src and should work.
Also, please check this guide in order to embed correctly flash files http://latrine.dgx.cz/how-to-correctly-insert-a-flash-into-xhtml
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenSSL: unable to verify the first certificate for Experian URL I am trying to verify an SSL connection to Experian in Ubuntu 10.10 with OpenSSL client.
openssl s_client -CApath /etc/ssl/certs/ -connect dm1.experian.com:443
The problem is that the connection closes with a Verify return code: 21 (unable to verify the first certificate).
I've checked the certificate list, and the Certificate used to sign Experian (VeriSign Class 3 Secure Server CA - G3) is included in the list.
/etc/ssl/certs/ca-certificates.crt
Yet I don't know why it is not able to verify the first certificate.
The entire response could be seen here:
https://gist.github.com/1248790
A: Adding additional information to emboss's answer.
To put it simply, there is an incorrect cert in your certificate chain.
For example, your certificate authority will have most likely given you 3 files.
*
*your_domain_name.crt
*DigiCertCA.crt # (Or whatever the name of your certificate authority is)
*TrustedRoot.crt
You most likely combined all of these files into one bundle.
-----BEGIN CERTIFICATE-----
(Your Primary SSL certificate: your_domain_name.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Intermediate certificate: DigiCertCA.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Root certificate: TrustedRoot.crt)
-----END CERTIFICATE-----
If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.
*
*SSL connections appear to work from browser
*SSL connections fail from other clients
*Curl fails with error: "curl: (60) SSL certificate : unable to get local issuer certificate"
*openssl s_client -connect gives error "verify error:num=20:unable to get local issuer certificate"
Redownload all certs from your certificate authority and make a fresh bundle.
A: The first error message is telling you more about the problem:
verify error:num=20:unable to get local issuer certificate
The issuing certificate authority of the end entity server certificate is
VeriSign Class 3 Secure Server CA - G3
Look closely in your CA file - you will not find this certificate since it is an intermediary CA - what you found was a similar-named G3 Public Primary CA of VeriSign.
But why does the other connection succeed, but this one doesn't? The problem is a misconfiguration of the servers (see for yourself using the -debug option). The "good" server sends the entire certificate chain during the handshake, therefore providing you with the necessary intermediate certificates.
But the server that is failing sends you only the end entity certificate, and OpenSSL is not capable of downloading the missing intermediate certificate "on the fly" (which would be possible by interpreting the Authority Information Access extension). Therefore your attempt fails using s_client but it would succeed nevertheless if you browse to the same URL using e.g. FireFox (which does support the "certificate discovery" feature).
Your options to solve the problem are either fixing this on the server side by making the server send the entire chain, too, or by passing the missing intermediate certificate to OpenSSL as a client-side parameter.
A: I came across the same issue installing my signed certificate on an Amazon Elastic Load Balancer instance.
All seemed find via a browser (Chrome) but accessing the site via my java client produced the exception javax.net.ssl.SSLPeerUnverifiedException
What I had not done was provide a "certificate chain" file when installing my certificate on my ELB instance (see https://serverfault.com/questions/419432/install-ssl-on-amazon-elastic-load-balancer-with-godaddy-wildcard-certificate)
We were only sent our signed public key from the signing authority so I had to create my own certificate chain file. Using my browser's certificate viewer panel I exported each certificate in the signing chain. (The order of the certificate chain in important, see https://forums.aws.amazon.com/message.jspa?messageID=222086)
A: Here is what you can do:-
Exim SSL certificates
By default, the /etc/exim.conf will use the cert/key files:
/etc/exim.cert
/etc/exim.key
so if you're wondering where to set your files, that's where.
They're controlled by the exim.conf's options:
tls_certificate = /etc/exim.cert
tls_privatekey = /etc/exim.key
Intermediate Certificates
If you have a CA Root certificate (ca bundle, chain, etc.) you'll add the contents of your CA into the exim.cert, after your actual certificate.
Probably a good idea to make sure you have a copy of everything elsewhere in case you make an error.
Dovecot and ProFtpd should also read it correctly, so dovecot no longer needs the ssl_ca option.
So for both cases, there is no need to make any changes to either the exim.conf or dovecot.conf(/etc/dovecot/conf/ssl.conf)
A: If you are using MacOS use:
sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs
after this Trust anchor not found error disappears
A: For those using zerossl.com certificates, drag and drop all certificates (as is) to their respective folders.
Cut and pasting text into existing files, may cause utf8 issues - depending upon OS, format and character spacings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "97"
}
|
Q: Run java from FTP How can I run a .jar (Java) file on a server using FTP? I use the ftp command to enter the server, provide the IP address, username, password. Is it possible to run the java file?
A: You cannot invoke non-ftp commands using ftp. Use ssh to access remote shell and invoke your commands.
A: FTP is File Transfer Protocol. It's supposed to be used for manipulating files only.
If you need to run a Java file, I suggest you use SSH, RSH, Telnet, or some other method of getting an actual shell.
A: You could use FTP to transfer your jar, and then use a crontab, or any other sort of scheduled task, to actually run it. It is not possible to execute commands using FTP.
A: I believe you mean using ssh command to enter the server and if so
I think this might be a starting point :
Can I run .jar file on Tomcat?
if not I don't think its possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a list of screen resolutions for all Android based phones and tablets? If not, is there a list of screen resolutions for the most popular Android phones and tablets.
A: You can see a lot of screen sizes on this site.
Parsed list of screens:
From http://www.emirweb.com/ScreenDeviceStatistics.php
####################################################################################################
# Filter out same-sized same-dp screens and width/height swap.
####################################################################################################
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 640 x 480 px (640 x 480 dp) mdpi
Size: 640 x 360 px (426 x 240 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi
Size: 280 x 280 px (186 x 186 dp) hdpi
####################################################################################################
# Sorted by smallest width.
####################################################################################################
sw800dp:
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi
sw720dp:
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi
sw600dp:
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi
sw480dp:
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 640 x 480 px (640 x 480 dp) mdpi
sw320dp:
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi
sw240dp:
Size: 640 x 360 px (426 x 240 dp) hdpi
lower:
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 280 x 280 px (186 x 186 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi
####################################################################################################
# Different size in px only.
####################################################################################################
2560 x 1600 px
2048 x 1536 px
1920 x 1200 px
1920 x 1152 px
1920 x 1080 px
1600 x 1200 px
1600 x 900 px
1440 x 904 px
1366 x 768 px
1360 x 768 px
1280 x 960 px
1280 x 800 px
1280 x 768 px
1280 x 720 px
1279 x 720 px
1152 x 720 px
1080 x 607 px
1024 x 960 px
1024 x 770 px
1024 x 768 px
1024 x 600 px
960 x 640 px
960 x 600 px
960 x 540 px
864 x 480 px
854 x 480 px
800 x 600 px
800 x 480 px
768 x 576 px
640 x 480 px
640 x 360 px
480 x 320 px
432 x 240 px
400 x 240 px
320 x 240 px
280 x 280 px
####################################################################################################
# Different size in dp only.
####################################################################################################
1920 x 1080 dp
1600 x 900 dp
1442 x 901 dp
1366 x 768 dp
1365 x 1024 dp
1365 x 800 dp
1360 x 768 dp
1280 x 800 dp
1280 x 768 dp
1280 x 720 dp
1152 x 720 dp
1066 x 800 dp
1066 x 640 dp
1024 x 960 dp
1024 x 770 dp
1024 x 768 dp
1024 x 600 dp
961 x 600 dp
961 x 540 dp
960 x 602 dp
960 x 600 dp
960 x 540 dp
853 x 533 dp
853 x 480 dp
800 x 480 dp
768 x 576 dp
720 x 404 dp
682 x 400 dp
640 x 480 dp
640 x 400 dp
640 x 384 dp
640 x 360 dp
639 x 360 dp
600 x 360 dp
576 x 320 dp
569 x 320 dp
533 x 320 dp
512 x 384 dp
480 x 320 dp
426 x 320 dp
426 x 240 dp
320 x 213 dp
266 x 160 dp
186 x 186 dp
I drop a lot of same-sized same-dp screens, ignore height/width swap and include some sorting results.
A: Here is a list of almost all resolutions of tablets :
2560*1600
1366*768
1280*800
1280*768
1024*768
1024*600
960*640
960*540
854*480
800*600
800*480
800*400
Of this, the most common resolutions are :
1280*800
1280*768
1024*600
1024*800
1024*768
800*400
800*480
Happy designing .. ! :)
A: These are the sizes. Try to take a look in Supporting Mutiple Screens
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
I use this to make more than one layout:
res/layout/main_activity.xml # For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger)
A: hdpi 480x800 px Samsung S2
xhdpi 720x1280 px - Nexus 4 phone - 4.7,4.8 inches
Samsung Galaxy S3
Motorola Moto G
xxhdpi 1080x1920 px - Nexus 5 phone - 4.95 inches
Samsung Galaxy S4
Samsung Galaxy S5
Samsung Galaxy Note 3 - 5.7 inches
LG G2
HTC One M8
HTC One M9
Sony Xperia Z1
Sony Xperia Z2
Sony Xperia Z3
Sony Xperia Z3+
xxxhdpi 1440x2560 px - Nexus 6 phablet - 6 inches
Samsung S6
Samsung S6 Edge
Samsung Galaxy Note 4 - 5.7 inches
LG G3
LG G4
xxhdpi 1920×1200 px - Nexus 7 tablet - 7 inches
Sony Z3 Tablet Compact
LG G Pad 8.3 - 8.3 inches
Sony Xperia Z2 Tablet - 10.1 inches
xxxhdpi 2560×1600 px - Nexus 10 tablet - 10.1 inches
~Google Nexus 9
Sony Xperia Z4 tablet
Samsung Galaxy Note Pro 12.2
Samsung Galaxy Note 10.1
Samsung Galaxy Tab S 10.5
Dell Venue 8 7840
A: Google recently added this comprehensive list of reference devices and resolutions, including new device types such as wearables and laptops:
https://design.google.com/devices/
A: (out of date) Spreadsheet of device metrics.
SEE ALSO:
Device Metrics - Material Design.
Screen Sizes.
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Galaxy Y 320 x 240 ldpi 0.75 120 427 x 320 4:3 1.3333 427 x 320
? 400 x 240 ldpi 0.75 120 533 x 320 5:3 1.6667 533 x 320
? 432 x 240 ldpi 0.75 120 576 x 320 9:5 1.8000 576 x 320
Galaxy Ace 480 x 320 mdpi 1 160 480 x 320 3:2 1.5000 480 x 320
Nexus S 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
"Galaxy SIII Mini" 800 x 480 hdpi 1.5 240 533 x 320 5:3 1.6667 533 x 320
? 854 x 480 hdpi 1.5 240 569 x 320 427:240 1.7792 569 x 320
Galaxy SIII 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Galaxy Nexus 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
HTC One X 4.7" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 5 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 YES 592 x 360
Galaxy S4 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One 5" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note III 5.7" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
HTC One Max 5.9" 1920 x 1080 xxhdpi 3 480 640 x 360 16:9 1.7778 640 x 360
Galaxy Note II 5.6" 1280 x 720 xhdpi 2 320 640 x 360 16:9 1.7778 640 x 360
Nexus 4 4.4" 1200 x 768 xhdpi 2 320 600 x 384 25:16 1.5625 YES 552 x 384
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
? 800 x 480 mdpi 1 160 800 x 480 5:3 1.6667 800 x 480
? 854 x 480 mdpi 1 160 854 x 480 427:240 1.7792 854 x 480
Galaxy Mega 6.3" 1280 x 720 hdpi 1.5 240 853 x 480 16:9 1.7778 853 x 480
Kindle Fire HD 7" 1280 x 800 hdpi 1.5 240 853 x 533 8:5 1.6000 853 x 533
Galaxy Mega 5.8" 960 x 540 tvdpi 1.33333 213.333 720 x 405 16:9 1.7778 720 x 405
Sony Xperia Z Ultra 6.4" 1920 x 1080 xhdpi 2 320 960 x 540 16:9 1.7778 960 x 540
Blackberry Priv 5.43" 2560 x 1440 ? 540 ? 16:9 1.7778
Blackberry Passport 4.5" 1440 x 1440 ? 453 ? 1:1 1.0
Kindle Fire (1st & 2nd gen) 7" 1024 x 600 mdpi 1 160 1024 x 600 128:75 1.7067 1024 x 600
Tesco Hudl 7" 1400 x 900 hdpi 1.5 240 933 x 600 14:9 1.5556 933 x 600
Nexus 7 (1st gen/2012) 7" 1280 x 800 tvdpi 1.33333 213.333 960 x 600 8:5 1.6000 YES 912 x 600
Nexus 7 (2nd gen/2013) 7" 1824 x 1200 xhdpi 2 320 912 x 600 38:25 1.5200 YES 864 x 600
Kindle Fire HDX 7" 1920 x 1200 xhdpi 2 320 960 x 600 8:5 1.6000 960 x 600
? 800 x 480 ldpi 0.75 120 1067 x 640 5:3 1.6667 1067 x 640
? 854 x 480 ldpi 0.75 120 1139 x 640 427:240 1.7792 1139 x 640
Kindle Fire HD 8.9" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Kindle Fire HDX 8.9" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 2 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Tab 3 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 10" 1280 x 800 mdpi 1 160 1280 x 800 8:5 1.6000 1280 x 800
ASUS Transformer 2 10" 1920 x 1200 hdpi 1.5 240 1280 x 800 8:5 1.6000 1280 x 800
Nexus 10 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
Galaxy Note 10.1 10" 2560 x 1600 xhdpi 2 320 1280 x 800 8:5 1.6000 1280 x 800
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Device Inches ResolutionPX Density DPI ResolutionDP AspectRatios SysNavYorN ContentResolutionDP
--------------------------- ----- ------------ --------------- ------- ----------- ---------------- --- ----------
Coping with different aspect ratios
The different aspect ratios seen above are (from most square; h/w):
1:1 1.0 <- rare for phone; common for watch
4:3 1.3333 <- matches iPad (when portrait)
3:2 1.5000
38:25 1.5200
14:9 1.5556 <- rare
25:16 1.5625
8:5 1.6000 <- aka 16:10
5:3 1.6667
128:75 1.7067
16:9 1.7778 <- matches iPhone 5-7
427:240 1.7792 <- rare
37:18 2.0555 <- Galaxy S8
If you skip the extreme aspect ratios, that are rarely seen at phone size or larger, all the other devices fit a range from 1.3333 to 1.7778, which conveniently matches the current iPhone/iPad ratios (considering all devices in portrait mode). Note that there are quite a few variations within that range, so if you are creating a small number of fixed aspect-ratio layouts, you will need to decide how to handle the odd "in-between" screens.
Minimum "portrait mode" solution is to support 1.3333, which results in unused space at top and bottom, on all the resolutions with larger aspect ratio.
Most likely, you would instead design it to stretch over the 1.333 to 1.778 range. But sometimes part of your design looks too distorted then.
Advanced layout ideas:
For text, you can design for 1.3333, then increase line spacing for 1.666 - though that will look quite sparse. For graphics, design for an intermediate ratio, so that on some screens it is slightly squashed, on others it is slightly stretched. geometric mean of Sqrt(1333 x 1667) ~= 1491. So you design for 1491 x 1000, which will be stretched/squashed by +-12% when assigned to the extreme cases.
Next refinement is to design layout as a stack of different-height "bands" that each fill the width of the screen. Then determine where you can most pleasingly "stretch-or-squash" a band's height, to adjust for different ratios.
For example, consider imaginary phones with 1333 x 1000 pixels and 1666 x 1000 pixels. Suppose you have two "bands", and your main "band" is square, so it is 1000 x 1000. Second band is 333 x 1000 on one screen, 666 x 1000 on the other - quite a range to design for.
You might decide your main band looks okay altered 10% up-or-down, and squash it 900 x 1000 on the 1333 x 1000 screen, leaving 433 x 1000. Then stretch it to 1100 x 1000 on 1666 x 1000 screen, leaving 566 x 1000. So your second band now needs to adjust over only 433 to 566, which has geometric mean of Sqrt(433 x 566) ~= 495. So you design for 495 x 1000, which will be stretched/squashed by +-14% when assigned to the extreme cases.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "105"
}
|
Q: Jquery disabling submit button I have a form with a text box and a submit button. I disable the submit button once it is clicked for 5 seconds. If nothing is typed in the text field and the user tries submitting, the button is disabled for 1 second and nothing is posted.
The problem I am having is that on a friends Mac in Chrome and Firefox, when the button is disabled, the button disappears and a grey box is left until the 5 seconds are up, but on my Windows computer with Chrome and Firefox the button is just faded out. Is there a reason why this is happening? He said that it was working fine and then it suddenly started happening.
Here is my HTML:
<form style="position:relative; top:-5px;" action="" method="post">
<strong>Message:</strong>
<input type="text" id="message" name="message" class="message">
<input type="submit" id="submit" value="Submit"/>
</form>
And JavaScript:
<script type="text/javascript">
$(function() {
refresh_shoutbox();
setInterval("refresh_shoutbox()", 15000);
var running = false;
$("#message").keypress(function(e) {
if(e.which == 13 && running === true) {
return false;
}
});
$("#submit").click(function(event) {
if(this.disabled) {
event.preventDefault();
}
if($("#message").val() != '') {
running = true;
$("#submit").attr("disabled","disabled");
setTimeout(function() {
$("#submit").removeAttr("disabled")
running = false;
}, 5000);
} else {
$("#submit").attr("disabled", "disabled");
setTimeout(function() {
$("#submit").removeAttr("disabled")
running = false;
}, 1000);
return false;
}
// Ajax calls and the rest of the script
A: I think there's a bug in the latest webkit. I have buttons that were rendering ok until a week ago showing a weird grey rectangle now as well
You should use the html inspector and check that the button tag has
disabled="disabled"
as an attribute
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Query database in weekly interval I have a database with a created_at column containing the datetime in Y-m-d H:i:s format.
The latest datetime entry is 2011-09-28 00:10:02.
I need the query to be relative to the latest datetime entry.
*
*The first value in the query should be the latest datetime entry.
*The second value in the query should be the entry closest to 7 days from the first value.
*The third value should be the entry closest to 7 days from the second value.
*REPEAT #3.
What I mean by "closest to 7 days from":
The following are dates, the interval I desire is a week, in seconds a week is 604800 seconds.
7 days from the first value is equal to 1316578202 (1317183002-604800)
the value closest to 1316578202 (7 days) is... 1316571974
unix timestamp | Y-m-d H:i:s
1317183002 | 2011-09-28 00:10:02 -> appear in query (first value)
1317101233 | 2011-09-27 01:27:13
1317009182 | 2011-09-25 23:53:02
1316916554 | 2011-09-24 22:09:14
1316836656 | 2011-09-23 23:57:36
1316745220 | 2011-09-22 22:33:40
1316659915 | 2011-09-21 22:51:55
1316571974 | 2011-09-20 22:26:14 -> closest to 7 days from 1317183002 (first value)
1316499187 | 2011-09-20 02:13:07
1316064243 | 2011-09-15 01:24:03
1315967707 | 2011-09-13 22:35:07 -> closest to 7 days from 1316571974 (second value)
1315881414 | 2011-09-12 22:36:54
1315794048 | 2011-09-11 22:20:48
1315715786 | 2011-09-11 00:36:26
1315622142 | 2011-09-09 22:35:42
I would really appreciate any help, I have not been able to do this via mysql and no online resources seem to deal with relative date manipulation such as this. I would like the query to be modular enough to be able to change the interval weekly, monthly, or yearly. Thanks in advance!
Answer #1 Reply:
SELECT
UNIX_TIMESTAMP(created_at)
AS unix_timestamp,
(
SELECT MIN(UNIX_TIMESTAMP(created_at))
FROM my_table
WHERE created_at >=
(
SELECT max(created_at) - 7
FROM my_table
)
)
AS `random_1`,
(
SELECT MIN(UNIX_TIMESTAMP(created_at))
FROM my_table
WHERE created_at >=
(
SELECT MAX(created_at) - 14
FROM my_table
)
)
AS `random_2`
FROM my_table
WHERE created_at =
(
SELECT MAX(created_at)
FROM my_table
)
Returns:
unix_timestamp | random_1 | random_2
1317183002 | 1317183002 | 1317183002
Answer #2 Reply:
RESULT SET:
This is the result set for a yearly interval:
id | created_at | period_index | period_timestamp
267 | 2010-09-27 22:57:05 | 0 | 1317183002
1 | 2009-12-10 15:08:00 | 1 | 1285554786
I desire this result:
id | created_at | period_index | period_timestamp
626 | 2011-09-28 00:10:02 | 0 | 0
267 | 2010-09-27 22:57:05 | 1 | 1317183002
I hope this makes more sense.
A: It's not exactly what you asked for, but the following example is pretty close....
Example 1:
select
floor(timestampdiff(SECOND, tbl.time, most_recent.time)/604800) as period_index,
unix_timestamp(max(tbl.time)) as period_timestamp
from
tbl
, (select max(time) as time from tbl) most_recent
group by period_index
gives results:
+--------------+------------------+
| period_index | period_timestamp |
+--------------+------------------+
| 0 | 1317183002 |
| 1 | 1316571974 |
| 2 | 1315967707 |
+--------------+------------------+
This breaks the dataset into groups based on "periods", where (in this example) each period is 7-days (604800 seconds) long. The period_timestamp that is returned for each period is the 'latest' (most recent) timestamp that falls within that period.
The period boundaries are all computed based on the most recent timestamp in the database, rather than computing each period's start and end time individually based on the timestamp of the period before it. The difference is subtle - your question requests the latter (iterative approach), but I'm hoping that the former (approach I've described here) will suffice for your needs, since SQL doesn't lend itself well to implementing iterative algorithms.
If you really do need to determine each period based on the timestamp in the previous period, then your best bet is going to be an iterative approach -- either using a programming language of your choice (like php), or by building a stored procedure that uses a cursor.
Edit #1
Here's the table structure for the above example.
CREATE TABLE `tbl` (
`id` int(10) unsigned NOT NULL auto_increment PRIMARY KEY,
`time` datetime NOT NULL
)
Edit #2
Ok, first: I've improved the original example query (see revised "Example 1" above). It still works the same way, and gives the same results, but it's cleaner, more efficient, and easier to understand.
Now... the query above is a group-by query, meaning it shows aggregate results for the "period" groups as I described above - not row-by-row results like a "normal" query. With a group-by query, you're limited to using aggregate columns only. Aggregate columns are those columns that are named in the group by clause, or that are computed by an aggregate function like MAX(time)). It is not possible to extract meaningful values for non-aggregate columns (like id) from within the projection of a group-by query.
Unfortunately, mysql doesn't generate an error when you try to do this. Instead, it just picks a value at random from within the grouped rows, and shows that value for the non-aggregate column in the grouped result. This is what's causing the odd behavior the OP reported when trying to use the code from Example #1.
Fortunately, this problem is fairly easy to solve. Just wrap another query around the group query, to select the row-by-row information you're interested in...
Example 2:
SELECT
entries.id,
entries.time,
periods.idx as period_index,
unix_timestamp(periods.time) as period_timestamp
FROM
tbl entries
JOIN
(select
floor(timestampdiff( SECOND, tbl.time, most_recent.time)/31536000) as idx,
max(tbl.time) as time
from
tbl
, (select max(time) as time from tbl) most_recent
group by idx
) periods
ON entries.time = periods.time
Result:
+-----+---------------------+--------------+------------------+
| id | time | period_index | period_timestamp |
+-----+---------------------+--------------+------------------+
| 598 | 2011-09-28 04:10:02 | 0 | 1317183002 |
| 996 | 2010-09-27 22:57:05 | 1 | 1285628225 |
+-----+---------------------+--------------+------------------+
Notes:
*
*Example 2 uses a period length of 31536000 seconds (365-days). While Example 1 (above) uses a period of 604800 seconds (7-days). Other than that, the inner query in Example 2 is the same as the primary query shown in Example 1.
*If a matching period_time belongs to more than one entry (i.e. two or more entries have the exact same time, and that time matches one of the selected period_time values), then the above query (Example 2) will include multiple rows for the given period timestamp (one for each match). Whatever code consumes this result set should be prepared to handle such an edge case.
*It's also worth noting that these queries will perform much, much better if you define an index on your datetime column. For my example schema, that would look like this:
ALTER TABLE tbl ADD INDEX idx_time ( time )
A: If you're willing to go for the closest that is after the week is out then this'll work. You can extend it to work out the closest but it'll look so disgusting it's probably not worth it.
select unix_timestamp
, ( select min(unix_tstamp)
from my_table
where sql_tstamp >= ( select max(sql_tstamp) - 7
from my_table )
)
, ( select min(unix_tstamp)
from my_table
where sql_tstamp >= ( select max(sql_tstamp) - 14
from my_table )
)
from my_table
where sql_tstamp = ( select max(sql_tstamp)
from my_table )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Django. Cancel button for form in admin site Is there any functionality in admin site that allow to implement for every add/change form cancel button, that redirects me to list of that form objects. I mean some general solution for any form.
A: Add admin/submit_line.html in your project's templates directory. Use the code from the default submit_line.html, and add your cancel button. You can link it to just "../" to make it always just go up one level. Then do any necessary CSS styling to make it look right.
A: Create a file: yourapp/templates/admin/submit_line.html
I use Bootstrap, but you can change this easily
{% extends "admin/submit_line.html" %}
{% block submit-row %}
{{ block.super }}
<a href="../../" class="btn btn-secondary" style="color: white">Cancel</a>
{% endblock %}
Be sure that your application is above "admin" in INSTALLED_APPS.
Looks like this in German locale:
A: <a href="{% url opts|admin_urlname:'changelist' %}"><input type="button" name="Cancel" value="Cancel"></a>
You can this line anywhere inside admin/submit_line.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Nested html dl dt dd I want to check my thinking. I need to create HTML code for the UI design below and I have used nested dls in my markup. Is this semantically valid? If not, how else should I implement this design in HTML?
UI design
<dl>
<dt>Section one</dt>
<dd>
<dl>
<dt>Sub-Section one</dt>
<dd>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis justo justo, aliquam vel imperdiet a, semper sed felis. Nunc nec odio non massa pellentesque blandit et in velit. Proin massa libero, pulvinar at consectetur ut, ullamcorper id ipsum. Mauris in lorem ligula. </dd>
<dt>Sub-Section two</dt>
<dd>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis justo justo, aliquam vel imperdiet a, semper sed felis. Nunc nec odio non massa pellentesque blandit et in velit. Proin massa libero, pulvinar at consectetur ut, ullamcorper id ipsum. Mauris in lorem ligula. </dd>
<dt>Sub-Section three</dt>
<dd>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis justo justo, aliquam vel imperdiet a, semper sed felis. Nunc nec odio non massa pellentesque blandit et in velit. Proin massa libero, pulvinar at consectetur ut, ullamcorper id ipsum. Mauris in lorem ligula. </dd>
<dt>Sub-Section four</dt>
<dd>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis justo justo, aliquam vel imperdiet a, semper sed felis. Nunc nec odio non massa pellentesque blandit et in velit. Proin massa libero, pulvinar at consectetur ut, ullamcorper id ipsum. Mauris in lorem ligula. </dd>
<dt>Sub-Section five</dt>
<dd>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis justo justo, aliquam vel imperdiet a, semper sed felis. Nunc nec odio non massa pellentesque blandit et in velit. Proin massa libero, pulvinar at consectetur ut, ullamcorper id ipsum. Mauris in lorem ligula. </dd>
</dl>
</dd>
<dt>Section two</dt>
<dd>etc..</dd>
<dt>Section three</dt>
<dd>etc..</dd>
<dt>Section four</dt>
<dd>etc..</dd>
</dl>
A: I would probably have used nested unordered lists using h* tags for the section titles, but your DL use seems fine. People debate constantly about what is the proper use of DLs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Not sure what this line does (or (parse-integer (prompt-read "Rating") :junk-allowed t) 0)
This line confuses me quite a bit. the full program is here if you need it to follow: http://paste.lisp.org/display/124929
'Parse-integer' will turn a string into and integer right? if possible. And ':junk-allowed t' makes it accept junk strings somehow right?
Not sure what the 'or' and the 0 at the end are though.
Thanks.
A: or goes through the forms passed to it, evaluates them in order until it finds one that does not evaluate to nil, and returns that result. So this will return the result of parse-integer if that call succeeds in parsing an integer, or 0 if not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bash eval inside quotes I have a bash script which takes one parameter and does something like this:
ssh -t someserver "setenv DISPLAY $1; /usr/bin/someprogram"
How can I force bash to substitute in the $1 instead of passing the literal characters "$1" as the display variable?
A: Edit Are you aware of
ssh -X ...
ssh -Y ...
which already support X forwarding out of the box? Also look at
xhost +
in case you need to increase permissions to 'guests'.
If you want to forward non-standard X display address, you could always use
DISPLAY=localhost:3 ssh -XCt user@remote xterm
Bonus: to make ssh background after authentication, add '-f'
What locally? That should already work as shown. Remotely? escape the $: \$
However, I'm not sure where the command would be taking it's arguments ($1) from
A: Based on your comment on sehe's answer, it sounds like you just want the remote command to use the local X display — so that the program is running on your remote server (someserver) but being displayed on the machine you ran the ssh command on.
This can be done by just passing -X, e.g.
ssh -X someserver /usr/bin/someprogram
For some reason, this doesn't work with a few programs, for example evince. I'm not really sure why. I'm pretty sure that evince is the only app I've had trouble forwarding back over an SSH connection.
If this isn't what you're aiming to do, please explain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Maven Error : Could not resolve dependencies for project I am new to Maven . I am running Maven POM.xml file From Eclipse IDE , There was a error occurred in console , i even tried with mvn install -X , but of no use .
Please see the stack trace
Failed to execute goal on project bayer-ws: Could not resolve dependencies for project com.tataaig:bayer-ws:war:1.0:
Failed to collect dependencies for [com.tataaig:bayer-util:jar:1.0 (compile), com.tataaig:bayer-model:jar:1.0 (compile), com.tataaig:bayer-samples:jar:1.0 (compile), com.tataaig:bayer-mw:jar:1.0 (compile), com.tataaig:bayer-fixml:jar:1.0 (compile), cglib:cglib-nodep:jar:2.1_3 (runtime), jdom:jdom:jar:1.1 (compile), org.apache.ws.commons.schema:XmlSchema:jar:1.4.5 (runtime), javax.servlet:servlet-api:jar:2.5 (provided), junit:junit:jar:4.4 (test), org.easymock:easymockclassextension:jar:2.3 (test), org.easymock:easymock:jar:2.3 (test), org.apache.cxf:cxf-rt-bindings-http:jar:2.2.1 (compile), org.apache.cxf:cxf-rt-ws-security:jar:2.2.1 (compile), org.apache.derby:derby:jar:10.3.1.4 (test), org.springframework:spring-beans:jar:2.5.2 (compile), org.springframework:spring-context:jar:2.5.2 (compile), org.springframework:spring-core:jar:2.5.2 (compile), org.springframework:spring-web:jar:2.5.2 (compile), log4j:log4j:jar:1.2.14 (runtime), commons-logging:commons-logging:jar:1.1.1 (runtime), com.tataaig:middleware:jar:5.0.0 (compile), com.tataaig:PRO:jar:1.0.0 (compile), com.tataaig:legacy.backoffice:jar:1.0.0 (compile), hessian:hessian:jar:3.1.6 (compile), commons-httpclient:commons-httpclient:jar:3.1 (runtime), xstream:xstream:jar:1.2.2 (compile), bouncycastle:bcprov-jdk16:jar:140 (runtime), org.apache.ws.security:wss4j:jar:1.5.8 (compile), net.sf.ehcache:ehcache-core:jar:2.4.1 (runtime)]: Failed to read artifact descriptor for commons-logging:commons-logging:jar:99.1: Could not transfer artifact commons-logging:commons-logging:pom:99.1 from/to maven-central (http://repo1.maven.org/maven/): No connector available to access repository maven-central (http://repo1.maven.org/maven/) of type legacy using the available factories AsyncRepositoryConnectorFactory, WagonRepositoryConnectorFactory -> [Help 1]
Anybody please help me , i am badly struck .
A: Let me answer my questions so that may be useful to others, as i was successful with maven build now .
For installing Application jar files we must use mvn install -- path to jar file .
Please see the syntax
mvn install:install-file -Dfile=your-artifact-1.0.jar \
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: list google apps accounts How can I determine if a specific google account is a Google Apps account?
I have 2 accounts on my phone.
a normal Google acc and a Google Apps account
accountManager = AccountManager.get(getApplicationContext());
Account[] accounts = accountManager.getAccounts();
for ( int i = 0; i < accounts.length; i++ )
{
Log.d(TAG, accounts[i].name + " - " + accounts[i].type);
}
It prints "com.google" as type for both.
A: I was wondering too, but determine based on @gmail.com or @googlemail.com as many suggested isn't accountable. Through some entrances, users can actually register a Google Account using emails other than Gmail. Try this sign-up entrance: https://accounts.google.com/newaccount?hl=en
A: AFAIK account.name contains email, right?
Google account (aka gmail) email address contains @gmail.com or @googlemail.com. Google Apps account always have custom domains. This way you can distinguish them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Enum property mapped to a varchar column on EF June 2011 CTP I'm trying to create a model with Code First approach.
I wanted to know if it's possible to map an Enum property to a varchar column in the database.
I know you can do it with byte, small, int, long.
This is a project for an old database and it has many columns with constraints. It would be nice to have this structure mapped to enum values.
Thanks
A: No it is not possible. Enum in EF June 2011 CTP can work only with enums supported by .NET platform itself and .NET supports enum only on integral types except char. That means only byte, sbyte, short, ushort, int, uint, long, or ulong are supported. The same is true about mapping in EF. EF can map enum only to column with integer type.
You can check more about that here. It also contains description of internal types supported by EF for enum:
Similarly to CLR enums the EF enums have underlying type which is one
of Edm.SByte, Edm.Byte, Edm.Int16, Edm.Int32 or Edm.Int64 with
Edm.Int32 being the default underlying type if none has been
specified.
You can also check my comment under that article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set a timer but don't run repeatly In my case I created a object and planned to release it after 20 minutes(accuracy is not necessary). I know by using java.util.Timer I can create a timer.But I just want it run once. After that,the timer should stop and been released too.
Is there any way just like setTimeOut() in javascript?
Thanks.
A: int numberOfMillisecondsInTheFuture = 10000; // 10 sec
Date timeToRun = new Date(System.currentTimeMillis()+numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// Task here ...
}
}, timeToRun);
Modify above so that you can schedule a job 20 minutes in future.
A: Use Timer::schedule(TimerTask, long) or look into the ScheduledThreadPoolExecutor or ScheduledExecutorService classes.
A: You can start a new thread and call sleep with the number of milliseconds to wait, then execute your instructions (on either thread). See http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Thread.html for reference, and look at the various online thread tutorials if you need more help.
A: java.util.Timer has a cancel method in it:
http://download.oracle.com/javase/6/docs/api/java/util/Timer.html#cancel%28%29
However, as far as I know, in timer if you do not specify a period, scheduled task will run only once.
A: package com.stevej;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class StackOverflowMain {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Runnable myAction = new Runnable() {
@Override
public void run() {
System.out.println("Hello (2 minutes into the future)");
}
};
executor.schedule(myAction, 2, TimeUnit.MINUTES);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do I get a "The result of a query cannot be enumerated more than once" when I get the Count() before enumerating the result? This my code. Simplified for readability
var query = from p in people select p;
// here is the point that probably causes the issue
ObjectResult<int> idsThatMatch = getIdsThatMatchFullTextSearch("andre");
query = from p in query where idsThatMatch.Contains(p.id) select p;
var count = query.Count();
query = query.OrderBy(p => p.id);
var pessoas = query.Skip(90).Take(30).ToList();
I need to read the count before skip/take to get the total amount of records before paging. The count works fine. But at the last line of my excerpt it triggers the exception
The result of a query cannot be enumerated more than once
Why? The count isn't supposed to enumerate anything by the way. And how can I solve that? Thank you
EDIT
People thought I was using stored procedures but I'm not. Actually I'm using a "select in". The code is bellow the comment.
EDIT 2
I just tested the above code without the "select in" part and it works fine
EDIT 3
Using this line works:
ObjectResult<int> idsThatMatch = (getIdsThatMatchFullTextSearch("andre");
query = from p in query where idsThatMatch.Contains(p.id) select p).ToArray();
Thank you
A: The problem is this line:
ObjectResult<int> idsThatMatch = getIdsThatMatchFullTextSearch("andre");
This returns ObjectResult not ObjectQuery or IQueryable. Result can be iterated only once. Once you execute your first query with Count you cannot use result anymore and your second query execution will fail because it will try to iterate result again.
ObjectResult is not processed on database side - it is the result of executed ObjectQuery and one execution can have only one enumeration of result set. It is like cursor to iterate through result set in your application.
A: Your people may be coming from a stored procedure mapped in Entity Framework model.
In that case you can not do filtering or skipping on it since the result has already been evaluated.
The result of a query cannot be enumerated more than once
The query results cannot be enumerated more than once?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do you check whether a Window is Maximised in Gtk? I want to give a window a specific property only when it is maximised and change it back when the maximised state ends. I am using Gtk# , but all GTK binding answers are welcome. What I am looking for is something like this (pseudocode):
OnMaximise += new Mhandler();
Mhandler(){ property = true;}
or:
Resize += delegate() {
if (isMaximised()) property=true; else property = false;};
or the C way:
gtk_window_on_maximise(GTK_WINDOW(mwin),onmax);
void onmax()
{
if (gtk_window_is_max(GTK_WINDOW(mwin))
gtk_window_set_property(GTK_WINDOW(mwin),true);
else gtk_window_set_property(GTK_WINDOW(mwin),false);
}
Any suggestions? Thanks
A: Set up the "window-state-event" signal when you create the window and watch for it. See http://developer.gnome.org/gtk/2.24/GtkWindow.html#gtk-window-maximize
and also
http://developer.gnome.org/gtk/2.24/GtkWidget.html#GtkWidget-window-state-event
Your onmax() would be the handler that would be called when GDK_WINDOW_STATE_MAXIMIZED becomes TRUE.
See http://developer.gnome.org/gdk/stable/gdk-Events.html#GDK-STRUCTURE-MASK:CAPS
and http://developer.gnome.org/gdk/stable/gdk-Event-Structures.html#GdkEventWindowState
and http://developer.gnome.org/gdk/stable/gdk-Event-Structures.html#GdkWindowState
Sorry, can't help much more than that without actually writing code. Google might have some good examples and then again might not. What documentation there is actually is for people who can already do GTK+ signals.
EDIT: I do GTK+ in C and the pages I cited are for C.
EDIT #2: The handler (callback) is executed whenever the signal is sent and the signal data is what matters. I would probably do a switch:case on each signal data value that interested me and possibly set a flag for other functions to read later on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Datagrid, first column to be left-justified, the rest be centered I have a DataGrid, that references another style that sets the property for the ColumnHeaderStyle to be centered.
<Style x:Key="CenterDataGridStyle" TargetType="{x:Type DataGrid}">
<Style.Setters>
<Setter Property="ColumnHeaderStyle" Value="{StaticResource CenterColumnHeaderStyle}"/>
</Style.Setters>
</Style>
Is there a way in the code behind to make the DataGrid have its first column to be left-justified instead of center? I got so far as:
dtGridReads.Columns[0].
then I'm not sure if there was a property I could set for this or not? Thanks.
A: There is not a single property like HorizontalAlignment that you can set on the column, instead you'll need to construct a Style similar to what you have in XAML, and apply it to the column.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I diff streams in ClearCase? Can I perform a diff between the latest versions of the files/directories (or perhaps the latest baselines) in two different streams that may reside in two different projects?
The two projects are basically branches of the same software and I need to diff the source tree between the branches.
A: You can do a cleartool diffbl in order two diff two baselines produced on those two stream.
And that will only work if there is a common ancestor found in the history of baselines of said streams.
But for the latest versions of a stream (as displayed by their respective associated view)... the simpler way remain to use any thirdparty diff tool (winmerge, Beyond Compare, KDiff3, ...) and diff the view contents.
Creating baselines just for a punctual comparison isn't worth the effort and the added metadata created just for that.
Two snapshot views on two streams will be enough to have a stable content (as opposed to a dynamic view whose content might change dynamically at any moment), and you can use any diff tools on those snapshot contents.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ruby : if i declare a variable in a method does another method in the same class know it exists? If i have a method called roll (as in a dice) and it has a variable called number.
can another method in the same class called stats use that variable in it ??
A: You mean like this?
class Die
def roll
@number = 5
end
def stats
puts @number
end
end
d = Die.new
d.roll
d.stats # prints 5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Should you hold a HTTP request while the server performs a time consuming operation? Or let the request go? Lets say an operation could take 2 to 10 minutes on the server to perform, for example to update an index which is time consuming.
Would you perform the operation while holding the request? ie not sending a HTTP Response until the operation has finished? And if the client/browser drops the request, just continue with the operation anyway?
What is the alternative? To kick-off the operation, and response with "long-time operation kicked off" ? What if the operation fails mid-way how would the client know? Maintain a server-side "status" of the operation?
Thanks
A: You might also use a chunked response. First, push a chunk with some code that would display the “please wait” screen, flush the response and start the work. Then you can either push and flush chunks with periodical progress updates or just push one at the end with a “completed” information. Obviously you can employ JavaScript to get a nice UI.
(The above does not apply if you're using WSGI as the first WSGI specification is written in a way that blocks using responses of unknown length so using chunked responses there is impossible.)
A: For requests that you know will take a long time (more than a few seconds) to process, you must assume at minimum that the connection may be forcibly severed by a firewall.
I would say you should implement a queue system on the backend. The request to perform the operation becomes a request to queue the operation. When the operation is actually completed, you can either wait for the client to poll, or proactively notify them somehow. For a browser, you'll pretty much have to either poll or send an e-mail.
A:
Would you perform the operation while holding the request? ie not sending a HTTP Response until the operation has finished?
What do your users expect?
And if the client/browser drops the request, just continue with the operation anyway?
What do your users expect?
What is the alternative?
To kick-off the operation, and response with "long-time operation kicked off" ?
What else could you possibly do? Ignore the request? Pretend it didn't happen? Obviously, you inform them.
What if the operation fails mid-way how would the client know?
Maintain a server-side "status" of the operation?
What's the alternative to that? Magic? Intuition? Obviously, you must retain status. And display the status.
Read up on celery.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sub-Domain Masking via htaccess EDITED
I set-up a wildcard subdomain dns zone on my server and would like to have each subdomain load the contents of the /users/ direcotry using .htaccess and mod-rewrite.
I would like the URL to remain unaltered in the browser bar so that it shows:
http://username.domian.com/../../
while showing the contents of:
http://www.domain.com/users/username/../../
Additionally, I would like to redirect (change the URL) to the subdomain version if the www version of the URL is accessed.
I'm not overly familiar with mod-rewrite rules and any help would be greatly appreciated!
Thank you.
A: Try this one:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$
RewriteCond %1 !=www
RewriteRule ^(.*)$ http://www.domain.com/users/%1/$1 [R=302,L]
If user will visit tom.domain.com/directory1/directory2/directory3/file.html he will be redirected (URL will be changed in browser) to www.domain.com/users/tom/directory1/directory2/directory3/file.html.
If that is not what you really after (as I'm a bit confused about this "masked" concept of yours) then please explain your requirements better so I can adjust the rule.
UPDATE:
To keep URL unchanged in browser:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/users/
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$
RewriteCond %1 !=www
RewriteRule ^(.*)$ /users/%1/$1 [L]
There one problem though: if directory1 will be called users (e.g. tom.domain.com/users/directory2/directory3/file.html), then this will not work -- that is the price you have pay for rewriting. Solution: rename users to something unique (e.g. users_dir_123_abc etc -- www.domain.com/users_dir_123_abc/tom/users/directory2/directory3/file.html).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is faster jQuery.load or jQuery.ajax() when loading HTML from PHP file? I have PHP file named "content.php" prepared for both kind of requests, just as an example:
<?php
// Id params passed via GET method
$get = $_GET['param'];
switch ($get) {
case "param_value":
?>
<div data-param="<?php echo $get; ?>">
// My HTML content here
</div>
<?php
break;
case default:
break;
}
// Id params passed via POST method
$post = $_POST['param'];
if ($post != "") {
$data['output'] = '
<div data-param="<?php echo $get; ?>">
// My HTML content here
</div>
';
echo json_encode($data);
}
?>
And than I have Javascript file, from which I am making an AJAX call to PHP:
var oWrapper = jQuery("#wrapper"),
// Loading HTML via jQuery.load() function
sParams = jQuery.param({ param: "value" });
oWrapper.load("/content.php?" + sParams, function () {
console.log("content loaded via load()");
});
// Loading HTML via jQuery.ajax() function
jQuery.ajax({
type: "POST",
dataType: "json",
url: "/content.php",
cache: false,
data: { "param": "value" },
success: function (data) {
oWrapper.html(data.output);
console.log("content loaded via ajax()");
}
});
Which way is faster?
Besides the speed of requests and returns, I wish to know which way is better for security of the app?!
A: Both ways do pretty much exactly the same thing.
Internally, $(selector).load() uses $.ajax() to get the data, then $(selector).html() to set the html of the selected element to the response of the $.ajax() call.
If you are loading html into an element, use $(selector).load() because it is more readable. One is just as secure and as fast as the other.
Note: Internally jQuery now uses $.parseHTML() rather than $(selector).html() to convert the string to html. This doesn't really change anything though.
A: I don't know the specifics but I dont't think there is a difference in security. load() and get() are "optimized" versions of ajax() so they will always be faster and better but I don't you or your visitors will ever feel the difference in a query like yours
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: call to undefined method php error I have a class called CHCID which has the two functions inside it:
public function UpdateDeliveryAddress($orderNumber, $deliveryaddress) {
$sql = "UPDATE `CIDOrders`
SET `DeliveryAddress` = '" . mysql_real_escape_string($deliveryaddress) . "'
WHERE `CIDOrderNumber` = " . $orderNumber . ";";
mysql_select_db(DB_DATABASE_NAME, $this->conn);
return mysql_query($sql, $this->conn);
}
public function UpdateInvoiceAddress($orderNumber, $invoiceAddress) {
$sql = "UPDATE `CIDOrders`
SET `InvoiceAddress` = '" . mysql_real_escape_string($invoiceaddress) . "'
WHERE `CIDOrderNumber` = " . $orderNumber . ";";
mysql_select_db(DB_DATABASE_NAME, $this->conn);
return mysql_query($sql, $this->conn);
}
I call this class in a page called createorder.php as follow:
// Add a new delivery address to the order
$cid->UpdateDeliveryAddress($_POST['orderNumber'], $_POST['deliveryaddress']);
// Add invoice address to the order
$cid->UpdateInvoiceAddress($_POST['orderNumber'], $_POST['invoiceaddress']);
I get the following error :
PHP Fatal error: Call to undefined method CHCID::UpdateDeliveryAddress()
Can anyone help.
Many thanks
Code initialising the class.
require_once $CID_INCLUDE_PATH . "/cid.php";
$cid = new CHCID();
Constructing class
class CHCID {
var $conn;
// Constructor, connect to the database
public function __construct() {
require_once "/var/www/reporting/settings.php";
if(!$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)) die(mysql_error());
if(!mysql_select_db(DB_DATABASE_NAME, $this->conn)) die(mysql_error());
}
A: If those function were really in your class, this would never happen.
Check $CID_INCLUDE_PATH, you're probably loading a different file, maybe an older version of the class. Also enable warnings, notices...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting "Error Code 207" only after deploying WCF services I have created a set of WCF services that use StructureMap by following this tutorial. Everything has been working as expected, but it appears that now that I have deployed it to the server, it fails with "Error Code 207: Internal exception while creating Instance".
This error is thrown when my MVC controller method is called via JavaScript to get some data from the service AJAX style.
What is odd is that I can't even hit the first line in the web method that uses the client for the WCF service.
Any ideas on where I can start with this problem?
Thanks.
A: Since the error occured when you deployed to the server and the first line of your code is not being hit. It is probably a rights issue on the server.
Check:
*
*Security settings in IIS
*Security settings in web.config
*Are you calling a service on a different server than is serving the page? In this case it could be that cross site scripting is being blocked.
A: I just got the same error on production.
Turned out that the instance structuremap was creating was throwing an exception
within the constructor due to missing configuration app settings.
So I would advise you check the code in your constructor for any potential errors.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I store data for payment processing on a confirmation page? I am adding a "confirm your payment" page to my new ASP.NET MVC 3 project. After validating the input, I then display a confirm page to allow the user to make sure they entered everything correctly. My next problem is how do I "store" the data entered so that I can process the payment after they click "Confirm". Obviously, I don't want to create hidden fields with the full credit card number.
I am using sessions for our shopping cart, but does that encrypt the data so that a credit card number could not be hacked? What is the recommended approach on this? The searches I have done on Google hasn't really turned up much.
I am display the information what they entered on the previous page (to confirm the data entry). Properly masking the credit card number of course.
Payment Information
Name on Credit Card: Name
Credit Card Number: XXXX XXXX XXXX 1111
Expiration Date: 10/2011
Card Verification Code: 100
Total to be Charged: $50.86
All numbers on this post are fake of course.
Here is the code I am using so far.
//
// POST: /Checkout/AddressAndPayment
[HttpPost]
public ActionResult AddressAndPayment(Cart cart, PaymentForm formData)
{
if (cart.Items.Count() == 0)
{
ModelState.AddModelError("", "Sorry your cart is empty!");
}
if (ModelState.IsValid)
{
var viewModel = new AddressPaymentViewModel
{
FormData = formData,
Cart = cart
};
return View("Confirm", viewModel);
}
else
{
var viewModel = new AddressPaymentViewModel
{
FormData = formData,
Cart = cart,
States = States.GetStatesDDL(),
CreditCardTypes = CreditCartTypes.GetCreditCardTypesDDL()
};
return View(viewModel);
}
}
//
// GET: /Checkout/Confirm
public ViewResult Confirm()
{
return View();
}
So from there, when I run
//
// POST: /Checkout/Confirm
[HttpPost]
public ViewResult Confirm(Cart cart, PaymentForm formData)
{
return View();
}
I need to still have the form data to send to the credit card processor.
Is there a better way to do this? What is the "best practice"?
Another method I have seen is to do a "PreAuth" and "PostAuth" with the credit card processor and not store that data period, just an order id.
A: After researching our options. We decided to do a Pre Authorization transaction. So all we have to store is the Order Id from the processor, then upon confirming the details, we will send a Post Authorization transaction to actually post the payment.
A: You could store the Model into a Session Variable before loading up the confirmation page. Remember that Session Variables are not necessarily only variables, but can be an entire object.
Session["submitted_data"] = util.Encrypt(Model); //Util.Encrypt would be your custom Encryption lib
EDIT
Oops, missed the CC credentials bit.
This is a little more tricky. You can either ask for credit card credentials AFTER the order confirmation page, OR you can create a Temp_Confirmation table in your database. From there you would encrypt the CC credentials, store it in the DB until after they go past the confirmation page (store the table GUID in a hidden field), and retrieve it on the other end. Just make sure to Encrypt and Decrypt, and also delete the record once you're done with it.
A: Don't actually show the credit card number on that page. Just show the last four digits so they can verify they are using the right credit card.
I know you probably want to display it to verify they didn't type it incorrectly. Besides the fact that few users will ever double check the entire credit card number, you can catch the majority of potential errors by validating the credit card number against the Luhn Algorithm. If the credit card number is incorrectly entered the chances of it getting past the Luhn algorithm is very, very small. Then you can request them to re-enter the card number before getting to the summary page.
A: Conceptually you just need to "save" the information server-side for processing later. There is no reason to send this information back down to the client as hidden fields, cookies, parms, or anything else. Now, given you need to save it server-side you have a couple of options:
1) Session state - advantage, it's there now, it's cleaned up automatically, and (maybe) it's memory-only. Disadvantages, you only have one of them per session. With the advent of tabbed browsing we've found that storing anything transactional in session-state is problematic.
2) Save in DB - advantage, it's simple to save and simple to retrieve. You can retrieve it in the same session, or in another session, or even from another machine so long as you have the correct keys. Disadvantages, you're persisting the info and you need to clean it up.
I'd select option 2. Just write the info into a table and then read it back when you need it. You should of course encrypt the CC number, but that's a trivial task.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is instantiating XmlDocument expensive? I have the following function:
public static XmlNode GetXMLNodeFromString(string strXML)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXML);
return doc.DocumentElement;
}
which can be called a million times in a line of code that gets returned from a database call:
while (reader.Read())
{
myXMLList.Add(GetXMLNodeFromString((string)reader["GMLString"]));
}
Is there a better way than to keep instantiating the xmlDocument for every row? Or is it fine to do so?
I don't want to this:
XmlDocument doc = new XmlDocument();
while (reader.Read())
{
myXMLList.Add(doc, GetXMLNodeFromString((string)reader["GMLString"]));
}
because in all reality there is a tree of functions that i would have to add it to. Not just GetXMLNodeFromString.
Can i do something like this:
public static class Common
{
public static XmlDocument doc = new XmlDocument();
public static XmlNode GetXMLNodeFromString(string strXML)
{
doc.LoadXml(strXML);
return doc.DocumentElement;
}
}
What should i do?
A: I recommend XmlReader if you're having performance problems, as it allows you to parse the XML as it comes in, rather than pre-parsing it and creating an in-memory object model that you're going to have to go back through again anyway. It can require restructuring your code a bit, however, as it gives you sequential (as opposed to random) access. If you don't need random access, it's a good choice.
A: We have found XmlDocument sluggish, but only because we're thrashing it beyond the scope of its design. Instantiating one for every table row however will cause you massive problems. It's a heavyweight class designed for in-place manipulation - which it is very good at - and if you're creating and destroying them faster than a human being could count in their head, you're overworking it.
A: I have experienced performance issue that You might get into. There was foreach loop that used XmlDocument to read xml from files. XmlDocument was instantiated outside of loop. After processing 300 000 files, performance was constantly and progressivly degrading. Putting XmlDocument instantiation inside loop solved the problem. I would never expect this behaviour, but i've measured it and seen it with my own eyes.
Please note that You have to test your own case. Consider:
*
*that behaviour might depend on xml structure
*maybe You can use XmlReader
*experience i wrote about is on .NET 2.0
I suggest rewriting your code to use XmlReader, because XmlDocument is meant to be used for manipulation. You probably don't need to read milions of rows with XmlDocument and then process 0 or just a few XmlDocuments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: emacs parenthethes matching wrong I wrote a small major-mode for a C++-like language(so I am using the C++ syntax table):
(setq tacc-mode-syntax-table c++-mode-syntax-table)
however, it seems that the character "'" in comments before baces can mess up the brace matching:
Foo {
Bar {
//This doesn't work - The } are not matched with the {
}
}
The stripped-down mode that still causes this problem is:
(setq tacc-mode-syntax-table c++-mode-syntax-table)
(setq tacc-font-lock-keywords c++-font-lock-keywords)
(define-derived-mode tacc-mode nil "Tacc"
"tacc"
(set (make-local-variable 'font-lock-defaults)
'(tacc-font-lock-keywords nil nil nil nil)))
(provide 'tacc)
As far as I'm aware, the syntax table should be controlling this - how should I fix this?
The results of desribe-syntax in the buffer are:
C-j > b which means: endcomment (comment style b)
RET > b which means: endcomment (comment style b)
% .. & . which means: punctuation
' " which means: string
* . 23 which means: punctuation,
is the second character of a comment-start sequence,
is the first character of a comment-end sequence
+ . which means: punctuation
- . which means: punctuation
/ . 124b which means: punctuation,
is the first character of a comment-start sequence,
is the second character of a comment-start sequence,
is the second character of a comment-end sequence (comment style b)
< .. > . which means: punctuation
\ \ which means: escape
_ _ which means: symbol
| . which means: punctuation
. which means: punctuation
The parent syntax table is:
C-@ .. C-h . which means: punctuation
TAB .. C-j which means: whitespace
C-k . which means: punctuation
C-l .. RET which means: whitespace
C-n .. C-_ . which means: punctuation
SPC which means: whitespace
! . which means: punctuation
" " which means: string
# . which means: punctuation
$ .. % w which means: word
& _ which means: symbol
' . which means: punctuation
( () which means: open, matches )
) )( which means: close, matches (
* .. + _ which means: symbol
, . which means: punctuation
- _ which means: symbol
. . which means: punctuation
/ _ which means: symbol
0 .. 9 w which means: word
: .. ; . which means: punctuation
< .. > _ which means: symbol
? .. @ . which means: punctuation
A .. Z w which means: word
[ (] which means: open, matches ]
\ \ which means: escape
] )[ which means: close, matches [
^ . which means: punctuation
_ _ which means: symbol
` . which means: punctuation
a .. z w which means: word
{ (} which means: open, matches }
| _ which means: symbol
} ){ which means: close, matches {
~ .. DEL . which means: punctuation
.. w which means: word
A: parse-sexp dives into comments unless parse-sexp-ignore-comments is true. C++ mode sets parse-sexp-ignore-comments to true, as do many other programming modes.
Additionally, you need to declare the use of the syntax table (define-derived-mode doesn't use it implicitly).
(define-derived-mode tacc-mode nil "Tacc"
"tacc"
:syntax-table tacc-mode-syntax-table
(set (make-local-variable 'parse-sexp-ignore-comments) t)
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: add prebuild object files I'm building static library with ndk-4 and assembler coredumps on some of my assembly files. I used codesourcery assembler to create objects for these files. Now, I have no clue how to add these prebuild object files to the project. I tried to check inside their makefiles, but I don't see anything. I tried to add them to LOCAL_OBJECTS
LOCAL_OBJECTS += $(NEON_LOCAL_OBJECTS)
but it doesn't work. The value LOCAL_OBJECTS is reset to nothing inside build/core/build-binary.mk
Most likely I'd be able to avoid that problem by swithing NDK, or build workstation (I'm using windows), but for now I only want to fix that simple problem by adding preassembled objects to the static library.
If that's impossible to do, maybe somebody can say what kind of rule I could add so that after my static library is build my rule kick-in and adds my preassembled files to the target lib?
Anybody?
A: I have run into the same problem. After much googling I may have just stumbled onto the answer, although I haven't had the time to try it out yet. This is the Google Groups question where a similar question is posted, the poster is advised to archive the object files into a library (e.g. libfoo.a) and link that. Here is an article I found on archiving the object files into a library. Hope this is helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jquery find element by specific class when element has multiple classes So I am working on something that wasn't well thought out in the build from the backend team. That leaves me with a document full of divs.
What I am doing is rolling back from the element I need to click on, get the parent container then find an element within the parent which has class="alert-box warn", class="alert-box dead", etc... Essentially, I'm trying to use multiple class selectors on each element. When I try to find just alert-box it doesn't seem to be working right. I'm assuming because it has warn,dead, ``fine, etc...
How can I find just alert-box* or equivalent to a wildcard concept?
A: You can combine selectors like this
$(".alert-box.warn, .alert-box.dead");
Or if you want a wildcard use the attribute-contains selector
$("[class*='alert-box']");
Note: Preferably you would know the element type or tag when using the selectors above. Knowing the tag can make the selector more efficient.
$("div.alert-box.warn, div.alert-box.dead");
$("div[class*='alert-box']");
A: var divs = $("div[class*='alert-box']");
A: An element can have any number of classNames, however, it can only have one class attribute; only the first one will be read by jQuery.
Using the code you posted, $(".alert-box.warn") will work but $(".alert-box.dead") will not.
A: You can select elements with multiple classes like so:
$("element.firstClass.anotherClass");
Simply chain the next class onto the first one, without a space (spaces mean "children of").
A: you are looking for http://api.jquery.com/hasClass/
<div id="mydiv" class="foo bar"></div>
$('#mydiv').hasClass('foo') //returns ture
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: Detect mouse over bezier or quadratic curve
Possible Duplicate:
Detect mouseover of certain points within an HTML canvas?
I have some Bezier and/or quadratic curves drawn on an HTML5 canvas.
How can I detect when the mouse is over a curve and select it when the mouse is clicked?
Is there a quick way of checking if the mouse pointer lies over a curve?
I'm using the JavaScript InfoVis Toolkit and JQuery.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I move to the next song using a MVVM mediaelement I'm learning C#/WPF/MVVM by building a simple media player. I am using ICollectionView in the MainViewModel for the playlist. I built a separate usercontrol for the mediaelement with some code-behind to handle the volume, position, timeline (http://www.codeproject.com/KB/smart/RSSVideoReader.aspx). I know one of the goals of MVVM is to eliminate code-behind, but the WPF mediaelement is unique. I am now stuck trying to figure how to get the code-behind mediaelement's MediaEnded event to tell the MainViewModel's ICollectionView to MoveCurrentToNext.
This code fails:
MainViewModel
public void GoNext()
{
this.collectionView.MoveCurrentToNext();
}
MyMediaElement.xaml.cs (Code behind)
private void mPlayDefault_MediaEnded(object sender, RoutedEventArgs e)
{
mPlayDefault.Stop();
this.GoNext();
}
How do I get the MainViewModel to react to MyMediaElement's event?
Thank You
A: This is the best I could come up with:
inside of the ViewModel:
public ICommand PlayCommand
{
get
{
if (_playCommand == null)
_playCommand = new RelayCommand(player => this.play(player), param => this.canPlay);
return _playCommand;
}
}
void play(object player)
{
if (_player == null)
{
_player = (MediaElement)player;
_player.MediaEnded += new RoutedEventHandler((s, e) =>
{
if (canPlayNext)
playNext();
});
}
_player.Play();
}
...but I am still open for other ideas.
A: Daniel Pratt was correct (See Comments). Using Interaction.Triggers worked as I had hoped. I ran into a problem with the expressions dll and was totally frustrated. Downloading the dll directly from codeplex and unblocking it solved the problem. Many thanks to Daniel and Stackoverflow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Passing NULL for array parameter in C/C++ void DoSomeThing(CHAR parm[])
{
}
int main()
{
DoSomeThing(NULL);
}
Is the passing NULL for array parameter allowed in C/C++?
A: What you cannot do is pass an array by value. The signature of the function
void f( char array[] );
is transformed into:
void f( char *array );
and you can always pass NULL as argument to a function taking a pointer.
You can however pass an array by reference in C++, and in that case you will not be able to pass a NULL pointer (or any other pointer):
void g( char (&array)[ 10 ] );
Note that the size of the array is part of the type, and thus part of the signature, which means that g will only accept lvalue-expressions of type array of 10 characters
A: Short answer is yes, you can pass NULL in this instance (at least for C, and I think the same is true for C++).
There are two reasons for this. First, in the context of a function parameter declaration, the declarations T a[] and T a[N] are synonymous with T *a; IOW, despite the array notation, a is declared as a pointer to T, rather than an array of T. From the C language standard:
6.7.5.3 Function declarators (including prototypes)
...
7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to
type’’, where the type qualifiers (if any) are those specified within the [ and ] of the
array type derivation. If the keyword static also appears within the [ and ] of the
array type derivation, then for each call to the function, the value of the corresponding
actual argument shall provide access to the first element of an array with at least as many
elements as specified by the size expression.
The second reason is that when an expression of array type appears in most contexts (such as in a function call), the type of that expression is implicitly converted ("decays") to a pointer type, so what actually gets passed to the function is a pointer value, not an array:
6.3.2.1 Lvalues, arrays, and function designators
...
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a
string literal used to initialize an array, an expression that has type ‘‘array of type’’ is
converted to an expression with type ‘‘pointer to type’’ that points to the initial element of
the array object and is not an lvalue. If the array object has register storage class, the
behavior is undefined.
A: First off, what you're passing to the function is a pointer and not an array. The array notation used for the parm parameter is just syntactic sugar for CHAR *parm.
So yes, you can pass a NULL pointer.
A: The only issue would be if DoSomeThing were overloaded, in which case the compiler might not be able to distinguish which function to call. But casting to the appropriate type would theoretically fix that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MouseEnter and MouseLeave I have a user control in WPF. I have a button control within the control. I want the control to fade in and out when the mouse enters and leaves the control. The problem is when the mouse enters the button and leaves the control, it fades. Below is the code.
<UserControl x:Class="WpfPresentationEditor.PresentationWindowControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="68" d:DesignWidth="793">
<UserControl.Resources>
<Storyboard x:Key="onMouseEnter">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="LayoutRoot">
<EasingDoubleKeyFrame KeyTime="0:0:0" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<BackEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="onMouseLeave">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="LayoutRoot">
<EasingDoubleKeyFrame KeyTime="0:0:3" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<BackEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<UserControl.Triggers>
<EventTrigger RoutedEvent="Mouse.MouseEnter">
<BeginStoryboard x:Name="onMouseEnter_BeginStoryBoard" Storyboard="{StaticResource onMouseEnter}"/>
</EventTrigger>
<EventTrigger RoutedEvent="Mouse.MouseLeave">
<BeginStoryboard x:Name="onMouseLeave_BeginStoryBoard" Storyboard="{StaticResource onMouseLeave}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UserControl.Loaded">
<BeginStoryboard Storyboard="{StaticResource onMouseLeave}" />
</EventTrigger>
</UserControl.Triggers>
<Grid x:Name="LayoutRoot" Opacity=".5">
<Canvas HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Transparent"></Canvas>
<Button Click="btnClose_Click" Height="44" HorizontalAlignment="Left" Name="btnClose" VerticalAlignment="Center" Width="44" Margin="12,12,0,12">
<Button.Background>
<ImageBrush ImageSource="images/exit.png" />
</Button.Background>
</Button>
</Grid>
A: This is what I ended up doing to make this work as desired.
I changed the RoutedEvent to UserControl.MouseEnter rather than Mouse.MouseEnter.
Then I created my own user control and created an Image button like this http://blogs.msdn.com/b/knom/archive/2007/10/31/wpf-control-development-3-ways-to-build-an-imagebutton.aspx.
So my altered code now looks like this....
<UserControl x:Class="WpfPresentationEditor.PresentationWindowControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="68" d:DesignWidth="793" xmlns:my="clr-namespace:WpfPresentationEditor">
<UserControl.Resources>
<ImageBrush x:Key="exitImage" ImageSource="images/exit.png"/>
<!--These are the story boards for the control-->
<Storyboard x:Key="onMouseEnter">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="LayoutRoot">
<EasingDoubleKeyFrame KeyTime="0:0:0" Value="1">
<EasingDoubleKeyFrame.EasingFunction>
<BackEase EasingMode="EaseIn"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
<Storyboard x:Key="onMouseLeave">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="LayoutRoot">
<EasingDoubleKeyFrame KeyTime="0:0:3" Value="0">
<EasingDoubleKeyFrame.EasingFunction>
<BackEase EasingMode="EaseOut"/>
</EasingDoubleKeyFrame.EasingFunction>
</EasingDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<UserControl.Triggers>
<EventTrigger RoutedEvent="UserControl.MouseEnter">
<BeginStoryboard x:Name="onMouseEnter_BeginStoryBoard" Storyboard="{StaticResource onMouseEnter}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UserControl.MouseLeave">
<BeginStoryboard x:Name="onMouseLeave_BeginStoryBoard" Storyboard="{StaticResource onMouseLeave}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UserControl.Loaded">
<BeginStoryboard Storyboard="{StaticResource onMouseLeave}" />
</EventTrigger>
</UserControl.Triggers>
<StackPanel x:Name="LayoutRoot" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Orientation="Horizontal" Background="Black">
<my:ImageButtonControl ButtonBase.Click="btnClose_Click" x:Name="imageButtonControl1" Width="44" Image="images/exit.png" Height="44"/>
</StackPanel>
A: I would make 2 controls, one containing everything but your button and another one with just the button.
Then put them both in a grid so they will stack upon each other, and voila.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Frameworks in the Cloud So I'm trying to finally grasp how cloud-based, enterprise applications work, and what their architectures typically look like. Say I use a cloud provider like Amazon. I assume (please correct me if I'm wrong) that I would be paying for 1+ virtual machines that would house a stack of software per my application's needs.
I'm confused with how frameworks like jclouds or Terracotta fit into the picture. jclouds advertises itself as "an open source library that helps you get started in the cloud", and lists off a number of huge features that don't mean much to me without meaningful examples. Terracotta boasts itself as a high-scaling clustering framework. Why would I need to use something like jclouds? What specific, concrete scenarios would I use it for?
Again, if I'm using Amazon as my cloud provider, wouldn't they already be highly-scaled? Why would I need Terracotta in the cloud?
A: So you have your Linux machine (virtual instance) and it is working OK. But suddenly you need to scale - that is you need to fire up more instances as demand go high and shut them as it goes down. So what you can do is basically use Amazon's API to start EC2 instances - provision them with everything you can do from the administrative console (and even more). But using amazon's API's basically ties your hands to amazon. With frameworks such as JCloud what you do is something like (this is pseudo code):
CloudProvider provider = new CloudProvider.getProvider("Amazon");
provider.authenticate("username", "password");
provider.startInstance("some option", numOfInstances);
So say you have to scale and you are deployed on Amazon using JClouds - you are going to use something like the above BUT suddenly you decide to move from amazon to Rackspace so instead of re-engineering all the logic of your app which has to do with provisioning instances and working with them you can just change the
CloudProvider provider = new CloudProvider.getProvider("Amazon");
to something like
CloudProvider provider = new CloudProvider.getProvider("RackSpace");
and continue using the authenticate method and startInstance but then the library would take of how to actually "translate" this library method to the specific method which the given cloud provider supports. Basically it is a way of abstracting the code which has to deal with the underlying cloud provider - you shouldn't care who it is as long as it is providing the service, right?
A: Taking an app "into the cloud" has at least two aspects.
Firstly you have to manage the nodes: deploy your app on all nodes, monitor them, start new nodes to actually scale, detect and replace failed nodes, realize some update scenario for new app versions, and so on. Usually this can't be done reasonably without tools. JClouds fits in here, since it covers some of these points.
Secondly your app itself must be "cloud ready". You can't take an arbitrary app, put it on multiple nodes and expect it to scale well. The main point here is to define how to scale the access to the shared data between all nodes (SQL database, NoSQL datastore, potentially session replication, ...). Usually you use some existent framework/appserver/datastore to manage your shared state. Terracotta is one of them, basically it provides an efficient way to share memory between JVM instances on multiple nodes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to fix PHP Warning: file_get_contents? I'm getting following warning:
Warning: file_get_contents(C:\xampp\htdocs\test/wp-content/themes/test\images) [function.file-get-contents]: failed to open stream: Permission denied in ..\plugins\theme-check\main.php on line 29
The line 29 of main.php reads as:
$other[$filename] = file_get_contents( $filename );
Here is code related to $files:
$files = listdir( $theme );
$files = array_merge( listdir( $parent ), $files );
if ( $files ) {
foreach( $files as $key => $filename ) {
if ( substr( $filename, -4 ) == '.php' ) {
$php[$filename] = php_strip_whitespace( $filename );
}
else if ( substr( $filename, -4 ) == '.css' ) {
$css[$filename] = file_get_contents( $filename );
}
else {
$other[$filename] = file_get_contents( $filename );
}
}
// run the checks
$failed = !run_themechecks($php, $css, $other);
As far I have understood, its the permission error. As the file can't seem to access that folder. I'm using XAMPP on Windows 7. I dont know how can i change the folder permissions on windows.
PS. Please notice the folder path in the warning, it has \ and also /.
I don't want to turn off the Warning etc., instead want to fix the warning.
A: Marc B hit it on the head. You need to add a test to check if the filename is a directory with php function is_dir($filename)
if ( $files ) {
foreach( $files as $key => $filename ) {
if ( substr( $filename, -4 ) == '.php' ) {
$php[$filename] = php_strip_whitespace( $filename );
}
else if ( substr( $filename, -4 ) == '.css' ) {
$css[$filename] = file_get_contents( $filename );
}
else {
if(!is_dir($filename)) $other[$filename] = file_get_contents( $filename );
}
}
Edit
If you are doing something like a directory view online. You could go further and include the directories in a seperate array and sort them and list them out first. and then list the files. I have created something like this for a dynamic gallery.
A: Try using this PHP function to replace the windows path: getcwd().
You will need to concatenate the file names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Replace radio buttons with images using JQuery I have group of radio buttons which I want to replace with images when checked and unchecked.
<div id="answerOptions">
<input type="radio" name="answeroption" id="r1" value="radio1" checked=''checked'/>radio1<br/>
<input type="radio" name="answeroption" id="r2" value="radio2"/>radio2<br/>
</div>
I have two images 1. button_on.JPG for checked radio button and 2. button_off.JPG for not checked radio button.
I want to accomplish following tasks
1. I want to replace radio buttons with these images.
2. On load of the page checked radio button should have correct image.
Note: Radio buttons are generated dynamically and their ids as well as value do change on each request.
I need the help using Jquery. Appritiate your inputs.
A: Don't reinvent the wheel, use a nice library for this:
http://uniformjs.com/
A: The following code does two things: 1. replaces the radio buttons on load. 2. Changes them when the images are clicked. I'm not going to garuntee that it is perfect for your situation, but it should be enough to get you started.
// on load
$(function() {
// replace the checkboxes with the images
$("input name='answeroption']").each(function() {
if ($(this).attr('checked')) { // radio button is checked onload
$(this).hide();
$(this).after($("<img src='button_on.jpg' class='radioButtonImage' />"));
} else { // radio button is not checked
$(this).hide();
$(this).after($("<img src='button_off.jpg' class='radioButtonImage' />"));
}
});
// setup click events to change the images
$("input.radioButtonImage").click(function() {
if($(this).attr('src') == 'button_on.jpg') { // its checked, so uncheck it
$(this).attr('src', 'button_off.jpg');
$(this).prev().attr('checked', 'false');
} else { // its not checked, so check it
$(this).attr('src', 'button_on.jpg');
$(this).prev().attr('checked', 'true');
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to handle incoming control characters in a custom terminal? For my project I needed to create a custom terminal-like window and connect to a Cisco router through console port. So I inherited a TextBox and created a custom control in WPF. And I thought it would be enough; just to add some code to implement extra features I wanted. I'm sending one character at a time and wait for responses. But then I saw that my custom terminal does not handle special characters, those basic like \n sure are recognized but all the others not. I have written responses to a text file and I see i got quite a lot of those special ones but I don't know how should I react.
Maybe someone knows or have found some links with info about how to react for a specific control character? I have only found what characters are send here , but nothing else about it. I understand that for a "BS" I will delete one character before carriage but what should I do when I get "ACK" or "DC1" ? Maybe I should just skip them ? Any ideas?
Edit:
Apart from sending one character at a time I'll get response only when I send enter or characters like ? or TAB. Then when I receive a response it's mixed with special chars to format the text like in 80x25 terminal window. And I would like just to display it like it wants, but that means I need to know how to react when I get special chars I don't need to display them, just to format normal text based on the special ones I'm also receiving. When I get BS i need to clear the character before carriage, when I get DEL I need to clear the character after carriage. And I would like to know what I need to do when I'm getting other special chars. I know I can do it the hard way and just send those to a working terminal and see what it will do but it will take a while so I wonder if someone maybe knows the answer.
A: Ok, I played the hard way with terminal and now I know that the only special character I need to handle is BS (of course I only tried this with Cisco routers but I just need to work on them), the only problem is that you need to create your own code to get it work and move caret on the right place based on the BS count. And better create your own variable to store caret index because TextBox CaretIndex just didn't want to work as I expected. The rest of special characters can be, as far as I know, omitted. And it works great as I wanted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7587998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding Keys to Heroku with Rails 3 and RVM When attempting the command:
heroku keys:add
I get the following error (I put just the first line of the error):
/home/john/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': no such file to load -- readline (LoadError)
Any ideas on how to solve this?
Thanks,
John
A: You need to recompile Ruby with readline support. Check out this link: RVM: Ruby Version Manager - 'rvm pkg install readline'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Php syntax error t_variable error? Im trying to post to the users wall i have there id and offline token stored in the database
$result22 = mysql_query("SELECT token FROM usersoffline", $link2);
$num_rows2 = mysql_num_rows($result22);
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM usersoffline")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>id</th> <th>Toekn</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['uid'];
echo "</td><td>";
echo $row['token'];
echo "</td></tr>";
$target = $row['uid'] ;
$attachment = array(
'access_token' => $row['token'],
'message' => 'Did a Test Post :',
'name' => "Offline posting using stored tokens",
'link' => "url",
'description' => "This post was made using a stored access token",
'picture'=>"",
);
$ret_code=$facebook->api('/'.$target.'/feed', 'POST', $attachment);
}
echo "</table>";
for some resson it is not posting ???
A: $target = $row['uid'] needs a semicolon after it.
A: *
*Make sure you are including and initializing the Facebook library properly: $facebook = new Facebook(...);
*Make sure your app has granted the publish_stream permission
*wrap your Facebook calls in a try/catch clause to catch errors - reference
*You don't need the offline_access permission
*Based on #4, you don't need to append the access_token in your $attachment var
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: styling tabs using styles.xml I have a row of 5 tabs at the bottom of my app. The problem is the text is cut off on some of them. I want to be able to have the text in each tab stack on top of each other instead of following along horizontally aswell as move the text into the center of the tab instead of sitting at the bottom.
I have created a styles.xml file and have altered the text size but I am not sure how to add the requirments I stated above to it. Can anyone help?
Thanks
A: The style resources uses the same XML attributes as an XML file. You altered the text size successfully, so just add the attributes for the other desired styles. If you don't know which attributes to use, just go to your XML file and type android: and your IDE should pop up a list of all Android XML attributes. If not, go to the View page and read up on the "XML Attributes" section.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JSF - Scrollable DataTable Is there any way to implement a scrollable datatable without using Rich Faces ? If there is can anyone point me to some code samples or example pages ? Thanks.
A: Use div component for scrollable datatable in jsf and mention
properties height: 200px; overflow: auto; in style attribute.
<div style="height: 200px; overflow: auto;">
<h:dataTable value="#{facesBean.files}" var="file">
<h:column>
<f:facet name="header">
<h:outputText value="Image"></h:outputText>
</f:facet>
<h:graphicImage value="#{files.image}" style="width:100px; height:100px;"></h:graphicImage>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Description"></h:outputText>
</f:facet>
<h:outputText style="font-weight:bold;" value="File Name:"></h:outputText>
<h:outputText value="#{file.alt}"></h:outputText>
</h:column>
</h:dataTable>
</div>
A: This can be achieved via CSS. You must use the css property overflow:scroll or overflow-x and overflow-y. But take note that different browsers treat this property differently so you it may result to different behavior.
You make a h:dataTable wrap inside a div.
Change the property of the div using css and add overflow property to scroll.
Make sure that your table has a fixed sized.
You may want to look at this
http://anaturb.net/csstips/sheader.htm
-cheers :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I smooth texture objects in OpenGL ES 1.1 (iPhone) I'm currently experimenting with OpenGL ES 1.1 on the iPhone and trying to get my head around some of the basics. So far I've managed to draw a grid of objects which are lit with one GL_LIGHT. Here is a screenshot of the current output (question to follow)...
So you can see that my test consists of a grid of about 140 cubes - some slightly elevated so I can see how the shaded areas work. Each cube consists of this model (from Blender) and have normals / texture coordinates...
What's puzzling me, is why I don't get a 'uniform' lighting across the entire surface. Each cube seems to be lit individually and I can kind of understand why that would be... but is it not possible to have the light transition 'normally' like it would if you arranged this model out of blocks and shone a light across it. I'd expect to not see a dark edge on each individual cube, but rather a smooth transition across the whole area.
(I'm still inwardly chuffed that I managed to get this far!)
Any help or explanations would be awesome.
Thanks,
Simon
A: The reason why you don't get 'uniform' lighting is because I presume you are using per vertex lighting. That is the lighting is calculated per vertex and interpolated over each triangle making up the model. Since your cube has a pretty low polygon count the transition of light across the model won't look smooth.
Using OpenGL ES 1.1 there are two solutions to this. You can use higher polygon count models or implement per-pixel (DOT3) lighting. I've not implemented this myself but have come across this problem before (my solution was to switch to OpenGL ES 2.0 and use shaders to perform per-pixel lighting).
Here is a link, which may be of use: What is DOT3 lighting?
All the best!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to make an overlapped image clickable in android? I have a image of a map and i want to plot some points/markers on the map. These markers must be clickable. I have used a custom view class to plot the markers at my required points.The markers are getting plotted but the problem is that either the marker is not clickable or when i set onClick listener on the custom view,the whole image receives the click event(whereever i click on image, onClick is called,but i want only click on the marker to initiate onClick). Can someone please help me with this?
A: You have to create your custom MapOverlay and inside put the code the function. In this code above, Override the OnTap method.
public class MapOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public MapOverlay(Drawable defaultMarker,Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
@Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mOverlays.get(i);
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void clearOverlay() {
mOverlays.clear();
populate();
}
@Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
@Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to write labels in barplot on x-axis with duplicated names? I am trying to make a simple barplot but i have a problem that I have duplicated names on x-axis. So when ever I am trying to write names on x-axis it does not show complete string. I have following data
x <- c(1.8405917,0.3265986,1.5723623,464.7370299,0.0000000,3.2235716,
3.1223534, 7.0999787, 1.7122258,3.2005524,3.7531266,469.4436828)
and I am using barplot
barplot(x,xlab=c("AA/AA","AA/CC","AA/AC","AA/NC","CC/AA","CC/CC","CC/AC",
"CC/NC","AC/AA","AC/CC","AC/AC","AC/NC"))
But it does not work. I also used
axis()
But it does not work as well.
Thanks in advance.
A: The way to use axis() is to capture the midpoints, which is what the barplot function returns. See ?barplot:
mids <- barplot(x, xlab="")
axis(1, at=mids, labels=c("AA/AA","AA/CC","AA/AC","AA/NC","CC/AA","CC/CC",
"CC/AC","CC/NC","AC/AA","AC/CC","AC/AC","AC/NC"),
las=3)
A: Try this:
barplot(x, cex.names=0.7,
names.arg=c("AA/AA","AA/CC","AA/AC","AA/NC","CC/AA","CC/CC","CC/AC",
"CC/NC","AC/AA","AC/CC","AC/AC","AC/NC"))
A: No, xlab is for providing a label for the entire x-axis of the plot, not for labelling the individual bars.
barplot() takes the labels for the bars from the names of the vector plotted (or something that can be derived into a set of names).
> names(x) <- c("AA/AA", "AA/CC", "AA/AC", "AA/NC", "CC/AA", "CC/CC", "CC/AC",
+ "CC/NC", "AC/AA", "AC/CC", "AC/AC", "AC/NC")
> barplot(x)
> ## or with labels rotated, see ?par
> barplot(x, las = 2)
Edit: As @Aaron mentions, barplot() also has a names.arg to supply the labels for the bars. This is what ?barplot has to say:
names.arg: a vector of names to be plotted below each bar or group of
bars. If this argument is omitted, then the names are taken
from the names attribute of height if this is a vector,
or the column names if it is a matrix.
Which explains the default behaviour if names.arg is not supplied - which is to take the names from the object plotted. Which usage is most useful for you will mainly be a matter of taste. Not having the row/column/names might speed code up slightly, but many of R's functions will take the names attribute (or similar, e.g. row names) directly from objects so you don't have to keep providing labels for plotting/labelling of results etc.
A: xlab should be names.arg. See ?barplot for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Using Custom PropertyTab in System.Windows.Forms.PropertyGrid Control I am trying to use the customisable property tab feature of the WinForms PropertyGrid control but it has me beaten. I am specifically trying to use in runtime a PropertyGrid to display object properties, as opposed to trying to create design-time support for a control, though they seem to be applications of similar technology.
This question has me seriously confused. I have attempted to follow several tutorials on the topic and none come to any real solid conclusion.
Literature Review
http://msdn.microsoft.com/en-us/library/aa302334.aspx#vsnetpropbrow_topic05
This article informs the reader that adding property tabs is easily doable and that the code sample is in the included FunkyButton project, that, isn't included anywhere.
http://www.codeproject.com/KB/grid/PropertyGridExWinForms.aspx
This project suggests the only way to use custom property tabs is to extend the base property grid functionality by overriding for instance the GetService() private method. I am quite sure this is not required, and attempted to use its information to create a service provider. It did however enlighten me that the class of the SelectedObject in the property grid needs the class attribute PropertyTabAttribute to be assigned to an extended System.Windows.Forms.PropertyGridInternal.PropertiesTab, which I have created and used.
http://www.dacris.com/blog/2008/01/02/net-how-to-show-events-tab-in-a-property-grid/
This article indicates that the property grid itself requires the tab to be added using the PropertyGrid.PropertyTabs.AddTabType() method. It then reveals that the Site property of the property grid needs to be assigned and then smugly suggests I should already know how to do this: "...you need to set the Site property of the grid to some designer site that you’ve implemented. If you’re hosting your own designers, you should know how to retrieve this."
http://www.syncfusion.com/FAQ/windowsforms/faq_c83c.aspx#q913q
In starting to write this question I found a link to this short article on the topic with included code. This project is more focused it seems on design-time functionality however when I used an instance of their object in a completely vanilla PropertyGrid, it showed up both the Properties tab button and their Custom Tab object. I was able to switch between the associated views effortlessly. However the project seems to suggest now custom attributes are required to distinguish properties between the available views. This article now suggests I ignore the Site definitions, specialised PropertyGrids and service providers, and concentrate on the displayed object itself.
Frustratingly, in modifying this project to closer reflect my application, I moved the operational property grid to a tab control's tab page, wherein it broke the ability for the property grid to show the default Properties tab, thus meaning I could switch to the custom property tab, but never back.
Conclusion
I am at a complete loss. I must be close, but of all the avenues I have tried to make this work, perhaps my brain is just fried. What is the key to making property tabs work?
Is it:
*
*The specific class definition of the PropertyGrid.SelectedObject?
*Settings for the property grid itself?
*All about the custom tab definition?
Did the last project described only work because the SelectedObject inherited from UserControl? Does the SelectedObject need to inherit from System.ComponentModel.Component?
If someone could try to clear this all up and provide the most concise possible description of how to make it work, I would be most grateful.
Many thanks.
A: Here is the code of a custom property tab:
public class CustomTab : PropertyTab
{
private Bitmap _bitmap;
// the tooltip displayed in the grid
public override string TabName
{
get
{
return "CustomTab";
}
}
// the icon displayed in the grid
public override Bitmap Bitmap
{
get
{
if (_bitmap == null)
{
// 1. create a file named "CustomTab.bmp". It must be a 16x16, 8-bit bitmap. Transparency pixel is magenta.
// 2. place it in the project aside this .cs
// 3. configure its build action to "Embedded Resource"
_bitmap = new Bitmap(GetType(), GetType().Name + ".bmp");
}
return _bitmap;
}
}
// TODO: return the descriptor corresponding to the properties you want to show
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object component, Attribute[] attributes)
{
return new PropertyDescriptorCollection(null);
}
public override PropertyDescriptorCollection GetProperties(object component, Attribute[] attributes)
{
return GetProperties(null, component, attributes);
}
}
And here is how you can add it to the property grid:
CustomTab tab = new CustomTab();
grid.PropertyTabs.AddTabType(typeof(CustomTab), PropertyTabScope.Global);
It will display nothing because I don't return any PropertyDescriptor in the GetProperties overload, but this is where you need to defined what descriptor you want to use.
OP Edit:
It appears that the crux of making property tabs work, clearing up the confusion of the information available on the web:
*
*The displayed object need not inherit anything like Control or Component
*The PropertyGrid.Site property need not be set
*The property grid need not be extended with a custom class
*The property grid need not even explicitly add the tab if it is called out in the SelectedObject by an attribute. Of course a persistent tab would need to be added.
*Ensure all three PropertiesTab.GetProperties methods are overridden and point to the required method and not the base method.
*The tab's bitmap override must actually do something!
A: The code samples are available now on the MSDN page you referred to in your description. The download link is located between "Summary" and "Contents"; searching for "Codesamples.exe" will probably take you there quickly.
A: I think the sample code from MSDN is quite sufficient:
On a Form place a PropertyGrid.
When you compile the sample code, a component appears in the VS Toolbox. Put it on the form and in Properties window, set it to PropertyGrid.SelectedObject property.
BTW, The actual customization takes place in PropertyTab::GetProperties.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: XML and C# - WriteEndElement I'm using System.Xml to create an XML document in C#
My question is hopefully a simple one, do I need to use the WriteEndElement to close an XML tag?
For example, I have found that the following code will compile with or without 'writer.WriteEndElement();' and produce the same XML either way, however if I put 'writer.WriteEndElement();' twice, the program throws an exception.
writer.WriteStartElement("CustomerNo");
writer.WriteString("12345");
writer.WriteEndElement();
I'm not lazy and don't mind putting this in where it needs to be if this is how it's supposed to be, I just need some guidance here.
Thanks
John
A: Generally speaking: Yes, for each WriteStartElement() there must be a matching WriteEndElement().
Think of the containment hierarchy as a stack - the Starts ("pushes") and Ends ("pops") must balance. If you try to "pop" beyond the end, it's a failure and an exception is thrown, like you describe.
As an example, to write a B element within the A element:
WriteStartElement("A");
WriteStartElement("B");
// ... attributes or content added here will become part af B element
WriteEndElement(); // Closes the open B element.
WriteEndElement(); // Closes the open A element.
Update: As @Sam points out in another answer, when - as in the example you give - you want to only write out simple content elements (no attributes or child elements), you may want to take a look at the convenience method WriteElementString(), which automatically wraps the content in start/end tags.
Hope this helps.
A: I agree with Cumbayah's answer, however you can alternatively use XmlTextWriter's WriteElementString(string,string) method if you just want an element with a value inside (no attributes, no child elements).
Example:
writer.WriteElementString("CustomerNo", "12345");
I highly recommend this as it will save a lot of space and make the code more readable.
Also, to really go the extra mile you could do:
writer.WriteElementString(XmlConvert.EncodeName("CustomerNo"), "12345");
Encode and Decode XML Element and Attribute Names and ID Values
The XmlTextWriter class does not perform character checks by default.
For example, the code WriteElementString("Order Detail", "My order"),
produces an invalid element of My order.
To encode the element value, the correct encoding is
writer.WriteElementString(XmlConvert.EncodeName("Order Detail"), "My
order") which produces the valid element My
order.
A: Somewhere, there's a call to XmlWriter.Close, which—among other things—makes sure
Any elements or attributes left open are automatically closed.
If you didn't call XmlWriter.Close explicitly, C# will do so itself (via XmlWriter.Dispose after the object goes out of scope)
A: I use XDoument to create my XM Files, here is what I use to create an XML FIle:
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment(" "),
new XComment("My Company, Inc"),
new XComment("Comment XML File\n"),
new XComment("Don't edit this file with first consulting with Me."),
new XComment(" "),
new XComment(" "),
new XElement("Main1",
new XElement("Application",
new XElement("RemoteServer", "127.0.0.1"),
new XElement("AppVersion", "1.00.0000"),"
new XElement("UpdateNecessary", "No")
),
new XElement("Departments",
new XElement("Item", "Sales"),
new XElement("Item", "Shipping"),
new XElement("Item", "Human Resources"),
new XElement("Item", "Technical Support")
)
));
A: I would suggest using XMLSerialization in C# to first create a ObjectModel, which can be filled easily, and afterwards you can just save it down to XML.
Just Tag your ObjectModel Serializable and use Datatype which can be serialized or Implement ISerializable to do so.
Any Problems with different stylings, or even structural changes can be handled smooth via the ObjectModel. And the XMLSerializer is doing the job for you.
If you can't use an ObjectModel, i would suggest using an XmlDocument
To Create the Nodes. Here you can also use NamespaceTables and as far as i know, you can't create corrupt XML Files.
A: Response.Clear();
Response.ContentType = "application/rss+xml";
XmlTextWriter writer = new XmlTextWriter(@"E:\product.xml",
System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.WriteStartElement("rss");
writer.WriteAttributeString("version", "2.0");
writer.WriteStartElement("produts");
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
createNode("1", "Product 1", "1000", writer);
createNode("2", "Product 2", "2000", writer);
createNode("3", "Product 3", "3000", writer);
createNode("4", "Product 4", "4000", writer);
writer.WriteEndElement();
writer.WriteEndElement();
writer.Close();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Hiphop for php "can not execute binary file" The old question is below. The problem was ftp transfer mode wasn't binary.
But now i have another issue.
Running hiphop compiled file gives following error (The one compiled on another computer).
"error while loading shared libraries: libmemcached.so.7:cannot open shared object file:No such file or directory."
But native compiled one works with no trouble.
How can i link or load such library?
Can anybody help me out?
I'm using ubuntu 11.04 on both home and vps server.
I followed this (https://github.com/facebook/hiphop-php/wiki/Building-and-Installing-on-Ubuntu-11.04) instruction to set facebook's hiphop up. And i did achived to compile my php sources to executable binary on both server and home pc.
But if i send the binary file to server which s compiled from home pc it doesn't run and prompts as "can not execute binary file".
But server can run the binary file compiled in itself.
Why i just can't run this home compiled file on server. (It runs at home)
A: Are your desktop and server using the same architecture? Binaries compiled on a 64-bit system will not run on a 32-bit OS, and binaries compiled on a 32-bit OS will require the ia32-libs package to be installed on a 64-bit system.
A: I figured it out.
I created same user name on my vps as i have on my home computer.
Gave it sudoers right. (visudo)
And build hiphop in the same directory as i did on my home computer.
Now it runs with the new user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sharing types in a modular application architecture I have an application under development that is following a modular application design. There is a 'core' vertical stack that provides common, central services such as authentication/authorization, logging, data access, etc. Context-specific areas are implemented in modules that reference the core assembly in the same logical layer.
The application is a service app with a facade layer, domain layer and infrastructure code containing the data access code. Each module will implement a domain layer assembly. If the module has a public API, it will also implement a facade assembly.
For example, the solution contains:
*Core.Api - Facade assembly for the core API
*Core - Domain assembly for the core services, entities, etc.
*Core.Data - Core data access assembly
*ModuleA.Api - Facade assembly for module A (references Core.Api)
*ModuleA - Domain assembly for module A (references Core)
*ModuleB.Api - Facade assembly for module B (references Core.Api)
*ModuleB - Domain assembly for module B (references Core)
(and so on. We'll have about 24 modules when done.)
All of this is bound together using DI with Unity as the IoC container. The WebHost project defines the configuration where the various implementations are mapped to the interfaces they fullfill.
This approach is not simply for logical purposes but to allow us flexibility in implementation (i.e. we can change the implementation of a module without breaking or even touching the other code). It also makes it extremely ease to divide work across teams and to extend the application with new modules with little risk of regression error in other code.
My question is what to do when ModuleB requires one or more types defined in ModuleA? Is it acceptable for ModuleB to reference ModuleA or do I need to move ModuleA into Core?
UPDATE
In looking at implementing some of the changes discussed below I ran into a gotcha that leads me to this clarification...
There are two places where my modules are inter-dependent. Following the approach discussed below, I can move the interfaces and types I want shared from Module1 to Core which allows ModuleB to make use of them without tightly coupling ModuleA and ModuleB. However, I also need to use some of the data contracts defined in ModuleA.Api for the service operations in ModuleB.Api. This makes me question the design.
Because of IP, I can't describe our exact use-case but suffice it to say that ModuleA has an EntityA domain object. ModuleA.Api defines the EntityContractA data contract (DTO) that is exposed by the public API. ModuleB.Api has a method that requires EntityContractA as a parameter then delegates to a method in ModuleB that accepts EntityA as a parameter.
Again, moving EntityA into Core solves the domain layer problem but doesn't help me with the facade layer. Moving EntityContractA into Core.Api makes the whole thing smell a bit.
Here's an example what I need to accomplish:
In ModuleB.Api.ServiceFacadeB:
public EntityContractB FilterBy(EntityContractA contractA)
{
var entityA = Mapper.Map<EntityContractA, EntityA>(contractA);
var entityB = domainService.FilterBy(entityA);
var contractB = Mapper.Map<EntityB, EntityContractB>(entityB);
return contractB;
}
where domainService is ModuleA.ServiceB:
public EntityB FilterBy(EntityA entityA)
{
// Do work
}
A: Module2 need to have reference of Module1. interdependence between modules doesn't make a case for moving pieces to common core code.
A: The good news: what you describe is actually a good architecture with clear seperation of concerns and modularity patterns. It allows your teams to develop modules independent from each other and only have dependencies on each others interfaces (facade / API). This is a best practice!
The (potential) bad news: If you would start by directly referencing Module1 from Module2, you will single-handedly break this beautiful architecture. The team creating Module1 only needed to care about keeping their interface stable, but because of the direct reference now also need to be careful with changing their implementation.
My suggestion: If you need a type in Module2 that is now defined in Module1, make sure you move it into the Core API or the Module1 API classes. This formalizes the fact that your assembly is depending on those types and makes it clear they need to be kept stable.
A:
Is it acceptable for ModuleB to reference ModuleA or do I need to move
ModuleA into Core?
No, I'd redefine shared types somewhere that wasn't ties to a specific module. Just make sure that wherever you define these shared types is free of dependencies.
[Warning, self promotion:] In the 5-Layer Architecture view of the world, they'd go in the "Common" layer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Encrypting a string in PHP Okay, so I've got a php script something like the following:
<?php
$name = "Steve Jobs";
header('Location: http://www.apple.com/custom.php&name=' . $name);
?>
Now, I happen to find it kind of embarrasing having the URL of this custom "Hi there, Steve Jobs" page have a URL of http://www.apple.com/custom.php&name=Steve%20Jobs, and would therefore like to encode it.
Is there an easy way to make this name be more obscure? Is there a way to avoid passing it in the URL altogether?
A: To avoid passing variables around in the URL you could use session variables using the $_SESSION array.
You can check out the PHP docs for some basic usage, as well as other examples.
A: The easiest way is to base64_encode($name), then base64_decode on the other end.
A: First, you can store the name in cookie or session, read it on the next page, and remove it from session/cookie. In this way, it won't be included in the URL anyway
If you just do not want to pass it as a plain text, you can use base64_encode() and base64_decode(). But this won't stop any experienced user to read the actual value.
Use mcrypt() to crypt the message, base64_encode() to make the crypted version ASCII, include it in the URL, and on the next page decode and then decrypt. Be carefull, a lot of chippers use seed value, which also have to be saved and send to the next page, in order to be able to decrypt.
All scenarios assume the next page is part of the same application (or both applications are yours). If you want to encrypt the string for any URL, you can't, as the page you are redirecting to won't be able to read it.
A: Try these PHP functions convert_uuencode and convert_uudecode
It is much safer than using only base64
function encrypt_decrypt ($data, $encrypt) {
if ($encrypt == true) {
$output = base64_encode (convert_uuencode ($data));
} else {
$output = convert_uudecode (base64_decode ($data));
}
return $output;
}
$enc_txt = encrypt_decrypt ("TEXT PLAIN", true);
echo $enc_txt."\n";
// KjUkNTg1IiEwMyQlKTNAYGAKYAo=
echo encrypt_decrypt ($enc_txt, false);
// TEXT PLAIN
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Posting from one RequestHandler to another in App Engine Goal: Using app engine's basic webapp framework I want to create a new request, with post data, to send to another RequestHandler. Something like pageGenerator.post({'message':'the message','datum1':datum1,...})...
Problem Description: One request handler, call it pageGenerator, creates a page with a form on it. When the user submits the form, the post goes to a different handler: dataProcessor. If dataProcessor finds some problem with the submitted data it would send the submitted data plus an Error Message to 'pageGenerator`'s post method, and pageGenerator would serve up the page with the error message.
How do I pass data (and control) back and forth like this? I would like pageGenerator to be able to get the data with self.request.get('message').
A: Sounds like you're over-complicating things. Consider just having a common method to show the form that can be invoked in different circumstances:
class FormHandler(webapp.RequestHandler):
def get(self):
self.show_form()
def post(self):
if form_is_valid():
handle_success()
else:
self.show_form({'feedback':'Validation failed'})
def show_form(self, vals={}):
vals['field1'] = self.request.get('field1')
vals['field2'] = self.request.get('field2')
html = template.render('form.html', vals)
self.response.out.write(html)
If you really need "display form" and "process form" to be in different handler classes, you can accomplish the same thing by defining show_form() in a common parent class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: EdgeRenderingFunction and VertexRenderingFunction help I'm trying to construct a LayeredGraphPlot where some nodes connect to other nodes, like a tree. I would like to have the freedom to choose the thickness, color, presence or absence of labeling of each edge.
I would also like to have the freedom to display some vertex names and display some vertices as just "dots". I can't seem to understand how EdgeRenderingFunction and VertexRenderingFunction enable me to do this.
I am new to mathematica. I've clicked on more information on Wolfram help page but it appears to have a vague description and not precise syntax, followed by some cute but unhelpful (to me) examples (As compared to matlab at mathworks where the help provides precise syntax.. at least in my mind).
I have looked up about 10 mathematics books (Smith and Blachman, mathematica demystified.. etc etc) but they all seem to cover the function superficially with one or two examples and not provide the most general syntax.
Can someone help with this and I would also appreciate tips on how to learn mathematica? I'm a smart guy and I should not have so much trouble learning how to use commands.
LayeredGraphPlot[{1->2,1->3,2->4,3->5,3->6}]
So for example, I'd like to:
*
*Suppress all the vertex names except vertices 4,5 and 6.
*Color as blue and thick the edges from 3->6, 2->4 and 1->3
*All the other edges to be red and thin
A: VertexRenderingFunction and EdgeRenderingFunction allow you to take explicit control over the way that vertices and edges are drawn in the graph. Both functions are expected to return a symbolic graphics directive (or list of such directives) that is valid for the Graphics command.
Let's start with VertexRenderingFunction. We shall define a new function called drawVertex. A VertexRenderingFunction is called with two arguments: the position of the vertex (as an X/Y co-ordinate pair) and the name of the vertex.
drawVertex[position_, vertex:(4 | 5 | 6)] :=
Inset[Framed[vertex, Background -> LightMagenta], position]
drawVertex[position_, _] :=
{PointSize[Medium], Blue, Point[position]}
Two definitions are provided for drawVertex. The first is only applicable to the vertices 4 or 5 or 6. It draws those vertices as framed labels. The second definition is applicable to all other vertices and draws simple blue points.
Now for an EdgeRenderingFunction named drawEdge. The function will be passed three arguments: the endpoints of the edge, a list of the source and target vertices of the edge, and the label for the edge (if any). In our case, all edges will be drawn as arrows but the colour and thickness will vary depending upon the edge. The helper function edgeStyle is introduced to capture those differences:
drawEdge[ends_, fromTo_, label_] :=
Join[edgeStyle[fromTo], {Arrowheads[{{Automatic, 0.5}}], Arrow[ends]}]
edgeStyle[{3, 6} | {2, 4} | {1, 3}] :=
{Blue, Thick}
edgeStyle[_] :=
{Red, Thin}
With these definitions in place, we can now use them in conjunction with LayeredGraphPlot to produce a customized diagram:
LayeredGraphPlot[{1 -> 2, 1 -> 3, 2 -> 4, 3 -> 5, 3 -> 6},
VertexRenderingFunction -> drawVertex, EdgeRenderingFunction -> drawEdge ]
A: LayeredGraphPlot[
{1 -> 2, 1 -> 3, 2 -> 4, 3 -> 5, 3 -> 6},
VertexRenderingFunction ->
(If[Intersection[{4, 5, 6}, {#2}] != {},
{White, EdgeForm[Black], Disk[#, .1], Black, Text[#2, #1]},
{PointSize[Large], Point[#1]}] &),
EdgeRenderingFunction ->
(If[Intersection[{{3, 6}, {2, 4}, {1, 3}}, {#2}] != {},
{Blue, Thick, Line[#1]},
{Red, Line[#1]}] &)
]
Mathematica syntax is daunting at first glance. Almost every powerful tool is.
I think the short snippets provided here in StackOverflow as answers to new Mma users are a good starting point for the first steps. Please note that there are also advanced and much more difficult questions posted.
Mathematica is not intended for the casual user. If you are not planning to invest some time in learning and getting accustomed, I suggest trying another tool.
Finally, the LayeredGraphPlot[] function is not covered in depth in the help system, simply because it is a cousin of GraphPlot[], whose help page is the root for all Graph...[] family help searches.
A: I mimicked your code and managed to produce something very close to what I actually wanted. Thanks a lot for your help!
{drawVertex[position_,
vertex : (1111 | 1112 | 1121 | 1122 | 1211 | 1212 | 1221 | 1222)] :=
Inset[Framed[
Text[If[vertex == 1111, "80,70",
If[vertex == 1112, "50,60",
If[vertex == 1121, "105,50", If[vertex == 1122, "70,55",
If[vertex == 1211, "70,40",
If[vertex == 1212, "90,50",
If[vertex == 1221, "85,60", "40,50"]]]]]]]],
Background -> White], position]
drawVertex[position_, _] := {PointSize[Medium], Blue, Point[position]}
drawEdge[ends_, fromTo_,
label_] := {Join[
edgeStyle[fromTo], {Arrowheads[{{Automatic, 1}}], Arrow[ends]}],
Text[label, Mean[ends]]}
edgeStyle[{1, 11} | {11, 111} | {111, 1111}] := {Blue, Thick}
edgeStyle[_] := {Red, Thin}
LayeredGraphPlot[{{1 -> 11, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"1\", \"L\"}]]\)"}, {1 -> 12, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"1\", \"R\"}]]\)"}, {11 -> 111,
"\!\(\*SubscriptBox[\"H\", \"L\"]\)"}, {11 -> 112,
"\!\(\*SubscriptBox[\"H\", \"H\"]\)"}, {12 -> 121,
"\!\(\*SubscriptBox[\"H\", \"L\"]\)"}, {12 -> 122,
"\!\(\*SubscriptBox[\"H\", \"H\"]\)"}, {111 -> 1111,
"\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"L\"}]]\)"}, {111 -> 1112, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"H\"}]]\)"}, {112 -> 1121, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"L\"}]]\)"}, {112 -> 1122, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"H\"}]]\)"}, {121 -> 1211, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"L\"}]]\)"}, {121 -> 1212, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"H\"}]]\)"}, {122 -> 1221, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"L\"}]]\)"}, {122 -> 1222, "\!\(\*SubscriptBox[\"C\",
RowBox[{\"0\", \"H\"}]]\)"}}, EdgeRenderingFunction -> drawEdge,
VertexRenderingFunction -> drawVertex]}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: XSLT - How to evaluate a single node in multiple places I am building an image rotator in XSLT that requires the following markup:
<div class="wrapper">
<div class="overlay"></div>
<div id="slider" class="slider">
[IMAGE FROM NODE A GOES HERE]
[IMAGE FROM NODE B GOES HERE]
...
</div>
<div id="htmlcaption" class="html-caption">
[CAPTION FOR NODE A GOES HERE]
[CAPTION FOR NODE B GOES HERE]
...
</div>
</div>
I need help constructing the XSLT so that Node A would get evaluated inside #slider then get re-evaluated in #htmlcaption, then Node B, and so on.
Any help would be greatly appreciated.
Thanks!
A: First, it is perfectly possible to evaluate a source element multiple times. Just use the same selector.
For example, considering the following XML:
<images>
<node id="a" image="foo.png" caption="foo" />
<node id="b" image="bar.png" caption="bar" />
</images>
This XSLT will repeatedly output stuff from the first node:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="images">
<div id="images">
<img><xsl:value-of select="node[@id='a']/@image"/></img>
<img><xsl:value-of select="node[@id='a']/@caption"/></img>
<img><xsl:value-of select="node[@id='a']/@image"/></img>
<img><xsl:value-of select="node[@id='a']/@caption"/></img>
</div>
</xsl:template>
Output:
<div id="images">
<img>foo.png</img>
<img>foo</img>
<img>foo.png</img>
<img>foo</img>
</div>
However it looks like what you really want is to loop over a bunch of nodes containing image and caption.
You could use a for-each loop to avoid selecting the nodes by name:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="images">
<div id="images">
<xsl:for-each select="node">
<img><xsl:value-of select="@image"/></img>
</xsl:for-each>
</div>
<div id="captions">
<xsl:for-each select="node">
<div><xsl:value-of select="@caption"/></div>
</xsl:for-each>
</div>
</xsl:template>
</xsl:stylesheet>
Which will produce:
<div id="images">
<img>foo.png</img>
<img>bar.png</img>
</div>
<div id="captions">
<div>foo</div>
<div>bar</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: warning - @return tag has no arguments I have 2 Warnings :
--The First is : HELPDESKGESTION2\src\java\glpi\action\LoginAction.java:37: warning - @return tag has no arguments.
--The second is : HELPDESKGESTION2\src\java\glpi\actionform\UtilisateurActionForm.java:67: warning - @return tag has no arguments.
The Code is :
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UtilisateurActionForm utiAF =(UtilisateurActionForm) form;
Utilisateur utilisateur = new Utilisateur();
utilisateur.setLogin(utiAF.getLogin());
utilisateur.setPassword(utiAF.getPassword());
IUtilisateurBO IutiBO = (IUtilisateurBO) ServiceFinder.getContext(request).getBean("UtilisateurBO");
if (IutiBO.checkLogin(utilisateur)==true){
return mapping.findForward(SUCCESS);
}
return mapping.findForward(ERROR);
}
A: the only @return that i'm aware of is javadoc. are you sure your "warnings" aren't generated by you ide to make sure you document your code properly?
A: @return is the javadoc for the methods return value. Can you check if the javadocs in the java file has an description for thr return comments. e.g.
* @return num squared.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: auto generate custom id with sql I am relatively new to sql and databases and would like some help in the following topic.
I have the following table: (junior male -> jm, junior female -> jf, adult male -> am, adult female-> af)
id code name
1 jm john
2 am patrick
3 af jane
4 jm peter
5 jm derrick
6 af mary
7 jf jessica
and would like to create a field inside the table as a reference which is made up of the code and autoincrement digits in this way:
id code name reference
1 jm john jm001
2 am patrick am001
3 af jane af001
4 jm peter jm002
5 jm derrick jm003
6 af mary af002
7 jf jessica jf001
can anyone give me some tips on how to do this? Thank you
A: First, ask yourself "Why?" as in Martin's comment. If you have a good answer to this question, then a sequence for each type is probably what you are looking for. For example in Oracle:
CREATE SEQUENCE jm_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;
CREATE SEQUENCE jf_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;
CREATE SEQUENCE am_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;
CREATE SEQUENCE af_seq START WITH 1 INCREMENT BY 1 NOMAXVALUE NOCYCLE;
Then, you can use these when you enter the specific types. For example, to enter a junior male, you'd use:
Insert into table_name
values (id_seq.nextVal, 'jm', 'Bart', 'jm' || jm_seq.nextVal);
Also, this will not give you leading zeros as in your example, so look into formatting your number if that is needed.
A: You can make use of this following Code in-order to arrive to your desired result... Cheers...
drop table if exists Custom_id_Dynamic;
create table Custom_id_Dynamic (id int primary key auto_increment , Code varchar(20),
Name varchar(20), Reference varchar(20));
drop procedure if exists Dynamic_id;
set @index:=0;
set @jm:=0;
set @unknown:=0;
set @am:=0;
set @af:=0;
set @jf:=0;
delimiter $$
create procedure Dynamic_id(
in code_new varchar(20), in name_new varchar(20)
)
begin
set code_new=lower(code_new);
if code_new='jm' then set @jm:=@jm+1, @index:=@jm;
elseif code_new='am' then set @am:=@am+1, @index:=@am;
elseif code_new='af' then set @af:=@af+1, @index:=@af;
elseif code_new='jf' then set @jf:=@jf+1, @index:=@jf;
else set @unknown:=@unknown+1, @index:=@unknown;
end if;
insert into Custom_id_Dynamic (Code, Name, Reference)
values (code_new, name_new, concat(code_new, lpad(@index,3,0)));
end;
call Dynamic_id('jm','john');
call Dynamic_id('am','patrick');
call Dynamic_id('af','jane');
call Dynamic_id('jm','peter');
call Dynamic_id('jm','derrick');
call Dynamic_id('af','mary');
call Dynamic_id('jf','jessica');
select * from Custom_id_Dynamic;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: (jQuery plugin: backstretch) Margin on the sides I am using this great jQuery plugin to have the fullscreen backgound for my website.
This plugin currently fills the entire background on the screen, I was wondering if it is possible to give it a margin.
For instance I want to have a gap in the right side of the screen for 150px (so I can see the body background) and the rest of the page will be filled with backstretch.
I have played with _adjustBG function but I can't get this working.
Any helps will be appreciated.
A: Since the author of this plugin didn't make an option for margin, I'll tweak it for you.
Below is the modified _adjustBG() function that you may need.
Just open the file "jquery.backstretch.js" (the normal version, not the minimized) then replace the original _adjustBG() function (at the end of file) with this function.
function _adjustBG(fn) {
var rightMargin = 150; //--- edit the margin value here
try {
bgCSS = {left: 0, top: 0}
bgWidth = rootElement.width()-rightMargin;
bgHeight = bgWidth / imgRatio;
// Make adjustments based on image ratio
// Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
if(bgHeight >= rootElement.height()) {
bgOffset = (bgHeight - rootElement.height()) /2;
if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"});
} else {
bgHeight = rootElement.height();
bgWidth = bgHeight * imgRatio-rightMargin;
bgOffset = (bgWidth - rootElement.width()) / 2;
if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
}
$("#backstretch, #backstretch img:last").width( bgWidth ).height( bgHeight )
.filter("img").css(bgCSS);
} catch(err) {
// IE7 seems to trigger _adjustBG before the image is loaded.
// This try/catch block is a hack to let it fail gracefully.
}
// Executed the passed in function, if necessary
if (typeof fn == "function") fn();
}
A: Update:
By poking around w/ console, I found that if you subtract 150 from the width of the background-image, it will, by default, give you a margin on the right. You may want to adjust the height so your image scales, but, maybe something like this to run in $(document).ready():
var $bg = $('#backstretch');
var newImgWidth = $bg.width() - 150;
$bg.css('width', newImgWidth);
A: If IE6 is no issue, you can try to put the following in your stylesheet:
#backstretch{
width: auto !important;
right: 150px;
}
I tried this on the backstretch homepage and it worked as I would expect. As I am not totally familiar with this plugin please feel free to correct me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to debug Android project I'm new to the Android framework (using Eclipse) and I have a question about debugging. Recently I did this error in an activity:
// The installation button
Button button = (Button) findViewById(R.id.preparationInstallButtonID);
button.setOnClickListener(this);
setContentView(R.layout.preparation);
i.e. I tried to add an onclick-event prior the layout had been rendered. This crashed the program, "Sorry, the application xxx has stopped unexpectedly". Running it again, with debug-mode, Eclipse opens a Debug-window containing "Thread<3> (Suspended)" etc (I'm sure you know which window I'm talking about).
Now, how am I able to extract useful data here? Regarding the problem above I found how to fix it by trial-and-erroring, but let's say I'm not able to do trial-and-error, how can the debug-window help me find the source of the error? It says "exception RuntimeException", but I don't see any pointers as of where in my code the exception occured.
A: If You want to debug:
Right click left of Your part of code You want to debug (at line number). select Toggle Breakpoint.
You can see small circle beside the line number, that is the breakpoint.
Then, make run configuration, click small arrow beside run icon, and click 'run configurations..'
Click on android application, you will see this dialog window:
Read it, "highlight" this: 'Press new button to create a configuration of the selected type'. Click the New button, above the tab, You will see this dialog:
fill it, browse Your project,
for example, I add Scrumptious project, and launch default activity. Click on Target Tab, choose Your emulator. If You want to run on physical device, click 'Always prompt to pick device'. I run on physical device this time,
for the Common tab, if maybe You want to check Display in favorites menu for 'Debug' or 'Run' option. It is optional. Click apply.
click debug icon - and select your project. If You activate 'Debug' on Display in favorites menu, the project will shown at the debug option menu.
I choose 'Always prompt to pick device', this dialog will shown. I want to run at physical device, so I click the device at the 'Choose a running Android Device', and click 'Ok'. You can also run on emulator. Just click your emulator, and click Ok.
If eclipse give confirmation to open perspective, select Yes
Then, if You want to know what is value of the variable, just put your mouse to the instance of variable, or You can browse at 'Variables' window at Debug perspective.
A: Use the LogCat this will give you the error messages and everything else that goes on in your testdevice/emulator.
Window -> Show View -> Other -> LogCat
A: I strongly recommend this tutorial on debugging in general.
http://www.vogella.com/articles/EclipseDebugging/article.html
It takes you through all the features Eclipse offers in that department and is well worth the time.
As far as the particular trick that might've helped, it might have been useful to set a breakpoint (i.e., clicking in the left margin of the code to make one of those blue pins appear). Then, when running in debug, you could stop near where the problem occurred, and step forward, beat by beat, using the "step into," "step forward," and "step return" commands at the top of debug window. While you're stepping around the code in that way, you might have the variables window open, so you could see what things are set in a manner they should be, etc.
Alternatively, you could set a breakpoint on RuntimeException (even one that's caught), by clicking on the Breakpoints window in debug, and then licking the "J!" button (the mouseover text shows "add Java Exception Breakpoint."
The debug view lets you do other cool stuff too, like:
*
*letting you set "watchpoints", so you can see when the application changes relevant fields, etc.
*"Drop to frame" so you can start your app in the middle.
*Set up step filters, so that "stepping" through I mentioned earlier can be done more efficiently.
*Create a detail formatter, a little snippet of java code that formats the output of a field so you can view it more cleanly in the debugger.
*And much more!
Again, I recommend the above-referenced tutorial. And welcome to the wonderful world of debugging.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot use class in jsp I'm trying to use a class I defined in a package in my Java Web Project, however I keep getting errors when I use the class I defined in the package. The error is saying that the class cannot be resolved to a type. I am importing the package that I made that contains the class that I want to use.
A: The class needs to be located in webapp's /WEB-INF/classes in a folder structure which represents the declared package. So if you have for example
package com.example;
public class Foo {
// ...
}
then you should have a /WEB-INF/classes/com/example/Foo.class file. Please keep in mind that this is case sensitive as everything else in Java.
Another possible cause is when you're trying to use it in a <jsp:useBean> tag, that it should have a (implicit) default constructor which doesn't throw an exception upon construction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Loading custom UIView from nib, all subviews contained in nib are nil? I have a custom UIView object with a nib that defines the view/subview layout. My outlets are connected, and when I init the object from initWithFrame: everything is in order.
The problem I'm having is when I'm using IB to embed the UIView into another nib; the custom UIView appears, but none of the subviews it contains appear - in fact their symbols all resolve to nil. I have a very minimal initWithCoder: and awakeFromNib: implementation (just does logging) and my understanding is that as the nib is deserialized the subviews should at least be initialized during the process?
The only conclusion I'm coming to on my own is that one of two things is happening: either my outlet references are corrupt/bad and aren't working, or my understanding of load-from-nib process is faulty and I'm missing something.
Thanks in advance!
Edit: (Code posted for Nekto as requested... as you'll see, it does logging and thats it, heh.)
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
NSLog(@"ThumbnailGridView.initWithCoder frame= %f, %f", self.frame.size.width, self.frame.size.height);
}
return self;
}
- (void)awakeFromNib
{
NSLog(@"ThumbnailGridView:awakeFromNib");
}
Edit 2: Nibs, controllers, subviews, etc.
Nibs: I have a single nib containing a UIView. This UIView contains a single UIScrollView, which is filled with a grid of UIViews that are defined in another nib. (Note: this part works fine, as the fill is done programmatically and works with an initWithFrame: call.) The problem here is that the UIScrollView symbol is nil after initWithCoder: and awakeFromNib: are both called, so objects are just being added to nil and nothing happens. If the scrollview symbol was not nil, I'm sure this would work.
Controllers: There are two controllers that utilize this, one is done with initWithFrame: and works perfectly, the other embeds it as a nib-based reference. (As mentioned elsewhere here, defining a UIView in IB, setting the custom class.) I stepped through the code, and that view -is- being initialized properly - only its subviews are "missing".
Does this help give a clearer picture of the situation at all?
A: You may be misunderstanding how nib loading works. If you define a custom UIView and create a nib file to lay out its subviews you can't just add a UIView to another nib file, change the class name in IB to your custom class and expect the nib loading system to figure it out. You need to modify initWithCoder of your custom UIView class to programmatically load the nib that defines its subview layout. e.g.:
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil];
[self addSubview:self.toplevelSubView];
}
return self;
}
Your custom view's nib file needs to have the 'File's owner' class set to your custom view class and you need to have an outlet in your custom class called 'toplevelSubView' connected to a view in your custom view nib file that is acting as a container for all the subviews. Add additional outlets to your view class and connect up the subviews to 'File's owner' (your custom UIView).
Alternatively, just create your custom view programmatically and bypass IB.
A: Check that you are calling the 'super' implementation of initWithCoder: and awakeFromNib in each of your overridden methods i.e.
- (id)initWithCoder:(NSCoder *)decoder {
if ((self = [super initWithCoder:decoder])) {
...your init code...
}
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
...your init code...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
}
|
Q: OpenCV: Save video in IYUV I'm trying to save a video that have been captured by a camera.
It works well when I try with DIVX fourcc but what I'm trying to do is to save with IYUV fourcc but it gives awful results: colors seem to be merged, openCV seen to not do the conversion.
I've tried cv::cvtColor (src, dst, CV_BGR2YCrCb) and cv::cvtColor (src, dst, CV_BGR2YUV) ans manual conversion from RGB to YUV but the result is the same.
Have you any idea how to save a video in YUV format ?
Thanks.
Arthur.
A: See this ticket on OpenCV bugtracker. That problem looks very similar to yours.
Also manual calling of cv::cvtColor makes no sense because it is not able to convert to yuv420p used internally by video codec.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does Java takes Input in String format only? In java when we take input from console we get a String, even if we want an integer as input we get a input in String format, then we covert it in integer format using several methods, like Integer.parseInt(). Where as C/C++ also take input from console but there we get integer values directly from console we does not require methods to convert them. Then why does java follows such long procedure. **What is the reason behind such an architecture of Java ?
//In java we follow the following process
public static void main(String args[])
{int i = Integer.parseInt( args[0]);// here we get input in String format and then convert it
}
//In C++ we follow the following :
void main()
{int i;
cin>>i;
}
Both C/C++ and Java takes input form Console then why java takes it in String Format and C++ does not ??
A: Check out java.util.Scanner, it might do what you need:
http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
A: Java - If you use the Scanner class you can get the input in the required data type. It's not only String java accepts.
A: If you take an integer from the console in C, it will require you to atoi() the input.
A: You always get a string when reading from stdin. In C++ however, the >> operator overload used when writing to an int performs the conversion - so it's just a different way of converting but in both languages it's necessary.
You are right that it's nicer in C++ though since you can use pretty much the same code no matter what data type you have.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Filtering ListView which is part of a ViewPager Fragment I recently converted my application from using Activites and TabHost to using Fragments and ViewPager from the Android Compat Library for API v4
I was able to fix/resolve most problems but am unable to retain the previous behavior with filtering text in ListViews using the setTextFilterEnabled method.
My ViewPagerAdapter contains Fragments which each have a ListView. As users swipe through the ViewPager, I would like the currently active Fragment's ListView to filter text as users type, just like I was able to do with the TabHost-Activity model. Currently, it looks like the first Fragment's ListView will respond correctly, but if I swipe to the next Fragment and try to filter its ListView, the filtering will still apply to the first one. If I swipe past the first two and then filter, the results are non deterministic. The currently active Fragment will never apply the filter. Sometimes a neighboring fragment will, sometimes it won't.
I tried to fix this by adding custom callbacks which let me monitor which Fragment is currently visible, and which are hidden. When a fragment becomes visible as the main Fragment of the ViewPager, I set the setTextFilterEnabled on its ListView to true, and set all others to false. This didn't seem to help at all (I verified that I was toggling the flag correctly for the right Fragments).
I suspect this needs some kind of deeper integration with ViewPager, but I can't really figure out what I need to wire up. Any ideas on how I can make this work? I'm happy to muck with the ACL code if needed.
A: You could implement the method onPageSelected extending OnPageChangeListener. Perhaps you already do this. From there you can set the adapter to the current ListView or requery your cursorAdapter if that's the case. Note that the Adapter used must implement the Filterable interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Error logging in via FTP script in KornShell I am trying to FTP a file using a script in KornShell (ksh) and I am getting a login failed message. I can login manually just fine but when I try the automated script, it does not like the password portion of the login information.
Here's my script:
ftp -n ftp.stmp.com <<EOF
user quser pass Sky3s3ch
binary
hash
prompt
put chr*.dat
EOF
And this is the error that I get:
dns: /u04/lms/ora_shell/clients/STMP > LMS_STMP_ECHI_FTP.ksh
Not logged in.
Login failed.
Please login with USER and PASS.
Hash mark printing on (1024 bytes/hash mark).
Interactive mode off.
Please login with USER and PASS.
Please login with USER and PASS.
I would appreciate any help I can get in figuring this out. Thanks in advance.
A: there are many different ftp clients, but I'm not familiar with one that requires the word pass as part of a single line login like you are using. Try
ftp -n ftp.stmp.com <<EOF
user quser Sky3s3ch
. . .
EOF
Another common form is to move the hostname inside the ftp input stream, i.e.
ftp -in <<EOF
open ftp.stmp.com
quser Sky3s3ch
. . .
EOF
I don't have my sample code availab.e You may need user on the 2nd line of input, but I don't think so.
Edit
Finally, I noticed you have put chr*.dat in your input script. To transfer multiple files at the same time, you'll need the mput command instead.
I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to correctly setup Akka.Actors compared to Scala.Actors How do I run 2 Akka actors with the caller sending the consumer a message every n seconds?
As there are no loop-react methods as in the Scala.Actors library I am stuck
somehow, the following will not compile and produces:
overriding method receive in trait Actor of type =>
Caller.this.Receive; method receive has incompatible type
object Foo {
def init() {
actorOf[Caller].start()
actorOf[Consumer].start()
}
}
class Caller extends Actor {
def receive {
while (true) {
self ! "msg"
Thread.sleep(1000)
}
}
}
class Consumer extends Actor {
def receive = {
case msg:String => doStuff()
case e => _
}
}
A: You're missing the equals sign after receive in Caller. Without it, the method is defined as returning Unit (i.e. no useful value), and akka needs you to return a PartialFunction[Any,Unit] from receive.
Now, to actually implement your logic in the idiomatic way, you probably want to use a ReceiveTimeout, like so:
class Caller extends Actor {
self.receiveTimeout = Some(1000)
def receive = {
case ReceiveTimeout =>
self ! "msg"
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do Unix capabilities work? it seems that starting kernel 2.2, they introduced the concept of Capabilities. According to the unix man page on capabilities, it says if you're not a root user, you can grant yourself of capabilities by calling cap_set_proc per thread basis. So does this mean that if you're writing a malware for unix, do you just grant yourself bunch of capabilities and compromise the system? If not, how does one grant capabilities required to run the program?
it seems that Unix's security model is quite flawed primitive. Am I getting this right?
I'll go more specific:
How do you (when running as a non-root user) send a signal to another process that is running under different user? On signal man page, it says you need CAP_KILL capability to perform this. However, reading the capabilities man page, I'm not sure how I can grant a process that capability.
A: From man cap_set_proc:
Please note, by default, the only processes that have CAP_SETPCAP available to them are processes started as a kernel-thread. (Typically this includes init(8), kflushd and kswapd). You will need to recompile the kernel to modify this default.
Trust me if it was that easy I'm sure someone would have exploited it by now. Unix's security model may be simple by comparison to other operating systems, but it doesn't mean it's "flawed".
A: it's impossible. Use Socket or File instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to (computed) goto and longjmp in C++? I don't usually code C++, but a strange comp sci friend of mine got sick of looking at my wonderful FORTRAN programs and challenged me to rewrite one of them in C++, since he likes my C++ codes better. (We're betting money here.) Exact terms being that it needs to be compilable in a modern C++ compiler. Maybe he hates a good conio.h - I don't know.
Now I realize there are perfectly good ways of writing in C++, but I'm going for a personal win here by trying to make my C++ version as FORTRAN-esque as possible. For bonus points, this might save me some time and effort when I'm converting code.
SO! This brings me to the following related queries:
On gotos:
*
*How do you work a goto?
*What are the constraints on gotos in C++?
*Any concerns about scope? (I'm going to try to globally scope as much as possible, but you never know.)
*If I use the GCC extension to goto to a void pointer array, are there any new concerns about undefined behavior, etc?
On longjmp:
*
*How would you safely use a longjmp?
*What are the constraints on longjmps in C++?
*What does it do to scope?
*Are there any specific moments when it looks like a longjmp should be safe but in fact it isn't that I should watch out for?
*How would I simulate a computed goto with longjmp?
*Is there any tangible benefit to using longjmp over goto if I only have one function in my program?
Right now my main concern is making a computed goto work for this. It looks like I'll probably use the longjmp to make this work because a void pointer array isn't a part of the C++ standard but a GCC specific extension.
A: I'll bite and take the downvote.
I seriously doubt that your friend will find Fortran written in C++ any easier (which is effectively what you'll get if you use goto and longjmp significantly) to read and he might even find it harder to follow. The C++ language is rather different from Fortran and I really don't think you should attempt a straight conversion from Fortran to C++. It will just make the C++ harder to maintain and you might as well stay with your existing codebase.
goto: You set up a label (my_label:) and then use the goto command goto my_label; which will cause your program flow to execute at the statement following the goto. You can't jump past the initialization of a variable or between functions. You can't create an array of goto targets but you can create an array of object or function pointers to jump to.
longjmp: There is no reason to prefer longjmp over goto if you have only one function. But if you have only one function, again, you really aren't writing C++ and you'll be better off in the long run just maintaining your Fortran.
A: You'll get plenty of haterade about using goto at all. Normally I'd jump right on the bandwagon, but in this particular case it sounds more like code golf to me. So here you go.
Use goto to move the instruction pointer to a "label" in your code, which is a C++ identifier followed by a colon. Here's a simple example of a working program:
#include <iostream>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i = 0;
step:
cout << "i = " << i;
++i;
if( i < 10 )
goto step;
}
In this case, step: is the label.
There are concerns about context.
*
*You can only goto to a label within the current function.
*If your goto skips the initialization of a variable, you may evoke Undefined Behavior (Code which will compile, but you can't say for sure what it will actually do.).
*You cannot goto in to a try block or catch handler. However, you can goto out of a try block.
You "can goto" with pointers etc provided the other concerns are met. If the pointer in question is in-scope at the call site and in-scope at the branch site, no problem.
A: I think this reference has most of the information you are looking for.
goto
longjmp
A: computed goto --> switch
Really, they share a (common, but not universal) underling implementation as a jump table.
A: If I understand the original question, the question is actually an interesting one. Rewording the question (to what I think is an equivalent question): "How do you do a FORTRAN computed goto in C?"
First we need to know what a computed goto is: Here is a link to one explanation: http://h21007.www2.hp.com/portal/download/files/unprot/fortran/docs/lrm/lrm0124.htm.
An example of a computed GOTO is:
GO TO (12,24,36), INDEX
Where 12, 24, and 36 are statement numbers. (C language labels could serve as an equivalent, but is not the only thing that could be an equivalent.)
And where INDEX is a variable, but could be the result of a formula.
Here is one way (but not the only way) to do the same thing in C:
int SITU(int J, int K)
{
int raw_value = (J * 5) + K;
int index = (raw_value % 5) - 1;
return index;
}
int main(void)
{
int J = 5, K= 2;
// fortran computed goto statement: GO TO (320,330,340,350,360), SITU(J,K) + 1
switch (SITU(J,K) + 1)
{
case 0: // 320
// code statement 320 goes here
printf("Statement 320");
break;
case 1: // 330
// code statement 330 goes here
printf("Statement 330");
break;
case 2: // 340
// code statement 340 goes here
printf("Statement 340");
break;
case 3: // 350
// code statement 350 goes here
printf("Statement 350");
break;
case 4: // 360
// code statement 360 goes here
printf("Statement 360");
break;
}
printf("\nPress Enter\n");
getchar();
return 0;
}
In this particular example, we see that you do not need C gotos to implement a FORTRAN computed goto!
A: Longjmp can get you out of a signal handler which can be nice - and it'll add some confusion as it will not reset automatic (stack-based) variables in the function it long jumps to defined prior to the setjmp line. :)
A: There is a GCC extension called Labels as Values that will help you code golf, essentially giving you computed goto. You can generate the labels automatically, of course. You will probably need to do that since you can't know how many bytes of machine code each line will generate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Could not validate certificate signature? I use the SSL Socket and Trustmanager from this side Self signed SSL
but i keep getting following error:
09-28 19:52:41.942: WARN/System.err(10101): javax.net.ssl.SSLHandshakeException: org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate signature.
What is wrong?
I already checked different posts on stackoverflow but i can`t seem to get it to work.
My code:
SchemeRegistry schemeRegistry = new SchemeRegistry();
// http scheme
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// https scheme
schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
params = new BasicHttpParams();
params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "utf8");
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope("www.example.com", AuthScope.ANY_PORT),
new UsernamePasswordCredentials("user", "password"));
clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
context = new BasicHttpContext();
context.setAttribute("http.auth.credentials-provider", credentialsProvider);
DefaultHttpClient client = new DefaultHttpClient(clientConnectionManager, params);
HttpGet get = new HttpGet("https://www.example.com/web/restricted/form/formelement=512663");
HttpResponse response = client.execute(get, context);
Log.w("Response ","Status line : "+ response.toString());
A: As Michael Levy mentioned, the reason I was getting this exception is that I had left my Android Emulator open for a few days and the clock had gotten pretty far out of sync. Once I restarted the emulator, the exception went away.
A: Most probably server returned certificate chain with authorities you do not trust.
(means: authority certificates are not known to your device as trusted)
Solution: carefully examine certificates coming from HTTPS website, and add respective authorities to your truststore - but this part seems to be tricky
( here some explanations :
http://groups.google.com/group/android-security-discuss/browse_thread/thread/0bf726de4f5275a3/391b900631d7f358 )
A: UPDATE
I also got another error on API 16 emulator:
routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
(external/openssl/ssl/s23_clnt.c:741'.
Reading 1 and 2, I changed code so:
val okHttpClient = getOkHttpBuilder().build()
private fun getOkHttpBuilder(): OkHttpClient.Builder {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Security.insertProviderAt(Conscrypt.newProvider(), 1)
}
return OkHttpClient().newBuilder()
}
// build.gradle:
implementation 'org.conscrypt:conscrypt-android:2.5.1'
But the library adds 3.4 Mb to apk.
I also removed these lines from MyApplication:
try {
ProviderInstaller.installIfNeeded(applicationContext)
val sslContext = SSLContext.getInstance("TLSv1.2")
sslContext.init(null, null, null)
sslContext.createSSLEngine()
} catch (e: GooglePlayServicesRepairableException) {
Timber.e(e.stackTraceToString())
// Prompt the user to install/update/enable Google Play services.
GoogleApiAvailability.getInstance().showErrorNotification(this, e.connectionStatusCode)
} catch (e: GooglePlayServicesNotAvailableException) {
Timber.e(e.stackTraceToString())
// Prompt the user to install/update/enable Google Play services.
// GoogleApiAvailability.getInstance().showErrorNotification(this, e.errorCode)
} catch (e: NoSuchAlgorithmException) {
Timber.e(e.stackTraceToString())
} catch (e: KeyManagementException) {
Timber.e(e.stackTraceToString())
}
=== Old answer ===
In my case a following error raised on Android 4 and 5:
Caused by:
com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException:
Could not validate certificate: Certificate expired at Sat May 30
10:48:38 GMT+00:00 2020 (compared to Thu Aug 13 11:47:00 GMT+00:00
2020)
...
Caused by: java.security.cert.CertificateExpiredException:
Certificate expired at Sat May 30 10:48:38 GMT+00:00 2020 (compared to
Thu Aug 13 11:47:00 GMT+00:00 2020)
The server has certificate error (probably expired).
For Retrofit see https://stackoverflow.com/a/60507560/2914140. If you use Fuel as a REST library, see kotlin library that can do httpS connection without certificate verification (like curl --insecure).
You can trust all certificates, but it's dangerous.
import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.*
import javax.security.cert.CertificateException
companion object {
private val gson: Gson
private val retrofit: Retrofit
init {
val okHttpClient = getOkHttpBuilder().build()
gson = GsonBuilder().setLenient().create()
retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
private fun getOkHttpBuilder(): OkHttpClient.Builder =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
OkHttpClient().newBuilder()
} else {
getUnsafeOkHttpClient()
}
private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =
try {
// Create a trust manager that does not validate certificate chains
val trustAllCerts: Array<TrustManager> = arrayOf(
object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array<X509Certificate?>?,
authType: String?) = Unit
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<X509Certificate?>?,
authType: String?) = Unit
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
)
// Install the all-trusting trust manager
val sslContext: SSLContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
val builder = OkHttpClient.Builder()
builder.sslSocketFactory(sslSocketFactory,
trustAllCerts[0] as X509TrustManager)
builder.hostnameVerifier { _, _ -> true }
builder
} catch (e: Exception) {
throw RuntimeException(e)
}
}
See also https://stackoverflow.com/a/60507560/2914140 for Android version check and Glide connection.
A: Check the time of your device, correct it and then check again.
A: BTW,we could re-produce this error easily -- just change the date of the phone to several years later.
NOTE: the error might be a little difference in different phone. Some might show that the certificate has expired.
A: Looks like wrong date/time of the device
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: iPad Canvas Draw Image Error For some reason Safari on iPad is throwing an error when I draw an image as follows:
INDEX_SIZE_ERR:DOM Exception 1: Index or size was negative, or greater than the allowed value
var img = new Image;
img.src = node.data.userimg;
ctx.drawImage(img, 20, 20, 38, 38);
where node.data.userimg is a URL to a twitter profile icon. This error is not thrown in normal desktop browsers. Originally these imgs were drawn at a dynamic point in relation to the node object but even setting them statically at 20, 20 is still throwing this error. Can iPad's Safari not scale images without throwing this error? The images all seem to still draw in correctly if a bit slowly on most draw calls. I fear it might just be a performance issue since so much is being drawn on the canvas (a graph representing cities and associated tweets when clicked/touched).
A: Maybe these links help you ...
there is a chance that you get negative values... or that the image has not loaded before you want to draw it...
Both cases are not much liked by the canvas...
http://blog.ryanrampersad.com/2010/06/04/index_size_err-dom-exception-1-html-canvas/
Canvas: JavaScript Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1
Uncaught Error: INDEX_SIZE_ERR
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to override/extend an inner class from a subclass? I want to change how a method of a class executes without overriding the method, and only overriding (or ideally extending) the inner class. Assume that I cannot change the fact that I need to do this (I am modifying an existing open source code base and there would be friction to pulling out classes or whatnot).
public class A {
static class Thing {
public int value() { return 10+value2(); }
public int value2() { return 10; }
}
public String toString() {
Thing t = new Thing();
return Integer.toString(t.value());
}
}
public class B extends A {
static class Thing {
public int value2() { return 20; }
}
}
My goal is, by changing only Thing, getting B's toString() to return "30", where currently it will return "20". The ideal would be to change only the method value2 (thus leaving any other methods unchanged), but I don't know if this is possible.
Thanks
A: I think you need a factory method for this. Consider the following example (derived from your snippet):
static class A {
static class Thing {
public int value() {
return 10 + value2();
}
public int value2() {
return 10;
}
}
protected Thing createThing() {
return new Thing();
}
public String toString() {
return Integer.toString(createThing().value());
}
}
static class B extends A {
static class Thing extends A.Thing {
public int value2() {
return 20;
}
}
@Override
protected Thing createThing() {
return new Thing(); // creates B.Thing
}
}
public static void main(String[] args) {
System.out.println(new B());
}
Output:
30
A: You should be able to just extend the inner class with Thing extends A.Thing. As long as it's visible in your scope it shouldn't be a problem.
A: It's not possible by only changing value2. The problem is that 'new' calls aren't dispatched dynamically - the 'new' in toString will always create A::Thing. You could fix this creating a factory : something like this:
public class A {
static class Thing {
public int value() { return 10+value2(); }
public int value2() { return 10; }
}
private Thing makeThing() { return new Thing(); }
public String toString() {
Thing t = new Thing();
return Integer.toString(t.value());
}
}
public class B extends A {
static class Thing extends A.Thing {
public int value2() { return 20; }
}
private Thing makeThing() { return new Thing(); }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
}
|
Q: Prevent link popups in phonegap I am using the phonegap api, to create a native iPhone application. However when creating links between pages, if you hold down the links for a few seconds a popup comes up asking you if you wish to open or copy the links. I was wondering how I could disable these popups from coming up, to make the application run more smoothly etc?
A: I know this is almost a year ago, but I thought I could share some thought.
the suggestion is a good one, but it doesn't quite work for me working with Cordova 2.2 and JQM 1.2. Tapping and holding on a button or a tab (actually a link, A element), the actionsheet still pops up from the bottom of the screen (of an iphone, let's say).
This is what that does it for me:
.yourclassname {
-webkit-touch-callout: none;
}
A: You can disable it entirely, or only for links.
Set it in the CSS for links:
.class_name {
-webkit-user-select: text;
}
Or for everything:
.class_name {
-webkit-user-select: none;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Loading and changing images asynchronous Im loading 4 images from a website asynchronous,and after the loading i change them with a timer,but looks like on the array of the images is always the first image,when i change to another position of the array it contains the same image,dont change at all...
- (void)viewDidLoad
{
[super viewDidLoad];
[self getImages];
}
-(void)getImages
{
receivedData = [[NSMutableData alloc]init];
myImages = [[NSMutableArray alloc]init];
myImagesAdresses = [[NSMutableArray alloc]initWithCapacity:5];
[myImagesAdresses addObject:@"adress/Images/3.png"];
[myImagesAdresses addObject:@"adress/Images/2.png"];
[myImagesAdresses addObject:@"adress/Images/1.png"];
[myImagesAdresses addObject:@"adress/Images/0.png"];
[self loadNextImage];
}
-(void)loadNextImage
{
if([myImagesAdresses count])
{
NSURL * imageURL = [NSURL URLWithString:[myImagesAdresses lastObject]];
NSURLRequest * myRequest = [NSURLRequest requestWithURL:imageURL];
[[NSURLConnection alloc]initWithRequest:myRequest delegate:self];
NSLog(@"Start load URL %@",imageURL);
}
else {
[self.theImage setImage:[myImages objectAtIndex:2]];
[self changeImage];
NSLog(@"No More Images to Load");
}
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
[connection release];
connection = nil;
NSLog(@"Image from %@ loaded",[myImagesAdresses lastObject]);
[myImagesAdresses removeLastObject];
[self loadNextImage];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
connection =nil;
NSLog(@"Image from %@ not loaded", [myImagesAdresses lastObject]);
[myImagesAdresses removeLastObject];
[self loadNextImage];
}
and the code to change the image:
-(void)changeImage
{
SEL selectorToCall = @selector(change: );
NSMethodSignature *methodSignature = [[self class] instanceMethodSignatureForSelector:selectorToCall];
NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget:self];
[invocation setSelector:selectorToCall];
NSTimer * newTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 invocation:invocation repeats:YES];
self.paintingTimer = newTimer;
}
- (void) change:(NSTimer *)paramTimer
{
static NSInteger currentElement = 0;
if(++currentElement == [myImages count]) currentElement = 0;
[self.theImage setImage:[myImages objectAtIndex:currentElement]];
}
- (void) stopPainting
{
if (self.paintingTimer != nil){
[self.paintingTimer invalidate];
}
}
I dont getting any error,but the image simply dont change...
A: It looks like receivedData is an ivar that you repeatedly append to, but it never gets cleared. So after the first image is received, the second image is appended to it, etc.
After this line, you should empty receivedData:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
A: You should add this line of code after:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
like this:
[myImages addObject:[UIImage imageWithData:[NSData dataWithData:receivedData]]];
[receivedData setData:nil];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get a handle to a popup window in gwt? Hi can someone tell me how to do something like the following in gwt?
test(){
var win =
window.open("http://www.stackoverflow.com",
"mywindow",
"location=1,status=1,scrollbars=1,width=100,height=100");
win.location = "http://www.yahoo.com";
}
A: OK, trying again.
Off the top of my head, use a PopupPanel or some subclass of that Widget. Then you have a "handle" to it. Insert a Frame widget in the panel and set the URL of the Frame to the external site you want. Handle the sizing and other aspects using the methods provided by the PopupPanel class.
http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/client/ui/PopupPanel.html
http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/client/ui/Frame.html
A: You can get and manipulate window handles by creating an overlay type:
public class MyWindow extends JavaScriptObject {
protected MyWindow() {
}
public static native MyWindow open(String url, String name) /*-{
return $wnd.open(url, name);
}-*/;
public static native MyWindow open(String url, String name, String options) /*-{
return $wnd.open(url, name, options);
}-*/;
public native void setHref(String href) /*-{
if (this.location) {
this.location.href = href;
}
}-*/;
}
Note that once the window origin changes you will no longer be able to manipulate the window.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best practice for placing template views and backbone view code I am creating a ASP.Net MVC 3 application using Backbone.js. I am also using the jQuery templates for the views.
My question is how do I organize the files in an efficient way?
Currently I have a XXX.js file for the backbone application and inlined templates stored in the page that shows the backbone application, Index.cshtml. How can I move the templates into a different file that I can include like I include XXX.js?
App/
Scripts/
backbone.js
underscore.js
jquery-1.6.4.js
jquery.tmpl.js
myBackboneApplication.js
Views/
Home/
Index.cshtml
Controllers/
HomeController.cs
I would like to move the templates out of Index.cshtml and into something related to myBackboneApplication.js. Something that I can include as a file inside Index.cshtml instead of inlined.
A: You might check out this related question. The two basic options are:
*
*Create your templates as strings and include the Javascript file in your index file.
*Create your templates as HTML in separate files, and insert them into the index file at build time, most likely within <script type="text/template"> tags.
In my current Backbone.js project, I'm using the second option - I keep all my templates in a separate folder, and I insert them into my index file during my ant build. Each template (e.g. my-view-template.html) is inserted into a <script> tag with id="my-view-template", and then I use jQuery to create the templates using $("#my-view-template").html() as the template string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Game center authenticate on simulator, but nor actual device I am attempting to add game center to my application and all goes well for the simulator, but when I run it on the device, it always says game is not recognized by game center. I have attempted to log out of game center than back in hoping it places me in "sand box" but it apparently does not.
If it matters, my devices are running iOS 5 beta 7. Any ideas why okay on simulator and not device? Thanks in advance.
Geo...
A: So it must have been something to do with running beta and something got "hung", because I restarted the iPad and all is well. Although I did have to make sure I was logged out of Game Center on the device and then log in via my app.
Geo...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In a view, why does visual studio not know that a semi colon after a model directive is going to cause a runtime error? I'm very very new to MVC3, and ran in to a problem very soon after going thru the asp.net mvc3 tutorials from pluralsight.
Trying out the strongly typed example of the introduction 'adding a model' section, This works:
@model MvcApplication1.Models.RestaurantReview
@{
ViewBag.Title = "Home Page 1";
}
...
But this doesn't... it builds, and then chokes on a runtime error:
@model MvcApplication1.Models.RestaurantReview;
@{
ViewBag.Title = "Home Page 1";
}
...
The only difference being that semi colon after the @model directive, turning it in to a statement, rather than a directive.
Why doesn't visual studio know that this is going to crash? The error message that IIS presents during the crash isn't even the correct line number of where the error actually is in the code.
VS does underline the line in red, telling me that only such and such can be used in a statement, but it doesn't prevent the build success.
This seems like it would be a nightmare to debug in a big project if it wasn't caught right away, no?
A: It's obviously a bug. We are aware of it and will fix it for the next version of MVC (in fact the fix is already in the MVC 4 Developer Preview).
A: Compile your views on the build event and it should make your views choked if there is any syntax error.
To make your views to be compiled, please do the following;
*
*Unload your project by right right
clicking the project on the solution
explorer in VS and clicking unload
project
*Right click the project which has
been converted to unavailable
project and click "Edit
your_project_name.csproj" (that
would be vbproj I guess if your
project is VB project)
*See the following code;
<!--There some lines of code here and I deleted them to get to the point quickly-->
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<MvcBuildViews>false</MvcBuildViews>
*Change the MvcBuildViews node value from false to true
*After this action, save it and reload your
project.
Then, build your solution to compile it. You will see that your views will be compiled as well.
UPDATE
Tried your example and it choked as supposed. So it has Works on My Machine Seal of Approval
UPDATE
I have written a quick blog post on this topic. See the details :
http://www.tugberkugurlu.com/archive/how-to-detect-errors-of-our-asp-net-mvc-views-on-compile-time-blow-up-in-my-face-theory
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: iOS & XCode 4 Build Setting: Install Directory When developing iOS apps with XCode, there is a build setting called Install Directory. Does XCode ignore this? I've changed it to /Applications and the app still gets installed in the sandbox. I'm using a jailbroken phone and would like my app to get installed in /Applications for system read privileges. The only other way, it seems, is to use SSH to drop the bundle in /Applications. Doing that forces me to build+archive, thus I can't use the debugger for console output.
Is there a solution to this problem? (I am a paid dev with a proper certificate, no hacks)
A: This setting is mainly for OSX apps, but I think it may also place the main executable inside that directory inside of the App bundle. So if you had Test.app, the executable binary file would be in Test.app/Applications/test. At least it did that for me a while back when I was messing around with different settings. It may have changed.
You can use the xcode 'Behaviors' settings to specify a script to run when a build succeeds, or you can set 'Pre-build' and 'Post-build' actions (can also run a custom script) for each scheme in your project. You could automate the process of SSH'ing and moving the bundle with a post-build script.
Edit:
I just tested changing this setting and building debug/release/test/etc versions of my project, and nothing changed about the bundle or archive that was build. Seems this setting has no effect on iOS apps.
Actually, after more testing it does change the directory inside a release archive. This is how the archive looks after changing that setting to ApplicationsTest:
[ 12:12 Jonathan@MacBookPro ~/Library/Developer/Xcode/Archives/2011-09-28 ]$ cd Universal\ 9-28-11\ 12.11\ PM.xcarchive/Products/
[ 12:12 Jonathan@MacBookPro ~/Library/Developer/Xcode/Archives/2011-09-28/Universal 9-28-11 12.11 PM.xcarchive/Products ]$ ll
total 0
drwxr-xr-x 3 Jonathan staff 102B Sep 28 12:11 ApplicationsTest
[ 12:12 Jonathan@MacBookPro ~/Library/Developer/Xcode/Archives/2011-09-28/Universal 9-28-11 12.11 PM.xcarchive/Products ]$ ll ApplicationsTest/
total 0
drwxr-xr-x 187 Jonathan staff 6.2K Sep 28 12:11 Universal.app
And changing it to SomethingElse:
[ 12:15 Jonathan@MacBookPro ~/Library/Developer/Xcode/Archives/2011-09-28/Universal 9-28-11 12.15 PM.xcarchive/Products ]$ pwd
/Users/Jonathan/Library/Developer/Xcode/Archives/2011-09-28/Universal 9-28-11 12.15 PM.xcarchive/Products
[ 12:15 Jonathan@MacBookPro ~/Library/Developer/Xcode/Archives/2011-09-28/Universal 9-28-11 12.15 PM.xcarchive/Products ]$ ll
total 0
drwxr-xr-x 3 Jonathan staff 102B Sep 28 12:14 SomethingElse
[ 12:15 Jonathan@MacBookPro ~/Library/Developer/Xcode/Archives/2011-09-28/Universal 9-28-11 12.15 PM.xcarchive/Products ]$ ll SomethingElse/
total 0
drwxr-xr-x 187 Jonathan staff 6.2K Sep 28 12:15 Universal.app
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Most efficient way to concatenate list within list without a loop public class Unicorn
{
public List<int> Numbers { get; set; }
}
unicorns.Add(new Unicorn() { Numbers = {1, 2, 3} } );
unicorns.Add(new Unicorn() { Numbers = {4, 5, 6} } );
unicorns.Add(new Unicorn() { Numbers = {7, 8, 9} } );
What's the most efficient way in c# 4 to concatenate all the lists into one list of {1, 2, 3, 4, 5, 6, 7, 8, 9 } ?
Preferably (ideally; by preference; if one had a choice) no loops and Linq-less. I tinkered around with .FindAll, but it's not digging it.
A: List<int> theInts = unicorns.SelectMany(unicorn => unicorn.Numbers).ToList();
Without measuring, the only thing in here that gives me pause from a performance perspective is the .ToList
If there are a TON of numbers, it's possible that ToList may repeatedly re-allocate its backing array. In order to escape this behavior, you have to have some idea about how many Numbers to expect.
List<int> theInts = new List<int>(expectedSize);
theInts.AddRange(unicorns.SelectMany(unicorn => unicorn.Numbers));
A: Here's a solution that fully meets your requirements: No Linq and no loop - I'm pretty sure you do not want to use this code though:
List<Unicorn> unicorns = new List<Unicorn>();
unicorns.Add(new Unicorn() { Numbers = new List<int>{1, 2, 3} } );
unicorns.Add(new Unicorn() { Numbers = new List<int> { 4, 5, 6 } });
unicorns.Add(new Unicorn() { Numbers = new List<int> { 7, 8, 9 } });
List<int> numbers = new List<int>();
int count = 0;
AddUnicorn:
if(count < unicorns.Count)
{
numbers.AddRange(unicorns[count++].Numbers);
goto AddUnicorn;
}
A: Your requirements are quite out of the ordinary, but I guess you can always write:
var numbers = new List<int>();
unicorns.ForEach(unicorn => numbers.AddRange(unicorn.Numbers));
ForEach() arguably qualifies as "LINQ-less", since it's a genuine member of List<T>, not an extension method on IEnumerable<T>, and it actually predates LINQ itself.
A: Using .NET 4.0's Zip operator:
var sums = b.Zip(a, (x, y) => x + y)
.Concat(b.Skip(a.Count()));
If you want to generalize this, check which has more elements and use that as the "b" above
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
}
|
Q: Proper Guid Mapping. Nhibernate I use an abstract Entity class which contains a Guid:
public abstract class Entity
{
public /*virtual*/ Guid Id { get; set; }
}
Suppose I also have a class like:
public class Post : Entity
{
public String Title { get; set; }
public String Content { get; set; }
public DateTime Timestamp { get; set; }
}
How do I properly map Post class using xml-mapping? I'm asking about Id.
A: <id name="Id">
<generator class="guid"/>
</id>
This will generate Guids on the client using the Guid.NewGuid() method.
Alternative generators are:
*
*guid.native - generates the Guids on the server side, e.g. using NEWID() on SQL server
*guid.comb - generates "sequential" Guids, which reduces index fragmentation.
I would recommend guid.comb for most applications that use Guid identifiers.
A: I'm using Asp.Net Core, with the Oracle.ManagedDataAccess NuGet package, and FluentNhibernate as mapping strategy.
In my case it was giving some errors when trying to get the data. The errors stopped, after mapping the Guid column as follows:
Id(x => x.Id, x =>
{
x.Generator(Generators.Guid);
x.Type(NHibernateUtil.Guid);
x.Column("ID");
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Elastic WrapPanel and TextTrimming I am attempting to create an Elastic WrapPanel.
Which means that each columns stretch itself to fit the panel's width until a new column fits inside the panel.
The columns width is based on a ItemMinWidth.
I was able to create the panel, but my problem is that if i put a TextBlock and set TextTrimming to CharacterEllipsis. In my panel it won't work. The 3 dots won't appear. It looks like the width of the column works, but the content seems to receive infinity as a width.
Here's my panel:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace WrapPanelTest
{
public class ElasticWrapPanel : Panel
{
#region Constructor
public ElasticWrapPanel()
{
}
#endregion
#region Properties
[TypeConverter(typeof(LengthConverter))]
public double ItemMinWidth
{
get
{
return (double)GetValue(ItemMinWidthProperty);
}
set
{
SetValue(ItemMinWidthProperty, value);
}
}
public static readonly DependencyProperty ItemMinWidthProperty = DependencyProperty.Register("ItemMinWidth", typeof(double), typeof(ElasticWrapPanel));
[TypeConverter(typeof(LengthConverter))]
public double ColumnWidth
{
get
{
return (double)GetValue(ColumnWidthProperty);
}
private set
{
SetValue(ColumnWidthProperty, value);
}
}
public static readonly DependencyProperty ColumnWidthProperty = DependencyProperty.Register("ColumnWidth", typeof(double), typeof(ElasticWrapPanel));
#endregion
#region Protected methods
protected override Size MeasureOverride(Size availableSize)
{
_uiElementsRect.Clear();
_columnCount = CalculateColumnCount(availableSize);
if (_columnCount > 0)
{
ColumnWidth = (int)Math.Floor(availableSize.Width / _columnCount);
double rowHeight = 0;
double lastRowHeight = 0;
int currentColumn = 0;
int currentRow = 0;
foreach (UIElement children in InternalChildren)
{
children.Measure(availableSize);
rowHeight = Math.Max(rowHeight, children.DesiredSize.Height);
Rect childrenRect = new Rect(0, 0, 0, 0);
childrenRect.X = currentColumn * ColumnWidth;
childrenRect.Y = lastRowHeight;
childrenRect.Width = ColumnWidth;
childrenRect.Height = children.DesiredSize.Height;
_uiElementsRect.Add(children, childrenRect);
currentColumn++;
if (currentColumn == _columnCount)
{
lastRowHeight += rowHeight;
currentRow++;
rowHeight = 0;
currentColumn = 0;
}
}
}
if (_uiElementsRect.Any())
{
double maxBottom = _uiElementsRect.Max(ui => ui.Value.Bottom);
return new Size(availableSize.Width, maxBottom);
}
else
return base.MeasureOverride(availableSize);
}
protected override Size ArrangeOverride(Size finalSize)
{
if (_columnCount > 0)
foreach (KeyValuePair<UIElement, Rect> keyValuePair in _uiElementsRect)
keyValuePair.Key.Arrange(keyValuePair.Value);
return base.ArrangeOverride(finalSize);
}
#endregion
#region Private methods
private int CalculateColumnCount(Size availableSize)
{
if (ItemMinWidth == 0 || Double.IsNaN(ItemMinWidth) || Double.IsInfinity(availableSize.Width))
return 0;
else
return (int)Math.Floor(availableSize.Width / ItemMinWidth);
}
#endregion
#region Private members
int _columnCount = 0;
IDictionary<UIElement, Rect> _uiElementsRect = new Dictionary<UIElement, Rect>();
#endregion
}
}
And here's an exemple, compared to a WrapPanel in which TextTrimming works:
<Window x:Class="WrapPanelTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WrapPanelTest"
Title="MainWindow"
Height="480"
Width="640">
<Window.Resources>
<Style x:Key="TextBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="Lorem ipsum dolor sit amet, consectetur adipiscing elit."/>
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
<Setter Property="Margin" Value="1"/>
<Setter Property="Background" Value="Silver"/>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<WrapPanel ItemWidth="200">
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
</WrapPanel>
<local:ElasticWrapPanel ItemMinWidth="200" Grid.Row="1">
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
<TextBlock Style="{StaticResource TextBlockStyle}"/>
</local:ElasticWrapPanel>
</Grid>
</Window>
You should see that in the WrapPanel the 3 dots appear at the end of each elements, but not in my panel.
A: Your TextBlocks don't have a size set, so are allowed to stretch as wide as they would like.
As an alternative, consider limiting their size in your MeasureOverride method
foreach (UIElement children in InternalChildren)
{
children.Measure(availableSize);
((FrameworkElement)children).MaxWidth = ColumnWidth;
// Other code
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: (To me) unexplainable value in character array I'm stuck with something I really don't understand and I hope someone over here does.
Can anybody explain me why 'nextOne' holds the value 51? It's clear that at index 2 in the expression array is the number 3 so why does it store 51 in stead of 3 in nextOne?
Here it is:
A: The character in the array is '3'. That has a Unicode value of 51 - it's character U+0033.
If you change the type of nextOne to char instead of int, you'll see '3' instead.
It's important to understand the difference between digits as characters, and integer values - and also to understand the numbers which lurk behind characters; in Java they're UTF-16 code units, basically.
A: Because 51 is the ASCII value for the numeral 3.
A: The character '3' corresponds to an integer value of 51 (it's ascii/unicode value).
A: The first digit is 3 and its ASCII code is 51.
A: nextOne contains the value of the character, which, in the case of the character '3' is 51.
If you want the digit represented by the character, you need to convert it. With ASCII, that can be done by subtracting the value of the character '0'.
A: 51 is the ASCII code for three, since expression is an array of chars, and nextOne is an int, you have to convert the char to an int
A: The ASCII code of the number 3 is 51. The following expression will print "true" in the console.
System.out.println('3' == (char) 51);
Have a look at an ASCII table for more information.
A: you see the ascii code of the character '3' if you want the digit you need to subtract '0' to get the integer value
A: I did it! It works now and I couldn't have done it without you guys.
However! Funny how all of you suggested options for me but not the (in my opinion) ultimate one. You guys told me the integer that was being stored is the ASCII code for 3, not the actual integer 3. That reminded me of a method in the Character class, getNumericValue(char). With this method I simply retrieved the integer 3 from the char array without converting myself.
nextNumber = nextNumber * 10 + Character.getNumericValue(expression[k]);
Thanks @howard for editing the link into the uploaded image
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL Left Join + Min Seemingly simple MySQL question, but I've never had to do this before..
I have two tables, items and prices, with a one-to-many relationship.
Items Table
id, name
Prices Table
id, item_id, price
Where
prices.item_id = items.id
What I have so far:
SELECT items.id, items.name, MIN(prices.price)
FROM items
LEFT JOIN prices ON items.id = prices.item_id
GROUP BY items.id
How do I also return the corresponding prices.id for that minimum price? Thanks!
A: This will return multiple records for a record in Items if there are multiple Prices records for it with the minimum price:
select items.id, items.name, prices.price, prices.id
from items
left join prices on (
items.id = prices.item_id
and prices.price = (
select min(price)
from prices
where item_id = items.id
)
);
A: New, working answer, based on the final example in the MySQL 5.0 Reference Manual - 3.6.4. The Rows Holding the Group-wise Maximum of a Certain Column:
SELECT items.id, items.name, prices.price, prices.id
FROM items
LEFT JOIN prices
ON prices.item_id = items.id
LEFT JOIN prices AS filter
ON filter.item_id = prices.item_id
AND filter.price < prices.price
WHERE filter.id IS NULL
The LEFT JOIN works on the basis that when prices.price is at its minimum value, there is no filter.price with a smaller value and the filter rows values will be NULL.
Original incorrect answer:
SELECT items.id, items.name, prices.price, prices.id
FROM items
LEFT JOIN prices ON prices.item_id = items.id
ORDER BY prices.price ASC
LIMIT 1
A: Ok, how about?
SELECT items.id, items.name, MIN(prices.price), prices.id
FROM items
LEFT JOIN prices ON items.id = prices.item_id
GROUP BY items.id, MIN(prices.price)
A: SELECT top 1 items.id, items.name, prices.price, prices.id
FROM items
LEFT JOIN prices ON items.id = prices.item_id
ORDER BY prices.price ASC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Adding a line break to a custom header css style? Newbie Q here: How can I add a linebreak in a custom header style?
h21
{
font-size: 1.52em;
/*Equivalent of a line break here...????*/
}
A: You cant add a linebreak in a class declaration, but you can add margin-bottom or padding-bottom: -10px or similar varieties. You can use firebug to measure how high a linebreak on your page appears and use that value for padding or margin -bottom.
h21 {
font-size:12.1px;
padding-bottom: 30px;
display: block;
}
A: you can use the word-wrap property. see here
an example:
h21 {
word-wrap: break-word;
}
obs: the container element should have a width
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Grails - Unit test a controller's method using the reCaptcha plugin I would like to unit test the following method:
def handleEmailSharing = { EmailSharingCommand esc ->
if (params.send) {
def recaptchaOK = true
if (!recaptchaService.verifyAnswer(session, request.getRemoteAddr(), params)) {
recaptchaOK = false
}
}
...
This is the way I am trying to do it:
import com.megatome.grails.RecaptchaService
class EmailSharerControllerTests extends ControllerUnitTestCase {
protected void setUp() {
controller.recaptchaService = new RecaptchaService()
}
void testHandleEmailSharingSendAndSuccess() {
mockCommandObject(EmailSharingCommand)
def emailSharingCommand = new EmailSharingCommand(from: "acorrect@emailaddress.fr",
to: " anothercorrect@emailaddress.fr , whichis@notalone.it ",
cc: "",
bcc:"someonein@bcc.com.br",
trimmedListOfToRecipients: ["anothercorrect@emailaddress.fr", "whichis@notalone.it"])
emailSharingCommand.validate()
}
controller.handleEmailSharing(emailSharingCommand)
But I get the following error:
Cannot get property 'recaptcha' on null object
java.lang.NullPointerException: Cannot get property 'recaptcha' on null object
at com.megatome.grails.RecaptchaService.getRecaptchaConfig(RecaptchaService.groovy:33)
at com.megatome.grails.RecaptchaService.this$2$getRecaptchaConfig(RecaptchaService.groovy)
at com.megatome.grails.RecaptchaService$this$2$getRecaptchaConfig.callCurrent(Unknown Source)
at com.megatome.grails.RecaptchaService.isEnabled(RecaptchaService.groovy:100)
at com.megatome.grails.RecaptchaService$isEnabled.callCurrent(Unknown Source)
at com.megatome.grails.RecaptchaService.verifyAnswer(RecaptchaService.groovy:81)
at com.megatome.grails.RecaptchaService$verifyAnswer.call(Unknown Source)
at bankemist.personalcreditcomparator.EmailSharerController$_closure2.doCall(EmailSharerController.groovy:49)
at bankemist.personalcreditcomparator.EmailSharerControllerTests.testHandleEmailSharingSendButtonButMissingFromAndTo(EmailSharerControllerTests.groovy:49)
Which is strange, because it basically says that my org.codehaus.groovy.grails.commons.ConfigurationHolder is null, or the recaptcha object it contains. The call line 33 of RecaptchaService.groovyis:
if (ConfigurationHolder.config.recaptcha) {...}
Or (last one :) ) this how my RecaptchaConfig.groovy is set:
recaptcha {
// These keys are generated by the ReCaptcha service
publicKey = "xxx"
privateKey = "xxx"
// Include the noscript tags in the generated captcha
includeNoScript = true
}
mailhide {
// Generated by the Mailhide service
publicKey = ""
privateKey = ""
}
environments {
development {
recaptcha {
// Set to false to disable the display of captcha
enabled = true
// Communicate using HTTPS
useSecureAPI = false
}
}
test {
recaptcha {
// Set to false to disable the display of captcha
enabled = true
// Communicate using HTTPS
useSecureAPI = false
}
}
I do not manage to work around this issue.
I have tried to import the configurationHolder into the test file but it does not chage anything. Any help greatly appreciated.
A: Unit tests will not have ConfigurationHolder because they are not executed inside the running framework. In unit tests the best option is to mock the RecaptchaService, so like this inside your test method:
def recapMock = mockFor(RecaptchaService)
recapMock.demand.verifyAnswer(1..1) { session, remoteAddr, params ->
return true // Or false if you want it to fail in your test
}
controller.recaptchaService = recapMock.createMock()
// Then run your test
controller.handleEmailSharing(emailSharingCommand)
A: You should inject a recaptchaService and mock the verifyAnswer to return whatever you want to return for your test case.
def recaptchaServiceMock = mockFor(recaptchaService)
recaptchaServiceMock.demand.verifyAnswer() {Session session,
Map params->
return true
}
currentService.recaptchaService = recaptchaServiceMock.createMock()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing objects to new objects $P1 = new Player(array(
'name' => 'Player 1',
'strat' => new Strategy(&$this)
));
This is more or less what I'm trying to do. The reference to $this is obviously wrong. What is the best way to accomplish something like this?
Basically, the new Strategy object needs to know what Player it belongs to.
Sure I could do like:
$P1 = new Player();
$P1->strat = new Strategy(&P1);
but that doesn't seem as concise.
Update:
I guess instead of passing the new strategy object in the array, I would pass the name of the strategy class instead, and then instantiate a new object in the Player constructor.
A: $P1->strat->owner =$P1;
That will be good enough.
Talk is on.
Okay, if we approach this question from theoretical and conceptual standpoint, we can address the implied question in a couple of different ways. Let's consider what Strategy to Player is.
As the name implies, Strategy is basically a driver, that could affect the behavior of the play in a particular environment. This further suggests that following approach would make sense:
$player->useStrategy($strategy);
further, player most likely would be to act in given scope, so, it would use the $strategy object as a controller, and would pass the input from whatever the conditions are met to the strategic behavior controller. That, given the player could either:
1) help on determining the activities to be undertaken
2) use players interface to respond to whatever the action the strategical behavior has to be applied to.
Now, we could assume that there could be different strategies, that could be easily applied to any Player, given that the strategy classes implement the Strategy Interface. In this scenario, Strategy, would not need to know anything about the player. If only, the there are different type of players having different interfaces that would allow for different set of controls. But in that case, it would be wiser to setup extended classes for the particular player classes to implement the extra functionality that those players provide.
class Strategy {
private $player;
public usePlayer($player){
$this->player = $player;
}
public makeNextMove($input){
1) return array($a,$b);
2) return new Behavior_NextMove()->setTarget($a,$b);
3) $this->player->move($a, $b);
}
}
class Strategy_MegaPlayer extends Strategy {
public makeNextMove($input){
parent::makeNextMove($input);
$player->useMegaPlayerSpecialPower();
}
}
Alternatively, there could be centralized Strategy object, which, through configuration interface, based on the type of the player would decided on the proper actions and strategies, both based on the player type and the configuration of its.
but it seems that properly structured strategic support classes would benefit you most.
A: You should use getters/setters:
$strategy = new Strategy();
$player = new Player('Player 1', $strategy);
$strategy->setPlayer($player);
Using the ampersand (&) prefix is unnecessary because objects pass by reference.
A: You could have the Player constructor pass $this to the Strategy object that was passed in by calling a setter on the Strategy.
However, you might want to reconsider whether the Strategy object really needs to point to the Player object or whether the Player object really needs to point to the Strategy object. If those two classes are that tightly coupled, it's a code smell. Perhaps some functionality needs to be moved from one to the other.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Objective C: Serializing/Archiving issues I'm an Android dev who's recently started IOSing. In all my of my Android projects, I have an IO class that does the following:
public static Object load(String fname , Context cont)
{
FileInputStream fis = cont.openFileInput(fname);
ObjectInputStream ois = new ObjectInputStream(fis);
Object loadedObject = ois.readObject();
ois.close();
fis.close();
Father.print("Loaded from file "+fname+" successfully");
return loadedObject;
}
and the equivalent for save. It works great, I can load and save instances from anything with it.
In Objective C, I'm using NSKeyedArchiver/NSKeyedUnarchiver. Archiving seems to work, but unarchiving causes this:
*** -[NSKeyedUnarchiver initForReadingWithData:]: data is empty; did you forget to send -finishEncoding to the NSKeyedArchiver?
I'm using the following static methods:
+(BOOL)saveObject: (id<NSCoding>)obj forKey:(NSString*)key;
{
NSKeyedArchiver *archiver;
NSMutableData *bytes = [NSMutableData data];
archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:bytes];
[archiver encodeObject:obj forKey:key];
[archiver finishEncoding];
NSLog(@"Successfully saved object <%@> to %@", obj, key);
return TRUE;
}
and
+(id)loadForKey:(NSString*)key
{
NSMutableData *bytes = [NSMutableData data];
NSKeyedUnarchiver *unrar = [[NSKeyedUnarchiver alloc] initForReadingWithData:bytes];
id result = [unrar decodeObjectForKey:key];
[unrar finishDecoding];
NSLog(@"Successfully loaded object <%@>", result);
return result;
}
I'm calling them as such
[IVIO saveObject:thing forKey:@"thekey"];
Thing *miracle = [IVIO loadForKey:@"thekey"];
What's going on?
Thank you
A: In your +loadForKey:
NSMutableData *bytes = [NSMutableData data];
NSKeyedUnarchiver *unrar = [[NSKeyedUnarchiver alloc] initForReadingWithData:bytes];
you're trying to read from an empty data object. Creating a mutable data object using [NSMutableData data] just gives you an object that contains nothing. You'll need to READ the data from somewhere. Likewise, in your +saveObject:forKey: you successfully archive the object, but you don't do anything with the resulting data object.
To fix, you'll want to write the data into a file or URL in your save method, and read it from a file or URL in your load method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Adding Html button and Onclick using Jquery? Here is what I am trying to do.
function showDescription(td)
{
var desc = $(td).children("input:first").val();
var Button = $('<input type="button" value="Accept" onClick=validateUserInput(' + desc + '); style="float:right;"/>');
var dlg = $("#div");
dlg.append(Button);
}
desc is in format of 49.595,-126.592 49.620,-126.602 49.642,-126.606
When I inspect the view source I see it in format.
<input type="button" style="float: right;" 49.620,-126.602);="" 49.642,-126.606="" onclick="validateUserInput(49.595,-126.592" value="something">
How do I indent desc so that its read as one single string.
Thanks.
A: You need to put quotes around the onClick attribute, otherwise it is treating each set of numbers as an attribute, not a value. Your button code should look like this:
var Button = $('<input type="button" value="Accept" onClick="validateUserInput(' + desc + ');" style="float:right;"/>');
A: To have it passed to the function as a single string surround your onclick method in single quotes and the value in double quotes (single always precedes double):
var Button = $('<input type="button"
value="Accept"
onClick=\'validateUserInput("' + desc + '")\';
style="float:right;"/>');
And if you want to parse them later:
function validateUserInput(string desc)
{
var descVals = desc.split(',');
// descVals[0] = "49.595"
// descVals[1] = "-126.592 49.620"
// etc.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to customize UISegmentedControl font color and UIToolbar gradient? It seems Apple's UIToolbar and some of the controls you can place on it, such as UISegmentedControl, allow very limited customization. For example, we want our toolbar to looks something like this mock:
However, UIToolbar only has a single tintColor and 3 built-in barStyle values that you can apply to it, so we can't get the gradient we're after. Is there some way to set the background image like many of the other controls?
Even worse, the UISegmentedControl doesn't let you specify font or font color. It seems to enforce white 11pt Helvetica with a drop shadow, and the white is almost unreadable with the light tintColor we're using.
I'd hate to rewrite UISegmentedControl just to change the text color. But the only solution I've seen is very hacky -- it digs into the subviews of the subviews and changes properties on those -- seems likely to stop working whenever Apple feels like changing or disallowing it.
Is Apple really against us changing the text color on our segmented controls, or is there something I'm missing here?
Update: Apple finally added functions for customizing appearance in iOS 5. See jfortmann's answer.
A: You want to use the setBackgroundImage:forState:barMetrics: methods (probably on your appearance proxy) to set the background image. The text can be modified with setTitleTextAttributes:forState:. And finally, you'll need to change the divider for the possible states with setDividerImage:...
The docs are very informative as to how the images have to look.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Typing Urdu/Arabic in TextEdit/TextView in Android I want to create a database in which i can add and retrieve the Urdu words. for this purpose i installed Inpage 2009 professional and copied its fonts (.ttf) into assets folder but it gave an error i.e
I also installed UrduFonts.exe and copied its font JameelNooriNastaleeq.ttf but it also gave the same error. i need the Urdu font that is compatible to the android , the font that can add and retrieve Urdu to and from the database using android.
this is how i coded foa a Lcd2Mono.ttf and i am having the true experience of that font but i am unsuccessful. here is my piece of code..
private EditText txt,start,urdu;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
urdu=(EditText) findViewById(R.id.urdu);
try
{
urdu.setTypeface(Typeface.createFromAsset(this.getAssets(),"urdu.ttf"));
urdu.setText("ur text");
}
catch(Exception ex)
{
start.setText(ex.toString());
}
i did some with Inpage Fonts and got Exception that Native Font.....
A: i think JameelNooriNastaleeq.ttf font is very huge, more than 10M (maybe somehow connected to your problem), i recommend to try something much more smaller like: http://www.quran.or.kr/urdu/font/asunaskh.ttf
but still issue with connecting the urdu characters, like in this question:
how to add language support to android
what exception you got?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Facebook Like button using PHP My knowledge of Facebook's PHP SDK is limited at this point but is it possible to use their PHP SDK to create a text link version of their 'Like' button?
A: No, I'm afraid this is not possible.
A: I am currently using the Like button as well as the like box on our Website but the JS SDK has a kind of high execution time and takes a while to load and thus I am currently looking for a proper way to avoid the JS SDK.
The Like button can - more or less - be replaced with the Graph API whereas the like box can't.
To set a like for an object (website, photo, link, whatever) you can simply call the graph api with the method=post Parameter.
<?php
require_once("facebook.php"); //from the FB SDK
$config = array();
$config['appId'] = 'your_app_id';
$config['secret'] = 'your_app_secret';
$facebook = new Facebook($config);
$user = $facebook->getUser();
if(!$user){
$loginUrl = $facebook->getLoginUrl(array('scope'=>'publish_stream, user_likes', 'redirect_uri'=>'www.example.com'));
}
if($user){
try{
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$access_token = $facebook->getAccessToken();
$attend = "https://graph.facebook.com/www.example.com/like?method=post&access_token=".$access_token;
file($attend);
}
catch(FacebookApiException $e){
error_log($e);
$user = NULL;
}
}
else{
echo '<a href="'.$loginUrl.'">Please login via Facebook</a>';
}
?>
You'll need an FB Application though, as you have to specify the app_id and app_secret for the PHP SDK, which you don't have to when you are using just the like button.
A: There's a /likes graph API object that the docs say you can write to with the proper permissions. I've never tried it though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create different RootViewController instances depending on the target I want to instance the RootViewController with different objects depending on the target I'm the running.
For example,
I have 3 RootViewControllers (RVCBase, RVCA, RCB) and 4 targets (T1, T2, T3, T4). I want that whenever T1 is running, RVCA shows as the RootViewController; when T2 runs, RVCB; and when either T3 or T4 is running, the RCVBase shows.
Any help?
Thanks in advance.
A: Add define for exemple (T1, T2, T3, T4) with preprocessor macros. see build settings tab
You can handle in code with:
#ifdef T1
//do something
#elif T2
//do something
#elif T3
...
#endif
A: Use [self.window setRootViewController:rvca]; to set the RootViewController for the window.
You will have to set for the target and then pass in the RVC you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ajax call works great, but non-ajax call renders wrong in browser. What did I miss? In a non-ajax call, the ordering of divs inside other divs gets messed up and the page renders wrong. When the same call is done via Ajax, the page renders perfectly.
So I have this search form on my master page:
<form action="<%=Url.Action("Search") %>" method="post" id="search1" class="search-form">
Search:
<%=Html.TextBox("SearchBox1", null)%>
<input type="submit" value="Go" />
</form>
.....
<div id="search-results">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
I also have this javascript to submit the search form using Ajax:
$('.search-form').ajaxSubmit(GetSearchAjaxFormOptions());
and
function GetSearchAjaxFormOptions() {
return { target: '#search-results',
data: GetSearchData(),
success: RunAfterAjaxSubmit()
};
}
when the form is sumbitted via Ajax, everything renders beautifully. When I turn Ajax off and submit the form, The rendered html is messed up. Like there was a misplaced element or something in there. The divs on the page do not end up inside the right divs. I looked at and diffed and ... all sorts of thing to find the difference, and I cant see any thing that would cause this.
My controller method is:
public ActionResult Search()
{
if (Request.IsAjaxRequest())
{
return View("SearchResultsPartial", sm);
}
else
{
return View("Index", sm);
}
}
My Index.aspx is:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
Html.RenderPartial("SearchResultsPartial");
</asp:Content>
and my SearchResultsPartial.ascx is:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyWebSite.Models.SearchModel>" %>
<%
int count = Model.searchResults.Count();
for (int i = 0; i < count; i++)
{
Response.Write(Model.searchResults.ElementAt(i));
}
%>
My model has:
public IEnumerable<String> searchResults;
So an important thing is that the search engine returns to the model a collection of strings. Each string is an html of a search result. This was generated by using linq to xml and is really the result of the XElement.ToString() call.
And my master page has:
<div id="search-results" class="yui-u">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
Any help in finding what to do to fix this is most appreciated. I have ran out of things to look at myself.
Many thanks!
A: Okay,
The linq to xml engine does not understand that div tags are not self closing and for empty div tags it creates <div />. Somehow the browsers handle this just fine when doing an ajax call and mess it up when doing a non-ajax call. This behavior is standard among all browsers.
So the solution was to put a blank space in the empty div tags generated by linq to xml. So we end up with <div> </div> and not <div/>.
new XElement("div", new XAttribute("class", "my-class"), "");
And then everything works out perfectly.
A: Try to replace
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
Html.RenderPartial("SearchResultsPartial");
</asp:Content>
with
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<div id="search-results">
Html.RenderPartial("SearchResultsPartial");
</div>
</asp:Content>
in Index.aspx.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Arrary with URL's--Convert to Clickable Links I have an array of URL's that I'm getting from a CAML query (something like: http://www.domain.com/site/files/doc1.pdf,http://www.domain.com/site/files/doc2.pdf). The array can have any number of comma-separated URL's depending on the query. What I need to do, and cannot wrap my head around, is take each one of those URL's, get the filename, then somehow create DOM elements such as <a href=http://www.domain.com/site/files/doc1.pdf>doc1</a>. I don't know if it would need a 2D array or what but this is a bit above my level. The array name is 'filesarray' and I know that you can get the filename from the URL by doing:
var index = filesarray.lastIndexOf("/");
var filename = filesarrary.substr(index);
Apart from that I'm pretty lost. Any help would be greatly appreciated.
A: var arr = [
'http://www.domain.com/site/files/doc1.pdf',
'http://www.domain.com/site/files/doc2.pdf',
]
for (i in arr) {
var href = arr[i];
var text = arr[i].split('/').pop();
$('body').wrap('<a href="'+href +'">'+text+'</a>'); //or append/prepend/html istead wrap
}
A: How about something like this?
var urlArray = listOfUrls.split(",");
var i;
var index = 0;
var filename = "";
$(urlArray).each(function(i, url){
index = filesarray.lastIndexOf("/");
filename = filesarrary.substr(index);
var elem = $('<a href="'+url+'">'+filename+'</a>');
//do whatever you want with the dom element,like:
$("body").append(elem);
});
I'm assuming that listOfUrls holds a comma separated list of urls (as you stated).
Let me know if it works the way you want it, or I can modify it a bit.
A: try this:
<div id="linksHolder"></div>
<script type="text/javascript">
var stringOfLinks = "http://something.com/something.pdf, http://something1.com/somethingElse.doc";
var arrayOfLinks = stingOfLinks.split(",");
var fileName = '';
var index = '';
for(var i=0; i<arrayOfLinks.length; i++) {
index = arrayOfLinks[i].lastIndexOf("/");
fileName = arrayOfLinks[i].substr(index);
$("#linksHolder").add('<a href="'+arrayOfLinks[i]+'">'+fileName+'</a>')
}
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why Animals[] animals = new Cat[5] compiles, but List animals = new List() does not? In his book C# in Depth, Jon Skeet tries to answer the following question:
Why can't I convert List<string> to List<object>?
To explain it, he started with a code-snippet, which includes these two lines:
Animal[] animals = new Cat[5]; //Ok. Compiles fine!
List<Animal> animals = new List<Cat>(); //Compilation error!
As the comments read, the first one compiles fine, but the second one gives compilation error. I didn't really understand the reason. Jon Skeet explained this with saying only that first one compiles because in .NET, arrays are covariant, and second one doesn't compile because generics are not covariant (they're invariant, instead). And furthermore, arrays are covariant in .NET, because arrays are covariant in Java and .NET made it similar to Java.
I'm not completely statisfied with this short-answer. I want to know it in a more detail, with some insight into how compiler handles the difference, and how it generates IL and all.
Also, if I write (taken from the book itself):
Animal[] animals = new Cat[5]; //Ok. Compiles fine!
animals.Add(new Turtle()); //this too compiles fine!
It compiles fine, but fails at runtime. If it has to fail at runtime(which means what I write shouldn't make sense), then why does it compile in the first place? Can I use the instance animals in my code, and which also runs with no runtime error?
A:
If it has to fail at runtime, then why does it compile in the first place?
That's precisely why array covariance is broken. The fact that we allow it means that we allow what should be an error that gets caught at compilation time to be ignored, and instead get caught at runtime.
I'm not completely statisfied with this short-answer. I want to know it in a more detail, with some insight into how compiler handles the difference ...
The compiler handles the difference easily enough. The compiler has a whole bunch of code that determines when one type is compatible with another. Part of that code deals with array-to-array conversions. Part of that code deals with generic-to-generic conversions. The code is a straightforward translation of the relevant lines of the specification.
... and how it generates IL and all.
There is no need to generate any IL whatsoever for a covariant array conversion. Why would we need to generate IL for a conversion between two reference-compatible types? It's like asking what IL we generate for converting a string to an object. A string already is an object, so there's no code generated.
A: Arrays have a weird history with variance in .NET. Proper support for variance was added in the 2.0 version of the CLR - and the language in C# 4.0. Arrays however, have always had a covariant behavior.
Eric Lippert goes into great detail on that in a blog post.
The interesting bit:
Ever since C# 1.0, arrays where the element type is a reference type are covariant. This is perfectly legal:
Animal[] animals = new Giraffe[10];
Since Giraffe is smaller than Animal, and “make an array of” is a covariant operation on types, Giraffe[] is smaller than Animal[], so an instance fits into that variable.
Unfortunately, this particular kind of covariance is broken. It was added to the CLR because Java requires it and the CLR designers wanted to be able to support Java-like languages. We then up and added it to C# because it was in the CLR. This decision was quite controversial at the time and I am not very happy about it, but there’s nothing we can do about it now.
Emphasis added by myself.
A: I think Jon Skeet explained it rather well, however if you need that "Ahah" moment consider how generics work.
A generic class like List<> is, for most purposes, treated externally
as a normal class. e.g. when you say List<string>() the compiler says
ListString() (which contains strings) and the compiler can't be smart
enough to convert a ListString to a ListObject by casting the items of
its internal collection.
From reading MSDN blog post, it appears that covariance and contravariance is supported in .NET 4.0 when when working with delegates and interfaces. It mentions Eric's articles also in the second sentence.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Can Fiddler monitor traffic other than HTTP I have developed a Client/Server type application. XML data is passed between the client and server. I want to simulate how it would run on a very slow network (i.e. radio @ 9.6kps). I understand Fiddler can be used in simulate modem speeds mode. But no matter what I do I cannot configure Fiddler to accept traffic from the client and redirect it to the server. And I have also tried a "reverse proxy" too.
Does Fiddler work with protocols other than HTTP?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: pyramid_handlers not working I'm currently moving a project from Pylons 1.0 to Pyramid.
My problem so far is how to use restful routes in Pyramid. I'm currently using pyramid_handlers since it seemed like a good start. I'm using Akhet.
So here is the two important lines in my route:
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts")
# or
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new")
My action:
@action(name="new_account", renderer='accounts/new.mako', request_method='GET')
The errors:
TypeError: 'Accounts' object is not callable
or
ValueError: Could not convert view return value "{}" into a response Object.
Accounts... so far so good, it is easy to understand that pyramid_handlers doesn't seem to register normally or handle name as it should... that said in request.matched_route, I do have "new_account".
If I add "action='new'" in the route definition, it will find the function but it will not listen to the action definition. In other words, it will fail to find a renderer and expect a response object. The request_method parameter doesn't actually do anything yet, so removing it doesn't change any results.
In short, the @action(name="..." doesn't work. Pyramid fails to find the function by itself and if the function name is defined it fails to execute the action statement.
No idea what I'm doing wrong.
Correct way to do it.
config.add_handler("new_account", "/accounts/new", "sproci2.handlers.accounts:Accounts", action="new_account")
EDIT
route_name is probably going to get used by url generator functions. While action is the actual name in @action. As I understood, @action name was the route_name and not the action name. That makes more sense now.
A: Well a call to add_handler needs an action pattern. So that's either adding {action} to the url pattern, or setting action= as an argument. Those actions must match the names defined in @action decorators. In your example, you named the action new_account, yet you called add_handler with an action of new. Thus they aren't properly connected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Serialize list of employees in java I have a simple employee class:
class Employee {
private int id;
private String firstName;
private String lastName;
private String streetAddress;
private String city;
private String state;
private String zip;
private String cellularPhoneNumber;
private String homePhoneNumber;
public Employee(int id, String firstName, String lastName, String streetAddress, String city, String state, String zip, String cellularPhoneNumber, String homePhoneNumber) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.streetAddress = streetAddress;
this.city = city;
this.state = state;
this.zip = zip;
this.cellularPhoneNumber = cellularPhoneNumber;
this.homePhoneNumber = homePhoneNumber;
}
}
How could I go about serializing multiple employees to a file? I know how to serialize one object, but how could I have multiple ones?
Could somebody point me in the right direction or provide a sample of serializing multiple objects? Would I be better off using a database like SQLite?
Much thanks in advanced.
A: The collections in java.util are Serializable. So if you make your Employee class implement Serializable, then put your employees in an ArrayList, then you can serialize the list and it will save the employees.
HSQLDB and H2 are in-memory databases implemented in Java that may be good alternatives to SQLite (meaning easier to use from a Java program). For general learning purposes using a database is a more practical skill, serializing things is not something I do a lot (when my code does use serialized classes the actual serialization is left up to the environment, such as when storing things in an HttpSession).
A: *
*add(..) the objects to a List - for example an ArrayList
*serialize the list
As for your SQLite question - I can't tell. Generally, you shouldn't use serialization as a database storage, but if your application is simple, it should suffice.
A: List<Employee> e = new ArrayList<Employee>() {{
add(new Employee(...));
add(new Employee(...));
add(new Employee(...));
add(new Employee(...));
add(new Employee(...));
}};
Employee implements Serializable {
.....
}
?
A: I would recommend to go for serialization using Jackson , JSON .
The benefit is that after serializing, you can atleast see your Data. Java Serialization is limiting in many aspects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem with pay pal subscriptions I have implemented pay pal subscriptions (daily) for some service on site. But I have problem with time.
User pay for subscription at 10:30AM I receive IPN message save it to database and give user 24 hours to use service. When after 24 hours pass I want to give user another 24 hours to use service etc.
I tested this yesterday and next IPN message I have received at 1:20PM today. This is more than 24 hours. But I can't let user wait 2 or 3 hours more for payed subscription.
I have option to give user 24 + 5 hours but I don't know is this ideal solution or it is?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating an URL with javascript and a variable for jQuery ajax call I'm trying to use timthumb to dynamically resize an image using jQuery ajax:
load_link = "/images/timthumb.php&src=" + link + "&h=194&w=263";
/* /images/timthumb.php&src=http://farm4.static.flickr.com/3631/5836439169_2230db5e6d_m.jpg&h=194&w=263 */
$.get(load_link, updateLink);
function updateLink(data) {
$('#flickr-first-photo').attr('src',data);
}
But I'm getting no response back from the ajax call. Does anyone know if this is even possible with timthumb?
A: probably because the URL is not valid. Try to use this:
load_link = "/images/timthumb.php&src=" + encodeURI(link) + "&h=194&w=263";
A: This worked:
load_link = encodeURI("&src=" + link + "&h=194&w=263&marko=1");
$.get('/images/timthumb.php', load_link, updateLink);
function updateLink(data) {
$('#flickr-first-photo').attr('src',data);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7588201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.