text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How to inherit keyboard property? Hi I have created my own keyboard and added my keyboard to the inputview of the uitextview it is working properly. Now I want to inherit all the property of uitextview like Auto-correct,word-capital etc etc.How can I inherit all that property.
I have tried like this
[uitextview conformsToProtocol:@protocol(UITextInputTraits)];
but this doesn't work. what can I try more to get all the property of uitextview
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java Code - NullPointerException I'm making a game and it is giving me a NullPointerException which I believe means the variable or what I'm trying to do is not returning a value? I'm using the code below:
package OurGame;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Coin extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Image img;
int x,y;
Timer t;
Random r;
public Coin() {
x = 50;
y = 50;
System.out.println("New coin created: " + x + ", " +y);
ImageIcon i = new ImageIcon("C:/coin.png");
img = i.getImage();
System.out.println(i);
t = new Timer(3000,this);
t.start();
}
@Override
public void actionPerformed(ActionEvent arg0) {
move();
}
public void move() {
setX(r.nextInt(640));
setY(r.nextInt(480));
}
public void setX(int xs) {
x = xs;
}
public void setY(int ys) {
y = ys;
}
public Image getImage(){
return img;
}
public int getX(){
return x;
}
public int getY() {
return y;
}
}
The error is happening here:
setX(r.nextInt(640));
The full error output is below:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at OurGame.Coin.move(Coin.java:46)
at OurGame.Coin.actionPerformed(Coin.java:40)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I dont see any reason for this to happen but maybe you can help.
Thanks.
A: You are using r without ever saying r = new ....
A: You need to initialise the variable r. Check out the constructors for java.util.Random, for example:
Random r = new Random();
A: r is null. Initialize it first. Put this in your constructor:
r = new Random();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Waiting for an update What is the best way to wait for an event/update. For example, I am waiting for this data structure to be updated before doing something. Implementing it inside a loop is not the best way since it consumes much CPU time like:
while (true) {
// keep checking the data structure
// if data structure is updated
// break;
}
// do something here
What's a simple but efficient way to implement something like this in Java?
A: It really depends on the structure of the rest of your program. I would probably start by looking through java.util.concurrent to see if something in there suits you.
Examples of ways you could do this:
*
*Futures - If you have some 'work' to be done, you can have a thread pool executor service to perform the work. When you call submit() to do your work, you get a future that you can check or block until the work is completed.
*Queues - If you have one component doing the work and one component doing the waiting, you could have their communication done with queues. Any time one is done with working on the data, it can add to a queue. You could use the LinkedBlockingQueue and poll() for the work to be completed.
*Listeners - Without concurrent at all, you could use the Listener/Observer pattern.
There are lots of different options depending on your application structure.
A: wait-notifyAll is more efficient way than loop.
Standard idiom for wait():
synchronized (obj) {
while(condition not hold)
obj.wait();
}
But it's primitive way to control threads, you'd better use classes in java.util.concurrent package. Moreover, I will choose Chris Dail's answer if I meet such problem.
A: This is a code sample i would do.
In this logic I use join method in threads. This makes sure all the threads are joined before the execution of the main thread continues. I have put TODO for locations u need to add your code
import java.util.ArrayList;
import java.util.List;
public class MultiThread extends Thread{
public void run() {
System.out.println("Starting Thread - " + this.getName()+this.getThreadGroup());
//TODO data structure is updated here
}
public static void main(String[] args) {
List dataStructureList = new ArrayList() ;//TODO need to replace with list of data structure
//TODO dataStructureList contain list of items
Thread[] threadArr = new Thread[dataStructureList.size()];
for (int j = 0; j < threadArr.length; j++) {
threadArr[j] = new MultiThread();
threadArr[j].setName("Thread " + j);
threadArr[j].start();
}
try {
for (int j = 0; j < threadArr.length; j++) {
threadArr[j].join();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("All thread finished");
//TODO do something here
}
}
A: Assuming that you use multi-threading in an application. To use one object with several threads you should use synchronization. While one thread initializes data structure, other wait for finishing of initialization. This logic is usually implemented using wait/notify methods which can be called on any object.
Working thread(s):
while (initialized) {
synchronized (object) {
object.wait();
}
}
Initialization thread:
synchronized (object) {
// initialization
initialized = true;
object.notifyAll();
}
object is the data structure which should be initialized. The initialized flag used to indicate that the initialization has completed. It is better to use this flag because sometimes wait can be finished without corresponded notify.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to traverse a JSON file? The JSON I have is mentioned below :-
{ head: {
link: [],
vars: [
"CompanyName",
"Company_Name",
"Foundation_URI",
"Foundation_Name",
"Latitude",
"Longitude"
] }, results: {
distinct: false,
ordered: true,
bindings: [
{
CompanyName: {
type: "uri",
value: "http://dbpedia.org/resource/United_Christian_Broadcasters"
},
Company_Name: {
type: "literal",
xml:lang: "en",
value: "United Christian Broadcasters"
},
Foundation_URI: {
type: "uri",
value: "http://dbpedia.org/resource/Christchurch"
},
Foundation_Name: {
type: "literal",
xml:lang: "en",
value: "Christchurch"
},
Latitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "-43.52999877929688"
},
Longitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "172.6202850341797"
}
},
{
CompanyName: {
type: "uri",
value: "http://dbpedia.org/resource/United_Christian_Broadcasters"
},
Company_Name: {
type: "literal",
xml:lang: "en",
value: "UCB Media"
},
Foundation_URI: {
type: "uri",
value: "http://dbpedia.org/resource/Christchurch"
},
Foundation_Name: {
type: "literal",
xml:lang: "en",
value: "Christchurch"
},
Latitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "-43.52999877929688"
},
Longitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "172.6202850341797"
}
},
{
CompanyName: {
type: "uri",
value: "http://dbpedia.org/resource/Kathmandu_%28company%29"
},
Company_Name: {
type: "literal",
xml:lang: "en",
value: "Kathmandu"
},
Foundation_URI: {
type: "uri",
value: "http://dbpedia.org/resource/Christchurch"
},
Foundation_Name: {
type: "literal",
xml:lang: "en",
value: "Christchurch"
},
Latitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "-43.52999877929688"
},
Longitude: {
type: "typed-literal",
datatype: "http://www.w3.org/2001/XMLSchema#float",
value: "172.6202850341797"
}
}
] } }
I want to know that how can I traverse this JSON to get the values of the appropriate variables as mentioned in the JSON file. I would like to know this with respect to JavaScript as well as Java. Please let me know how to traverse this JSON so as to get data easily.
A: This is not a JSON string but luckily a YAML standrd format.
You can use YAML library to transverse your jSON-like string
A: Here is a rather simple tree traversal routine:
function traverse(o) {
if( o instanceof Object ) {
for( key in o ) {
traverse(o[key]);
}
}
else if( o instanceof Array ) {
for( value in o ) {
traverse(value);
}
}
else {
console.log(o);
}
}
var q = { name : 'me', data : [ { a: 'a1', b: 'b1' }, { a: 'a2', b: 'b2'} ] };
traverse(q);
However, I think this is not quite what you're looking for. Please clarify and I will update my answer accordingly.
A: Following is a simple traversing of JSON object, this should help you undersatnd your JSON object normal traversing. Check the https://github.com/substack/js-traverse link for a detailed tutorial for complex traversing of any javascript object
<script language="javascript">
var emp = {"details" : [
{
"Name" : "Nitin1",
"Salary" : 10000,
"DOJ" : "16th Sept 2010"
}
,
{"Name" : "Abhijit2",
"Salary" : 5000,
"DOJ" : "15th Sept 2010"}
,
{"Name" : "Nilesh",
"Salary" : 50000,
"DOJ" : "10th Sept 2010"}
]
};
document.writeln("<table border='1'><tr><td>Name</td><td>Salary</td><td>DOJ</td></tr>");
var i=0;
for(i=0;i<emp.details.length; i++)
{
document.writeln("<tr><td>" + emp.details[i].Name + "</td>");
document.writeln("<td>" + emp.details[i].Salary +"</td>");
document.writeln("<td>" + emp.details[i].DOJ +"</td></tr>");
}
document.writeln("</table>");
</script>
A: If you only want to retrieve particular values - you do not need to traverse the entire JSON file.
This can be done in Javascript as follows:
Declared JSON variable:
var myJSONObject = {"bindings": [
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
{"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
{"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
]
};
Fetch a particular value:
myJSONObject.bindings[0].method // "newURI"
For a full reference you can go here.
I do not use Java myself, but XML.java (documentation available here) allows you to convert the JSON into XML. Parsing an XML is easy - you will find plenty of tutorials on it for Java such as:
http://www.seas.gwu.edu/~simhaweb/java/xml/xml.html
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A C program to crash the system A few days back I had an interview, and I was asked to write a program in C which crashes the system/which shuts down the system. Needless to say I felt pretty dumb having no clue on how to even approach :(
Still I gave it a try, writing programs which use a lot of memory. But my interviewer was not satisfied with any of my techniques.
A: It's easy to write a program that invokes undefined or implementation-defined behavior. Some of those programs could potentially crash the system.
But by definition, this is inconsistent. And modern OSes take pains (though not 100% successfully) to prevent a rogue app from crashing the system.
A: There is no portable way to write a C program that crashes the system.
A fork bomb might or might not bog down a system. Of course fork is not portable -- and a system can defend itself against such attacks by limiting the number of processes a given account can create.
Of course there's always this:
#include <stdio.h>
int main(void) {
puts("HEY YOU, PULL THE PLUG!!");
return 0;
}
A: I would try writing garbage to /dev/kmem. There is a good chance that would cause an irrecoverable system crash.
A: Well, Have you tried following ?
void main(void) {
system("shutdown -P 0");
}
To execute this program on Linux you must log in as root.
A: One way to do that is by exploiting "Privilege Escalation" vulnerabilities of the current system.
Based on current configuration, you can search for vulnerabilities that impact the system. E.g. based on Kernel version. And then escalate privileges to root.
Once the process is "root", it can shutdown the system in various ways. Sending SIGPWR to "init" process is one clean way of doing that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: IE does not recognising .less file I create a less file which is working fine in chrome and firefox, but not even recognising in IE 9. Can anyone please suggest what needed to run it in IE 9.0. below is the css sample..
@import "../core/variables.less"; @import "Mixins.less";
.classname {
@fontweight:bold;
@width:99.9%;
@height:67px;
@color:#D3E2F2;
@icon-width:10px;
@icon-height:10px;
.div-carddropdownbox{
width:90%;
}
.span(@fontweight)
{
font-weight:@fontweight;
}
.span-underline(){
.span(bold);
text-decoration:underline;
}
.span-bold{
.span(bold);
text-decoration:none;
font-size: 15px;
}
.div(@width,@height)
{
float:left;
width:@width;
height:@height;
padding-top: 10px;
padding-bottom: 10px;
}
.div-tracethistransaction
{
.div(100%,100%);
border:1px solid black;
}
.div-servicerequestcharge{
.div(99.9%,67px);
background-color:@color;
border:1px solid black;
}
.div-account
{
.div(99.9%,35px);
background-color:@color;
}
.div-white-blank
{
.div(99.9%,2px);
}
.div-button
{
padding-top:110px;
}
.div-carddelivered
{
.div(100%,45px);
}
.icon(@icon-width,@icon-height)
{
width:@icon-width;
height:@icon-height;
}
.div-icon
{
.icon(20px,20px);
padding-left: 580px;
}
.round-button-cancel {
.rounded-button (7px, #ECECEC, #A9A9A9,none, bold, #52504C,
90px, 35px);
}
.round-button-submit {
.rounded-button (7px, #FAF5E9, #EFAE2C,none, bold, #8B4513,
Auto, 35px);
}
}
A: Check the LESS site, it says that it doesn't support IE. None of its versions.
A: Make sure you're including the less.js script. It's needed to parse less files.
http://lesscss.org/
If this is a .NET project, and you don't want to use less.js (which can add overhead on the client-side for larger .less files), you could add the DotLess library to your project.
http://www.dotlesscss.org/
A: I've run into the same issue. I simply compile it into a .css file and reference that for live testing, including IE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any XMPP Jingle Implementation in Javascript Is there any XMPP Jingle Implementation in Javascript, I only see libJingle library written in C++.
A: I know that this post is old, but there is one now: https://github.com/legastero/jingle.js
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how can get response from There is a simple web page which sends request, handles & manipulated by a servlet class and send back the response text.while i want ajax type handleing the request at client side that is why i am giving the response target to a invsible iframe. *but i want to print success on the page after iframe gets the response *
<html> <body>
<form action="test" method="post" target="IFrame"> /*response target is iframe*/
<input type="text" name="logic" />
<input type="submit" value="Submit" />
</form>
<iframe name="IFrame" style="width:0; height:0"> </iframe>
</body> </html>
i think this can be done using javascript or jquery, please guid me if you have any idea.
A: In the page which loads in the iframe, you will need to invoke a parent function.
<!-- This is the Parent. Call it JSTest1.html -->
<html>
<head>
</head>
<body>
<script type="text/javascript">
function parentAlert() {
alert('hey there from the parent');
}
</script>
I'm the parent
<iframe src="/JSTest2.html"></iframe>
</body>
<!-- this is the iframe html loaded. Call it JSTest2.html-->
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function() {
window.parent.parentAlert();
});
</script>
In the Iframe.
</body>
A: To send a message from Iframe to Parent window page:
<script type="text/javascript">
$(document).ready( function() {
//Message part is two parts Event name and Data you want to send
// Example message = "my_action,my_data"
message = "my_action,my_data"
parent.postMessage(message, "*");
});
</script>
At the parent window you can do the following to listen to this message and capture it:
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// Youe message which you send is captured here in e.data will split it on ',' to get the event and the data
message = e.data.split(',')[0]
value = e.data.split(',')[1]
if ( message === "my_action" ) {
myParentFunction(value)
}
},false);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook Graph Api pagination not working I have been trying to retrieve the wall feed of a facebook user using the graph api with the url https://graph.facebook.com/me/feed?access_token=ACCESS_TOKEN where ACCESS_TOKEN is the access_token used for querying.
The first query, i.e using the above url works fine, but it shows only few latest feeds from the user's wall. To get the next feeds, the url contained in the [next] field of the json array returned is to be used(as mentioned in the facebook documentation). Earlier it worked fine, but from last few days it just shows an Empty array.
Any Help Appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is there any way to reuse / make serializable LatLng and LatLngBounds types in GWT? Any alternatives? I was so excited to use GWT Maps API that wrote a service which takes LatLng and LatLngBounds in its interface... Only to find out at runtime that those classes do not implement Serializable, probably because they are Javascript native objects.
What would be the best approach to work with location data types on the server side with GWT then? Are there any libraries which already provide serializable classes and conversion to/from LatLng & company? Or everybody just writes their own wrappers?
A: See if any of this code I wrote helps you out:
https://github.com/dartmanx/mapmaker/blob/master/src/main/java/org/jason/mapmaker/client/util/GoogleMapUtil.java
GWT provides the ability to create Custom Field Serializers for classes that don't implement Serializable (or IsSerializable). However, JavaScriptObject is an odd duck indeed and doesn't let you directly access any of its data members on the Java side. So, writing a serializer is going to be a challenge at best.
You may also wish to have a look at google's docs about what sorts of values can be returned:
http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html#passing-javascript
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Maven2:List return type methods not getting generated from .xsd files while using xmlbeans plugin I am tring to build my project using maven2.This project was succesfully build using ANT in netbeans IDE.
Now the problem is, I am able to generate the .java files from .xsd files using xmlbeans maven plugin.But some getter setter methods having java.util.list as return type is not getting generated.
Please help me..I am not able to do my build beacuse of this :(
A: You need to set the javasource version to 1.5 to get List support in XmlBeans.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: U-boot 1.6.6 : I am trying to Edit the Source code to Enable PCI for MPC8640 Custom Board I have gone through the Source Code . The CONFIG_PCI is defined in the u-boot/include/configs/MPC8641HPCN.h file [General]. This MACRO has been Enabled in the .h file which says if i compile the configuration for this board the PCI will be Enumerated and will find out the devces Located on the Bus.
Using the Functions Defined : cmd_pci.c : u-boot/common/cmd_pci.c
void pci_header_show(pci_dev_t dev);
void pci_header_show_brief(pci_dev_t dev);
void pciinfo(int BusNum, int ShortPCIListing)
PCI_BDF(BusNum, Device, Function);
pci_read_config_word(dev, PCI_VENDOR_ID, &VendorID);
pci_read_config_byte(dev, PCI_HEADER_TYPE, &HeaderType);
Now guys , I have stucked and Some concept..Memory mapping...I have DDR interfaced to the Processor..and Also not able to find which code points to the Memory Mapping in the Current U-boot.
Also if any body could just state the Flow of Enumeration functions..files and Memory mapping ..with few hints will be Beneficial..I have been going through some books "PCI system Architecture " but they are general and does not point to any topic specifying..how to Enumerate A PCI ..when MPC8640 Processor is acting as HOST.
Thanks And Regard's
Hrishikesh!
A: U-Boot 1.6.6 doesn't exist. See the list of U-Boot releases at ftp://ftp.denx.de/pub/u-boot/. If you're talking about 1.1.6, then that's a prehistoric release, and you will hardly get any sort of support from the open-source community if you stick with such an old version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drawing charts on html5 canvas using jqplot I am using jqplot charts for drawing different charts on html5 canvas. All charts are working well in all browsers but vertical bar(stacked and clustered) and line charts are getting overlapped in safari. Any reason why is this happening?
The following code lines i have used to draw clustered bar chart:
function DrawChart(chartId, chartType, categories, seriesWithData, grouping)
{
/*for(var i=0;i<seriesWithData.length;i++)
{
eachSeriesArr = seriesWithData[i].split(";");
seriesLabels[i] = eachSeriesArr.splice(0,1);
eachSeriesArr.splice(eachSeriesArr.length-1, 1);
for(var j=0; j<eachSeriesArr.length;j++)
{
eachSeriesArr[j] = Math.round(eachSeriesArr[j]).toString();
}
globalSeriesArr.push(eachSeriesArr);
} */
// Testing with hard coded value
var s1 = [2, 6, 7, 10];
var s2 = [7, 5, 3, 4];
var s3 = [14, 9, 3, 8];
plotChart = $.jqplot(chartId, [s1,s2,s3], {
seriesDefaults:{
showLabel: true,
renderer:$.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true,
//showDataLabels: true,
barDirection: 'vertical',
},
pointLabels: {show: true}
},
axesDefaults: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
autoscale: true,
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: categories,
},
yaxis: { pad: 1.0 }
},
legend: {show: true, placement: 'outside', location: 'e' },
});
}
//This is the canvas div in html file
<div id="rId2" style="width:640px;height:426px;"></div>
<script type="text/javascript">
$(document).ready(function(){
alert('document loaded completely');
DrawChart('rId2', 'barChart;col', new Array(
"Category 1",
"Category 2",
"Category 3",
"Category 4"
), new Array(
"Series 1;4.3;2.5;3.5;4.5;",
"Series 2;2.4;4.4000000000000004;1.8;2.8;",
"Series 3;2;2;3;5;"
), 'clustered')
});
</script>
`
I am calling this function (defined in a javascript file) on document ready function from html file
Is anything missing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery alert hello Plugin doesnt work Im trying to make simple Jquery plugin. I went through the Jquery documention and I reduced the layout to make a simple alert. This is my Jquery Plugin code.
(function($){
$.fn.foo = function(){
alert("HI");
};
})(jQuery);
Than on my main page I have the Jquery reference URL and this code
<script type="text/javascript"src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
foo();
});
</script>
I keep getting errors in the debugger
SCRIPT5009: 'foo' is undefined
Please help me fix this.
A: you can invoke the foo method on some element or need to define it differently e.g.
<div id="test" />
Plugin -
(function($){
$.fn.foo = function(){
alert("HI");
};
$.otherfoo = function(){
alert('Hiiiii');
};
})(jQuery);
Test -
$(document).ready(function(){
$('#test').foo();
$.otherfoo();
});
should work fine.
A: You made a jquery plugin, you have to reference it in seperate jQuery function to fire it.
Here is my working example: http://jsfiddle.net/MarkKramer/Z9vz2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to install another exe(only if it is not already installed) while installing winform application using windows setup in VS2010? I have created a window setup file for my window project in visual studio 2010. this setup file is running properly and installed the software in computer. but for running my this software i need a another exe file(filezilla server.exe) to run.So, for that i specified using custom action.So,first time when i installing my application, it also successfully installed filezilla server automatically.
But while installing second time after uninstalling my application(not filezilla server),it is again install the filezilla server.so,filezilla installation get exception while installing.
So, I want to check before installing filezilla server whether it is already installed or not.If it is installed, then no need to install filezilla server at all.otherwise, i need to install the filezilla server.
Is there any option available in windows setup in visual Studio - 2010?
Please Guide me get out of this issue?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CursorAdapter 's ViewBinder lifecycle? Can someone help me understand SimpleCursorAdapter.ViewBinder lifecycle in terms of methods: setViewValue, bindView when are they called? Are instances re-used? Any source to understand all of it?
I basically have a ScrollView that that uses setViewValue to populate items but it doesn't refresh the view value even when setViewValue is called again and again.
A: bindView is called first and later setViewValue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Clear datagrid in MVVM ViewModel On my MVVM silverlight application I have a dataDrid (in the View) and the dataGrid ItemsSource is binding to a Domain Service Classes Sql stored procedure 'results' in the XAML file. The stored proc 'Results' is defined in ViewModel which calls the WCF's stored proc on a 'Model' class.
I need to erase all items on dataGrid when user clicks on 'Clear' button but the ViewModel did not have any object reference to the View (the UserControl) to re-set its binding.
I am able to set the dataGrid's ItemsSource to NULL to erase all items on dataGrid but I did not know how to make the 'binding' again later in 'ViewModel' when the 'Query' button is clicked. Is there any api to get the reference of 'UserControl' in 'View' from 'ViewModel'?
Thanks for any help.
A: If the grid has to be cleared, so should the ViewModel. The MVVM solution is to clear the collection in the ViewModel. The Grid will follow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pause an animation with OpenGL / glut To achieve an animation, i am just redrawing things on a loop.
However, I need to be able to pause when a key is pressed. I know the way i'm doing it now its wrong because it eats all of my cycles when the loop is going on.
Which way is better, and will allow for a key pause and resume?
I tried using a bool flag but obviously it didnt change the flag until the loop was done.
A: You have the correct very basic architecture sorted in that the everything needs to be updated in a loop, but you need to make your loop a lot smarter for a game (or other application requiring OpenGL animations).
However, I need to be able to pause when a key is pressed.
A basic way of doing this is to have a boolean value paused and to wrap the game into a loop.
while(!finished) {
while(!paused) {
update();
render();
}
}
Typically however you still want to do things such as look at your inventory, craft things, etc. while your game is paused, and many games still run their main loop while the game's paused, they just don't let the actors know any time has passed. For instance, it sounds like your animation frames simply have a number of game-frames to be visible for. This is a bad idea because if the animation speed increases or decreases on a different computer, the animation speed will look wrong on those computers. You can consider my answer here, and the linked samples to see how you can achieve framerate-independent animation by specifying animation frames in terms of millisecond duration and passing in the frame time in the update loop. For instance, your main game then changes to look like this:
float previousTime = 0.0f;
float thisTime = 0.0f;
float framePeriod = 0.0f;
while(!finished) {
thisTime = getTimeInMilliseconds();
framePeriod = previousTime - thisTime;
update(framePeriod);
render();
previousTime = thisTime;
}
Now, everything in the game that gets updated will know how much time has passed since the previous frame. This is helpful for all your physics calculations as all of our physical formulae are in terms of time + starting factors + decay factors (for instance, the SUVAT equations). The same information can be used for your animations to make them framerate independent as I have described with some links to examples here.
To answer the next part of the question:
it eats all of my cycles when the loop is going on.
This is because you're using 100% of the CPU and never going to sleep. If we consider that we want for instance 30fps on the target device (and we know that this is possible) then we know the period of one frame is 1/30th of a second. We've just calculated the time it takes to update and render our game, so we can sleep for any of the spare time:
float previousTime = 0.0f;
float thisTime = 0.0f;
float framePeriod = 0.0f;
float availablePeriod = 1 / 30.0f;
while (!finished) {
thisTime = getTimeInMilliseconds();
framePeriod = previousTime - thisTime;
update(framePeriod);
render();
previousTime = thisTime;
if (framePeriod < availablePeriod)
sleep(availablePeriod - framePeriod);
}
This technique is called framerate governance as you are manually controlling the rate at which you are rendering and updating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a way to add new items to enum in Objective-C?
Possible Duplicate:
Possible to add another item to an existing enum type?
Say I have a class Car with the following enum defined:
typedef enum
{
DrivingForward,
DrivingBackward
} DrivingState;
Then, let's say I have a subclass of Car called Tesla and it happens to drive sideways too. Is there a way for Tesla to add new items to that original enum so that the final enum becomes like the following?
typedef enum
{
DrivingForward,
DrivingBackward,
DrivingLeft,
DrivingRight
} DrivingState;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: startsWith autocomplete jsf Ill just why is it this error apperars when i add this code to my autosuggest
"CANT INSTANTIATE CORE.BEAN"
while(rs.next()) {
String s = rs.getString("name");
if(s.startsWith(text)){
data.add(s);}
here's my xhtml file
<p:autoComplete id="input" value="#{bean.text}" completeMethod="#{bean.complete}" maxResults="11" />
or if im doing it wrong, anyone who could correct me?
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IPhone Custom UIButton Cannot DismissModalViewController I have a custom UIButton class in my IPhone navigation application. When the user clicks the button I present a modal view which displays a tableview list of records that the user can select from.
On click of the button I create my viewController and show it using the following code:
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
dropDownPickerViewController = [[DropDownListingViewController alloc] initWithNibName:@"DropDownListingView" bundle:[NSBundle mainBundle]];
.....
.....
[[(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate] navigationController] presentModalViewController:dropDownPickerViewController animated:NO];
[dropDownPickerViewController release];
[super touchesEnded:touches withEvent:event];
}
As you can see the button could be on any viewController so I grab the navigationController from the app delegate. Than in my DropDownPickerViewController code i have the following when a user selects a record:
[[(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate] navigationController] dismissModalViewControllerAnimated:NO];
But nothing occurs. It seems to freeze and hang and not allow any interaction with the form. Any ideas on why my ModalViewController wouldnt be dismissing? Im thinking it is the way I use the app delegate to present the viewController. Is there a way to go self.ParentViewController in a UIButton class so I can get the ViewController of the view that the button is in (if this is the problem)?
Any ideas would be greatly appreciated.
Thanks
A: In your DropDownPickerViewController, Instead of this:
[[(AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate] navigationController] dismissModalViewControllerAnimated:NO];
Try
[self dismissModalViewControllerAnimated:NO];
A: I would call a method on the button's "parent" viewController and do it from there.
A: I did recall that I did have to do something similar once, and by looking at this post:
Get to UIViewController from UIView?
I was able to create some categories:
//
// UIKitCategories.h
//
#import <Foundation/Foundation.h>
@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
- (id) traverseResponderChainForUIViewController;
@end
@interface UIView (FindUINavigationController)
- (UINavigationController *) firstAvailableUINavigationController;
- (id) traverseResponderChainForUINavigationController;
@end
//
// UIKitCategories.m
//
#import "UIKitCategories.h"
@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
// convenience function for casting and to "mask" the recursive function
return (UIViewController *)[self traverseResponderChainForUIViewController];
}
- (id) traverseResponderChainForUIViewController {
id nextResponder = [self nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
return nextResponder;
} else if ([nextResponder isKindOfClass:[UIView class]]) {
return [nextResponder traverseResponderChainForUIViewController];
} else {
return nil;
}
}
@end
@implementation UIView (FindUINavigationController)
- (UINavigationController *) firstAvailableUINavigationController {
// convenience function for casting and to "mask" the recursive function
return (UINavigationController *)[self traverseResponderChainForUINavigationController];
}
- (id) traverseResponderChainForUINavigationController {
id nextResponder = [self nextResponder];
if ([nextResponder isKindOfClass:[UINavigationController class]]) {
return nextResponder;
} else {
if ([nextResponder isKindOfClass:[UIViewController class]]) {
//NSLog(@" this is a UIViewController ");
return [nextResponder traverseResponderChainForUINavigationController];
} else {
if ([nextResponder isKindOfClass:[UIView class]]) {
return [nextResponder traverseResponderChainForUINavigationController];
} else {
return nil;
}
}
}
}
@end
you can then call them like so:
UINavigationController *myNavController = [self firstAvailableUINavigationController];
UIViewController *myViewController = [self firstAvailableUIViewController];
maybe they will help you, I hope so.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding Menu in Action Bar I have a Action Bar where i want to add one help button using Menu. I am using Android 3.0.
My Menu code is like below:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/help_btn"
android:icon="@drawable/help"
android:title="Help"
android:showAsAction="ifRoom|withText"
/>
Now how can i add this menu in the action bar??
A: Update;
You can inflate a menu like this @override
Put in res/menu/YOUR_MENU.xml
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.YOUR_MENU, menu);
return true;
}
A: The same way you create regular menus:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
http://developer.android.com/guide/topics/ui/menus.html#OptionsMenu
A: I know this is a pretty old question, but I'll throw an answer at it anyway. If you're dealing with a Fragment, you'll need to let the system know you'd like to contribute to the action bar or onCreateOptionsMenu will never be called. https://stackoverflow.com/a/10049807/725752
A: Now with Jetpack Compose , you don't need separate menu XML
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar= {
TopAppBar(
title = {
Text(text = "Create New Recipe")
},
navigationIcon = {
IconButton(onClick = { }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "Back"
)
}
},
backgroundColor = Color.Blue,
contentColor = Color.White,
elevation = 2.dp,
actions = {
IconButton(onClick = {
uiController.hideSoftKeyboard()
...
}) {
Icon(
contentDescription = "Help",
painter = painterResource(R.drawable.help)
)
}
}
)
}, content = {
}
})
Here topBar contains code for Action Bar and actions contains menu button
Reference- https://androidlearnersite.wordpress.com/2021/08/03/jetpack-compose-1-0-0-sample-codes/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: PHP: Hashing code not working any longer? I used this hash function for a while (got it from the internet). The thing is it used to work immediately but now it is complaining about a paramter. The following is the code:
function generateHash($plainText, $salt = null)
{
if ($salt === null)
{
$salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
}
else
{
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($salt . $plainText);
}
So I would use this code in the method call:
validateUserInput($userid, $pass);
and validateUserInput is:
function validateUserInput($username, $password)
{
//$username = mysql_real_escape_string($username);
//$password = mysql_real_escape_string($password);
if(!$username || !$password)
{
//$errors['credentials'] = 'Missing Credentials!';
//$_SESSION['errors_array'] = $errors;
//echo $errors['credentials'];
header("LOCATION:XXXXXXX.php");
}
$local_salt = generateHash($password);
//echo $local_salt;
$groupid;
if($username != null && $password !=null)
{
connectToServer();
$result = mysql_query("SELECT * FROM users WHERE hashkey = '{$local_salt}'");
while($row_access = mysql_fetch_array($result))
{
$groupid = $row_access['groupid'];
}
if(!isset($result))
{
$errors['not_found_user'] = 'No Users Found with Provided Credentials!';
//$_SESSION['errors_array'] = $errors;
$userfound = 0;
$_SESSION['user_available'] = $userfound;
}elseif(isset($result)){
$_SESSION['user_logged'] = array('username' => $username, 'password' => $password, 'salt' => $local_salt, 'groupid' => $groupid);
$userfound = 1;
//echo "stored";
$_SESSION['user_available'] = $userfound;
}
}
}
finally the error is:
Warning: substr() expects parameter 3 to be long, string given in /home/XXXX.php on line 64
This is pointing to the function generateHash()
A: The error itself tells you everything. The constant SALT_LENGTH is not a long. I suspect it's not defined at all, so PHP converts the bare string to a string ("SALT_LENGTH") and passes that to substr(), which complains.
That being said... This code is dangerously wrong:
*
*if(!isset($result)): Really? This condition will always be false because $result will always be set (unless you run into a problem with mysql_query(), but that doesn't tell you anything about the valididty of the login). And since mysql_query() never returns null, no logins will ever be rejected.
*This query:
SELECT * FROM users WHERE hashkey = '{$local_salt}'
Is invalid. $local_salt = generateHash($password);. From the generateHash function, if a salt is not given, one will be randomly created for you. Thus, every call to generateHash will generate a new hash, which means it can't be compared to anything in the database.
On the basis of the two (very) egregious mistakes above, I would throw away this piece of code for good.
The correct way to check for a valid hash when a salt is used is something like:
$_SESSION['user_logged'] = null;
// fetch hashed pw from db, where username is the submitted username
$result = mysqli_query("SELECT hash FROM users WHERE username = '{$username}'");
if ($result->num_rows != 0)
{
$row = $result->fetch_assoc();
$hash = $row['hash'];
$salt = substr($hash, 0, SALT_LENGTH); // extract salt
if (generateHash($password, $salt) == $hash)
{
// login successful.
$_SESSION['user_logged'] = $username; // don't store passwords here
}
}
// if $_SESSION['user_logged'] is not set, the login failed
if (!isset($_SESSION['user_logged']))
{
// you *don't* want to tell people which one (login or pw) is invalid
echo 'Invalid login or password';
}
Note: It's very important that the SALT_LENGTH is at most 32, or this won't work because of the way generateHash() is implemented.
A: Clearly SALT_LENGTH is not an integer. Find where it's defined and correct this.
A: Instead of making a new hashing function each time you write an application , you should utilize the one provided to you by php: crypt() ( i would recommend to go with any blowfish or sha256+ hash ).
And when selecting information from database, you should select it by username and then, with php, check if hash fits the password.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to format a date in java? How can change this date format "2011-09-07T00:00:00+02:00" into the "dd.MM." i.e "07.09."
Thanks in advance!
A: here is a sample
edited the code:
public static void main(String[] args) throws ParseException {
String input = "2011-09-07T00:00:00+02:00";
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat outputDf = new SimpleDateFormat("dd.MM");
Date date = inputDf.parse(input.substring(0,9));
System.out.println(date);
System.out.println(outputDf.format(date));
}
A: Basically -
*
*Create a date format object from the above string
*Parse into a date object, and reformat however you prefer.
For example (I haven't tested this):
/*
* REFERENCE:
* http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/
*/
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample1 {
public static void main(String[] args) {
// Make a new Date object. It will be initialized to the current time.
DateFormat dfm = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date d = dfm.parse("2011-09-07 00:00:00");
// See what toString() returns
System.out.println(" 1. " + d.toString());
// Next, try the default DateFormat
System.out.println(" 2. " + DateFormat.getInstance().format(d));
// And the default time and date-time DateFormats
System.out.println(" 3. " + DateFormat.getTimeInstance().format(d));
System.out.println(" 4. " +
DateFormat.getDateTimeInstance().format(d));
// Next, try the short, medium and long variants of the
// default time format
System.out.println(" 5. " +
DateFormat.getTimeInstance(DateFormat.SHORT).format(d));
System.out.println(" 6. " +
DateFormat.getTimeInstance(DateFormat.MEDIUM).format(d));
System.out.println(" 7. " +
DateFormat.getTimeInstance(DateFormat.LONG).format(d));
// For the default date-time format, the length of both the
// date and time elements can be specified. Here are some examples:
System.out.println(" 8. " + DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT).format(d));
System.out.println(" 9. " + DateFormat.getDateTimeInstance(
DateFormat.MEDIUM, DateFormat.SHORT).format(d));
System.out.println("10. " + DateFormat.getDateTimeInstance(
DateFormat.LONG, DateFormat.LONG).format(d));
}
}
A: Your code needs a little correction on the following line
Date date = inputDf.parse(input.substring(0,9));
In place of (0,9) you need to enter (0,10) and you will be getting the desired output.
A: tl;dr
OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" ).format( DateTimeFormatter.ofPattern( "dd.MM" )
java.time
The Question and other Answers use old legacy classes that have proven to be troublesome and confusing. They have been supplanted by the java.time classes.
Your input string is in standard ISO 8601 format. These formats are used by default in java.time classes. So no need to specify a formatting pattern.
OffsetDateTime odt = OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" );
You can generate a String in your desired format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" );
String output = odt.format( f );
MonthDay
You want month and day-of-month. There is actually a class for that, MonthDay.
MonthDay md = MonthDay.from( odt );
You can generate a String in your desired format.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" );
String output = md.format( f );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Vim cursor goes line down when esc mapped to jk I have
imap jk <C-[>
in my vimrc, but when I use it on the end of line (when cursor is on $ when list is on) cursor goes to beginning of next line. How to fix it?
A: It works normally for me.
I assume interfering mappings or settings.
First you should try
:inoremap jk <C-[>
can you provide more details
*
*version
*verbose set 1
*map j
*map k
*map jk
I have a hunch it might be the virtualedit settings or stuff like that interfering
1 get it with
:redir >> ~/file.log
:verbose set
:redir END
A: I had the same problem and figured out that the described effect appears when you accidentally map
:inoremap jk <Esc> "comment => maped to '<Esc> '
Which would be EscSpace
Or if you have a trailing whitespace in this line. This can be observed by setting
:set list
A: First hack is:
imap jk <Left><C-[>
But maybe there is better solution?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Need to apply a css class to all textfields using Zend Framework I'm doing some bit of redesigning here for which we hired an outsourced freelance designer. He sent in the designs however he's used css class styles for the textboxes as opposed to my earlier attempts to apply a ganeral style to the inputs tag which had its hiccups.
I've used the Zend View Helpers to create the textboxes however I would like a simpler way to be able to set it up so by default all textfields would have the base css class 'textfield' - is there a way to do so in code without me having to explicitly make the addition in every call made to the view helper?
A: If you want to apply this style to all textfields on your page you just need a general textfield style and there is no need to even touch your markup.
If you have other textfields as well which you want to style differently, you will have to either extend Zend_Form, Zend_Form_Element or Zend_Form_Element_Text. Probably it would be easiest to extend the former and adding an attribute 'class' with the value 'textfield' to every text element while looping through all form elements.
But again. Why would you need to touch your markup at all, you just need a style for textfields.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rewrite rule for dynamic subdomain redirecting each file with subdomain arguments I want to redirect all the calls to files in a subdomain with an extra variable. like if a user access www.domain.com/news.php and in the subdomain he accesses the same page then it should add an extra argument to the url like xyz.domain.com/news.php should be re written like it calls the file news.php?subdomain=xyz. Also i have other rules for just simple domain.
RewriteCond %{HTTP_HOST} ^domain.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,NC]
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$
RewriteRule ^$ /index.php?subdomain=%1 [L]
A: RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,NC,L]
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC]
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ http://www.domain.com%{REQUEST_URI}?subdomain=%1 [L]
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC]
RewriteCond %{QUERY_STRING} !^$
RewriteRule ^(.*)$ http://www.domain.com%{REQUEST_URI}?%{QUERY_STRING}&subdomain=%1 [L]
A: The solution pointed to by adaptr at: https://serverfault.com/a/409171/128746 - would solve this problem very well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scala: using Nothing for singleton instances of polymorphic types Given a polymorphic trait like
trait Transform[T] { def apply( t: T ) : T }
one might like to implement various specialized instances, such as
case class Add[Double] extends Transform[Double] { def apply( t: Double ) ... }
case class Append[String] extends Transform[String] { def apply( t: String ) ... }
etc. Now a frequently desired transform is also the identity transform. Instead of specializing identity for each type T, it appears preferable to use just one singleton instance for all types T. My question is: what is the best way to accomplish this in Scala?
Here is what I found so far: looking at how List[T] implements List.empty[T] and Nil, I tried using Nothing as the type T. This seems to make sense, since Nothing is a subtype of every other type:
object Identity extends Transform[Nothing] {
def apply( t: Nothing ) = t
}
This seems to work. However, wherever I then want use this instance as-is, like here:
val array = Array[Transform[String]]( Transform.Identity )
I get the compiler error "type mismatch; found: Identity.type, required: Transform[String]". In order to use it, I have to explicitly cast it:
... Identity.asInstanceOf[Transform[String]]
I am not sure this is the best or even the 'proper' way to do it. Thanks for any advice.
A: As @Kim Stebel points out your Transform[T] is invariant in T (and has to be because T occurs in both co- and contra- variant positions in def apply(t : T) : T) so Transform[Nothing] is not a subtype of Transform[String] and can't be made to be.
If your main concern is the instance creation on each call of Kim's def Id[A] then your best model is the definition of conforms in in Predef,
private[this] final val singleton_<:< = new <:<[Any,Any] { def apply(x: Any): Any = x }
implicit def conforms[A]: A <:< A = singleton_<:<.asInstanceOf[A <:< A]
ie. use a polymorphic method, returning a singleton value cast to the appropriate type. This is one of occasions where erasure is a win.
Applied to your situation we would have,
object SingletonId extends Transform[Any] { def apply(t : Any) = t }
def Id[A] = SingletonId.asInstanceOf[Transform[A]]
Sample REPL session,
scala> Id("foo")
res0: java.lang.String = foo
scala> Id(23)
res1: Int = 23
A: Since the type parameter T in Transform[T] is invariant, Transform[Nothing] is not a subtype of Transform[String], thus the compiler complains about it. But using Nothing here doesn't make sense anyway, since there can never be an instance of Nothing. So how would you pass one to the apply method? You would need to cast yet again. The only option I can see is this:
scala> def Id[A] = new Transform[A] { override def apply(t:A) = t }
Id: [A]=> java.lang.Object with Transform[A]
scala> Id(4)
res0: Int = 4
scala> Id("")
res1: java.lang.String = ""
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Suggestions for range slider plugin for jQuery I've seen already standart jQuery range slider on jQuery website, but this is not quite, what I'm looking for.
I've also found very nice range slider http://blog.egorkhmelev.com/2009/11/jquery-slider-safari-style/, but this plugin is bit buggy and hard to fix, since it was selfmade and doesn't have almost any community.
Could anyone suggest other good looking jQuery plugin for that purpose?
A: Check out jqPlot (jqplot.com) with the 'draggable' plugin. Use can set it to constraint dragging to the x-axis.
Jqplot is well tested and has very extensive functionality
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails - Functional testing of redirect_to(request.referer) Maybe I just missing the forest for the trees again, but I can't seem to figure out a way to write a functional test that tests a :destroy action that redirects to request.referer.
Code is:
def destroy
@step = Step.find(params[:id])
@step.destroy
respond_to do |format|
format.html { redirect_to(request.referer) }
format.xml { head :ok }
end
end
Failing test is:
test "should destroy step" do
assert_difference('Step.count', -1) do
delete :destroy, :id => @step.to_param
end
assert_redirected_to request.referer
end
Having no luck using:
redirect_to(:back)
... as well.
A: Got it.
Passing test is:
test "should destroy step" do
assert_difference('Step.count', -1) do
@request.env['HTTP_REFERER'] = 'http://test.com/steps/1'
delete :destroy, :id => @step.to_param
end
assert_redirected_to @request.env['HTTP_REFERER']
end
Thanks to help from: How do I set HTTP_REFERER when testing in Rails?
A: you write an integration test and use one of delete_via_redirect which should follow the redirect. You may also have to set the the HTTP_REFERER header - see guide.rubyonrails.org
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: use 'as' in query I have a table like this and type is innodb and id and sid are indexed.
id | sid
##########
1 | 100
1 | 101
1 | 102
1 | 103
1 | 104
1 | 105
2 | 100
2 | 101
3 | 100
3 | 101
I need id's have sid 100,...105 like id=1.
I have this query
select t1.id
from test as t1, test as t2, test as t3,
test as t4, test as t5, test as t6
where t1.sid=100
and t2.sid=101
and t3.sid=102
and t4.sid=103
and t5.sid=104
and t6.sid=105
and t1.id = t2.id = t3.id = t4.id = t5.id = t6.id
but phpmyadmin hangs when I run query.
The number of records is 2000.
What is optimized query?
A: It is surprising that the SQL statement shown compiles/runs.
However, you can probably rescue it by rewriting what is currently the last line to:
select t1.id
from test as t1, test as t2, test as t3,
test as t4, test as t5, test as t6
where t1.sid = 100
and t2.sid = 101
and t3.sid = 102
and t4.sid = 103
and t5.sid = 104
and t6.sid = 105
and t1.id = t2.id
and t1.id = t3.id
and t1.id = t4.id
and t1.id = t5.id
and t1.id = t6.id;
Is this query optimal?
Given your comment to Maulik Vora's answer that the range { 100 .. 105 } is just an example, then we need to know whether it is always 6 values or whether it could be 5 or 7 or some other number. However, it is likely that the optimal structure uses a temporary table (call it ListToMatch with a non-null unique column SID) containing whatever values are needed, and that the query is:
SELECT T.ID
FROM Test AS T JOIN ListToMatch AS L ON T.SID = L.SID
GROUP BY T.ID
HAVING COUNT(*) = (SELECT COUNT(*) FROM ListToMatch);
You insert the set of values you're interested in to ListToMatch; you can then get the list of ID values that match. This is likely to be more nearly optimal, not least because it adapts to 1 value and 100 values as easily as it does to 6, whereas rewriting the SQL with a 100-way self-join doesn't bear much thinking about.
A: select t2.id from (select id, max(sid) as mxsid, min(sid) as mnsid from test
group by id having count(id) = 6) as t2
where t2.mxsid = 105 and t2.mnsid = 100
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make two tableview cell in one controller class in iphone I am making two tableview cell in one controller class on vertical style. I have different value both the cell. Left cell have some name value for eg(name :pradeep),and right side cell have some price value so if select on left cell on 3row and right side cell on 2 row so this two cell value I have to pass for open url.
Please help on this how to know which cell index are selected from both the tableview cell and what the value on that selected cell.
A: If I understand your requirements correctly then you should probably be using a UIPickerView:
http://www.youtube.com/watch?v=wnxS35JDqok
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIPickerView_Class/Reference/UIPickerView.html
A: You can add multiple tableview cell. You need to separate or identify them using Identifier. After creating custom cell, you can add tableview cell into Cellforrowatindex path method.Make sure don't forgot to import "custom cell.h" in your implementation file. Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: +colorWithPatternImage: should preserve transparency in Cocoa I have a custom NSView that is used for displaying a background color. This works. However, I have shadows in that image that are not preserved.
All transparent or semi-transparent areas of the image are rendered as black. How do I fix this?
- (void)drawRect:(NSRect)dirtyRect {
NSColor *pattern = [NSColor colorWithPatternImage:[NSImage imageNamed:@"bg"]];
[pattern setFill];
NSRectFill(dirtyRect);
}
Thanks.
A: NSRectFill() is a shortcut for NSRectFillUsingOperation(rect, NSCompositeCopy). This means that it won't composite the color's alpha channel with the background, it simply draws the source color in the rectangle you pass in. Instead, you should use:
NSRectFillUsingOperation(rect, NSCompositeSourceOver);
The NSCompositeSourceOver compositing operation will display the source image wherever the source image is opaque and the destination image elsewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jquery fancybox width issue The jquery fancybox width is abnormal. means it is equal to the width of the page. If i change the class name to 'iframe' width works fine else width is miss behaving.
$(".iframe_reg2").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false,
'width' : 400
});
And my Html is
<a class="iframe_reg2" href="http://google.com">Google</a>
A: U need to set autoDimensions to false if you're specifying the width yourself. So ideally , the call should be
$(".iframe_reg2").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false,
'autoDimensions': false,
'width' : 400
});
I think this should work :)
A: Your anchor tag does not have an href value, which is a key attribute to making the plugin work. (edit: I see now what the "iframe" class is for, but I like using the query string instead). It's a bit difficult to tell what you mean to do with your sample, but my guess is that you're attempting to grab Google and put it into the fancybox (as a test).
You should also remove the comma from your last attribute, as it will trip up some browsers.
I can't see why this wouldn't work:
$(".pageViewer").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false
});
with HTML
<a class="pageViewer" href="http://google.com?iframe">Google</a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Safari browser input text field display value error @@Edit
I have a link which is showing on screen keyboard.
http://designshack.co.uk/tutorialexamples/vkeyboard/
By using this link and Safari browser,
I click keyboard link button and press any key not less than round about 30 times.
At that time, password text box did not show me last inputted value.
So let me know the way to solve this problem please.
@@Old Question
At my web page, there is two controls.
1) Text box
2) On Screen Keyboard which is using JQuery.
Every keys is shown,
whenever I press any key at that keyboard control.
Let's say, when i press A or B, this keys will show at text box
AB..... and so on.It is correct.
But when I use Safari Browser,
the text box cannot show the last inputted key value.
It only show older value.
For example please try this link... [by using safari browser]
http://designshack.co.uk/tutorialexamples/vkeyboard/
1.please click keyboard hyber link control
2.click any keys till password text box did not show you last inputted key value.
It is where the problem start.
[This problem only occur when using Safari browser.]
Please let me know how to fix this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ant colony behavior using genetic programming I'm looking at evolving ants capable of food foraging behaviour using genetic programming, as described by Koza here. Each time step, I loop through each ant, executing its computer program (the same program is used by all ants in the colony). Currently, I have defined simple instructions like MOVE-ONE-STEP, TURN-LEFT, TURN-RIGHT, etc. But I also have a function PROGN that executes arguments in sequence. The problem I am having is that because PROGN can execute instructions in sequence, it means an ant can do multiple actions in a single time step. Unlike nature, I cannot run the ants in parallel, meaning one ant might go and perform several actions, manipulating the environment whilst all of the other ants are waiting to have their turn.
I'm just wondering, is this how it is normally done, or is there a better way? Koza does not seem to mention anything about it. Thing is, I want to expand the scenario to have other agents (e.g. enemies), which might rely on things occurring only once in a single time step.
A: I am not familiar with Koza's work, but I think a reasonable approach is to give each ant its own instruction queue that persists across time steps. By doing this, you can get the ants to execute PROGN functions one instruction per time step. For instance, the high-level logic for the time step of an ant can be:
Do-Time-Step(ant):
1. if ant.Q is empty: // then put the next instruction(s) into the queue
2. instructions <- ant.Get-Next-Instructions()
3. for instruction in instructions:
4. ant.Q.enqueue(instruction)
5. end for
6. end if
7. instruction <- ant.Q.dequeue() // get the next instruction in the queue
8. ant.execute(instruction) // have that ant do its job
A: Another similar approach to queuing instructions would be to preprocess the set of instructions an expand instances of PROGN to the set of component instructions. This would have to be done recursively if you allow PROGNs to invoke other PROGNs. The downside to this is that the candidate programs get a bit bloated, but this is only at runtime. On the other hand, it is easy, quick, and pretty easy to debug.
Example:
Say PROGN1 = {inst-p1 inst-p2}
Then the candidate program would start off as {inst1 PROGN1 inst2} and would be expanded to {inst1 inst-p1 inst-p2 inst2} when it was ready to be evaluated in simulation.
A: It all depends on your particular GP implementation.
In my GP kernel programs are either evaluated repeatedly or in parallel - as a whole, i.e. the 'atomic' operation in this scenario is a single program evaluation.
So all individuals in the population are repeated n times sequentially before evaluating the next program or all individuals are executed just once, then again for n times.
I've had pretty nice results with virtual agents using this level of concurrency.
It is definitely possible to break it down even more, however at that point you'll reduce the scalability of your algorithm:
While it is easy to distribute the evaluation of programs amongst several CPUs or cores it'll be next to worthless doing the same with per-node evaluation just due to the amount of synchronization required between all programs.
Given the rapidly increasing number of CPUs/cores in modern systems (even smartphones) and the 'CPU-hunger' of GP you might want to rethink your approach - do you really want to include move/turn instructions in your programs?
Why not redesign it to use primitives that store away direction and speed parameters in some registers/variables during program evaluation?
The simulation step then takes these parameters to actually move/turn your agents based on the instructions stored away by the programs.
*
*evaluate programs (in parallel)
*execute simulation
*repeat for n times
*evaluate fitness, selection, ...
Cheers,
Jay
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Datagridview cellcontent click event not working properly I wrote an event to retrieve the first cell value of the clicked cell's row on CellContentClick event in datagridview. but the event is getting raised only when i click the third cell and not getting raised when i click the first or second cell of datagridview.
Please help me.
A: To add to Rami's answer, you will also need to update the default generated code in your Form's Designer.cs.
Original code:
this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
Change it to:
this.dataGridView1.*CellClick* += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
A: Try to implement the CellClick event instead of CellContentClick event
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView theGrid = sender as DataGridView;
if(theGrid != null)
{
DataGridViewCell selectedCell = theGrid.SelectedCells[0];
//Do your logic here
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: not able to create a dynamic form in Delphi 7 I have put together this code for creating a dynamic form
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type
TForm2 = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
a:TForm2;
begin
a:=TForm2.Create(nil);
end;
end.
I get an error saying resource tform2 cannot be found. What must i do?
Thanks
A: In Delphi you must declare only one form per unit, also each form needs a dfm file, that file store the form definition and components properties. In your code you have this error because the application can't found the dfm file for the TForm2 form. So to fix the problem just create a new form (TForm2) in a separate unit and then add the unit a name to the unit where you need to call the TForm2.
A: You are calling the TForm.Create() constructor that loads the TForm contents from a DFM, but your project does not have a DFM for TForm2, which is why you are getting the resource error. To skip that, you need to use the TForm.CreateNew() constructor instead.
procedure TForm1.Button1Click(Sender: TObject);
var
a: TForm2;
begin
a := TForm2.CreateNew(nil, 0);
...
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: no such file to load -- RMagick.rb Rails, Ubuntu I have ruby and my gems installed in my home directory using rvm. 'require RMagick' works from the console and irb, but not from within my Rails app. I have the gem listed in my Gemfile.
require 'RMagick'
class PetsController < ApplicationController
def image
image = Image.new(image_path("base/Base.png"))
#image = Pet.composite(0, '4a4a4a')
@response.headers["Content-type"] = image.mime_type
render :text => image.to_blob
end
end
If I remove the require from my controller, I get
uninitialized constant PetsController::Image
I also have tried require 'RMagick' in boot.rb, and by referring to the Image object using Magick::Image (which gives me uninitialized constant PetsController::Magick.
What am I doing wrong?
A: Solved it! Restarting the server fixed it. I guess I hadn't restarted the server when I added rmagick to my gemfile.
A: Is it possible that you are running the rails app with another user than the one that has the RMagick gem installed?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simple function onSubmit? I'm trying to call a simple function onsubmit. I tried using onsubmit and also a listener with jQuery. My problem is that when the user presses enter he gets redirected to mysite.com?
<form id="teleport">
<input id="tInput" type="text" value="Type a location" />
<input type="button" id="tSubmit" value="Submit"/>
</form>
$("#teleport").submit(function () {
teleport(document.getElementById('tInput').value);
});
How do I prevent anything from happening when submitting? Also .submit() is only detecting the enter key, how do I listen for both enter key and clicks on the submit button?
A: You need to prevent the default action of the form. You can do that with event.preventDefault():
$("#teleport").submit(function (e) {
e.preventDefault();
teleport(document.getElementById('tInput').value);
});
Alternatively, you could return false inside the submit event handler for the same effect.
The easiest way to make the button submit the form too will be to change it's type to submit:
<input type="submit" id="tSubmit" value="Submit" />
Or you could attach a click event handler to your current button and trigger the submit event of the form.
A: Prevent submiting a form:
$("#teleport").submit(function (e) {
teleport(document.getElementById('tInput').value);
e.preventDefault();
});
Submit event catches any way of submitting a form - both with clicking the submit button and enter key press.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Read/ Parse Data of Signed_Request from Registration Script in Php 5.1.6 I'm trying to implement the Facebook registration script.
The form is getting submitted fine and the server is receiving the signed request. However, it is not able to read/parse the signed request.
I used the script recommended on the registration page https://developers.facebook.com/docs/plugins/registration/ (code below) and all I see for output is:
signed_request contents:
I have verified that the signed_Request is being received. If I pass it to: http://developers.facebook.com/tools/echo?signed_request= I see data.
However on my server with the script below nothing.
The server is http NOT https and using php 5.1.6 (which doesn't have some of the JSON support) Do I need PHP SDK installed? Or the jsonwrapper? I've tried the jsonwrapper but not PHP SDK.
Any help on why the signed_request can not be read would be appreciated.
Code below from facebook
<?php
include ('jsonwrapper/jsonwrapper.php');
define('FACEBOOK_APP_ID', 'XXX');
define('FACEBOOK_SECRET', 'XXX');
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
if ($_REQUEST) {
echo '<p>signed_request contents:</p>';
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
echo '<pre>';
print_r($response);
echo '</pre>';
} else {
echo '$_REQUEST is empty';
}
?>
output is
"signed_request contents:"
If I add:
print_r($_REQUEST); to the script I do see the request but can't parse it
A: I had something similar with the signed request coming back blank. On your application make sure you first download and inlude the php sdk from http://developers.facebook.com/docs/reference/php/. Next add
require_once("facebook.php");
to your script at the top, or to where you uploaded it to. Now in your application settings for the application, in Facebook, make sure your url to the application has the www in it or not. For example: In the application you have it pointing to example.com/index.php?tab=test but when you put it in the browser it always comes up www,example.com/index.php?tab=test. Not including the www can mess it up.
EDIT - WORKED FOR ME
<?php
#error_reporting(E_ALL);
include ('{{PATH TO facebook.php}}');
$appapikey = 'xxxx';
$appsecret = 'xxxx';
$facebook = new Facebook($appapikey, $appsecret);
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
if (isset($_REQUEST['signed_request'])) {
echo '<p>signed_request contents:</p>';
$response = parse_signed_request($_REQUEST['signed_request'],
$appsecret);
echo '<pre>';
print_r($response);
echo '</pre>';
} else {
echo '$_REQUEST is empty';
}
?>
<iframe src="https://www.facebook.com/plugins/registration.php?
client_id=134219456661289&
redirect_uri={{YOUR SITE URL ENCODED}}&fields=name,birthday,gender,location,email"
scrolling="auto"
frameborder="no"
style="border:none"
allowTransparency="true"
width="100%"
height="330">
</iframe>
function getDefinedVars($varList, $excludeList)
{
$temp1 = array_values(array_diff(array_keys($varList), $excludeList));
$temp2 = array();
while (list($key, $value) = each($temp1)) {
global $$value;
$temp2[$value] = $$value;
}
return $temp2;
}
To view All SYSTEM Variables (except globals/files/cookies/post/get) to make sure Signed Request is passed you can use this snippet of code
/**
* @desc holds the variable that are to be excluded from the list.
* Add or drop new elements as per your preference.
* @var array
*/
$excludeList = array('GLOBALS', '_FILES', '_COOKIE', '_POST', '_GET', 'excludeList');
//some dummy variables; add your own or include a file.
$firstName = 'kailash';
$lastName = 'Badu';
$test = array('Pratistha', 'sanu', 'fuchhi');
//get all variables defined in current scope
$varList = get_defined_vars();
//Time to call the function
print "<pre>";
print_r(getDefinedVars($varList, $excludeList));
print "</pre>";
A: You don't need the PHP SDK for this. It may make it easier to do this and various other things, but it is not necessary if you want to do the decode yourself.
Are you sure you actually have a json_decode function? I don't think it's usually part of jsonwrapper.php, so I suspect your script is crashing on that function call. You can use the following function as a substitute, just change the call to usr_json_decode and include the following at the bottom of your script:
function usr_json_decode($json, $assoc=FALSE, $limit=512, $n=0, $state=0, $waitfor=0)
{
$val=NULL;
static $lang_eq = array("true" => TRUE, "false" => FALSE, "null" => NULL);
static $str_eq = array("n"=>"\012", "r"=>"\015", "\\"=>"\\", '"'=>'"', "f"=>"\f", "b"=>"\b", "t"=>"\t", "/"=>"/");
for (; $n<strlen($json); /*n*/)
{
$c=$json[$n];
if ($state==='"')
{
if ($c=='\\')
{
$c=$json[++$n];
if (isset($str_eq[$c]))
$val.=$str_eq[$c];
else if ($c=='u')
{
$hex=hexdec(substr($json, $n+1, 4));
$n+=4;
if ($hex<0x80) $val .= chr($hex);
else if ($hex<0x800) $val.=chr(0xC0+$hex>>6).chr(0x80+$hex&63);
else if ($hex<=0xFFFF) $val.=chr(0xE0+$hex>>12).chr(0x80+($hex>>6)&63).chr(0x80+$hex&63);
}
else
$val.="\\".$c;
}
else if ($c=='"') $state=0;
else $val.=$c;
}
else if ($waitfor && (strpos($waitfor, $c)!==false))
return array($val, $n);
else if ($state===']')
{
list($v, $n)=usr_json_decode($json, $assoc, $limit, $n, 0, ",]");
$val[]=$v;
if ($json[$n]=="]") return array($val, $n);
}
else
{
if (preg_match("/\s/", $c)) { }
else if ($c=='"') $state='"';
else if ($c=="{")
{
list($val, $n)=usr_json_decode($json, $assoc, $limit-1, $n+1, '}', "}");
if ($val && $n) $val=$assoc?(array)$val:(object)$val;
}
else if ($c=="[")
list($val, $n)=usr_json_decode($json, $assoc, $limit-1, $n+1, ']', "]");
elseif (($c=="/") && ($json[$n+1]=="*"))
($n=strpos($json, "*/", $n+1)) or ($n=strlen($json));
elseif (preg_match("#^(-?\d+(?:\.\d+)?)(?:[eE]([-+]?\d+))?#", substr($json, $n), $uu))
{
$val = $uu[1];
$n+=strlen($uu[0])-1;
if (strpos($val, ".")) $val=(float)$val;
else if ($val[0]=="0") $val=octdec($val);
else $val=(int)$val;
if (isset($uu[2])) $val*=pow(10, (int)$uu[2]);
}
else if (preg_match("#^(true|false|null)\b#", substr($json, $n), $uu))
{
$val=$lang_eq[$uu[1]];
$n+=strlen($uu[1])-1;
}
else
{
return $waitfor ? array(NULL, 1<<30) : NULL;
}
}
if ($n===NULL) return NULL;
$n++;
}
return ($val);
}
BTW though, this should be very easy to track down using your error log, turning on extra debugging and adding some echo or var_dump statements as necessary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I access a file in a systems jboss bin, from other system I have a file in the jboss bin folder, on a system. I have to access this file from other system. How can I achieve this ?
Thanks
-Aj
A: Make the file available via a webapp or an ejb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Which Project Type to select in InstallShield : Basic MSI or C#.Net Wizard for WPF application? I have created one WPF application...
Now, in installshield, i want to make installation package for the same, so which project type i should select?
Actualy, now i have used basic MSI project....
but m still struggling with another problem....
i have created setup in English and German languages.... and i want to install .Net framework language pack according to the language selected by user....
Can any1 help me out...??
A: The C# wizard adds the InstallShield project to your visual studio solution. Personally I never put my application code and installer code in the same solution so I would just choose the Basic MSI project type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can not transform correctly using XSLT I tried to use a XSLT transformation (below) to a RSS with this type with no result. Why is that ?
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:gd="http://schemas.google.com/g/2005" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/"CUACQXg6fyp7ImA9WhdUFUo."">
and the structure of it is
<feed>
tags tags tags like <title></title>
<entry><published></published><title></title><content></content>....</entry>
</feed>
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:include href="identity.xsl"/>
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="node() | @*" />
</xsl:copy>
</xsl:template>
<xsl:template match="entry"/>
</xsl:stylesheet>
A: Your stylesheet is constructed for the default XML namespace (xmlns=""). An RSS feed has the Atom (xmlns="http://www.w3.org/2005/Atom") namespace defined and possibly others if you have nested XML content.
To 'match' anything in that namespace, you need to define it in your stylesheet also. You probably want to define Atom with a prefix like: xmlns:a="http://www.w3.org/2005/Atom". Then your match would become
<xsl:template match="a:entry"/>
Also, the above matches entry but you're not doing anything with it. You probably want it to print out a transformed value when you get an entry but the above is just excluding it from the result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: is flexunit is really required for Flex application? I have a doubt on Flex unit. Unit test cases are really required for flex application for displaying data.
A: So, you should remember that not everything in Flex is a UI Component.
I, personally, find that FlexUnit (or a unit testing framework) is great for testing services and other non-visual ActionScript / Flex classes. Was the property set after I set it? Was the order this ArrayCollection changed after I changed the value of the "orderBy" property on this custom class? Was my file created after I called a method to create the file?
These are things that unit testing can help answer.
With much of Flex, I find that UI testing, such as FlexMonkey or RIATest is much more applicable. Did this effect run after I change properties on the ViewStack? Did the background color change after I clicked this button? Was the second ComboBox populated with dat after I selected a value in the first Combobo?
these are the sort of questions that User Interface testing can help with.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Where I can subscribe a list of Javascript API to be obsoleted before the browser release? I am just hitting a bug due to Firefox 7 has removed some non-standard attribute (they have no moz- prefix) and cause my scripts fail on Firefox7.
Ref: https://developer.mozilla.org/en/DOM/File
In order to prevent it happen again. I am interesting to get a list of API to be obsoleted. So that I can handle them before the browser release, without testing twenty alpha/beta/nightly build of browsers everyday.
It there any page, blog, or RSS who give warning before the feature disappear?
A: You cannot get fast and easy warnings about future changes. But here are some blogs for you, where you can read about changes that just got implemented:
*
*IE Blog - http://blogs.msdn.com/b/ie/
*Opera Desktop Team - http://my.opera.com/desktopteam/blog/
*Webkit changelogs in human language, by Peter Beverloo - http://peter.sh
*Firefox changelog monitor - http://www.squarefree.com/burningedge/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stats based on Access Token? My app stores the Facebook Access Token for offline use. The main purpose of the app is to allow users to automatically posts on the walls of people within a specified number of days of their friends birthday.
My app has been blocked by Facebook due to spam (some users are sending marketing messages to their friends instead of using the app for it's purpose).
I want to find out who those users are and block their access to my application. The only problem is that my Facebook App has a few hundred access tokens (one for each user of my application). The insights dashboard does not provide me with stats per access token. I need to find out which of my users are getting their wall posts reported as spam.
Is there any way of doing this?
After appealing, Facebook has unblocked my application but I don't want it to happen again. As far as I can tell, I can find out the number of people who have reported the wall posts as spam...but I don't know which access token made those posts...and hence don't know which of my users is posting spam messages.
A: It's not Facebook job to keep track of your application internal activities. You should be logging every activity, at least posts ids returned when someone posts anything on their friends' wall.
And one more time... you DON'T need the offline_access permission to publish something when the user is offline!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TimerTask start stop only executing once Problem, I can only execute my timer once. I know its because I called the function timer2.cancel(); and timer1.cancel(); :: Cancel being "Never run this ever again". I need a replacement function, one that actually stops a timer, but can be started back up again when I reschedule it. How do I go about doing that?
public void actionPerformed (ActionEvent e){
if (e.getSource()==jbtStart)
{
System.out.println("Start is pressed");
timer2.cancel();
timer1.schedule(new Task(), 0, delay);
}
else if (e.getSource()==jbtStop)
{
System.out.println("Stop is pressed");
timer1.cancel();
timer2.schedule(new Task2(), 0, delay);
}
A: Why not just create a new Timer at that point? Either that, or keep hold of the TimerTask as well as the timer, and cancel that instead of the timer itself.
As a third possible alternative, have a single timer task and a single timer, but make the timer task aware of what it's meant to do at any point - it looks like you're effectively toggling what you want to do each time the timer ticks. You could always keep two separate classes to separate the logical functionality, and then have a "wrapper" task which allows you to replace what behaviour is executed on each run.
A: I would cancel the TimerTasks instead of the Timers (and I would use only one Timer).
UPDATE:
private Task task1;
private Task2 task2;
public void actionPerformed (ActionEvent e){
if (e.getSource()==jbtStart)
{
System.out.println("Start is pressed");
if (task2 != null) {
task2.cancel();
}
task1 = new Task();
timer.schedule(task1, 0, delay);
}
else if (e.getSource()==jbtStop)
{
System.out.println("Stop is pressed");
if (task1 != null) {
task1.cancel();
}
task2 = new Task2();
timer.schedule(task2, 0, delay);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: what's the best Rules Framework that can work in conjunction with Spring Batch ( 500k objects)? I've used both spring-batch and drools on previous projects, separately. In my current project, I have a design where I need to process upto 500k xml objects, convert them to jaxB, apply rule on each of the object (the rule itself is fairly simple: compare properties and update two flags in a 'notification' object), and finally send an event so a spring web flow viewmodel (that can be a listener) will update itself. That's not the requirement for design but it's what I have implemented:
1) ItemReader (JaxB)
2) ItemProcessor:-maps to a ksession (stateful) and fires rules based on a drl file.
3) ItemWriter: prepares the necessary cleanup and raises appropriate events
Seems to me that the logic itself is straight forward, but when I added all the gluecode of batch job: itemReader, Itemprocessor, etc., a simple rule didn't work. Also, after reading several forums it seems RETE algo isn't going to scale well on batch applications.
In summary, is drools the best way to integrate a basic rules framework in spring-batch OR are there any light weight alternatives?
A: *
*the rule itself is fairly simple: compare properties and update two flags in a 'notification' object
No need for any Rules Framework. That is what Spring Batch's ItemProcessor is for
from ItemProcessor JavaDocs:
"..an extension point which allows for the application of business logic in an item oriented processing scenario"
No need to complicate things with Drools or any other rules engine, unless you really need it => e.g. have dozens / hundreds of complex rules + that are not trivial to code.
A: usually the RETE algorithm is not a problem is a huge advantage. You need to design your solution with the assumption that it will be a batch process and it will work fine. You need to take into account that the big overhead in your scenario is creating all the 500k objects from the XML code. Once you get the objects if you design your business rules correctly it will perform correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create form that contain data from 2 tables and save data to one table i have 2 tables:
Employee:
ID
SalaryPerDay
Name (unique)
.....
.....
Schedule:
ID
EmployeeID
Date
Attending (boolean)
loan
discount
overTimeHours
and a query
EmployeeNameQuery: that return all employees names
i create a datasheet contains
column 1: employees names (EmployeeNameQuery)
column 2: Date (Schedule)
column 3: Attening (Schedule)
column 1: OverTimeHours (Schedule)
column 4: Loan (Schedule)
column 5: Discount (Schedule)
this data sheet display rows as employees names count
Questions:
1- Decimal number display as (280) how can i display them as (280.00) i can insert decimal number but i display values with .00 without .00
2- How to create form that contain data from 2 tables and save data to one table,
when i fill all datasheet with attending i want to submit these information to Schedule Table with each field with related one in the table and insert EmployeeID of selected employeeName.
A: In regard to both one and two, it seems that you have not bound your form to a table or query. Datasheets and continuous forms only work properly if all the data-entry controls are bound to fields. It is nearly always best to use a continuous form rather than a datasheet. If you are not familiar with form design, it is nearly always best to use the wizards, because they will set up the form with all the bindings in place.
For currency, choose the currency data type, not decimal - this is important for more than display. In addition, fields have a format property that can be set in table design.
I suggest you do some reading if you intend to continue to work in Access. You will find lists of books here on Stackoverflow - The Access Cookbook Getz, Litwin and Baron is often recommended.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Entity Framework - Row size greater than allowable maximum row size of 8060 I have an entity with a binary datatype and a corresponding varbinary(max) column in SQL Server. EF creates this:
CREATE TABLE [dbo].[Attachments]
(
[Id] INT IDENTITY(1,1) NOT NULL,
[FileName] NVARCHAR(255) NOT NULL,
[Attachment] VARBINARY(MAX) NOT NULL
);
When I try to call .SaveChanges() from Entity Framework, I get an error:
Cannot create a row of size 8061 which is greater than the allowable maximum row size of 8060
I understand the error, there's plenty of that on Google but I don't understand why I'm getting it. Shouldn't this be managed by Entity Framework / SQL Server?
Richard
A: The only way I can see you getting this error with that table definition is if you have previously had a large fixed width column that has since been dropped.
CREATE TABLE [dbo].[Attachments] (
[Id] int IDENTITY(1,1) NOT NULL,
[FileName] nvarchar(255) NOT NULL,
[Attachment] varbinary(max) NOT NULL,
Filler char(8000),
Filler2 char(49)
);
ALTER TABLE [dbo].[Attachments] DROP COLUMN Filler,Filler2
INSERT INTO [dbo].[Attachments]
([FileName],[Attachment])
VALUES
('Foo',0x010203)
Which Gives
Msg 511, Level 16, State 1, Line 12 Cannot create a row of size 8075
which is greater than the allowable maximum row size of 8060.
If this is the case then try rebuilding the table
ALTER TABLE [dbo].[Attachments] REBUILD
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: get tomcat installation path in pom.xml i want to get the root directory of apache tomcat installed in my system in the pom.xml
for example my tomcat is installed in c:\apache-tomcat-6.0.32
<execution>
<id>generate.bat</id>
<phase>test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>here i want to get tomcat director</executable>
<workingDirectory>here i want to get tomcat directory</workingDirectory>
</configuration>
</execution>
A: Maven will not be able to guess where is installed your Tomcat.
But you can use properties to do this.
For instance you can change define ${tomcat.dir}.
<execution>
<id>generate.bat</id>
<phase>test</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${tomcat.dir}</executable>
<workingDirectory>${tomcat.dir}</workingDirectory>
</configuration>
</execution>
And then either you call Maven add to you maven command line -Dtomcat.dir=/your/path/ or you can define the property in the POM.
<project>
...
<properties>
<tomcat.dir>/your/tomcat/path</tomcat.dir>
</properties>
...
</project>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .htaccess to two subdirectories I am trying to make a .htaccess control the access to my websites. I have two websites: one with a wordpress blog and other with a wiki-site placed mydomain.com/wordpress and mydomain.com/wiki.
I want my domain to access /wordpress without showing this in the http-adressebar. (wordpress has been configuration right).
The wiki-site should just be shown under /wiki.
I have tried a lot of solutions (also on stackoverflow), but nothing worked so far.
RewriteEngine On
RewriteBase /mydomain.com/
# WIKI
RewriteCond %{REQUEST_FILENAME} !-f # Existing File
RewriteCond %{REQUEST_FILENAME} !-d # Existing Directory
RewriteRule ^wiki/(.*)$ wiki/index.php?title=$1 [L,QSA]
# WORDPRESS
# RewriteCond %{REQUEST_FILENAME} !-f # Existing File
# RewriteCond %{REQUEST_FILENAME} !-d # Existing Directory
# RewriteRule ^/*$ /wordpress/index.php [L,QSA]
EDIT
www.mydomain.com -> www.mydomain.com/wordpress
www.mydomain.com/wiki/(.*)$ -> www.mydomain.com/wiki/index.php?title=$1
A: Simple answer - you can't do it that way, because, let's say you have an url that points to
http://www.yourdoamain.com/index.php - what would you expect your apache to hit - the wiki, or the blog?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PowerShell: how to get if else construct right? I'm trying to learn powershell and tried to construct a if else statement:
if ((Get-Process | Select-Object name) -eq "svchost") {
Write-Host "seen"
}
else {
Write-Host "not seen"
}
This ends up into "not seen", although there is svchost processes. How to modify this to get correct results?
A: You can simply ask Get-Process to get the process you're after:
if (Get-Process -Name svchost -ErrorAction SilentlyContinue)
{
Write-Host "seen"
}
else
{
Write-Host "not seen"
}
A: Your if-else construct is perfect, but change the if condition like below:
(Get-Process | Select-Object -expand name) -eq "svchost"
Initially you were comparing an object to the "svchost" which will evaluate to false. With the -expandProperty flag, you are getting that property of the object, which is a string and can be properly compared to "svchost".
Note that in the above you are comparing array of strings, which contains the name of process, to "svchost". In case of arrays -eq is true if the array contains the other expression, in this case the "svchost"
There are other "better" ways to check as well:
if (Get-Process | ?{ $_.Name -eq "svchost"}) {
Write-Host "seen"
}
else {
Write-Host "not seen"
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: PopupScreen not show after pushing I push the pop screen using following code, what pop screen not displays.
Please tell me what I missed.?
LabelField statusMsg = new LabelField("Hello");
PopupScreen statusScreen = new PopupScreen((fieldHFM));
UiApplication app = UiApplication.getUiApplication();
app.pushScreen(statusScreen);
A: Try
to do in following way
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().pushScreen(statusScreen);
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to solve orientation issue? I want to make 480x800, 600x800, 600x1024 and 800x1280 resolution layouts.
i have to show both orientation(portrait and landscape) with resolution 600x800, 600x1024 and 800x1280 and resolution 480x800 show only landscape mode.
Right now it is showing both orientation mode.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nga.swp" android:versionCode="1" android:versionName="1.0">
<supports-screens android:resizeable="true"
android:largeScreens="true" android:normalScreens="false"
android:smallScreens="false" android:anyDensity="true" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:label="@string/app_name" android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PhraseListActivity"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:label="@string/app_name" android:windowSoftInputMode="adjustPan" />
<activity android:name=".ViewActivity" android:theme="@android:style/Theme.NoTitleBar"
android:label="@string/app_name" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-sdk android:minSdkVersion="8" />
</manifest>
my issue is how i am able to show landscape mode only with resolution 480x800.
what changes i have to do in my menifest file.
A: The best way to have conditional layouts is by using qualified directory names inside the /res directory.
But in your case, you would need to change the android:screenOrientation of your activity. Alas, it is in the manifest and it does not seem to be setable in your activity layout.
So, I guess you have to use code in your activity onCreate.
First get the screen dimension using:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Then conditionally adapt screen orientation using :
if((width != 480) && (height !=800))
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
See ActivityInfo.screenOrientation for further orientation modes.
A: I think you should make
layout-land
layout
put your xml in that.
480x800, 600x800, 600x1024 and 800x1280 resolution layouts for that..
you should make drawable-ldip, drawable-mdip, drawable-hdip folder and put your images in that.
Android direct take & differentiated resolution.
A: First of all check your device resolution by using:
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Then get the device's height & width using display.getHeight() and display.getWidth().
It is much easier to do the next operations.
You can use OrientationListener in order to check the orientation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to control the status of BeginInvoke? I have a function as below.
private void AddPrice(String value)
{
Delegate del=new Action<String>(AddToCollection);
this.Dispatcher.BeginInvoke(del,DipatcherPriority.Background,value);
}
In AddToCollection method, the value will be added to Observable Collection.
"AddPrice" function will be called based on user input(Eg. 100 times, 200 times, 300 times).
the maximum count of Observable collection is 150. If it reaches 150, I have to pop up Messagebox to user and need to cancle adding values. But, If the function is called 200 times, the messagebox is showing 50 times bse of BeginInvoke. How can I modify this? thanks.
A: You have two options:
*
*Set some flag once user cancels adding values, and ignore AddToCollection calls after this.
*Replace BeginInvoke with Invoke and return false when adding is canceled. Stop calling Invoke when it returns false.
So, you can stop this process on receiver or on the sender side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I've just deleted one week of work! How to undo git rm -r --cached? I commited a wrong file, so I wanted to clean it up, but accidentally I overwrote all my files in the directory with last files committed to git.
Help please!
What I did:
git add fileIdidnotwanttoadd
git rm -r --cached .
git reset --hard HEAD
result: All my fixes are gone! I fixed 3 very hard bugs and it's all gone!
Edit:
Thank you all. I used most of your suggestions, still had to redo a few things, but all is restored now. No more perfectionism, I learned my lesson!
A: *
*If you did commit locally those bugfixes, you can recover them with git reflog.
(for a single file, you can also try git rev-list)
*If you didn't commit them (ie. they were only in the working tree, not the repo), they are gone from your local working tree.
*If you did add them to the index (but not commit them), see Mark's answer.
A: There are various situations in which you may be able to recover your files:
*
*If you staged your changes before doing the above commands (i.e. ran git add <file> when <file> contained the content you want to get back) then it should be possible to (somewhat laboriously) get that file back by following this method.
*If you ever created a commit that contained those files, then you can return to that commit by finding the object name of the commit in the reflog and then creating a new branch based on it. However, it sounds from the above as if you never committed those files.
*Supposing you ever ran git stash while working on those files, they are recoverable either via git stash list, or methods 1. or 2. above.
Otherwise, I'm afraid you may be out of luck. :(
A: (from: Recover from git reset --hard?)
You cannot get back uncommitted changes in general, so the real answer here would be: look at your backup. Perhaps your editor/IDE stores temp copies under /tmp or C:\TEMP and things like that.[1]
git reset HEAD@{1}
This will restore to the previous HEAD - in case you had something committed earlier
[1]
*
*vim e.g. optionally stores persistent undo,
*eclipse IDE stores local history;
such features might save your a**
A: I did not find any of the above solutions successful. Running
git status
in the root you will see all the uncommitted changes. To discard those changes caused by the
git -rm --cached <files>
you would want to use
git checkout -- *
I hope this helps alleviate your stress.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How to implement double tap for Android live wallpapers? I want to implement a double tap event for a Android live wallpaper.
Sadly, I couldn´t find any specific code how to do that.
At the moment I´ve found a workarround using the onTouchEvent-method of the Engine-class:
public void onTouchEvent(MotionEvent event) {
long time = android.os.SystemClock.currentThreadTimeMillis();
if(((time - mLastTouchTime) < 500) && ((time - mLastTouchTime) > 100))
{
if(!mIsPlayed && mSound)
{
mIsPlayed = true;
int sound = R.raw.hell;
if(mTheme.equals("rose"))
sound = R.raw.rose;
if(mTheme.equals("greed"))
sound = R.raw.greed;
MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
mIsPlayed = false;
}
});
}
}
mLastTouchTime = time;
super.onTouchEvent(event);
}
Well, that´s not an elegant solution. I know there are wallpapers which implemented the double tap. But I have no idea, how to do it on my own.
So a "tap" in the right direction would be nice. If nescessary, I will accept a "double tap". :D
Greetings,
Robert
A: Use http://developer.android.com/reference/android/view/GestureDetector.html
for example:
public class AndroidTestActivity extends Activity {
private GestureDetector gestureDetector;
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.e("onDoubleTap", e.toString());
//handle double tap
return true;
}
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL User Defined Java Function (Character conversion between CCSID 65535 and CCSID 1200 not valid) I have been having a problem with an iSeries Function whereby it is not connverting data properly becuase my default user profile is using CCSID 65535. I can change the job to CCSID 37 and everything works fine.
I want a solution whereby the user does not need to change their job properties.
The function is running a java application and looks like this
CREATE FUNCTION mylib/re_Test2(input VARCHAR(500) CCSID 37,
regex VARCHAR(500) CCSID 37)
RETURNS INTEGER
EXTERNAL NAME 'UDFs.re_Test'
LANGUAGE Java
PARAMETER STYLE Java
FENCED
NO SQL
RETURNS NULL ON NULL INPUT
SCRATCHPAD
DETERMINISTIC
I tried it without using the CCSID 37 initially but found some posts suggesting that adding this would force any parameters to be converted to US English. It does not seem to be working for me.
Any suggestions?
I tried running from STRSQL and an RPGLE script but both don't work, however, from SQLSquirrel (an open source SQL program that uses ODBC) it works.
A: CCSID 65535 means 'no translation of characters' ... so if your table is created with a specific CCSID, I would suggest running the application with that CCSID.
A: I had the same problem. I found out it doesn't concern function parameters (I had integers).
The matter is how you call the function. For example in my case calling it with System i Navigator worked, but not with an RPG program (which probably uses the user CCSID, that is 65535).
For the latter I solved with CHGJOB CCSID(37) (37 is for "COM EUROPE EBCDIC", anyone can choose the proper code page) and then putting again CHGJOB CCSID(65535).
Another similar way is CHGUSRPRF USRPRF(MYUSER) CCSID(37). Haven't found anything better...
A: The above select works fine too, except if you try to put in a :INTO host variable within RPG it will through an error. Solution is do a chgjob of CCSID to 37, then run your embedded SQL, then changejob CCSID back to 65535. Works fine then. If you want more information or samples, send me email at [email protected] for more information. I came across this problem using the ENCODE/DECODE functions in the RPG world. Thanks.
A: use simple cast, where CSSID 37 = CSSID 65535,
Example:
select cast( campo1 as varchar(500) CCSID 37 ) from biblioteca.tabla
db2 is unusual
A: Solution is do a CHGUSRPRF of CCSID to 37, then run your embedded SQL, then changejob CCSID back to 65535. Works fine then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: creating a CustomView I am trying to implement this game, and I am confused about how to start.
Should I use ImageButtons and implement this game, or should Icreate some custom view?
I am not asking you the code, but what custom view I should create. Basically, I need a plan as to how to implement this game.
A: It looks like line drawing.
So extend View, implement onDraw method, and there draw lines to Canvas.
If there're other parts to draw, you may possibly use Bitmap to draw these onto the Canvas.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How to handle back button in windows phone 7? I have an application, the main page contains few functions. To explain in detail - I have save, color palette button in my main page. When any of these buttons are clicked, save pop up or color palette appears. How to handle back button of the device, when color palette or save pop up is opened. When back button is pressed at these scenario it should just make them invisible and stay on the main page. When nothing is being performed in the main page, then it should come out of the app. I tried to make their visibility collapsed on back button press. But it still is coming out of the application.
Please, guide me in this. Thanks in advance.
A: Override PhoneApplicationPage.OnBackKeyPress and then set CancelEventArgs.Cancel to true if you want to stop it from actually going back.
protected override void OnBackKeyPress(CancelEventArgs args)
{
if (PanelIsShowing)
{
HidePanel();
args.Cancel = true;
}
}
A: The back button behaves as is intended by Microsoft.
If you change its behavior you risk your application not being certified for the Marketplace.
If you want the back button to close the popups, turn the popups into pages so the back button navigates back to the main page..
A: You need to use
protected override void OnBackKeyPress(CancelEventArgs e)
{
if (_popup.IsOpen)
{
_popup.IsOpen= false;
e.Cancel = true;
}
else
{
base.OnBackKeyPress(e);
}
}
That should do the trick.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery. Remove element by attribute name. How? Is there a way to remove a DIV based on it's custom attribute comment_id?
I have the following code but it does not quite work yet.
<script type="text/javascript">
$('.delete_comment').live('click', function() {
// Url we request data from
$.get( "http://www.site.com/pages/delete/user_comment.php",
// Url parameters to send
{id:$(this).attr('comment_id'),c:'yes'},
// Output data from php file generated by PHP echo.
function(data)
{
var comment_id = $(this).attr('comment_id').val();
//alert(comment_id);
if (comment_id == data) {
$(this).remove();
}
});
});
</script>
A: Yes, possible
http://api.jquery.com/category/selectors/
http://api.jquery.com/jQuery.each/
$('div[comment_id="value"]').remove();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: C#. Security and Efficiency Loopholes When Uploading Files through a .Net Application via SFTP I need advice from developers who have either faced or have experience dealing with a situation similar to the one described below; just to avoid reinventing the wheel.
Situation:
We have a C# Winform application running at multiple sites (100+) where each site generate an average of 30 new data files per week varying in sizes from 10-40 MB per file. We want to maintain a data store for all data generated in the field using a one-way synch. It is a medical application hence the security of this data during transmission is extremely important.
Our Solution:
Since all new data is created in new files, we think that a diff based data replication system (such as rsync) is NOT essential. Instead, we are writing a custom application that runs in the background as a Windows service and uses an SFTP.Net wrapper (chilkat) to upload new data files to our Linux server at regular intervals. Data from each site is uploaded to a separate pre-configured folder on the server. Our custom client application keeps track of which files it has uploaded in a local SQLlite database. The Chilkat API allows us to authenticate using username/password or keys.
Questions:
*
*Would you consider above solution to be prone to security flaws with respect to data transmission?
*Would you have effeciency concerns with our approach?
*Are there any better alternatives than what we are proposing. Our client machine are Windows and the server is Linux based (we can move to a Windows server too, but that is certainly not a prefernce.)
Thanks in advance....
m.umer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error when use UIAplication.getUIApllication.pushScreen(screen) on Blackberry? I have a "Back" button that I created.
Action for it is ----- UIAplication.getUIApllication.pushScreen(screen1)
I did so because I want to refresh screen 1 when I cick "Back ".
But there have an error that " OutOfMemoryError" when I click "Back" few times.
If I replace with - UIAplication.getUIApllication.popScreen(this) , there have no error .
But I really want to refresh screen1.
Why I gotthis error ? How to solve it ? ( I use Persistenobject to save data for my app ).
Please help me . Thanks a lot.
A: Pushing the same screen again adds additional screen to stack and takes additional memory.
And it is logical that you get outofmemory error.
If you want to refresh field's/manager's contents use invalidate() method of a particular field or manager.
A: You can try popping the old screen1 and then pushing it again:
UIAplication.getUIApllication.popScreen(getScreenBelow());
UIAplication.getUIApllication.pushScreen(new screen1());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to scroll ListBoxes naturally on the touch-screens in WPF application? I am developing WPF application which will be executing on the 21-inch touch-screen.
Along with ListBoxes in my application I have vertical scroll-bars for each of them. What I want is to get rid of those scroll-bars and just allow user to scroll naturally by touching lists itself. How can I achieve that? Is there out-of-the-box support for that in Windows 7 and .NET 4.0?
A: I know this is an old question, but it came up for me first in Google. So just in case someone else comes here, the answer to this is in this SO question. Simply set the PanningMode, PanningDeceleration, and PanningRatio for the ScrollViewer.
It worked for me on a ComboBox as well.
<ComboBox ... ScrollViewer.PanningMode="VerticalOnly" />
A: Have a look at this similar question
Although WPF supports touch events out of the box WPF is very limited for this kind of scenario.
I am hoping for 3rd parties (or even Microsoft) to add the Windows 8/Metro touch experience to WPF
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to upgrade from grails 1.2.2 to 1.3.7? I tried to upgrade my current project to grails 1.3.7 (from 1.2.2)
I tried to grails upgrade first, and then I tried to update all the plugins. I use ofchart, jsecurity and liquibase.
When I tried to run the grails (with grails run-app)
it won't start the apps instead it shut down. When I checked on my stacktrace.log I found something like this:
2011-10-03 11:59:09,250 [main] ERROR StackTrace - Sanitizing stacktrace:
groovy.lang.MissingMethodException: No signature of method: org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy.setMinEvictableIdleTimeMillis() is applicable for argument types: (java.lang.Integer) values: [1800000]
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:54)
at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:46)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
at BootStrap$_closure1.doCall(BootStrap.groovy:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1058)
at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:930)
at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:886)
at groovy.lang.Closure.call(Closure.java:282)
at groovy.lang.Closure.call(Closure.java:277)
Any idea how to fix this ? Thank you very much.
ps: I'm using latest / newest java.
here is my script for running the app
set JAVA_OPTS=-Xmx512m -XX:MaxPermSize=512m
grails run-app -Dserver.port=9090 -Ddisable.auto.recompile=false
List of plugins:
Plug-ins you currently have installed are listed below:
-------------------------------------------------------------
hibernate 1.3.7 -- Hibernate for Grails
jetty 1.2-SNAPSHOT -- Jetty Plugin
jsecurity 0.4.1 -- Security support via the JSecurity framework.
ofchart 0.6.3 -- Plugin summary/headline
A: The dataSource bean is now a proxy for the real datasource. It's an instance of TransactionAwareDataSourceProxy which implements the DataSource interface, but since it's not the 'real' datasource you can't call non-standard methods on it.
I'm assuming you have a def dataSource field - just change it to def dataSourceUnproxied and then you can call methods like setMinEvictableIdleTimeMillis() on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows Phone 7 browser control with additional script running in browser I am developing a windows phone application in visual studio (Silverlight in C#) and I added a browser control to the application that i develop to show some random website.
Now i need to run a javascript along with that page in the browser control. How do i add the script to that. is there anyway to append the script directly when the html loads?
The script can be loaded from remote server or from the application itself. Its just to modify the pages a bit and display.
A: Instead of using the NavigateTo(URI) method of the WebBrowserControl directly with the URL, you can get the source of the HTML page as a string, modify it by injecting your javascript and use the NavigateToString(string html) method to display the content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook Publishing Score I am trying to publish scores from my app. But unfortunately I am unable to do so. I even tried using the code snippet at http://developers.facebook.com/blog/post/539/ but for some odd reason it didn't work for me. If someone can provide me with some basic guidelines I would really be helpful as that would help me build upon that system and move forward. I don't want any fancy publishing technique I am just looking forward to publishing score at the end of the game.
Using https://graph.facebook.com/user id/scores?score=10&access_token=acess_token returns
{
"data": [
]
}
A: Your example looks like a HTTP GET request (i.e. 'show me the scores of this user')
To update a score you either need to make a POST request, or 'fake' the POST request by adding ?method=post to your GET call
You'll also need to use an App Access Token, the instructions for obtaining this are at:
https://developers.facebook.com/docs/authentication/#applogin
A: I've done it using javascript sdk, you can check out the source code for my game
https://apps.facebook.com/tgif-game/
you should be checking out scripts/gameui.js for the calls to posting scores and getting the list of scores.
A: In the FaceBook Developer Dashboard set your app category as games.
Then only you'll be able to post scores.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to play Next song Automatically when First one is finish? In my app I am using AudioStreamer to play a song through server,
I am refering this tutorial,
http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html
How to play next song Automatically when using AudioStreamer?
A: In the tutorial is mentioned callback function which is triggered when a song finish playing. Your goal is to write functionality for your list of songs to move on the next one when this function is called.
void MyAudioQueueIsRunningCallback( void * inClientData,
AudioSessionPropertyID inID,
UInt32 inDataSize,
const void * inData)
{
move to the next song
}
A: I got answer,
In that tutorial there isplaybackStateChanged:(NSNotification *)aNotification method,
- (void)playbackStateChanged:(NSNotification *)aNotification
{
if ([songStreamer isWaiting])
{
}
if ([songStreamer isPlaying])
{
}
else if ([songStreamer isIdle])
{
[self playnextsong];
}
else if ([songStreamer isPaused])
{
}
}
When song completes through streaming,
It going to idle state.
So in idle state i call a method of playing next song.
And it Runs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set Values for other columns in gridview based on selected value of dropdownlist inside gridview(edit mode) in ASP.Net I have gridview with Employee Name, Emp Code, Designation. I am populating Employee Names dropdownlist with values in rowdatabound event. In edit mode of, on selection of a value in Employee Names dropdownlist, the EmpCode and Designation should change accordingly. The empCode and Designation label controls are in templatefield. I have writtern selectionchanged event for the Employee Names drodownlist,
ddlEmp.SelectedIndexChanged += new EventHandler(grd_ddlEmp_SelectedIndexChanged);
but I do not know how to change Emp Code and Designation values inside the particular row in gridview.
A: You need to put your gridview in UpdatePanel and do it in code behind of SelectedIndexChanged event like I have done in datalist below :
<asp:DataList ID="dlstPassengers" runat="server" OnItemDataBound="dlstPassengers_ItemDataBound"
RepeatDirection="Horizontal" RepeatColumns="2" Width="100%">
<ItemTemplate>
<div class="form-linebg" style="line-height: 32px;">
<asp:DropDownList ID="ddlCountry" AutoPostBack="true" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"
CssClass="select-3" Style="width: 145px; margin-bottom: 9px;" runat="server">
</asp:DropDownList>
<br />
<asp:DropDownList ID="ddlCity" CssClass="select-3" Style="width: 145px; margin-bottom: 10px;"
runat="server">
</asp:DropDownList>
</div>
</ItemTemplate>
</asp:DataList>
In code behind :
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlCountry = (DropDownList)sender;
DropDownList ddlCity = (DropDownList)((DropDownList)sender).Parent.FindControl("ddlCity");
BindCity(ddlCity, ddlCountry.SelectedValue);
}
private void BindCity(DropDownList ddlCity, string countryCode)
{
// Binding code of city based selected country
}
You need to set EmpCode and Designation columns on SelectedIndexChanged event of dropdown by finding control in code behind.
A: In the SelectedIndexChanged function, find the selected value of the drop down box
DropDownList ddl = (GridView1.Rows[GridView1.SelectedIndex].FindControl("DropDownList1") AS DropDownList);
var selectedVal = ddl.SelectedValue;
Execute some code to determine the Emp Code and Desgination and then populate the relevant label ( or other control):
Label lbl = GridView1.Rows[GridView1.SelectedIndex].FindControl("Label1") as Label;
Assign value to the label.
A: Does these things inside the SelectedIndexChanged event of the DropDownList
*
*First find the row.
*Then access the controls and change accordingly.
Pseudo Code
protected void grd_ddlEmp_SelectedIndexChanged(object sender, EventArgs e)
{
GridView row = ((DropDownList)sender).NamingContainer as GridViewRow;
Label Designation = row.FindControl("id of the designation label") as Label;
Designation.Text = "new Designation Name";
}
A: use in your dropdown AutoPostBack="true"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery Mobile, can i create a function that emulates a tap screen My Goal is to set a function that fires every 30 seconds that emulates a tap on the screen so that the screen stays on. Is this at all possible, or what is the best way to enable this without having to program it natively in Java.
I'll be happy if i can do it via phonegap.
A: You can disable the Idle Timer if you're in PhoneGap, you'll need to add this to the UIApplication object.
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mixing cell types in a DataGridViewColumn Is it possible to have both DataGridViewComboBoxCells and DataGridViewTextBoxCells in a single DataGridViewColumn? Or am I absolutely restricted to having one type per column?
A: There is a weird solution for this.
By default create the column as TextBox.
Handle the cell click or cell enter event.
In the event if the ColumnIndex matches, Convert the column type to ComboBox and set the items. Once the cell leave event fires from the respective column index, convert it back to textbox.
Dont forget to read the text from Combo before converting and set it to TextBox.
I know this is not apt solution but works.
I am eager to know if anyone has a better idea.
Questioner's EDIT:
Here was the code I ultimately wrote:
// Using CellClick and CellLeave in this way allows us
// to stick combo boxes in a particular row, even if the
// parent column type is different
private void dataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= FIRST_COL && e.ColumnIndex <= LAST_COL && e.RowIndex == ROW_OF_INTEREST)
{
object value = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
dataGrid.Columns[e.ColumnIndex].CellTemplate = new DataGridViewComboBoxCell();
var cell = new DataGridViewComboBoxCell {Value = value};
cell.Items.AddRange(_values);
dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell;
}
}
private void dataGrid_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= FIRST_COL && e.ColumnIndex <= LAST_COL && e.RowIndex == ROW_OF_INTEREST)
{
object value = dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
dataGrid.Columns[e.ColumnIndex].CellTemplate = new DataGridViewTextBoxCell();
var cell = new DataGridViewTextBoxCell {Value = value};
dataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex] = cell;
}
}
Also, when creating the column, I had to make sure it was a generic column; i.e. not a DataGridViewTextBoxColumn:
var col = new DataGridViewColumn
{
CellTemplate = new DataGridViewTextBoxCell()
};
That way, I could change the CellTemplate later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Needing jQuery listener for input field - keyup and change not working I need to enable a submit button on my form once the user enters some text into the email address field. Problem is they may be on the form for the second or third time, and the browser saves their email addresses in a drop-down menu under the input.
See here: http://i.imgur.com/7Q40A.jpg
When they click that, it doesn't work. How can i get jquery to listen for that as well?
A: check the email input box value of keydown event.
A: Very strange. When I tried it yesterday with .change instead of with .keyup, it did not work. But today it is. Thanks anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FullText INDEXING on MyISAM is really slow I have a table
CREATE TABLE `dataFullText` (
`id` int(11) NOT NULL,
`title` char(255) NOT NULL,
`description` text NOT NULL,
`name` char(100) NOT NULL,
`ref` char(50) NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `fulltext` (`ref`,`name`,`title`,`description`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
Which has around 100k records.
mysql> select * from information_schema.TABLES WHERE TABLE_NAME='jobsFullText'\G
*************************** 1. row ***************************
TABLE_CATALOG: NULL
TABLE_SCHEMA: ****
TABLE_NAME: dataFullText
TABLE_TYPE: BASE TABLE
ENGINE: MyISAM
VERSION: 10
ROW_FORMAT: Dynamic
TABLE_ROWS: 79495
AVG_ROW_LENGTH: 791
DATA_LENGTH: 62938804
MAX_DATA_LENGTH: 281474976710655
INDEX_LENGTH: 53625856
DATA_FREE: 51328
AUTO_INCREMENT: NULL
CREATE_TIME: 2011-10-03 13:38:25
UPDATE_TIME: 2011-10-03 13:55:56
CHECK_TIME: 2011-10-03 13:38:48
TABLE_COLLATION: utf8_general_ci
CHECKSUM: NULL
CREATE_OPTIONS:
TABLE_COMMENT:
This table is updated every hour with a LOAD DATA INFILE, which has around 8k records.
The time the table is locked is around 30 seconds. Which correspond to the time I make a
mysql> alter table dataFullText drop index title;
Query OK, 79495 rows affected (1.33 sec)
Records: 79495 Duplicates: 0 Warnings: 0
mysql> alter table dataFullText add fulltext index (ref,name,title,description);
Query OK, 79495 rows affected (22.96 sec)
Records: 79495 Duplicates: 0 Warnings: 0
My problem is that 30seconds is really a long time. This table is queried 5 times/seconds, which make the queue reach 30 x 5 = 150 . Because our max connection limit is set to 100, the mysql server begin to reject some incoming connections.
We plan to have at least 1 Million row in this table in the future, and I guess this won't get faster.
Is there anything I can do to reduce the time mysql uses for updating the index ?
A: In a general SQL DBMS, fully indexing a table like this doesn't help you out. The index being in fact larger than the table itself, the time it will take to access it will be even bigger than the time to access the table without the index.
Now, this really depends on the particular installation you have: the amount of RAM, the overall speed of the system.
Before to add indexes and, yes, updating/recreating indexes is slow, just be sure it's worth it, in the particular conditions you are in.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NullReferenceException using AutoMapper and StructureMap So, I get a NullReferenceException thrown on a production server. It's not reproducible and happens once every ~100 request.
This is the code.
var userInfo = Mapper.Map<UserSubscribedEvent, UserInfo>(userSubscribedEvent);
var subscription = repository.GetActiveSubscriptionForUser(userInfo.UserId);
The exception appears on the second line. So it's either userInfo that is null or it is the repository.
The repository is injected into the class from the constructor using StructureMap so it really should not be null (since it usually works) and userInfo is created using AutoMapper and should not be null either.
So my question is - Can Mapper.Map return null in AutoMapper, if so, when?
If not, have anyone experienced that StructureMap randomly injects null dependencies into the constructor?
If so, can it be avoided?
Thanks!
A:
Can Mapper.Map return null in AutoMapper
Yes.
if so, when?
If you pass null as argument. In your case this would be the userSubscribedEvent variable.
A: SOLVED: The problem was actually on the line below when used a property on subscription (embarrassed), the server ran with a file that had an extra empty line at the top. There where no active subscriptions since the client sent in the request just after it had closed the active subscription. :-/
Thanks again for your help and sorry for not checking my own production code better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When not to use MySQL or other relational DBs? Simple question, when should one not use MySQL?
There are two facets to my curiosity:
*
*When to avoid MySQL in particular?
*When to not use relational databases in general?
I wanted to be sure of my choice of MySQL (with PHP on Apache) as my employer was insistent on using something that's not free or open-source but I insisted otherwise. So I just want to be sure.
A: When your data is not relational, or when (based on your data access pattern and/or data model) you can choose better model, than the relational, use it. If you are not sure there is a better model for your problem, use RDBMS - of of the reasons of it's popularity is that it fits really good for most of the problems. Facebook and Google use MySQL (although not only MySQL, but major part of Facebook is on top of MySQL), so thing about this when you considering a NoSQL solution.
There are different type of databases, like graph databases, which are good for specific tasks. If you have such specific task, research the field of the task.
As for choosing vendor for a RDBMS, this is more a business objective, then a technical one. Sometimes the presense of support, certified professionals, training/consulting, and even matching the company infrastructure (if it has extensive Windows network and experienced windows-administrator it may prefer using windows server over a linux-based one) are the reasons particular software to be choosen.
A:
1. When to avoid MySQL in particular?
When concurrent database sessions are both modifying and querying the database.
MySQL is fine for read-only or read-mostly scenarios (it is no accident that MySQL is frequently used for Web), but more advanced multi-version concurrency control capabilities of Oracle, MS SQL Server, PostgreSQL or even Firebird/Interbase can often handle read-write workloads not just with better performance but with better correctness as well (i.e. they are better at avoiding various concurrency artifacts that may endanger data consistency).
Even traditional "locking" databases such as DB2 or Sybase are likely to handle read-write workloads better than MySQL.
2. When to not use relational databases in general?
In short: when your data is not relational (i.e. it does not fit well in the paradigm of entities, attributes and relationships).
That being said, many modern DBMSes have capabilities outside traditional relational model, such as ability to "understand" hierarchical structure of XML. So even unstructured data that would not normally be stored in the relational DB (or at best would be stored in a BLOB) is no longer necessarily off-limits.
A: Not a difficult question to answer. Don't use MySQL if another DBMS is going to prove cheaper / better value. Other leading DBMSs like Oracle or SQL Server have many features that MySQL does not. Also if your employer already has a large investment in other DBMSs it may be prohibitively expensive and difficult to support MySQL without good reason. For what reason are you insisting on MySQL?
Also bear in mind that no business buys a DBMS. They buy a complete solution of which the DBMS is part. Consider the return on investment of the whole solution and not just the DBMS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Synchronize video to openGL animation I am trying to sync a video to an animation drawn using openGL on iPad, and there are two things I am not sure how to do:
*
*Find the currently playing video frame.
*Make sure the update of the video and update of the openGL drawing occurs at the exact same time, as even a slight sync issue may cause visual artifacts.
A: Not sure it will work but instead of using MPMoviePlayerController you could use an AVPlayer and use and AVSynchronizedLayer to synchronize your OpenGL layer timing with the AVPlayerLayer's one.
You could create the video player like this:
NSURL *videoURL = [NSURL fileURLWithPath:@"your_url"];
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
UIView *playerView = [[UIView alloc] initWithFrame:frame];
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
[playerLayer setFrame:[[playerView layer] bounds]];
Then create a AVSynchronizedLayer layer and sync it with the playerLayer:
AVSynchronizedLayer *syncLayer = [AVSynchronizedLayer synchronizedLayerWithPlayerItem:playerItem];
[syncLayer addSublayer:yourGlView.layer];
[playerView.layer addSublayer:playerLayer];
[playerView.layer addSublayer:syncLayer];
[self.view addSubview:playerView];
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: how to express this in regex I have this :
<title>Title</title>
All I want to do is express this in regex. I have:
/<[A-Za-z]>\w<\/[A-Za-z]>
Can anyone help
A: You need a + after each of the [] and after the \w to represent "one or more".
/<[A-Za-z]+>\w+<\/[A-Za-z]+>/
But it looks like you're trying to parse HTML with regex. You might want to consider not doing that.
A: You should use a backreference. If you don't then you will match:
<title>blabla</otherTag>
Try this:
/<([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>(.*?)</\1>/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I ensure that a workflow is triggers email notification only after user clicks OK and not when the edit properties is clicked I have a custom workflow built using SP DEsigner and the SP sites is created using wss 3.0. I have a customer column and values associated with it which is checked for teh workflow to trigger. Example:
When the status = SME Review, an email shoudl trigger to the assigned to person with a message to take some action on the file. However when a user edits the properties, and if the file is already in SME REview and assigned to someone, it triggers an email before Ok is clicked.
This should not happen, becuase the file is bieng edited to change it to Content Review and will eb assigned to a new person. So the notficaition is going to the SME rather than the content reviewer. I am unable to stop this. Does anyone have any suggestions?
A: On which position do you edit the element or is it a document?
*
*When you edit the listelement in Data Grid View the changes you make in a field are instantly saved when you are changing the field.
*If you are using the EditForm than it would submit the changed values only by clicking the okay buton.
Please put some more details to describe your Problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use the AWS SDK for IOS? Iam developing one application.In that i want to use the amazon web services.I downloaded the AWS SDK for IOS.But i dont know how to write the code for access the AWS.In this i want to use the AWS S3.SO please tell me how to do this.
A: Here's a simple sample app showing how to up/download files from Amazon S3 from your iOS App using Access & Secret Key credentials, i.e. NOT using Cognito which is only available in two regions at the moment: http://bit.ly/awss3v2ios
A: This is how I did it.
*
*Download the aws-ios-sdk or integrate it into your project using cocoapods. (Using cocoapods is really helpful).
*Add -Objc flag to your other linker flags of your build target.
*Make sure your build phases has Foundation.framework and libz.dylib added.
*On AWS Console create your app and go to the Cognito settings.
*Create a new identity pool.
*In step 2 of this process, it'll ask you to provide IAM role. I tried using existing role but was not successful, so create a new IAM role and click update role.
*This will provide you a startup code, use this exactly in your iOS code.
*If you want to have full access to S3 (upload, download, change access settings, remove), then go to IAM section from the AWS console and add the S3 role policy to the role.
*Now the AWS-Console setup is done and you can continue with accessing the S3 from your iOS code. You can find the necessary code in the sample app.
A: I was also strucked in this and sharing you my findings.You can easily integrate the AWS iOS sdk in your app. You have to create the cognito id to use this. Also for testing purpose you can test it directly with your credentials. However using credentials in the app is avoided.You can download the sample app and also get detailed description from here. Click here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Android Sqlite database - constraint failes I have a problem with inserting data in my sqlite database. I'm getting JSON data over the internet and then trying to put that data in sqlite database, but it's throwing me an constraint fails error. I know that means I've already inserted the same data, or at least with the same id, but when I look at my database from emulator, that table is empty and there is no data. Here is the code that I'am using :
public boolean executeInsert() {
UserDatabaseHelper userDbHelper = new UserDatabaseHelper(context, null, 1);
userDbHelper.initialize(context);
ContentValues values = new ContentValues();
values.put("objectId", objectId);
Log.i("objectd Id ", "object ID : " + objectId);
values.put("objectOid", objectOid);
Log.i("objectd Oid ", "object OID : " + objectOid);
try {
String jsonData = new String(collectionBuffer, "UTF-8");
Log.w("JSONDATA", "JSONDATA VALID OR NOT : " + jsonData);
json = new JSONObject(jsonData);
JSONObject jsonObj = (JSONObject) new JSONTokener(jsonData).nextValue();
locale = jsonObj.getString("locale"); // don't put in database
Log.i("Locale", "Locale : " + locale);
id = Integer.parseInt(jsonObj.getString("id"));
Log.i("Id", "Id : " + id);
genreId = Integer.parseInt(jsonObj.getString("genre_id"));
Log.i("Genre ID ", "Genre Id : " + genreId);
values.put("genreId", genreId); //genreId
dateCreated = jsonObj.getString("date_created");
Log.i("date Created", "Date Created : " + dateCreated);
values.put("dateCreated", dateCreated);
title = jsonObj.getString("title");
Log.i("title", "title : " + title);
values.put("title", title);
isRecommended = Integer.parseInt(jsonObj.getString("is_recommended"));
Log.i("Is Recommended", "IS Recommended : " + isRecommended);
values.put("isRecommended", isRecommended);
userCount = Integer.parseInt(jsonObj.getString("subscribed_users_count"));
Log.i("USubscribed Users Count", "Subscribed Users Count : " + userCount);
values.put("usersCount", userCount);
envelopeCost = Double.parseDouble(jsonObj.getString("envelope_cost"));
Log.i("envelope cost", "envelope cost" + envelopeCost);
values.put("envelopeCost", envelopeCost);
alias = jsonObj.getString("alias");
Log.i("alias", "alias : " + alias);
values.put("alias", alias);
imageWidth = Integer.parseInt(jsonObj.getString("category_big_image_width"));
Log.i("category_big_image_width", "category_big_image_width : " + imageWidth);
totalCardsCount = Integer.parseInt(jsonObj.getString("total_cards_count"));
Log.i("Total Cards Count", "Total Cards Count : " + totalCardsCount);
values.put("cardsCount", totalCardsCount);
ownedCardsCount = Integer.parseInt(jsonObj.getString("owned_cards_count"));
Log.i("Owner Cards Count", "Owned Cards Count : " + ownedCardsCount);
values.put("ownedCardsCount", ownedCardsCount);
elemOrder = Integer.parseInt(jsonObj.getString("elem_order"));
Log.i("elem order", "elem order : " + elemOrder);
values.put("elemOrder", elemOrder);
intro = jsonObj.getString("intro_text");
Log.i("Intro text", "Intro text : " + intro);
values.put("introText", intro);
createdBy = jsonObj.getString("created_by");
Log.i("created By", "Created By : " + createdBy);
values.put("createdBy", createdBy);
right = jsonObj.getString("reserved_rights_to");
Log.i("reserved_rights_to", "reserved_rights_to : " + right);
values.put("reservedRightsTo", right);
legals = jsonObj.getString("legal_notice");
Log.i("legals", "legals : " + legals);
values.put("legalNotice", legals);
isSubscribed = Integer.parseInt(jsonObj.getString("is_subscribed"));
Log.i("is subscribed", "Is subcribed : " + isSubscribed);
values.put("isSubscribed", isSubscribed);
cardsPerEnvelop = Integer.parseInt(jsonObj.getString("cards_per_envelope"));
Log.i("Cards per envelope", "Carda per envelope : " + cardsPerEnvelop);
values.put("cardsPerEnvelope", cardsPerEnvelop);
JSONArray langs = jsonObj.getJSONArray("languages");
for (int i = 0; i < langs.length(); i++) {
Log.i("Languages", "Languages : " + langs.getJSONObject(i).getString("locale"));
Log.i("Languages", "Languages : " + langs.getJSONObject(i).getString("title"));
}
tagTitle = jsonObj.getString("tag_title");
Log.i("tag title", "tag title : " + tagTitle);
values.put("tagTitle", tagTitle);
categoryTitle = jsonObj.getString("category_title");
Log.i("category title", "category title : " + categoryTitle);
values.put("categoryTitle", categoryTitle);
dateTitle = jsonObj.getString("date_title");
Log.i("date title", "date title : " + dateTitle);
values.put("dateTitle", dateTitle);
JSONArray stats = jsonObj.getJSONArray("statistics_cats");
for (int i = 0; i < stats.length(); i++) {
//String row = stats.get(i).toString();
Log.w("Element", "Show Statistics cats : " + stats.getJSONObject(i).getString("type"));
Log.w("Element", "Show Statistics cats : " + stats.getJSONObject(i).getString("value"));
Log.w("Element", "Show Statistics cats : " + stats.getJSONObject(i).getString("name"));
}
isEnabled = Integer.parseInt(jsonObj.getString("is_enabled"));
Log.i("is enabled", "is enabled : " + isEnabled);
values.put("isEnabled", isEnabled);
hasOwnerContent = Integer.parseInt(jsonObj.getString("has_owned_content"));
Log.i("has owned content", "has owned content : " + hasOwnerContent);
values.put("hasOwnedContent", hasOwnerContent);
isCommingSoon = Integer.parseInt(jsonObj.getString("is_coming_soon"));
Log.i("is comming soon", "is comming soon : " + isCommingSoon);
isPublic = Integer.parseInt(jsonObj.getString("is_public"));
Log.i("is public", "is public : " + isPublic);
//values.put("isPublic", isPublic);
visibleCountries = jsonObj.getString("visible_countries");
Log.i("visible countries", "visible countries : " + visibleCountries);
visibleLanguages = jsonObj.getString("visible_languages");
Log.i("visible languages", "visible languages : " + visibleLanguages);
columnTitle1 = jsonObj.optString("column_title_1");
Log.i("column title 1", "columtn title 1 : " + columnTitle1);
values.put("columnTitle1", columnTitle1);
columnTitle2 = jsonObj.optString("column_title_2");
Log.i("column title 2", "columtn title 2 : " + columnTitle2);
values.put("columnTitle2", columnTitle2);
columnTitle3 = jsonObj.optString("column_title_3");
Log.i("column title 3", "columtn title 3 : " + columnTitle3);
values.put("columnTitle3", columnTitle3);
columnTitle4 = jsonObj.optString("column_title_4");
Log.i("column title 4", "columtn title 4 : " + columnTitle4);
values.put("columnTitle4", columnTitle4);
columnTitle5 = jsonObj.optString("column_title_5");
Log.i("column title 5", "columtn title 5 : " + columnTitle5);
values.put("columnTitle5", columnTitle5);
String sql = "SELECT * FROM collections WHERE objectId = " + objectId;
Cursor mCursor = userDbHelper.executeSQLQuery(sql);
if (mCursor.getCount() == 0) {
userDbHelper.executeQuery("collections", values);
mCursor.close();
} else {
for (mCursor.moveToFirst(); mCursor.moveToNext(); mCursor.isAfterLast()) {
int mObjectId = mCursor.getInt(mCursor.getColumnIndex("objectId"));
if (objectId != mObjectId) {
userDbHelper.executeQuery("collections", values);
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.w("Error", "ERROR : " + e);
} catch (JSONException e) {
e.printStackTrace();
Log.w("Error", "ERROR : " + e);
} finally {
userDbHelper.close();
}
return true;
}
and here is the exception which I got :
10-03 09:07:48.899: ERROR/Database(30136): Error inserting cardsPerEnvelope=1 hasOwnedContent=1 legalNotice=legals elemOrder=4 dateTitle=Datee tagTitle=Taggv title=Nimasystems 11er objectId=6 introText=txt cardsCount=2 isRecommended=1 usersCount=3 isSubscribed=1 columnTitle1= categoryTitle=Catt alias=nima1r envelopeCost=3.0 ownedCardsCount=1 isEnabled=1 objectOid=00529a1c5597334a96e337feda879831 createdBy=created ny reservedRightsTo=nonono dateCreated=2011-09-27 columnTitle3= columnTitle2= columnTitle5= columnTitle4= genreId=3
10-03 09:07:48.899: ERROR/Database(30136): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
10-03 09:07:48.899: ERROR/Database(30136): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
10-03 09:07:48.899: ERROR/Database(30136): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55)
10-03 09:07:48.899: ERROR/Database(30136): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1623)
10-03 09:07:48.899: ERROR/Database(30136): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1484)
10-03 09:07:48.899: ERROR/Database(30136): at com.stampii.stampii.comm.rpc.UserDatabaseHelper.execQuery(UserDatabaseHelper.java:252)
10-03 09:07:48.899: ERROR/Database(30136): at com.stampii.stampii.comm.rpc.UserDatabaseHelper.executeQuery(UserDatabaseHelper.java:247)
10-03 09:07:48.899: ERROR/Database(30136): at com.stampii.stampii.comm.rpc.CollectionRPCPacket.executeInsert(CollectionRPCPacket.java:441)
10-03 09:07:48.899: ERROR/Database(30136): at com.stampii.stampii.synchronization.Synchronization$2.run(Synchronization.java:434)
10-03 09:07:48.899: ERROR/Database(30136): at java.lang.Thread.run(Thread.java:1102)
UserDbHelper class is my database helper class. I'm using it to put data in sqlite. I don't have any problems with other tables. I can put data on them with similar code to this, but collections table just doesn't want to work..
So any suggestions/help or something else which can help me to solve my problem?
Thanks!
A: As we know Sqlite is a lighter version of the database which is available on the multiple mobile platforms. Since it is not a full fledged RDBMS it supports some datatypes and not all of them.
Please check whether you are inserting data appropriately.
A: There are a few things that can throw this exception. I think you first need o check if you are inserting all NOT NULL rows, so you can be sure that all binding rows are inserted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I clean up this query? I am generating queries which carry out tag searches on the following tables:
entry : id, name, desc
tag : id, name
entry_tag : entry, tag, val
The query is generated from a user-entered predicate such as:
(year >= 1990 and year < 2000) and (status = 'complete' or status = 'pending')
It resembles the following:
select * from entry where id in
(select entry
from
(select t0.entry, t0.val as c0, t1.val as c1, …[1]
from
(select entry, val from entry_tag where tag in
(select id from tag where name = 'year')) as t0,
(select entry, val from entry_tag where tag in
(select id from tag where name = 'status')) as t1,
…[2]
where t0.entry = t1.entry and …[3]) as t
where
…[4]);
(The deep nesting is my naïve attempt to minimise the number of roundtrips, assuming of course that that’s a Good Thing™ to do.)
*
*Find tags by name and alias each value to c0…cn in order of input appearance.
*Alias each tag_entry query to the corresponding t0…tn.
*Group tag mappings by entry.
*Insert the transformed Boolean expression directly into the where clause, e.g.:
(cast(c0 as signed) >= 1990 and cast(c0 as signed) < 2000)
and (c1 = 'complete' or c1 = 'pending')
Is there a better way to go about this, or am I on the right track?
Having to produce this seems wrong:
t0.entry = t1.entry and … and t0.entry = tn.entry
I’m just not sure how else to go about this in a way that preserves the structure of the predicate entered by the user. I don’t want to generate a mangled series of joins when I can do a straightforward mechanical transformation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble displaying texture in OpenGL ES with C++ I'm trying to write a small, portable 2D engine for iOS to learn C++ and OpenGL. Right now I'm trying to display a texture that I've loaded in. I've been successful displaying a texture when loading in the with CoreGraphic libraries, but now I'm trying to load the file in C++ with fread and libpng and all I see is a white box.
My texture is 64x64 so it's not a power of 2 problem. Also I have enabled GL_TEXTURE_2D.
The first block of code is used to load the png, convert the png to image data, and load the data into OpenGL.
void AssetManager::loadImage(const std::string &filename)
{
Texture texture(filename);
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
png_bytep *row_pointers = NULL;
int bitDepth, colourType;
FILE *pngFile = fopen(std::string(Game::environmentData.basePath + "/" + filename).c_str(), "rb");
if(!pngFile)
return;
png_byte sig[8];
fread(&sig, 8, sizeof(png_byte), pngFile);
rewind(pngFile);//so when we init io it won't bitch
if(!png_check_sig(sig, 8))
return;
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL,NULL,NULL);
if(!png_ptr)
return;
if(setjmp(png_jmpbuf(png_ptr)))
return;
info_ptr = png_create_info_struct(png_ptr);
if(!info_ptr)
return;
png_init_io(png_ptr, pngFile);
png_read_info(png_ptr, info_ptr);
bitDepth = png_get_bit_depth(png_ptr, info_ptr);
colourType = png_get_color_type(png_ptr, info_ptr);
if(colourType == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png_ptr);
/*if(colourType == PNG_COLOR_TYPE_GRAY && bitDepth < 8)
png_set_gray_1_2_4_to_8(png_ptr);*/
if(png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png_ptr);
if(bitDepth == 16)
png_set_strip_16(png_ptr);
else if(bitDepth < 8)
png_set_packing(png_ptr);
png_read_update_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &texture.width, &texture.height,
&bitDepth, &colourType, NULL, NULL, NULL);
int components = GetTextureInfo(colourType);
if(components == -1)
{
if(png_ptr)
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
return;
}
GLubyte *pixels = (GLubyte *)malloc(sizeof(GLubyte) * (texture.width * texture.height * components));
row_pointers = (png_bytep *)malloc(sizeof(png_bytep) * texture.height);
for(int i = 0; i < texture.height; ++i)
row_pointers[i] = (png_bytep)(pixels + (i * texture.width * components));
png_read_image(png_ptr, row_pointers);
png_read_end(png_ptr, NULL);
// make it
glGenTextures(1, &texture.name);
// bind it
glBindTexture(GL_TEXTURE_2D, texture.name);
GLuint glcolours;
switch (components) {
case 1:
glcolours = GL_LUMINANCE;
break;
case 2:
glcolours = GL_LUMINANCE_ALPHA;
break;
case 3:
glcolours = GL_RGB;
break;
case 4:
glcolours = GL_RGBA;
break;
}
glTexImage2D(GL_TEXTURE_2D, 0, components, texture.width, texture.height, 0, glcolours, GL_UNSIGNED_BYTE, pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
fclose(pngFile);
free(row_pointers);
free(pixels);
textures.push_back(texture);
}
Here is the code for my Texture class:
class Texture
{
public:
Texture(const std::string &filename) { this->filename = filename; }
unsigned int name;
unsigned int size;
unsigned int width;
unsigned int height;
std::string filename;
};
Here is how I setup my view:
void Renderer::Setup(Rectangle rect, CameraType cameraType)
{
_viewRect = rect;
glViewport(0,0,_viewRect.width,_viewRect.height);
if(cameraType == Renderer::Orthographic)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(_viewRect.x,_viewRect.width,_viewRect.y,_viewRect.height,kZNear,kZFar);
glMatrixMode(GL_MODELVIEW);
}
else
{
GLfloat size = kZNear * tanf(DegreesToRadians(kFieldOfView) / 2.0);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustumf(-size, size, -size / (_viewRect.width / _viewRect.height), size / (_viewRect.width / _viewRect.height), kZNear, kZFar);
glMatrixMode(GL_MODELVIEW);
}
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_ONE, GL_SRC_COLOR);
glEnable(GL_BLEND);
}
Now here is where I draw the texture:
void Renderer::DrawTexture(int x, int y, Texture &texture)
{
GLfloat vertices[] = {
x, _viewRect.height - y, 0.0,
x, _viewRect.height - (y + texture.height), 0.0,
x + texture.width, _viewRect.height - y, 0.0,
x + texture.width, _viewRect.height - (y + texture.height), 0.0
};
static const GLfloat normals[] = {
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0
};
GLfloat texCoords[] = {
0.0, 1.0,
0.0, 0.0,
1.0, 1.0,
1.0, 0.0
};
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glLoadIdentity();
glTranslatef(0.0, 0.0, -3.0);
glBindTexture(GL_TEXTURE_2D, texture.name);
glVertexPointer(3, GL_FLOAT, 0, vertices);
glNormalPointer(GL_FLOAT, 0, normals);
glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
UPDATE:
I changed the function I use to generate a texture. It now create a random test texture. I still see a white texture no matter what. Gonna keep digging into how I'm renderering.
Here's the new function:
void AssetManager::CreateNoisyTexture(const char * key)
{
Texture texture(key, 64, 64);
const unsigned int components = 4;
GLubyte *pixels = (GLubyte *)malloc(sizeof(GLubyte) * (texture.width * texture.height * components));
GLubyte *pitr1 = pixels;
GLubyte *pitr2 = pixels + (texture.width * texture.height * components);
while (pitr1 != pitr2) {
*pitr1 = rand() * 0xFF;
*(pitr1 + 1) = rand() * 0xFF;
*(pitr1 + 2) = rand() * 0xFF;
*(pitr1 + 3) = 0xFF;
pitr1 += 4;
}
glGenTextures(1, &texture.name);
glBindTexture(GL_TEXTURE_2D, texture.name);
glTexImage2D(GL_TEXTURE_2D, 0, components, texture.width, texture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
free(pixels);
printf("Created texture with key: %s name: %d", texture.key, texture.name);
textures.push_back(texture);
}
A: Ok I figured it out. The problem was that I was using the wrong internal pixel format.
glTexImage2D(GL_TEXTURE_2D, 0, 4, texture.width, texture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
Should be:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.width, texture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
I needed to pass in GL_RGBA instead of 4. In the docs I read this:
internalFormat - Specifies the number of color components in the texture. Must be 1, 2, 3, or 4, or one of the following symbolic constants:
I figured it didn't matter but I guess it does. One other thing to note, I figured this out by using glGetError() to figure out where the error was occurring. When I call glTexImage2D() the error was GL_INVALID_OPERATION.
Thanks for your help IronMensan!
UPDATE:
So the reason why I couldn't send 4 is because it is not allowed and internalFormat and format need to be the same in the OpenGL ES 1.1 spec. You can only send GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, or GL_LUMINANCE_ALPHA. Lesson learned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: iOS: How to remove object from memory with ARC enabled? I am developing an iOS app with the iOS 5 SDK, Automatic Reference Counting is enabled. But I have a specific object that is being created in large numbers and must be released after a second because otherwise the device will become very slow. It looks like they are not released, as the device is very slow. Is there a way to manually release an object when ARC is enabled?
EDIT: My code, this is called 200 times a second to generate sparkles. They fade out after 0.8 seconds so they are useless after then.
int xanimationdiff = arc4random() % 30;
int yanimationdiff = arc4random() % 30;
if (arc4random()%2 == 0) {
xanimationdiff = xanimationdiff * -1;
}
if (arc4random()%2 == 0) {
yanimationdiff = yanimationdiff * -1;
}
Sparkle *newSparkle = [[Sparkle alloc] initWithFrame:CGRectMake(20 + arc4random() % 280, 20, 10, 10)];
//[newSparkle setTransform:CGAffineTransformMakeRotation(arc4random() * (M_PI * 360 / 180))]; //Rotatie instellen (was niet mooi, net sneeuw)
[self.view addSubview:newSparkle];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.8];
[newSparkle setFrame:CGRectMake(newSparkle.frame.origin.x - xanimationdiff, newSparkle.frame.origin.y - yanimationdiff, newSparkle.frame.size.width, newSparkle.frame.size.height)];
newSparkle.alpha = 0;
[UIView commitAnimations];
The sparkle object code:
#import "Sparkle.h"
@implementation Sparkle
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"sparkle.png"]]];
}
return self;
}
@end
A: Object* myObject = [[Object alloc] init];
myObject = nil; // poof...
EDIT: You cannot directly control when an object is released BUT you can indirectly cause it to happen. How? Remember what ARC does EXACTLY. Unlike human coding convention, ARC parses your code and inserts release statements AS SOON AS OBJECTS CAN be released. This frees up the memory for new allocations straight away, which is awesome/necessary.
Meaning, setting an object to nil, or simply allowing a variable to go out of scope ... something that CAUSES A 0 RETAIN COUNT forces ARC to place its release calls there.
It must ... because it would leak otherwise.
A: Just surround the section of code that is going to be called 200 times with an @autoreleasepool { ... } statement. This will cause the memory to be deallocated immediately as opposed to waiting for the control to go all the way back up the event chain to the top level autorelease pool.
A: I found the answer, it was actually really stupid. I didn't remove the sparkles from the superview. Now I remove them after 0.8 seconds with a timer and it performs great again :)
A: With ARC you cannot call dealloc, release, or retain, although you can still retain and release CoreFoundation objects (NB: you can implement dealloc methods for your own custom subclasses, but you can't call super dealloc). So the simple answer is 'no', you unfortunately cannot manually release an object when using ARC.
I'd double check you're sure they're not being released, because in theory if you no longer reference an object it should be released. What do you do with these objects once you create them? You simply create them then immediately destroy them?
Perhaps you could post the code you're using / the property declarations - are these weak or strong referenced objects?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Jquery selectbox script not auto-initializing I am trying to implement the jquery selectbox script. I have made all the changes needed to css and html markup and the selectbox is working and appearing fine. the problem is. It is not initializing automatically at page load.
I have to manually run $("SELECT").selectBox(); from the firebug script panel to make it work. I have tried everything from putting hte initializing command at the bottom of the page, and putting it in $(document).ready() as well. Nothing works. What am i missing?
EDIT: The code I am running involves dynamic select box generation from the server.
A: I googling for a solution to a similar problem, but found nothing.
It's giant waste of time. So I will just share the solution found.
I tried to remove element created by selectbox <span class="selectbox">...</span> before re-initializing, and its work.
$('#select').prev().remove();
$('#select').selectbox();
hope this helps.
A: Did you initialize it before the select boxes? It has to be initialized before them. And make sure jQuery is loaded before you do anything jQuery. (duh)
For example:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="/path/to/jquery.selectBox.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select").selectBox();
});
</script>
<select name="standard-dropdown">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3 has <a> really long label but it won't affect the control's display at all</option>
<option value="4">Item 4</option>
<option value="5" disabled="disabled">Item 5 (disabled)</option>
<option value="6">Item 6</option>
<option value="7">Item 7</option>
<option value="8">Item 8</option>
<option value="9">Item 9</option>
<option value="10">Item 10</option>
<option value="11">Item 11</option>
<option value="12">Item 12</option>
<option value="13">Item 13</option>
<option value="14">Item 14</option>
<option value="15" selected="selected">Item 15</option>
<option value="16">Item 16</option>
<option value="17">Item 17</option>
<option value="18">Item 18</option>
<option value="19">Item 19</option>
<option value="20">Item 20</option>
</select>
Hope this helps.
P.S Maybe you could show us full code, or a link to where you're having the issue?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Searching for Java library or 3rd party library thorugh which I write GUI componets to PDF I am searching any java library or 3rd party library using which I can make the PDF. Basically I need to generate the documentations which can contain Swing or SWT components. One option is to convert the GUI in Image the convert it into pdf. But wondering is any APIs library exists which can make the GUI components in PDF.
Please, give me any suggestion about this problem.
A: try with iText library.
you can download it from here : http://itextpdf.com/download.php
A: If you are making it from XML, there is FOP. For programmatically creating PDFs in Java IText is brilliant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Retrieving a million records from a database There is a database it contains 2 million records approx in a table . and i ran the query from my java code like this " select * from table" . will it fetch the complete data from the database in the result set . or not . If yes then how it will work i want to learn the working on this retrieveal ,
Please let me know , i have learnt somewhere that it will retrieve the complete data from the database and will store in the temporary storage from there it will show in the output .Is it fine .
Or is there something related to J2C
A: Here's nearly the same question. How to handle huge result sets from database
You ask if it will fetch the complete dataset. it will. therefore, it's advised to not fetch the whole database. Here's something about where it's saved java - mysql - select query outfile - where is file getting saved
A: Will it fetch the complete data from the database in the result set
There is no precise answer to it. Its always dependent on the database driver. The result set is an Interface and its implementation is done by a specific database driver. The ResultSet implementation may have its own optimization wherein for smaller set of data, everything is fetched where as for larger datasets, its buffered (or some default paging mechanism). So please refer to the database driver documentation.
There is a standard (at least the javadoc says so) way out to prevent the fetching of large data from database. Set the appropriate fetch size for the JDBC statement as follows java.sql.Statement.setFetchSize().
As the java doc
Gives the JDBC driver a hint as to the number of rows that should be
fetched from the database when more rows are needed. The number of
rows specified affects only result sets created using this statement.
If the value specified is zero, then the hint is ignored. The default
value is zero.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Unit-testing an action which calls session object How can I unit test a method which uses a session object inside of its body?
Let us say I have the following action:
[HttpPost]
public JsonResult GetSearchResultGrid(JqGridParams gridParams, Guid campaignId, string queryItemsString)
{
var queryItems = new JavaScriptSerializer().Deserialize<IList<FilledQueryItem>>(queryItemsString);
IPageData pageData = gridParams.ToPageData();
var extraFieldLinker = SessionHandler.CurrentExtraFieldsLinker;
var searchParams = new SearchParamsModel(extraFieldLinker, queryItems);
IList<CustomerSearchResultRow> searchResults = null;
searchResults = _customerService.SearchCustomersByUrlAndCampaign(campaignId,
searchParams.SearchString,
searchParams.AddressFilterPredicate,
pageData);
return GetGridData<CustomerSearchResultGridDefinition, CustomerSearchResultRow>(searchResults, pageData);
}
I made the following unit tests which fails so far because of the session thing:
[Test]
public void CanGetSearchResultGrid()
{
//Initialize
var mockJqGridParams = new Mock<JqGridParams>();
var mockPageData = new Mock<IPageData>();
IPagedList<CustomerSearchResultRow> mockPagedResult = new PagedList<CustomerSearchResultRow>(mockPageData.Object);
var guid= Guid.NewGuid();
const string searchString =
"[{\"Caption\":\"FirstName\",\"ConditionType\":\"contains\",\"Value\":\"d\",\"NextItem\":\"Last\"}]";
Func<Address,bool> addressFilterPredicate = (x => true);
//Setup
mockJqGridParams.Setup(x => x.ToPageData()).Returns(mockPageData.Object);
_customerService.Setup(x => x.SearchCustomersByUrlAndCampaign(guid, searchString, addressFilterPredicate, mockPageData.Object))
.Returns(mockPagedResult);
//Call
var result = _homeController.GetSearchResultGrid(mockJqGridParams.Object, guid, searchString);
mockJqGridParams.Verify(x => x.ToPageData(), Times.Once());
_customerService.Verify(x => x.SearchCustomersByUrlAndCampaign(guid, searchString, addressFilterPredicate, mockPageData.Object)
, Times.Once());
//Verify
Assert.That(result, Is.Not.Null);
Assert.That(result, Is.TypeOf(typeof(JsonResult)));
}
And the method from the helper of course:
public static ExtraFieldsLinker CurrentExtraFieldsLinker
{
get
{
object extraFieldLinker = GetSessionObject(EXTRA_FIELDS_LINKER);
return extraFieldLinker as ExtraFieldsLinker;
}
set { SetSessionObject(EXTRA_FIELDS_LINKER, value); }
}
A: I've solved similar issues (use of static data accessors that aren't mock friendly - in particular, HttpContext.Current) by wrapping the access in another object, and accessing it through an interface. You could do something like:
pubic interface ISessionData
{
ExtraFieldsLinker CurrentExtraFieldsLinker { get; set; }
}
public class SessionDataImpl : ISessionData
{
ExtraFieldsLinker CurrentExtraFieldsLinker
{
// Note: this code is somewhat bogus,
// since I think these are methods of your class.
// But it illustrates the point. You'd put all the access here
get { return (ExtraFieldsLinker)GetSessionObject(EXTRA_FIELDS_LINKER); }
set { SetSessionObject(EXTRA_FIELDS_LINKER, value); }
}
}
public class ClassThatContainsYourAction
{
static ClassThatContainsYourAction()
{
SessionData = new SessionDataImpl();
}
public static ISessionData SessionData { get; private set; }
// Making this access very ugly so you don't do it by accident
public void SetSessionDataForUnitTests(ISessionData sessionData)
{
SessionData = sessionData;
}
[HttpPost]
public JsonResult GetSearchResultGrid(JqGridParams gridParams,
Guid campaignId, string queryItemsString)
{
var queryItems = // ...
IPageData pageData = // ...
// Access your shared state only through SessionData
var extraFieldLinker = SessionData.CurrentExtraFieldsLinker;
// ...
}
}
Then your unit test can set the ISessionData instance to a mock object before calling GetSearchResultGrid.
Ideally you'd use a Dependency Injection library at some point, and get rid of the static constructor.
If you can figure out a way to make your ISessionData an instanced object instead of static, even better. Mock object frameworks tend to like to create a new mock type for every test case, and having mocks lying around from previous tests is kind of gross. I believe session state is going to be global to your session anyway, so you might not have to do anything tricky to make a non-static object work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ruby on Rails 3 Tutorial: Chapter 2 Section 2.2.1 A User Tour I am new to Ruby on Rails and am working through this tutorial book. I am on Windows Vista and using Cygwin. Here are the versions of the software that I am running:
Ruby version 1.9.2 (i386-cygwin)
RubyGems version 1.8.10
Rack version 1.3
Rails version 3.1.0
JavaScript Runtime JScript
Active Record version 3.1.0
Action Pack version 3.1.0
Active Resource version 3.1.0
Action Mailer version 3.1.0
Active Support version 3.1.0
In the beginning of section 2.2, I was able to successfully run: ($ rails generate scaffold User name:string email:string) and ($ rake db:migrate). But when I went to run the ($ rails server) command and opened up the webpage in Chrome, I did not see the screen shown in Fig. 2.4. But instead saw this instead: "Encoding::InvalidByteSequenceError in Users#index" I saw the post about switching the rake version from 0.9.2 to 0.8.7 and I tried this, but it didn't work for me. Does anybody now of anything else that I can try? Thank you, Nick.
A: I've tried rails learning with Windows 7 + Cygwin and it was a real pain in the ass. I strongly recommend you to run linux on the virtual machine or make a dual-boot.
A: Since you are using ruby 1.9.2 you can try to add # coding: utf-8 at the beginning of Controller file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: git svn and working with private branches? new git user here. I want to use git, but i'm in an SVN environment. From some books I've read and some simple experimenting, I've hit some troubling pitfalls and am hoping to get clarification on how to get starting without my colleagues wanting to kill me.
I want my workflow to be:
*
*a master git branch that stays in step with svn's trunk.
*local git branches that i do my feature and bug work in.
*I want to frequently bring the feature branches up to date with master.
*When i'm ready I want to merge a feature branch in with master and commit that back to svn.
Is this a typical workflow?
Initially I was using git merge to merge my master branch and feature branches. This led to all kinds of conflicts and problems. I later read to avoid using git merge alltogether and stick with git rebase. Would the following git commands, then, be correct?
*
*git svn rebase (to pull down latest changes to master)
*git checkout -b myAwesomeFeature (to make a feature branch to work on)
*... do some work, make commits to my feature branch
*<<< TIME GOES BY >>>
*git checkout master
*git svn rebase (to pull down new stuff)
*git checkout myAwesomeFeature
*git rebase master ( to get svn trunk's stuff into my feature branch)
*<<< READY TO PUSH MY FEATURE BRANCH >>>
*git checkout master
*git rebase myAwesomeFeature (to fast forward masters head to get my feature stuff in)
*git svn dcommit (to finally publish)
Any advice or suggestions to help an aspiring git user live in an svn world would be really appreciated. Thanks
A: Your workflow is about the same I have. It is good enough if you are only committing to the svn trunk. It gets complicated when you commit to multiple svn branches where rebase not only merges the contents, but also changes the pointed-to svn branch, in which case, you can only git cherry-pick when you need commits into one svn branch targeting git branch in another, as discussed here: Overcome git svn caveats
It is also worth understanding that SVN's inability to handle non-linear history and that git merge can't be used with it: git svn workflow - feature branches and merge
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What are the two precondition on Binary search? i have been asked in an interview what are the two preconditions of the binary search .I have told them array should be sorted in ascending order but i didn't know what could be the second precondition of binary search?
Anyone can tell me about the second precondition of Binary search?
A: Data Array should be sorted, and sorted in the right order. I.e.: if its sorted in ascending order when the binary search assumes descending order - it won't work.
Some clarifications, as it seems that people forgot their Algorithms 101.
Precondition is a condition, that if not met - the algorithm is not required to provide the correct result.
Random access is not a precondition for a binary search algorithm, as it can and should return the correct answer even if the random access is not available (Binary Search Trees rely on that).
less-than operator certainly doesn't have to be defined, as it is a language-specific implementation detail. But it is close to the truth.
Data structure must be sorted (weak-ordered) for any search other than linear to work.
Data structure must be sorted in the same order as the one assumed by the binary search algorithm. As I mentioned, if the data is sorted in the ascending order, like the OP said, it doesn't mean that the binary search will provide the correct result, if the search is built for descending order, for example. There are many orders, ascending, descending, lexicographic, etc etc.
When you use a binary search function you must ensure that the input is sorted, and sorted to the order you're going to use. If these two are not met - you're not required to provide correct result.
A: There is a good run-down of the pre-conditions of binary search here:
The array must be sorted in ascending order according to the ordering
used by the comparisons in the search function.
The author only specifies one pre-condition but I expect you could break it down to 2 conditions that are related to each other...
*
*Must be sorted in ascending or descending order, depending on your search algorithm
*Input must be compatible with the comparison algorithm
A: Maybe that you need random access for the binary search to be efficient. Or at least the array should be iterable multiple times.
A: The elements must have the less-than operator defined.
A: Elements need to be in a sorted array, so I guess they mean
1) The elements are in an array (or in any data structure that enables indexed access).
2) The storage is sorted according to the compare function.
A: That means
*
*Arrray must be sorted
*Sorting algorithm used
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to define a rotates function How to define a rotates function that generates all rotations of the given list?
For example: rotates [1,2,3,4] =[[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]]
I wrote a shift function that can rearrange the order
shift ::[Int]->[Int]
shift x=tail ++ take 1 x
but I don't how to generate these new arrays and append them together.
A: shift (x:xs) = xs ++ [x]
rotates xs = take (length xs) $ iterate shift xs
iterate f x returns the stream ("infinite list") [x, f x, f (f x), ...]. There are n rotations of an n-element list, so we take the first n of them.
A: The following
shift :: [a] -> Int -> [a]
shift l n = drop n l ++ take n l
allRotations :: [a] -> [[a]]
allRotations l = [ shift l i | i <- [0 .. (length l) -1]]
yields
> ghci
Prelude> :l test.hs
[1 of 1] Compiling Main ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> allRotations [1,2,3,4]
[[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]]
which is as you expect.
I think this is fairly readable, although not particularly efficient (no memoisation of previous shifts occurs).
If you care about efficiency, then
shift :: [a] -> [a]
shift [] = []
shift (x:xs) = xs ++ [x]
allRotations :: [a] -> [[a]]
allRotations l = take (length l) (iterate shift l)
will allow you to reuse the results of previous shifts, and avoid recomputing them.
Note that iterate returns an infinite list, and due to lazy evaluation, we only ever evaluate it up to length l into the list.
Note that in the first part, I've extended your shift function to ask how much to shift, and I've then a list comprehension for allRotations.
A: Another way to calculate all rotations of a list is to use the predefined functions tails and inits. The function tails yields a list of all final segments of a list while inits yields a list of all initial segments. For example,
tails [1,2,3] = [[1,2,3], [2,3], [3], []]
inits [1,2,3] = [[], [1], [1,2], [1,2,3]]
That is, if we concatenate these lists pointwise as indicated by the indentation we get all rotations. We only get the original list twice, namely, once by appending the empty initial segment at the end of original list and once by appending the empty final segment to the front of the original list. Therefore, we use the function init to drop the last element of the result of applying zipWith to the tails and inits of a list. The function zipWith applies its first argument pointwise to the provided lists.
allRotations :: [a] -> [[a]]
allRotations l = init (zipWith (++) (tails l) (inits l))
This solution has an advantage over the other solutions as it does not use length. The function length is quite strict in the sense that it does not yield a result before it has evaluated the list structure of its argument completely. For example, if we evaluate the application
allRotations [1..]
that is, we calculate all rotations of the infinite list of natural numbers, ghci happily starts printing the infinite list as first result. In contrast, an implementation that is based on length like suggested here does not terminate as it calculates the length of the infinite list.
A: The answers given so far work fine for finite lists, but will eventually error out when given an infinite list. (They all call length on the list.)
shift :: [a] -> [a]
shift xs = drop 1 xs ++ take 1 xs
rotations :: [a] -> [[a]]
rotations xs = zipWith const (iterate shift xs) xs
My solution uses zipWith const instead. zipWith const foos bars might appear at first glance to be identical to foos (recall that const x y = x). But the list returned from zipWith terminates when either of the input lists terminates.
So when xs is finite, the returned list is the same length as xs, as we want; and when xs is infinite, the returned list will not be truncated, so will be infinite, again as we want.
(In your particular application it may not make sense to try to rotate an infinite list. On the other hand, it might. I submit this answer for completeness only.)
A: I would prefer the following solutions, using the built-in functions cycle and tails:
rotations xs = take len $ map (take len) $ tails $ cycle xs where
len = length xs
For your example [1,2,3,4] the function cycle produces an infinite list [1,2,3,4,1,2,3,4,1,2...]. The function tails generates all possible tails from a given list, here [[1,2,3,4,1,2...],[2,3,4,1,2,3...],[3,4,1,2,3,4...],...]. Now all we need to do is cutting down the "tails"-lists to length 4, and cutting the overall list to length 4, which is done using take. The alias len was introduced to avoid to recalculate length xs several times.
A: I think it will be something like this (I don't have ghc right now, so I couldn't try it)
shift (x:xs) = xs ++ [x]
rotateHelper xs 0 = []
rotateHelper xs n = xs : (rotateHelper (shift xs) (n - 1))
rotate xs = rotateHelper xs (length xs)
A: myRotate lst = lst : myRotateiter lst lst
where myRotateiter (x:xs) orig
|temp == orig = []
|otherwise = temp : myRotateiter temp orig
where temp = xs ++ [x]
A: I suggest:
rotate l = l : rotate (drop 1 l ++ take 1 l)
distinctRotations l = take (length l) (rotate l)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: jQuery - Store drop down values from multiple selects in an array The following code populates the second select statement with HTML data. The problem I'm facing is that I clone the two select statements and on submission of the form, I'd like to save all of the selected option values from the two selects into an Array().
What would be the best way to iterate through all of the drop-down values (there's a maximum of 5 that can be added for both Subject Matter and Category)?
Thanks in advance.
$(".SubjectCategory").live("click", function () {
var $this = $(this);
var $elem = $this.closest('div').nextAll('div').first().find('select');
var a = $this.val();
$.get("/userControls/BookSubjectHandler.ashx?category=" + a, {}, function (data) {
$elem.html(data);
});
});
<div class="singleField subjectField">
<label id="Category" class="fieldSml">Subject Matter</label>
<div class="bookDetails ddl"><select id="ddlSubjectMatter" class="fieldSml SubjectCategory"></select></div>
<label id="Subjects" class="fieldSml">Category</label>
<div class="bookDetails ddl" id="subjectMatter"><select id="ddlSubjects" class="fieldSml Subjects"></select></div>
</div>
A: Using jQuery .map function you can retrieve all values at once:
var arrayOfValues = $(".bookDetails.ddl select").map(function (i, el) { return $(el).val(); }).get();
fiddle: http://jsfiddle.net/e9zxY/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Volume control for ios in flex mobile 4.5 or phone gap I am trying to develop an application for IOS in which the application needs to have control over the phone's volume.
Please do suggest if flash 4.5 mobile or phonegap is suitable for the following requirements.
*
*Increase/decrease volume
*Mute
*Play audio files
Thank you
A: PhoneGap has media module, record/play:
*
*http://docs.phonegap.com/en/1.0.0/phonegap_media_media.md.html
Also there seems to be a few plugins on related topics:
*
*https://github.com/phonegap/phonegap-plugins/tree/master/iPhone
*AudioRecord, SoundPlug, VolumeSlider
A: Using flex 4.5, you can do all of these tasks:
*
*play sound
*volume control (including muting)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: no launcher activity was found even if i had declared one in the manifest i declared the report file as my launcher. so its supposed to launch first when the app is started first. or do i get something wrong.
i get the error. no launch activity was found. thx guys
<activity android:name=".report" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.REPORT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Main" android:label="@string/app_name">
<intent-filter>
</intent-filter>
</activity>
A: You need to change the action:name from .REPORT to .MAIN. The action name corresponds to the intent action and not to the Activity name.
Fixed version of the above:
<activity android:name=".report" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Main" android:label="@string/app_name">
</activity>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: celery task does not terminate I've created a task where the program uploads a file and the task acts as expected i.e it successfully uploads the file but even after the task does its work, the task does not "terminate", the state still remains PENDING. How can I fix this?
A: From the celery docs:
PENDING: Task is waiting for execution or unknown. Any task id that is
not know is implied to be in the pending state.
Are you sure the task finishes what it does cleanly? Best to post code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to start with Programming in VB.Net? So far I have worked with C Programming and C++ Programming. I am fairly new to DOT NET environment and my current project requires VB.Net skills. I need to know
1)Which books to refer for starting with VB.Net language?
2)How to Start with VB.Net Programming?
3)Are there any forums/articles for quick head start.
Thanks in advance to all !
A: After mastering c/c++, VB.NET will be easy for you.
Where to start:
MSDN Visual Basic Programming Guide, specialy the Visual Basic Language Features, and Program Structure and Code Conventions.
Forums / Articles:
*
*Stackoverflow has lots of .NET experts, ask anything and you shell be answered! :)
*http://www.vbdotnetheaven.com/
*Visual Basic Developer Center
Since VB.NET and C# are both .NET languages, almost all code written in C# can be easily converted to VB. From my personal experience, C# is more widely spread and I often find myself converting C# code samples to VB.NET.
A: Since C# is similar to C, you could start by looking at this
http://www.harding.edu/fmccown/vbnet_csharp_comparison.html
To help you how to write VB. Then it's just a matter of learning the framework classes.
You could also look at the ".NET Framework Class Library" http://msdn.microsoft.com/en-us/library/w0x726c2.aspx to give you a quick list of every namespace/class available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AS3 Crazy Drop Down Menu Jittery Issue I have a few flash errors on my website. I started playing around with AS3 and created a list that expands when mouse is over and goes down when mouse is out. Kind of like a drop down menu. Problem is sometimes it acts really spastic. Anyone have any solutions?
Here is my website...
www.allencoded.com
Below it my code..
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.events.Event;
import flash.ui.Mouse;
import flash.net.URLRequest;
stop();
FeedBox.mouseChildren=false;
ProjectBox.mouseChildren=false;
//FeedBox Tween Stuff----------------------
var feedup:Tween = new Tween(FeedBox, "y", Strong.easeOut, 560, 290, 2, true);
var feeddown:Tween = new Tween(FeedBox, "y", Strong.easeOut, 290, 560, 2, true);
FeedBox.addEventListener(MouseEvent.MOUSE_OVER, mouseyOnFeed);
FeedBox.addEventListener(MouseEvent.MOUSE_OUT, mouseyOutBox);
function mouseyOnFeed(e:Event){
feedup.start();
}
function mouseyOutBox(e:Event){
feeddown.start();
}
//ProjectBox Tween stuff------------------------
var projectleft:Tween = new Tween(ProjectBox, "x", Strong.easeOut, 920, 565, 2, true);
var projectright:Tween = new Tween(ProjectBox, "x", Strong.easeOut, 565, 920, 2, true);
ProjectBox.addEventListener(MouseEvent.MOUSE_OVER, mouseyOnProj);
ProjectBox.addEventListener(MouseEvent.MOUSE_OUT, mouseyOutProj);
function mouseyOnProj(e:Event){
projectleft.start();
}
function mouseyOutProj(e:Event){
projectright.start();
}
//BLOG BUTTON
Blog.addEventListener(MouseEvent.CLICK, toBlog);
function toBlog(e:Event){
var blogaddy:URLRequest = new URLRequest("http://www.allencoded.com/blog");
navigateToURL(blogaddy);
}
A: function mouseyOnProj(e:Event){
projectleft.start();
ProjectBox.removeEventListener(MouseEvent.MOUSE_OVER, mouseyOnProj);
}
function mouseyOutProj(e:Event){
projectright.start();
ProjectBox.removeEventListener(MouseEvent.MOUSE_OUT, mouseyOutProj);
}
i would prefer to remove events while tweening and onCompletes addEventListeners back. Btw out source tweeners performes better for tweenings.
Ask again if you need more information.
A: The problem seems to be happening when the tab reaches the mouse cursor, causing the mouse to enter it before it has finished moving. Try
function mouseyOnProj(e:Event){
if (!projectleft.isPlaying) projectleft.start();//
}
function mouseyOutProj(e:Event){
if (!projectright.isPlaying) projectright.start();//
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I collapse elements in a list with jQuery? I have the following list:
<div class='sidebar-listview ui-listview' data-role='listview' data-theme='c'>
<li class='ui-li ui-li-static ui-body-c ui-li-has-icon io-sidebar-section io-sidebar-section-collapsed io-sidebar-section-advanced-toggle' id='0aa210f2-e811-4bae-aac0-649bf87fb240'>
<img src='/document/d5308dfc-af9e-41a4-ab0f-9b5ff6c4c43e/latest' class='ui-li-icon ui-li-thumb' height='16' width='16'/>
<div class='io-sidebar-link-text'>Activities</div>
</li>
<span io-sidebar-section='0aa210f2-e811-4bae-aac0-649bf87fb240'>
<li class='ui-li ui-li-static ui-body-d ui-li-has-icon io-sidebar-link io-sidebar-link-standard' data-theme='d' io-sidebar-section='0aa210f2-e811-4bae-aac0-649bf87fb240' io-object-view='/cms?url=ui/object&object=34029fec-b949-3780-b9e6-9522413b9f2c' io-record-view='/cms?url=ui/record&object=34029fec-b949-3780-b9e6-9522413b9f2c' style='display: block'>
<img src='/document/140075b9-878e-4fc8-9ed6-ac422046accf/latest' class='ui-li-icon ui-li-thumb' height='16' width='16'/>
<div class='io-sidebar-link-text'>Events</div>
</li>
<li class='ui-li ui-li-static ui-body-d ui-li-has-icon io-sidebar-link io-sidebar-link-standard' data-theme='d' io-sidebar-section='0aa210f2-e811-4bae-aac0-649bf87fb240' io-object-view='/cms?url=ui/object&object=db13a9ad-2494-34bb-8a59-cb99fd308051' io-record-view='/cms?url=ui/record&object=db13a9ad-2494-34bb-8a59-cb99fd308051' style='display: block'>
<img src='/document/423fc17f-08b2-46bb-a1db-a5395cd63b83/latest' class='ui-li-icon ui-li-thumb' height='16' width='16'/>
<div class='io-sidebar-link-text'>Tasks</div>
</li>
<li class='ui-li ui-li-static ui-body-d ui-li-has-icon io-sidebar-link io-sidebar-link-standard' data-theme='d' io-sidebar-section='0aa210f2-e811-4bae-aac0-649bf87fb240' io-object-view='/cms?url=ui/object&object=23505d2a-bf3b-11e0-8058-001ec93afa2c' io-record-view='/cms?url=ui/record&object=23505d2a-bf3b-11e0-8058-001ec93afa2c' style='display: block'>
<img src='/document/f7cd2d4c-1bbe-4131-b1bb-b6bff1e9bea5/latest' class='ui-li-icon ui-li-thumb' height='16' width='16'/>
<div class='io-sidebar-link-text'>Projects</div>
</li>
<li class='ui-li ui-li-static ui-body-d ui-li-has-icon io-sidebar-link io-sidebar-link-advanced' data-theme='d' io-sidebar-section='0aa210f2-e811-4bae-aac0-649bf87fb240' io-object-view='/cms?url=ui/object&object=5e0d648c-bf52-11e0-b7e6-001ec93afa2c' io-record-view='/cms?url=ui/record&object=5e0d648c-bf52-11e0-b7e6-001ec93afa2c' style='display: none'>
<img src='/document/8dbc2454-a2f8-47b0-ba32-d5b8552c0160/latest' class='ui-li-icon ui-li-thumb' height='16' width='16'/>
<div class='io-sidebar-link-text'>Milestones</div>
</li>
</span>
How can I catch the io-sidebar-section-collapsed click event and have it collapse everything underneath it in the span?
A: I think this should work:
var el = $('.io-sidebar-section-collapsed');
el.click(function() {
el.next().toggle();
});
If you don't want to toggle the display and just to collapse, replace .toggle with .hide.
EDIT: Looking at your code again, I'm not sure if it will work, because your markup is invalid. You could simply remove the span and replace the code above with:
var el = $('.io-sidebar-section-collapsed');
el.click(function() {
el.next().toggle();
el.next().next().toggle();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7631692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits