text
stringlengths 8
267k
| meta
dict |
---|---|
Q: WP7: Convert Accelometer and Compass data to mock Motion API I'm writing a small sample application for the Windows Phone 7.1 (Mango) and want to use the Combined Motion API to display the motion of the device. I need to write mock classes to be able to test my application when using the emulator which does not support all sensors of the device.
I already wrote a simple mock class to simulate a compass (it just simulates a rotating device) and for the accelerometer which is actually available in the emulator.
Now I would have to write a new mock object for the Motion API but I hope that I could calculate the values that are used for the Motion object using the values from compass and accelerometer. Unfortunately I found no sample for a simple conversion that is already doing this.
Does anybody know a code sample that does this conversion? As complex as this will be I wouldn't like to do this by myself, if there is already a solution.
A: A good starting point for doing your Mockup work is to have a look at the Motion API and how it works internally and which parameters are used by the API core:
http://msdn.microsoft.com/en-us/library/hh202984%28VS.92%29.aspx
Before you go on, have in mind that the Motion API is complex mathematical model which combines the inputs of the different phone sensors. You can find many different models to calculate motion by combining acceleration, position and rotation.. one good description you can find in this article:
http://www.instructables.com/id/Accelerometer-Gyro-Tutorial/
So in fact, you have to use the equations and functions shown in the article above and then calculate the values on your own.
It is everything else than a simple thing, but possible this way.
I hope i was able to help you :) and let the community know, if you've done it. I think a codeplex project would be nice to write a kind of mocking utilites for windows phone motion API.
A: I've run into the same issue again now that Windows Phone 8 is out and I don't have a handset to test with yet.
Much like the answer to WP7 Mock Microsoft.Devices.Sensors.Compass when using the emulator, I've created a wrapper class with the same methods as the Motion API. When the actual Motion API is supported it is used. Otherwise, in debug mode, mock data is returned that varies the roll, pitch, and yaw.
MotionWrapper
/// <summary>
/// Provides Windows Phone applications information about the device’s orientation and motion.
/// </summary>
public class MotionWrapper //: SensorBase<MotionReading> // No public constructors, nice one.
{
private Motion motion;
public event EventHandler<SensorReadingEventArgs<MockMotionReading>> CurrentValueChanged;
#region Properties
/// <summary>
/// Gets or sets the preferred time between Microsoft.Devices.Sensors.SensorBase<TSensorReading>.CurrentValueChanged events.
/// </summary>
public virtual TimeSpan TimeBetweenUpdates
{
get
{
return motion.TimeBetweenUpdates;
}
set
{
motion.TimeBetweenUpdates = value;
}
}
/// <summary>
/// Gets or sets whether the device on which the application is running supports the sensors required by the Microsoft.Devices.Sensors.Motion class.
/// </summary>
public static bool IsSupported
{
get
{
#if(DEBUG)
return true;
#else
return Motion.IsSupported;
#endif
}
}
#endregion
#region Constructors
protected MotionWrapper()
{
}
protected MotionWrapper(Motion motion)
{
this.motion = motion;
this.motion.CurrentValueChanged += motion_CurrentValueChanged;
}
#endregion
/// <summary>
/// Get an instance of the MotionWrappper that supports the Motion API
/// </summary>
/// <returns></returns>
public static MotionWrapper Instance()
{
#if(DEBUG)
if (!Motion.IsSupported)
{
return new MockMotionWrapper();
}
#endif
return new MotionWrapper(new Motion());
}
/// <summary>
/// The value from the underlying Motion API has changed. Relay it on within a MockMotionReading.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void motion_CurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> e)
{
var f = new SensorReadingEventArgs<MockMotionReading>();
f.SensorReading = new MockMotionReading(e.SensorReading);
RaiseValueChangedEvent(sender, f);
}
protected void RaiseValueChangedEvent(object sender, SensorReadingEventArgs<MockMotionReading> e)
{
if (CurrentValueChanged != null)
{
CurrentValueChanged(this, e);
}
}
/// <summary>
/// Starts acquisition of data from the sensor.
/// </summary>
public virtual void Start()
{
motion.Start();
}
/// <summary>
/// Stops acquisition of data from the sensor.
/// </summary>
public virtual void Stop()
{
motion.Stop();
}
}
MockMotionWrapper
/// <summary>
/// Provides Windows Phone applications mock information about the device’s orientation and motion.
/// </summary>
public class MockMotionWrapper : MotionWrapper
{
/// <summary>
/// Use a timer to trigger simulated data updates.
/// </summary>
private DispatcherTimer timer;
private MockMotionReading lastCompassReading = new MockMotionReading(true);
#region Properties
/// <summary>
/// Gets or sets the preferred time between Microsoft.Devices.Sensors.SensorBase<TSensorReading>.CurrentValueChanged events.
/// </summary>
public override TimeSpan TimeBetweenUpdates
{
get
{
return timer.Interval;
}
set
{
timer.Interval = value;
}
}
#endregion
#region Constructors
public MockMotionWrapper()
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(30);
timer.Tick += new EventHandler(timer_Tick);
}
#endregion
void timer_Tick(object sender, EventArgs e)
{
var reading = new Microsoft.Devices.Sensors.SensorReadingEventArgs<MockMotionReading>();
lastCompassReading = new MockMotionReading(lastCompassReading);
reading.SensorReading = lastCompassReading;
//if (lastCompassReading.HeadingAccuracy > 20)
//{
// RaiseValueChangedEvent(this, new CalibrationEventArgs());
//}
RaiseValueChangedEvent(this, reading);
}
/// <summary>
/// Starts acquisition of data from the sensor.
/// </summary>
public override void Start()
{
timer.Start();
}
/// <summary>
/// Stops acquisition of data from the sensor.
/// </summary>
public override void Stop()
{
timer.Stop();
}
}
MockMotionReading
//Microsoft.Devices.Sensors.MotionReading
/// <summary>
/// Contains information about the orientation and movement of the device.
/// </summary>
public struct MockMotionReading : Microsoft.Devices.Sensors.ISensorReading
{
public static bool RequiresCalibration = false;
#region Properties
/// <summary>
/// Gets the attitude (yaw, pitch, and roll) of the device, in radians.
/// </summary>
public MockAttitudeReading Attitude { get; internal set; }
/// <summary>
/// Gets the linear acceleration of the device, in gravitational units.
/// </summary>
public Vector3 DeviceAcceleration { get; internal set; }
/// <summary>
/// Gets the rotational velocity of the device, in radians per second.
/// </summary>
public Vector3 DeviceRotationRate { get; internal set; }
/// <summary>
/// Gets the gravity vector associated with the Microsoft.Devices.Sensors.MotionReading.
/// </summary>
public Vector3 Gravity { get; internal set; }
/// <summary>
/// Gets a timestamp indicating the time at which the accelerometer reading was
/// taken. This can be used to correlate readings across sensors and provide
/// additional input to algorithms that process raw sensor data.
/// </summary>
public DateTimeOffset Timestamp { get; internal set; }
#endregion
#region Constructors
/// <summary>
/// Initialize an instance from an actual MotionReading
/// </summary>
/// <param name="cr"></param>
public MockMotionReading(MotionReading cr)
: this()
{
this.Attitude = new MockAttitudeReading(cr.Attitude);
this.DeviceAcceleration = cr.DeviceAcceleration;
this.DeviceRotationRate = cr.DeviceRotationRate;
this.Gravity = cr.Gravity;
this.Timestamp = cr.Timestamp;
}
/// <summary>
/// Create an instance initialized with testing data
/// </summary>
/// <param name="test"></param>
public MockMotionReading(bool test)
: this()
{
float pitch = 0.01f;
float roll = 0.02f;
float yaw = 0.03f;
this.Attitude = new MockAttitudeReading()
{
Pitch = pitch,
Roll = roll,
Yaw = yaw,
RotationMatrix = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll),
Quaternion = Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll),
Timestamp = DateTimeOffset.Now
};
// TODO: pull data from the Accelerometer
this.Gravity = new Vector3(0, 0, 1f);
}
/// <summary>
/// Create a new mock instance based on the previous mock instance
/// </summary>
/// <param name="lastCompassReading"></param>
public MockMotionReading(MockMotionReading lastCompassReading)
: this()
{
// Adjust the pitch, roll, and yaw as required.
// -90 to 90 deg
float pitchDegrees = MathHelper.ToDegrees(lastCompassReading.Attitude.Pitch) - 0.5f;
//pitchDegrees = ((pitchDegrees + 90) % 180) - 90;
// -90 to 90 deg
float rollDegrees = MathHelper.ToDegrees(lastCompassReading.Attitude.Roll);
//rollDegrees = ((rollDegrees + 90) % 180) - 90;
// 0 to 360 deg
float yawDegrees = MathHelper.ToDegrees(lastCompassReading.Attitude.Yaw) + 0.5f;
//yawDegrees = yawDegrees % 360;
float pitch = MathHelper.ToRadians(pitchDegrees);
float roll = MathHelper.ToRadians(rollDegrees);
float yaw = MathHelper.ToRadians(yawDegrees);
this.Attitude = new MockAttitudeReading()
{
Pitch = pitch,
Roll = roll,
Yaw = yaw,
RotationMatrix = Matrix.CreateFromYawPitchRoll(yaw, pitch, roll),
Quaternion = Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll),
Timestamp = DateTimeOffset.Now
};
this.DeviceAcceleration = lastCompassReading.DeviceAcceleration;
this.DeviceRotationRate = lastCompassReading.DeviceRotationRate;
this.Gravity = lastCompassReading.Gravity;
Timestamp = DateTime.Now;
}
#endregion
}
MockAttitudeReading
public struct MockAttitudeReading : ISensorReading
{
public MockAttitudeReading(AttitudeReading attitudeReading) : this()
{
Pitch = attitudeReading.Pitch;
Quaternion = attitudeReading.Quaternion;
Roll = attitudeReading.Roll;
RotationMatrix = attitudeReading.RotationMatrix;
Timestamp = attitudeReading.Timestamp;
Yaw = attitudeReading.Yaw;
}
/// <summary>
/// Gets the pitch of the attitude reading in radians.
/// </summary>
public float Pitch { get; set; }
/// <summary>
/// Gets the quaternion representation of the attitude reading.
/// </summary>
public Quaternion Quaternion { get; set; }
/// <summary>
/// Gets the roll of the attitude reading in radians.
/// </summary>
public float Roll { get; set; }
/// <summary>
/// Gets the matrix representation of the attitude reading.
/// </summary>
public Matrix RotationMatrix { get; set; }
/// <summary>
/// Gets a timestamp indicating the time at which the accelerometer reading was
/// taken. This can be used to correlate readings across sensors and provide
/// additional input to algorithms that process raw sensor data.
/// </summary>
public DateTimeOffset Timestamp { get; set; }
/// <summary>
/// Gets the yaw of the attitude reading in radians.
/// </summary>
public float Yaw { get; set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the most efficient way of storing data read from a socket to be read by another thread? So I have a class using high speed I/O completion port sockets. The protocol of the data I am receiving has a 17 byte header, and a variable data payload which is specified in the header, so instead of calling ReceiveAsync individually for each header and the payload I am just grabbing up to a 1024 byte buffer chunk instead to save cpu usage.
However, I'm not sure what the best way of storing this data is? It has to be in order, and I want a separate thread to do the processing without having any threading or performance issues.
Should I be looking at a memorystream or something along those lines?
Any ideas?
A: Don't store it. And don't use another thread to read it. I would use the same thread to deserialize it into something more usable. Then queue it in another thread and let the IOCP thread continue with it's processing.
A: Don't store it. Have the other thread read it when it needs it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to accomplish property and control update in wpf? I have wpf application with 3 textboxes.
txb1 is for inserting text
txb2 displays certain value from inserted parsed text, it is int number
txb3 should display value from txb2 multiplyed by constant value
There is a class storing data.
class Data
{
private conts int Mul = 10;
public string Text {get; set;}
public int Number {get; set;}
private int MultiNumber
{
get
{
Number * Mul;
}
}
public string MultiNumberFormated
{
get
{
string.Format("{some format}", MultiNumber);
}
}
}
By clicking button in form I handle event, create new instance of Data, pass txb1.Text through constructor and call parsing function inside Data class, which set value to Number. Textboxes are defined with Text="{Binding SomeProperty}" and DataContext of container with textboxes is set on Data instance, so after button click values appers in corresponding boxes.
Now, I need a solution to make txb3 update when value in txb2 is changed.
This is a small example of complex application, with more chained textboxes. For example txb4 displays multiplyed MultiNumber, so I don't want winforms solution using button event to update. Is there such a way? I'd also appreciate code sample sitting for this specific application.
A: As said by Slaks, you will have to implement INotifyPropertyChanged in your ViewModel.
We are referring to the MVVM pattern, with a particular focus on the V (View) and VM (ViewModel).
You can find an example here
Then once you documented yourself on that, you actually want to use Mode=TwoWay on the binding of the TextBoxes that need to take input from your users.
Then in the getters of your string properties that populate the other textboxes (those who depend upon each parameters), you implement the logic that does the calculation.
In their setters, you will need to raise the PropertyChanged event.
You will quickly realize that WPF is tighly coupled with this interface, and the MVVM pattern.
Now once you did all that, I'll still be there to answer more specific questions ;-)
A: You need to implement INotifyPropertyChanged in your model and raise the PropertyChanged event in all dependent property setters.
A: You have a couple of options here. You will need to implement INotifyPropertyChanged on your Data object as SLaks said - there are plenty of tutorials on that - then you can either
*
*Make a new property on your Data class for the multiplied number and bind txb3 to that
*Implement a value converter to handle the multiplication for you, if it's going to be display only
I would also get away from your current approach of passing in values from a text box in a button handler.
I'd probably look at moving your MultiNumberFormatted function into a value converter for txb2 and databinding everything (including txb1 which is currently your entry point to the calculation and is not bound to anything?) to properties on an instance of Data created much sooner in the lifecycle - either constructed with the page or passed in.
Or, you could make MultiNumberFormatted a property on Data and set it explicitly from the setter of your initial number:
int InputNumber
{
get
{
_return _inputNumber;
}
set
{
_inputNumber = value;
MultiNumberFormatted=String.Format("whatever: {0}", InputNumber);
NotifyPropertyChanged("InputNumber");
}
}
string MultiNumberFormatted
{
get
{
return _multiNumber;
}
set
{
_multiNumber=value;
NotifyPropertyChanged("MultiNumberFormatted");
}
}
That's one way of doing it, there are others. The point is that if you bind everything to appropriate properties and let the WPF binding infrastructure do its thing, it's all 'live' and everything "just works".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to scan hundreds of log files containing SSN, and change the files to mask out the SSNs without changing the reset of the contents I was asked this question on an interview and I couldn't came up with an efficient idea to solve this problem.
"How to scan hundreds of log files containing SSN, and change the files to mask out the SSNs without changing the reset of the contents."
Can anybody give me a hint? Thank you.
UPDATE: It was a Java developer position interview.
A: Don't use java (the question never indicated you needed to use java).
sed/awk on a *nix is easier and less complicated.
Sometimes interviewers want to know if you only have one tool in your basket.
If you had to use java,
1) read the file line by line
2) use regex to replace each line of the file in form nnn-nn-nnnn with the appropriate mask (n is the digits)
3) while doing that write each line to the new file
4) when done, possibly delete the old file and change the name of the new file you created to the old file name.
A: I'd use sed. It's not java, but it's fast and already-made.
A: I know this isn't the answer they're looking for, but if I were asked that question my answer would be something along the lines of "I'd never rely on an automated process like this to try to obscure something as sensitive as a SSN" Too many things can go wrong - say you use a regular expression (with sed, for example), and one of the SSNs is missing its first digit. The first three digits are trivial to guess (figure out someone's birthplace) and your algorithm will miss it. The first time there's a mistake...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: linux kernel module memory management I'm experimenting with memory management in linux kernel modules and I was wondering why a thread does not see the same memory as the module's functions. What I mean is,
I have a int *x declared globally. I allocate space using kmalloc and assign 10 to it. Now when I try and access it from within a thread, I get a totally different value.
Why does this happen? How can I get around this?
EDIT:
I run my programs in x86 architecture on a single core (on a VM).
Here is my code: http://pastebin.com/94qGc6ZQ
A: On SMP architectures values that are cached are not updated across all cores so a thread on another core can be using a stale value.
Another issue you can have is concurrent access between threads that means Thread 1 read x before Thread 2 was able write x but Thread 2 continued and said x = 10 but Thread 1 is still using the old value when x was uninitialized.
The way to solve the second problem (which seems more likely) is to use locking to control access to that variable so only 1 thread can modify/read it at a time to avoid issues of stale values.
(Not hardware kernel module so don't use volatile ;P) use suggestion of smp_wb and smp_rb below.
EDIT: Looks like my first suggestion was right. So to solve this you can use smp_wb on x before doing kmalloc and assignment. Then a read barrier on x before attempting to print the value of x. This effectively tells the CPU read the new value because it might be bad or could have been reordered in access. You may be able to just use a read barrier on the other thread but for safety use barriers where access is done.
A: You need some sort of lock (and memory barrier that invalidates the cache.)
On SMP kernels, there are lock mechanisms implemented (for the kernel) that takes care of this:
Read http://www.mjmwired.net/kernel/Documentation/memory-barriers.txt
and especially "Inter-CPU locking barrier effects"
A: What architecture are you running on? I don't believe the other answers that say you are hitting memory ordering problems or cache coherency problems, because
*
*x86 is very strongly ordered, and kthread_run() internally takes so many locks etc. that I'm sure there is the equivalent of a memory barrier between the assignment to *x and the start of your thread. So even on more weakly ordered architectures, I don't think you are really missing a memory barrier.
*I don't believe there is any architecture where Linux runs that is cache-incoherent between CPUs. You have to be careful with external devices doing DMA into memory, but that's completely different from the issue here.
In other words I think the code as you have written it in your question looks fine. I suspect that this is boiled down from your real code, and in so doing you got rid of the real bug.
It certainly is true that if you have code that modifies a variable used in your thread after the kthread_run then you have a race condition which could lead to a bug like what you see here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: getting xml file from a website and copying it to a server My question is very broad since I do not know exactly what I ought to do. It will be my first trial. I hope I can express my need adequately.
I want to read and than copy an xml file from a website and copy it to my amazon cloud server account. I want to write the code on my amazon server on linux platform.
1- I need to check the xml file on the website every day.
2- If there is a change in the xml file, I will get it and copy it to my amazon cloud server.
(perhaps I can compare character lengths of today's and previous day's xml file in order to understand if there is a change)
3-I made a research and I found wget command can be used to copy a file.
Could you please give me some sample codes and guideline?
Many thanks,
I apologize if my question is nonsense or ambiguous .
A: Yes, you could use the wget or curl commands to download the XML file. You can use diff to compare the new file to the old file. Maybe look into creating a bash shell script to automate these processes, and schedule it to run periodically with cron. I think you could have this run directly on your "cloud server", rather than transfer the XML file there after doing these checks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Component layering Java Swing, Layers showing on hover I have two JPanels layered on top of each other in the same container. I am using container.add(jpanel, 0); and container.add(otherjpanel, 1). It works fine however in order for the top layer to show I have to hover over the components with the mouse.
Here is some executable code showing my problem.
Just hover mouse on upper part of screen.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.util.*;
public class test {
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
JFrame frame = new GUIframe();
frame.setVisible(true);
frame.setResizable(false);
}
}
class GUIframe extends JFrame{
public GUIframe(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300,400));
setSize(300, 400);
JLayeredPane content = new JLayeredPane();
content.setPreferredSize(new Dimension(300,400));
content.setSize(300,400);
JPanel board = new JPanel();
for (int i = 0;i<5;i++){
JButton button = new JButton("button");
board.add(button);
}
content.add(new ImagePanel());
this.add(content);
this.add(board);
}
}
class ImagePanel extends JPanel {
private Image img;
String imageLocation = "image location here";
ImagePanel() {
img = new ImageIcon(imageLocation).getImage();
setPreferredSize(new Dimension(300,400));
setSize(300,400);
setLayout(null);
setOpaque(false);
}
public void paint(Graphics g){
super.paint(g);
g.drawImage(img, 0, 0, this);
}
}
A: A contentPane's layout is by default BorderLayout. Have you changed this? Perhaps you should set your contentPane to be a JLayeredPane instead.
If anything about this recommendation is unclear, please leave a comment.
Edit 1: Example of JLayeredPane
You could solve this sort of thing with a layered pane as I described, something like listed below, but you must take care to set size and to make overlying JPanels non-opaque:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Test2 {
private static final int LP_WIDTH = 450;
private static final int LP_HEIGHT = 600;
private static final String IMAGE_SITE = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/b/b8/Laser_Towards_Milky_Ways_Centre.jpg/"
+ "660px-Laser_Towards_Milky_Ways_Centre.jpg";
private JLayeredPane layeredPanel = new JLayeredPane();
public Test2() {
layeredPanel.setPreferredSize(new Dimension(LP_WIDTH, LP_HEIGHT));
try {
URL url = new URL(IMAGE_SITE);
BufferedImage image = ImageIO.read(url);
ImagePanel2 imagePanel2 = new ImagePanel2(image);
imagePanel2.setSize(layeredPanel.getPreferredSize());
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
for (int i = 0; i < 8; i++) {
buttonPanel.add(new JButton("Button"));
}
buttonPanel.setSize(layeredPanel.getPreferredSize());
layeredPanel.add(imagePanel2, JLayeredPane.DEFAULT_LAYER);
layeredPanel.add(buttonPanel, JLayeredPane.PALETTE_LAYER);
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
private JComponent getMainComponent() {
return layeredPanel;
}
private static void createAndShowGui() {
Test2 test2 = new Test2();
JFrame frame = new JFrame("Test2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(test2.getMainComponent());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class ImagePanel2 extends JPanel {
private Image image;
public ImagePanel2(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
}
However if all you want is a background image, then that's what I'd do, create a JPanel that uses a background image, and then add stuff to it.
import java.awt.*;
import java.awt.image.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Test3 extends JPanel {
private static final int LP_WIDTH = 450;
private static final int LP_HEIGHT = 600;
private static final String IMAGE_SITE = "http://upload.wikimedia.org/wikipedia/"
+ "commons/thumb/b/b8/Laser_Towards_Milky_Ways_Centre.jpg/"
+ "660px-Laser_Towards_Milky_Ways_Centre.jpg";
private BufferedImage image;
public Test3() {
try {
URL url = new URL(IMAGE_SITE);
image = ImageIO.read(url);
for (int i = 0; i < 8; i++) {
add(new JButton("Button"));
}
} catch (MalformedURLException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(LP_WIDTH, LP_HEIGHT);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
private static void createAndShowGui() {
Test3 mainPanel = new Test3();
JFrame frame = new JFrame("Test3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to use commons-DBCP with Play! Framework How can I set up my Play! app to use a commons-dbcp connection pool instead of
the native one provided by C3P0?
UPDATE
I got some feedback from the Play! Framework forum and what I was asking is achievable accessing a configured commons-DBCP DataSource via JNDI, e.g. when deploying the PLay! app in a container.
I'm still searching if I can utilize JNDI running the Play! app in the "default" environment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google-API Calendar Feed for Java I'm currently using the new Google API 1.5 beta, and I can't find any examples for retrieving a calendar feed. The examples posted here only seem to provide a list of calendars per account and not their events. Is the old GData API the only way to retrieve a calendar feed right now? And if so, is it worth waiting for this feature to appear in the new API if I only want to retrieve an event feed?
A: Did some digging around in the other non-Android examples and found this to work:
CalendarUrl url = new CalendarUrl(calendar.getEventFeedLink());
try {
EventFeed feed = client.eventFeed().list().execute(url);
for(EventEntry entry : feed.getEntries()) {
// etc....
}
}
catch(IOException e) {
e.printStackTrace();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the proper way to make it so core graphics does not lag? I use UIBezierPath for finger painting (my app). I create it using path = [UIBezierPath bezier path]; . It constantly lags on the iPad (and calling it from within drawrect did not change anything). I have been working on this for hours on end and have found no solution, just lag. Would somebody be so kind to help me please? Also, I am using a NSTimer to call the function. That is the old way my app will work so please help me fix this lagggg!!!!!
A: Since none of your questions contains enough details on its own, I'm going to do something improper and post a meta-answer to your current last five questions.
First, draw in drawRect: and nowhere else.
That's so important that I'm going to say it again.
Draw in drawRect: and nowhere else.
Not touchesMoved:withEvent:.
Not touchesBegan: or Ended:.
drawRect: and nowhere else.
If you're making an image to save to a file, that's one thing. But when you're drawing to the screen, you don't do it anywhere other than drawRect:.
Seriously. It's that important.
Step 2: Don't attempt to force drawing to happen at any other time.
drawRect: is called for you when it's time for you to draw. By definition, at any other time, you don't need to draw, so drawing is doing things you don't need to do. By extension, don't call drawRect: yourself. You don't need to and it never helps.
Actually, that's just an extension of step 1. If you call drawRect:, it's no different from if you had the drawing code where you have the call. The drawing code isn't repeated everywhere, which is nice, but it's still running at the wrong time. Let drawRect: only be called when the system calls it.
setNeedsDisplay exists to tell the system that it's time to draw. You should do this when, and only when, something has changed that you'll need to draw. Your view's properties, something in the model—whenever what you will draw changes, send yourself setNeedsDisplay. Don't do it at any other time; you don't need to.
Cut out the timer. You don't need it. There's already a timer in place anyway, limiting you to 60 fps.
Core Graphics does not lag. No, really, it doesn't. Slowness or “lag” is because either you're trying to do too much or you're doing something wrong.
Don't cache unnecessarily. Nothing you're doing requires an image cache.
The “lag” is because you're trying to draw, or to force drawing, from touchesMoved:withEvent: and/or touchesBegan:/Ended:. See above.
Here's what you need to do:
In your touchesBegan:/Moved:/Ended: methods, or other responder methods as appropriate, update your state. This will include the Bézier path. Do not draw, and that includes do not call drawRect: or otherwise attempt to force drawing.
After you've updated your state, and only if you've done so, send yourself setNeedsDisplay.
In your drawRect: method, and only in your drawRect: method, draw the path, gradient, whatever, however you see fit.
Do these things, and your application will be fast. With Core Graphics. Without lag.
Also, some important reading:
*
*View Programming Guide for iOS
*Drawing … Programming Guide for iOS
*Quartz 2D (Core Graphics) Programming Guide
*Performance Overview (some parts are Mac OS X specific, but much of it is relevant on iOS as well)
*Instruments User Guide
A: don't use a timer to periodically redraw when your view must be redrawn based on response to user events.
instead, invalidate your view using setNeedsDisplay or setNeedsDisplayInRect: when you receive touches which require you to redraw portions of your view.
a complex touch drawing iPad app can be a lot to ask to render in realtime, especially when you are overdrawing. draw only when needed.
another option: work in layers
you probably don't have undo in your app, so it should be simple to implement. periodically composite your image down to a single view. when draw rect is called, you then have fewer paths to draw (1 large image + fewer paths). in that case, a cached backing bitmap would definitely help.
again, there's not a whole lot of detail in your posts, and you haven't told us what the profiler is showing you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MKCoordinateSpanMake: why specify longitude AND latitude delta? If the distance corresponding to one degree of longitude is a function of latitude, why do you have to specify longitudeDelta and latitudeDelta when calling MKCoordinateSpanMake in the iOS MapKit? Moreover, how am I supposed to know what the correct ratio is?
A: You don't need to specify both nor do you need to pre-calculate the ratio.
Both parameters are provided as a convenience if you have a previously saved span or you happen to know the exact span you want.
No matter what values you pass, the map view will still adjust the span so that it fits the map view frame and matches the zoom level that it can display.
You can in fact pass 0.0 for either parameter if you only know or care about one of them. The map view will do the calculations and adjust the span as needed.
To see what the adjusted span will be (or if you want to pre-calculate it), call the regionThatFits: method with a region containing a span such as (10,0).
Also, after calling setRegion:, mapView.region.span will contain the adjusted span as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Allegro5 and MS Visual Studio 2010 recently I treid to add Allegro5 library to Visual Studio 2010. I visited allegro.cc and downloaded package called: allegro-5.0.4-msvc-10.0 (following the name, I think it's correct one) and after extracxtion, and I copied:
/bin to C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin
/include to C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include
/lib to C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib
Allegro's dlls to C:\Windows\System32
I also added "alld.lib" in project -> properties -> linker -> input
And when I tried to use Allegro in my project, I could included Allegro's headers but it's an error when I tried to type something simple like:
#include <allegro5\allegro.h>
int main()
{
allegro_init();
return 0;
}
It generates an error (red underline in typing mode) : undefinded identifier "allegro_init".
Would anyone give me a tip what might be wrong in this configuration?
I'll be very glad for all hints and solutions.
Greetings,
A: Please see the documentation on the wiki for Allegro 5 and Visual Studio 2010. Especially note the bit about not modifying system folders like you have already done.
Anyway, the problem here is that you are trying to write Allegro 4 code but you've installed Allegro 5. The two are not compatible. Allegro 5 is completely rewritten and designed for modern hardware. The correct equivalent program is:
#include <allegro5/allegro.h>
int main(int argc, const char *argv[])
{
al_init();
return 0;
}
Also, you are linking with Allegro 4, judging by the name of the file. The libraries as included in the binary package are described here. There are many different versions included for debugging, for static run times, etc. The most direct equivalent for alld.lib is allegro-5.0.4-monolith-md-debug.lib.
You can find the manual here: http://www.allegro.cc/manual/5/
A: Well your big problem is, I'd guess, that you aren't actually telling the linker how to load the DLL.
You could do it manually using LoadLibrary and GetProcAddress.
However most of the time when you build a DLL you'll find you get a library which handles all the above dynamic linking for you. As a result you'll find its much easier to just add that lib to the linker "inputs".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery Validate: Group Validation But Not Field Validation I'm using jquery validate and I've set up groups. However, I'm having trouble figuring out the best way to validate each group seperately from the individual fields that it contains.
To illustrate this:
I have city, state, and zip ( in that order ). If someone enters a value for zip, they should get positive confirmation ( I've got that part working with a green checkmark by the input ), however, so long as either state and zip are empty the group validation message should still show.
On various attempts I've come up to the following problems:
- User skips over "city" and the validation the message displays but then when input is provided for "zip", the validation message goes away. ( this is weird...maybe a bug? )
- User enters "city" and they get the group error message before they even get to enter "state"
- User enters "city" but won't get the checkmark because the other inputs in the group are empty
I'm leaning towards addressing this by overwriting the "onfocusout" event ( by having it check all the inputs in the group on focusout ) but not sure if there is a better way via some of validate's built in methods
Thanks!
*UPDATE
The solutions I've come up with are rather ugly and none of them work consistently, below is an example, it results in the inverse of the first problem I listed above. Now the validation message only shows when the last field in a group is filled in.
Maybe group validation rely's on the validation result of the last test in a group?
Anyway...here's the mess I've come up with so far:
Set the group:
groups : { location : 'city state zip' }
Create a rule for the group ( note it has to be an array to preserve the order ):
rules : { location : ['city, 'state', 'zip']}
Now override the onfocusout:
onfocusout : function(el) {
var groups = this.groups
, elName = el.name
, elGroup = groups[elName]
, $el = $(el)
if (!this.checkable(el) ){
this.element(el));
}
// If the element belongs to a group, validate all elements in the group
// that come before the current element
if (elGroup) {
var groupMembers = this.settings.rules[elGroup];
for (var i=0; i<groupMembers.length; i++) {
if ( groupMembers[i] === elName ) {
break;
}
this.element( $('[name="' + groupMembers[i] + '"]') );
}
}
}
A: you can use groups for that, take this example:
$("form").validate({
rules: {
City: { required: true },
Zip: { required: true },
State: { required: true }
},
groups: {
Location: "City Zip State"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "City" || element.attr("name") == "Zip" || element.attr("name") == "State")
error.insertAfter("#State");
else
error.insertAfter(element);
}
});
*
*the rules set the 3 fields to true
*the groups defines them to be validated as a group
*and the errorPlacement function defines where to put the error message
A: It seems the "groups" feature of this plugin has a few issues that are still outstanding, a few of which look to be related to your problem.
https://github.com/jzaefferer/jquery-validation/issues/search?q=groups
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to sanitize SQL queries in C?
Possible Duplicate:
Preventing SQL Injection in C
I know PHP has some built in functions that help to sanitize queries, but does C have anything like that?
snprintf(&buff[0],1023,"UPDATE grades SET grade='%c' WHERE username='%s'",choice,&uname[0]);
if (mysql_query(connect,&buff[0]) != 0) {
// If it failed, tell the user
printf("Error: %s!\n", mysql_error(connect));
return;
}
A: The MySQL C API has a mysql_real_escape_string() function.
A: The C language and runtime have no such routine. Your particular database's particular client library might have something.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: BaseHTTPServer thread does not work My code is simple. Using BaseHTTPServer and ThreadInMix I want to run
a python script (Script1.py) for every request made simultaneously.
My Code-
from subprocess import PIPE, Popen
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import time
def simple_script(self):
print 'simple_script'
s = Popen('C:/Python27/python C:/Script1.py 5', shell=True,
stdout=PIPE, stderr=PIPE)
out, err = s.communicate()
print out, err
self.wfile.write(out)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write('{0}\n'.format(time.asctime()))
simple_script(self)
return
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
pass
if __name__ == '__main__':
server = ThreadedHTTPServer(('', 8080), Handler)
print 'Starting server, use <Ctrl-C> to stop'
server.serve_forever()
"""
# C:/Script1.py
import time, sys
s = time.time()
while True:
if time.time() - s > int(sys.argv[1]):
break
else:
time.sleep(1)
print time.asctime()
"""
I just found out that-
With URL: http://localhost:8080
If I open multiple tabs/browsers for IE, this works JUST FINE
But,
If I open multiple tabs/pages in Chrome or Firefox, the pages wait for previous page? This does not imply threading in Chrome or Firefox? Any help? Thanks
A: Works just fine for me:
Starting server, use to stop
localhost.localdomain - - [03/Oct/2011 16:25:55] "GET / HTTP/1.1" 200 -
simple_script
localhost.localdomain - - [03/Oct/2011 16:25:55] "GET / HTTP/1.1" 200 -
simple_script
Mon Oct 3 16:25:56 2011
Mon Oct 3 16:25:57 2011
Mon Oct 3 16:25:58 2011
Mon Oct 3 16:25:59 2011
Mon Oct 3 16:26:00 2011
Mon Oct 3 16:26:01 2011
Mon Oct 3 16:25:56 2011
Mon Oct 3 16:25:57 2011
Mon Oct 3 16:25:58 2011
Mon Oct 3 16:25:59 2011
Mon Oct 3 16:26:00 2011
Mon Oct 3 16:26:01 2011
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When should I call rawurlencode and rawurldecode? I'm writing a basic file browser in PHP as a homework assignment. I've got the whole thing working nicely and haven't really run into any problems - it's pretty simple. Open a directory, show directories and up-one-level as links, show files as plain-old-text.
I've read about rawurlencode and rawurldecode, and I was wondering when I should use them specifically, or if they're needed at all in this case.
Do PHP functions like opendir() work on encoded URLs, or should I decode URLs before passing them to the function?
Should I call rawurlencode() on the path I put in my hyperlinks to other directories?
Any suggestions are more than welcome, and let me know if I'm just barking up the wrong tree! :)
A: If you're passing the directory path to open through the URL, then yes, it would be a good idea to use rawurlencode in that. Then use rawurldecode when passing the parameter to opendir. Or, before doing that, check that the directory exists first with is_dir.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Disabling Rails middleware for some actions but not all It seems that ActionDispatch::ParamsParser is quite slow for some requests, in particular when there is a large JSON request body. I'd like to disable it for these requests, but for most of my application it works great. Is there a convenient way to disable the ParamsParser for some actions without removing it from the middleware stack entirely? This is using Rails 3.0.9.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python reading file in binary, binary data to string? I'm trying to learn Python and currently doing some exercises online. One of them involves reading zip files.
When I do:
import zipfile
zp=zipfile.ZipFile('MyZip.zip')
print(zp.read('MyText.txt'))
it prints:
b'Hello World'
I just want a string with "Hello World". I know it's stupid, but the only way I could think of was to do:
import re
re.match("b'(.*)'",zp.read('MyText.txt'))
How am I supposed to do it?
A: You need to decode the raw bytes in the string into real characters. Try running .decode('utf-8') on the value you are getting back from zp.read() before printing it.
A: You need to decode the bytes to text first.
print(zp.read('MyText.txt').decode('utf-8'))
A: Just decode the bytes:
print(zp.read('MyText.txt').decode('UTF-8'))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get text from an URL I want to get the plain text (that eventually is shown to the user) from an URL. I know how to extract all the contents, but what I get is all this html stuff, hidden stuff etc.
I just wat the plain text, without layout. Not really stripped all html tags from the content, but kind of parsed, and then without the layout. Firstly for comparison with other text and secondly to display it.
Is there any easy way to do this? (any existing code?)
A: Use the DOM.
First, load the resource into a WebView. You don't need to put it into a window.
Then, after it finishes loading, ask for the view's mainFrameDocument, then ask the document for its documentElement, then ask that for its textContent.
A: You can use readability to extract the content.
I do not know if there is Obj-C version but you can use javascript one with [yourWebView stringByEvaluatingJavaScriptFromString:@"readability_js_code"]
If you are retrieving the content (html) of the page not via UIWebView (ASIHTTP or custom code), try parsing with XML Parser (NSXMLParser for example)
Hope this helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XCode: Checking and assigning split string values to textField So i have been trying to test this out; basically i have a text file included named rawData.txt, it looks like this:
060315512 Name Lastname
050273616 Name LastName
i wanted to split the lines and then split each individual line and check the first part (with 9 digits) but it seems to not work at all (my window closes) is there any problem with this code?
NSString *path = [[NSBundle mainBundle] pathForResource: @"rawData" ofType:@"txt"];
if (path)
{
NSString *textFile = [NSString stringWithContentsOfFile:path];
NSArray *lines = [textFile componentsSeparatedByString:(@"\n")];
NSArray *line;
int i = 0;
while (i < [lines count])
{
line = [[lines objectAtIndex:i] componentsSeparatedByString:(@" ")];
if ([[line objectAtIndex:0] stringValue] == @"060315512")
{
idText.text = [[line objectAtIndex: 0] stringValue];
}
i++;
}
}
A: Yes if you want to compare 2 string you should use isEqualToString, because == compares the pointer value of the variables. So this is wrong:
if ([[line objectAtIndex:0] stringValue] == @"060315512")
You should write:
if ([[[line objectAtIndex:0] stringValue] isEqualToString: @"060315512"])
A: If you check your console log, you probably see something like "stringValue sent to object (NSString) that does respond" (or those effects). line is an array of strings, so [[line objectAtIndex:0] stringValue] is trying to call -[NSString stringValue] which does not exist.
You mean something more like this:
NSString *path = [[NSBundle mainBundle] pathForResource: @"rawData" ofType:@"txt"];
if (path)
{
NSString *textFile = [NSString stringWithContentsOfFile:path];
NSArray *lines = [textFile componentsSeparatedByString:@"\n"];
for (NSString *line in lines)
{
NSArray *columns = [line componentsSeparatedByString:@" "];
if ([[columns objectAtIndex:0] isEqualToString:@"060315512"])
{
idText.text = [columns objectAtIndex:0];
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to bind an Image's Source to an attached property? I created a custom control which contains an Image control.
I'd like to have the Source of the Image Control bound to an ImageSource Dependency Property.
The Dependency Property is created as such:
public static class ImageSourceProperty
{
public static readonly DependencyProperty CustomImageSourceProperty;
public static ImageSource GetCustomImageSource(DependencyObject dependencyObject)
{
return (ImageSource)dependencyObject.GetValue(CustomImageSourceProperty);
}
public static void SetCustomImageSource(DependencyObject dependencyObject, ImageSource value)
{
dependencyObject.SetValue(CustomImageSourceProperty, value);
}
static ImageSourceProperty()
{
CustomImageSourceProperty = DependencyProperty.RegisterAttached("CustomImageSource", typeof (ImageSource), typeof (ImageSourceProperty), new PropertyMetadata(default(ImageSource)));
}
}
And I'm trying to bind the Source of the Image of the Custom Control as such:
<UserControl
(...)
xmlns:AttachedProperties="clr-namespace:Codex.UserControls.AttachedProperties"
x:Class="Codex.UserControls.CustomControls.ImageWithBorder"
d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot">
<Border BorderBrush="White" BorderThickness="3" CornerRadius="3">
<Image Source="{Binding AttachedProperties:ImageSourceProperty.CustomImageSource}" Width="50" Height="50"/>
</Border>
</Grid>
I placed the user control in my view like this:
<CustomControls:ImageWithBorder (...) AttachedProperties:ImageSourceProperty.CustomImageSource="(...)"/>
I obtain the following error in the Output window upon launching the application:
System.Windows.Data Error: 40 : BindingExpression path error: 'AttachedProperties:ImageSourceProperty' property not found on 'object' ''ToolbarViewModel' (HashCode=20169503)'.
Why isn't the user control able to bind to the dependency property ? Is it looking for the dependency property in its code-behind and can't find it ?
A: Found the problem. I was not specifying the relative source of the binding.
Here's the correct UserControl declaration:
<Image Source="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type CustomControls:ImageWithBorder}},Path=(AttachedProperties:ImageSourceProperty.CustomImageSource), Mode=TwoWay}" Width="50" Height="50"/>
The problem was that the Dependency Property was not able to return the value since the dependency object wasn't valid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove index key from Array for accessing to object? How do I remove Index key from array?
For example:
$getProduct = Product::find($product->ProductID);
and the array structure will look something like this:
Array
(
[0] => Product Object
(
[id] => 26552
[name] => Product Name One
)
)
To get the value of name, I have to do this:
echo $getProduct[0]->name;
I want to get the value like this:
echo $getProduct->name;
A: $getProduct = $getProduct[0];
will put the first item in the array into it's own variable, from which you can then access
$getProduct->name
However I would suggest putting it into a variable with a different name for the sake of your code readability, maybe:
$product = $getProduct[0];
echo $product->name;
A: To get the value as you want, you should change your class "Product" in the way it returns you the object you are initializing after calling the find method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Nonblocking sleep in C#5.0 (like setTimeout in JavaScript) What is the analog of JavaScript's setTimeout(callback, milliseconds) for the C# in a new "async" style?
For example, how to rewrite the following continuation-passing-style JavaScript into modern async-enabled C#?
JavaScript:
function ReturnItAsync(message, callback) {
setTimeout(function(){ callback(message); }, 1000);
}
C#-5.0:
public static async Task<string> ReturnItAsync(string it) {
//return await ... ?
}
A: AsyncCTP has TaskEx.Delay. This wraps timers in your task. Note, that this is not production-ready code. TaskEx will be merged into Task when C# 5 arrives.
private static async Task ReturnItAsync(string it, Action<string> callback)
{
await TaskEx.Delay(1000);
callback(it);
}
Or if you want to return it:
private static async Task<string> ReturnItAsync(string it, Func<string, string> callback)
{
await TaskEx.Delay(1000);
return callback(it);
}
A: When I need to mimic the JavaScript's setTimeout(callback, milliseconds) function I use the code below:
Scheduling work to thread pool (fire-and-forget non-blocking scheduling):
Task.Run(() => Task
.Delay(TimeSpan.FromSeconds(1))
.ContinueWith(_ => callback(message)));
There are variations of this when one can provide a cancellation token to cancel the task before the delay has elapsed. Unless I misunderstood, the selected answer by Ilian Pinzon is more suited for an awaited situation, which in case of fire-and-forget (JavaScript) isn't what you wanted.
Note: the TimeSpan.FromSeconds(1) is for convenience, if milliseconds are desired the whole TimeSpan can be eschewed in favor of a millisecond value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Send messages to a safari window in the dashboard with applescript I'm trying to send messages via applescript to a safari window in the dashboard. Sending messages to normal safari is simple enough, but no clue how to do it in the dashboard. Is this possible?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery Lightbox single image display Is there a way to make lightbox only show the image clicked on and not show an entire gallery.
I am not interested in giving the user the ability to see other images aside from the one they clicked on, but the documentation doesn't seem to reflect this functionality.
Any help or examples would be greatly appreciated.
A: Try adding this to your CSS:
#lightbox-nav a {
display:none !important;
}
A: you can hide the navigation as explained in another answer here
but a nice solution is to initialize the lightbox plugin on each item separately.
instead of $('#gallery a').lightBox(); you can do this:
$('#gallery a').each(function(){
$(this).lightBox();
});
the gallery is actually made of each item that fits the selector,
if you select 10 items those will be your gallery, but if you launch .lightBox() on each separately, they each get added to their own gallery (convenientely the plugin hides the controls when only 1 items is in the gallery.)
see an example here:
http://jsfiddle.net/saelfaer/kwdBf/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stopping all current played youtube videos Is there way to make function in Action Script, or any other language, to stop all currently played youtube videos in current Tab?
Here's example, There are 10 youtube video objects on the site, i wanna have one button, to simply make them stop playing.
So, is there way to do this, and if yes, could you give any advices/directions where i can learn the technique?
Thanks in advance
A: You can take a look at YouTube Player API reference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cannot retrieve values from result set (jdbc) After ResultSet rs = stmt.executeQuery(query); , the code does not execute. Thus, the variables do not get the values from the result set . Can anybody help me resolve this ?
public User storeTempDetails(String s1){
Statement stmt = null;
String query = "select username, account_no,name from accounts where username = ?";
try {
connection = DriverManager.getConnection(DBurl, DBusername, DBpassword);
System.out.println("Database connected!");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("this line is not printed");
while (rs.next()) {
userName = rs.getString("username");
accountNo = rs.getString("account_no");
name = rs.getString("name");System.out.println("ss"+accountNo);
}
} catch (SQLException e ) {
throw new RuntimeException("Cannot connect the database!", e);
} finally {
User userObj=new User(userName,accountNo,name);
System.out.println("Closing the connection.");
if (connection != null) try { connection.close(); }
catch (SQLException ignore) {}
return userObj;
}
}
A: Start with something like this. These are utility classes that will make your life easier when you're starting off with JDBC:
package persistence;
import java.sql.*;
import java.util.*;
/**
* util.DatabaseUtils
* User: Michael
* Date: Aug 17, 2010
* Time: 7:58:02 PM
*/
public class DatabaseUtils
{
private static final String DEFAULT_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DEFAULT_URL = "jdbc:oracle:thin:@host:1521:database";
private static final String DEFAULT_USERNAME = "username";
private static final String DEFAULT_PASSWORD = "password";
/*
private static final String DEFAULT_DRIVER = "org.postgresql.Driver";
private static final String DEFAULT_URL = "jdbc:postgresql://localhost:5432/party";
private static final String DEFAULT_USERNAME = "pgsuper";
private static final String DEFAULT_PASSWORD = "pgsuper";
*/
/*
private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
private static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/party";
private static final String DEFAULT_USERNAME = "party";
private static final String DEFAULT_PASSWORD = "party";
*/
public static void main(String[] args)
{
long begTime = System.currentTimeMillis();
String driver = ((args.length > 0) ? args[0] : DEFAULT_DRIVER);
String url = ((args.length > 1) ? args[1] : DEFAULT_URL);
String username = ((args.length > 2) ? args[2] : DEFAULT_USERNAME);
String password = ((args.length > 3) ? args[3] : DEFAULT_PASSWORD);
Connection connection = null;
try
{
connection = createConnection(driver, url, username, password);
DatabaseMetaData meta = connection.getMetaData();
System.out.println(meta.getDatabaseProductName());
System.out.println(meta.getDatabaseProductVersion());
String sqlQuery = "SELECT PERSON_ID, FIRST_NAME, LAST_NAME FROM PERSON ORDER BY LAST_NAME";
System.out.println("before insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
connection.setAutoCommit(false);
String sqlUpdate = "INSERT INTO PERSON(FIRST_NAME, LAST_NAME) VALUES(?,?)";
List parameters = Arrays.asList( "Foo", "Bar" );
int numRowsUpdated = update(connection, sqlUpdate, parameters);
connection.commit();
System.out.println("# rows inserted: " + numRowsUpdated);
System.out.println("after insert: " + query(connection, sqlQuery, Collections.EMPTY_LIST));
}
catch (Exception e)
{
rollback(connection);
e.printStackTrace();
}
finally
{
close(connection);
long endTime = System.currentTimeMillis();
System.out.println("wall time: " + (endTime - begTime) + " ms");
}
}
public static Connection createConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException
{
Class.forName(driver);
if ((username == null) || (password == null) || (username.trim().length() == 0) || (password.trim().length() == 0))
{
return DriverManager.getConnection(url);
}
else
{
return DriverManager.getConnection(url, username, password);
}
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static List<Map<String, Object>> map(ResultSet rs) throws SQLException
{
List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
try
{
if (rs != null)
{
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>();
for (int i = 1; i <= numColumns; ++i)
{
String name = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(name, value);
}
results.add(row);
}
}
}
finally
{
close(rs);
}
return results;
}
public static List<Map<String, Object>> query(Connection connection, String sql, List<Object> parameters) throws SQLException
{
List<Map<String, Object>> results = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
rs = ps.executeQuery();
results = map(rs);
}
finally
{
close(rs);
close(ps);
}
return results;
}
public static int update(Connection connection, String sql, List<Object> parameters) throws SQLException
{
int numRowsUpdated = 0;
PreparedStatement ps = null;
try
{
ps = connection.prepareStatement(sql);
int i = 0;
for (Object parameter : parameters)
{
ps.setObject(++i, parameter);
}
numRowsUpdated = ps.executeUpdate();
}
finally
{
close(ps);
}
return numRowsUpdated;
}
}
Given those utilities, here's how I might write it. I'd probably put User in a model package, and UserDaoImpl would be a public class in its own .java file. I'm just being lazy:
package persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* UserDao
* @author Michael
* @since 10/2/11
*/
public interface UserDao
{
User find(String username);
}
class UserDaoImpl implements UserDao {
public static final String SELECT_USER_BY_USERNAME = "select username, account_no,name from accounts where username = ?";
private Connection connection;
UserDaoImpl(Connection connection)
{
this.connection = connection;
}
public User find(String username)
{
User user = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = this.connection.prepareStatement(SELECT_USER_BY_USERNAME);
ps.setString(1, username);
rs = ps.executeQuery();
while (rs.next()) {
String account = rs.getString("account_no");
String name = rs.getString("name");
user = new User(name, username, account);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return user;
}
}
class User {
private final String name;
private final String username;
private final String account;
User(String name, String username, String account)
{
this.name = name;
this.username = username;
this.account = account;
}
public String getName()
{
return name;
}
public String getUsername()
{
return username;
}
public String getAccount()
{
return account;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("User");
sb.append("{name='").append(name).append('\'');
sb.append(", username='").append(username).append('\'');
sb.append(", account='").append(account).append('\'');
sb.append('}');
return sb.toString();
}
}
A: There is an exception thrown. But that exception will never get anywhere, because of the return in the finally block. Google for "java", "return" and "finally" and you will get a feeling how bad that is.
Fix the code and show us the stacktrace.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Substract 1 month to update table SQL Server I need to update all the issuedat (date field) to be less than one month from the column paidat (date field)
ex:
if paidat = 01/02/2011 then issuedat should = 01/01/2011
UPDATE invoices SET invoices.issuedat = ????
A: UPDATE invoices SET invoices.issuedat = dateadd(MM,-1,paidat)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating python subclass issue I'm having some trouble with class inheritance in Python 3.1x that I am hoping to get some help with. I have a class called ClassA and I am trying to create another class called ClassB that inherits from ClassA. Here is the code I've written:
from myfile import ClassA
class ClassB(ClassA):
def __init__(self):
super(ClassB, self).__init__()
When I try to create an instance of ClassB I get this error:
>>> x = ClassB()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ClassB' is not defined
Which is my problem?
A: The problem is that you're not referring to what you've imported.
>>> import SomeModule
>>> x = SomeModule.ClassB()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL LIKE and MATCH results query Can someone explain why
column LIKE '%board%'
returns more results than
MATCH (column) AGAINST('board' IN BOOLEAN MODE)
is it because match against ignores words like 'Blackboard', 'Backboard' etc
Is there away to get MATCH AGAINST return Blackboard, backboard etc?
A: MATCH (column) AGAINST('keyword... will match against the literal string provided, where as LIKE "%keyword%" will match if a word contains the string provided.
A: This should do the trick for you:
MATCH (column) AGAINST('board*' IN BOOLEAN MODE)
Source: http://dev.mysql.com/doc/refman/5.5/en/fulltext-boolean.html
There are a lot of good examples of search queries there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Given rsync --link-dest, is it possible to determine which files were linked and which are new? I'm using rsync --link-dest to preform a differential back up of my computer. After each backup, I'd like to save out a log of the new/changed files. Is this possible? If so, how would I do it?
A: Answer from the rsync mailing list:
Use --itemize-changes
A: Here's another answer from the mailing list. There's a script by Kevin Korb:
If you want something you can run after the fact here is a tool I wrote
a while back that does a sort of diff across 2 --link-dest based backups:
http://sanitarium.net/unix_stuff/rspaghetti_backup/diff_backup.pl.txt
It will also tell you what files were not included in the newer backup
which --itemize-changes will not since it doesn't actually --delete
anything. The program is written in perl so it should be easy enough to
tweak it if it doesn't do exactly what you want.
A: For referance you can also compare using rsync to do a dryrun between hardlinked backup directories to see how they are changed.
rsync -aHin day_06_*/ day_05_* 2>&1 | grep -v '^\.d'
Shows files that are added, removed, or renamed//moved.
The later only happens if you have a re-linking program relinking files that were renamed/moved. That can be important if you say had simply renamed a directory (rsync backup breaks the links in that case).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python: super and __init__() vs __init__( self ) A:
super( BasicElement, self ).__init__()
B:
super( BasicElement, self ).__init__( self )
What is the difference between A and B? Most examples that I run across use A, but I am running into an issue where A is not calling the parent __init__ function, but B is. Why might this be? Which should be used and in which cases?
A: You should not need to do that second form, unless somehow BasicElement class's __init__ takes an argument.
class A(object):
def __init__(self):
print "Inside class A init"
class B(A):
def __init__(self):
super(B, self).__init__()
print "Inside class B init"
>>> b = B()
Inside class A init
Inside class B init
Or with classes that need init arguments:
class A(object):
def __init__(self, arg):
print "Inside class A init. arg =", arg
class B(A):
def __init__(self):
super(B, self).__init__("foo")
print "Inside class B init"
>>> b = B()
Inside class A init. arg = foo
Inside class B init
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Where should I put CMakeLists.txt files? We would like to develop a few dynamically-linked libraries in C, each for both Linux and Windows. We would like to use CMake.
How do we organize directories and where do we put those CMakeLists.txt files? (Or should we have just one?)
A: There is no single way that it must be done, but here is one possible way:
CMakeLists.txt
src/
CMakeLists.txt
lib1/
CMakeLists.txt
lib1.c
lib2/
CMakeLists.txt
lib2.c
app/
CMakeLists.txt
app.c
include/
lib1.h
lib2.h
While you can do everything in the top-level CMakeLists.txt file, it will get large and messy very quickly if your project is complex.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Is there a way to call a class "New"? Maybe a stupid question, but anyway...
Is there a way to call a class "New"?
Class New
{
..
}
Won't work of course, is there another way?
A: new is a reserved word in php. a class with name "new" is not valid php
http://www.php.net/manual/en/reserved.keywords.php
A: You cannot use (most of) PHPs keywords as identifier of classes, methods or functions. Just avoid them. However, New is a really bad classname anyway, because its anything, but not self-speaking.
A: No, the word "new" is a reserved keyword (in probably all modern languages). You can't name anything "new". See the documentation for more detail: http://www.php.net/manual/en/reserved.keywords.php
A: You can declare a class "New", but it requires some stupid workarounds to actually use it:
class Old { /* ... */ }
class_alias("Old", "New");
$New = "new";
$n = new $New;
That's the only way to circumvent the reserved keyword issue. (New and new are the same in PHP, as it is case-insensitive for bare identifiers.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mobile site with codeigniter sharing resources I have a desktop version of a site built with codeigniter ,and am creating the mobile version.
I create a sub domain, m.xyz.com whose document root is public_html/m
I have also place an index.php file in the /m folder
and edited the $system_folder and $application_folder to point the application and system folder of the desktop site in order to share controllers and models.
But when i try out the mobile domain, it still renders the desktop site.
What do i need to do to fix this
A: Use the User Agent Class: http://codeigniter.com/user_guide/libraries/user_agent.html
Use this in your controller to determine whether or not the user is on a mobile device:
if($this->agent->is_mobile())
{
// handle mobile devices
}
And then render your mobile views inside the if.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to narrow a Rectangle within a Sprite to exclude transparent pixels? I have a Sprite that contains opaque objects surrounded by transparent pixels. I also have a Rectangle that represents a part of the Sprite that I want to render using BitmapData.draw().
The problem is that the Rectangle that I obtained also contains transparent parts. How can I narrow the Rectangle to only include the opaque parts and ignore the transparent surroundings?
kapep's answer is just what I want to do, but the problem is that the source is a Sprite, not a BitmapData object, and I don't have getColorBoundsRect() on a Sprite.
A: You can use getColorBoundsRect for this.
var mask:uint = 0xFF000000; // ignore rgb, use alpha only
var transparent = 0x00000000;
var rect:Rectangle = imageBitmapData.getColorBoundsRect(mask, transparent, false);
To operate with the pixels of the sprite, it needs to be drawn to a BitmapData first (use BitmapData.draw). Then after getting a smaller rectangle with getColorBoundsRect, create a new BitmapData with the dimensions of that rectangle. The last step is to use copyPixels, to copy the area of the rectangle from first image to the new one.
var imageBitmapData:BitmapData = new BitmapData(image.width, image.height, true, 0);
imageBitmapData.draw(image);
// var rect = ... as above
var resultBitmapData:BitmapData = new BitmapData(rect.width, rect.height, true, 0);
resultBitmapData.copyPixels(imageBitmapData, rect, new Point(0,0));
A: I find your question a tad confusing, but if I do understand correctly, here's what you should do:
First, use BitmapData.draw() to take the "picture" of the Sprite, placing it in your new BitmapData instance. Then, you need to find the boundaries of the transparent area. Do this separately for each edge. Starting at each edge, look at pixels on a regular interval (e.g. every 10 pixels) and see if they're all transparent. If they are, move in towards the center by a certain number of pixels and repeat. Here's some example code (not tested!):
// Bitmap data already exists
var bmd:BitmapData; // content already exists
var isTransparent:Function = function(bmd:BitmapData, x:uint, y:uint):Boolean
{
var pixelValue:uint = bmd.getPixel32(0, 0);
var alphaValue:uint = pixelValue >> 24 & 0xFF;
return (alphaValue == 0);
};
// Look at right edge
var curX:uint = bmd.width-1;
var interval:uint = 10;
var iterations:uint = Math.ceil(bmd.height / interval);
var transparentX:uint = curX + 1;
var stillTransparent:Boolean = true;
while (stillTransparent)
{
for (var i:uint=0; i<iterations; i++)
{
var curY:int = i * interval;
if (!isTransparent(bmd, curX, curY))
{
stillTransparent = false;
break;
}
}
// If stillTransparent==true, this entire column was transparent.
// Get ready for next loop by moving in [interval] pixels
if (stillTransparent)
{
transparentX = curX
curX -= interval; // check needed if may be completely transparent
}
}
// transparentX now represents the last known x value on
// the right edge where everything was still transparent.
Finally, take the x and y results of the transparency boundary tests and use them to create a Rectangle and use BitmapData.draw to only copy the relevant non-transparent portion into a new BitmapData instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Opening New File using VBA on Mac I am using Excel 2011 for Mac and trying to open a new file.
However, I keep getting an error that file not found even though the file is there. The code I am using is below:
Dim theFile As String
theFile = "/Users/Dev/Desktop/RCM/test.xls"
Workbooks.Open FileName:=theFile
Any suggestions?
A: Mac uses a different path separator: switch your "/" to ":"
A: Make the open line:
Workbooks.Open Filename:="/Users/John/Downloads/File.xlsx"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Django custom tag: Inclusion tag with no context I've read through the custom tags and filters documentation, but I'm not seeing how this can be done. I want to make a custom tag that just renders a string. No context, just the same string literal every time. In this particular case, I would prefer this over putting {% include 'hello_world.htm' %} all over the place:
Foo, foo foo
<br>
{% hello_world %}
<br>
bar bar bar
Renders to:
Foo, foo foo
<br>
"Hello World"
<br>
bar bar bar
I feel like I should be able to do this with something like:
custom_tags.py:
from django import template
register = template.Library()
@register.inclusion_tag('hello_world.htm')
def hello_world():
return {}
# Or:
def hello_world():
return {}
register.inclusion_tag('hello_world.htm', takes_context=False)(hello_world)
No dice. I have other custom tags in custom_tags.py, I am loading them and they work fine, but always getting
Invalid block tag: 'hello_world', expected 'endblock' or 'endblock content'
The documentation says
Tags are more complex than filters, because tags can do anything.
... how do you do the simplest thing possible with tags?
A: You can do this with a simple tag: https://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#shortcut-for-simple-tags
from django import template
register = template.Library()
@register.simple_tag
def hello_world():
return u'Hello world'
then in your template you can write {% hello_world %} to render the string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to terminate tracepath when no-reply is returned? I'm writing a shell script (in Linux) to try to find all the IP address from one machine to another. Right now I'm scanning the network by limit the range of the possible IP addresses, but it won't be 100% accurate. There will be times hitting IP address that doesn't exists, when using tracepath 192.x.x.x will return me a long list of no-reply rather than waiting for it to eventually timeout. How do I quickly stop the current tracepath command inside a shell script ?
Is there anyway to read the output of the tracepath and detects if "no-reply" is returned, if so terminate the current tracepath IP address and moving on to the next one ?
A: You could try using expect to monitor the output of tracepath and do something when "no-reply" came out of it. Or maybe consider using traceroute which allows you to specify a maximum number of hops.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Focusing a window for scrolling I have some experience in Python and Java, but I dont really know the .NET framework and how to interact with Windows.
What I want to do is a little program/script (maybe I need a DLL?) that when I use the scrollwheel on my mouse, the program that is right under the pointer gets focused and scrolled. Sometimes I scroll, and because another program is focused then I have to click on the program and then scroll. Its not that annoying, but I just want to learn how I would accomplish that in Windows environment.
A: Well, not exactly the Katmouse program, but to get a start i suppose you could look at this and the tutorial for that
You might also wanna look at the new System.Reactive stuff in .net 4, i have seen people do some neat things with it. Here's one example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPad both orientations for graphics I am about to start developing an iPad app, and need to support both portrait and landscape orientations. What's the best way to approach the graphical part? As I need separate images for portrait and landscape orientations.
A: Ok, let's ignore your vagueness and tackle this from all sides.
If.
A: I need the app launch image to support both landscape and portrait:
Click on the Xcode project name in Xcode, then select the target and scroll down in the first tab until you see the launch images section. Simply right-click or drag in any material that fits the iPad's 768x1024 (or 1024x768) resolution just right or you'll get an annoying little yellow warning symbol.
B. I need my app to have a different image when it's turn (Interface Builder)
Simply select the item in question (usually a view) and go to the metrics (under that arrow looking tab in the right pane) and set individual pictures for the landscape and portrait orientations.
C. I need my app to change like the apple calculator app (Sans Interface Builder)
-(void)willRotateToInterfaceOrientation: (UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
D. I want my app to just support all orientations:
1. Go to that same target and under the "supported orientations" bit, make sure all of the orientations are highlighted.
OR
2. Put in a
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it bad to have magic variables? Say I have a variable or object I want to pass from one class to another through a test class. Let's say I have a test class, a chef class, and a waiter class.
Is it bad to do this in the test class:
chef.makeFood();
waiter.deliverFood(chef.getFood())
On that same note, should I instead do this:
chef.makeFood();
Food f = chef.getFood();
waiter.deliverFood(f);
A:
Is it bad to have magic variables?
It depends what you mean by "magic". If "magic" means to you "does something that is hard to understand or explain", then it is bad.
Is it bad to do this in the test class:
chef.makeFood();
waiter.deliverFood(chef.getFood())
I don't see anything wrong with that code per se, even if that is not how the classes are used in normal (non-test) code. (But there is a problem in the design/code that you are not showing us ...)
On that same note, should I instead do this:
chef.makeFood();
Food f = chef.getFood();
waiter.deliverFood(f);
It is OK to do that, or not to do that. It depends on whether you think that makes the code more readable. (Personally, I wouldn't bother with a local variable there, but that's just my opinion.)
On the other hand, I agree with @DaveNewton's comment about the "chef" object holding the food in "makeFood". This is certainly counter-intuitive and a bit "magic" ... if it was a deliberate design choice.
A simpler and better design would be this:
Food f = chef.makeFood();
waiter.deliverFood(f);
and entirely remove the getFood() method and the associated state variable from the Chef class.
There are a number of reasons why this is poor design / bad modelling:
*
*In the intuitive sense, it means that the chef object has to "stand around holding the plate" until the waiter takes it.
*From the class modelling perspective, you have a state variable that that is not necessary to the implement the Chef's behaviour.
*From the practical programming perspective, that means that:
*
*the code will be hard(er) to understand when you look at it in 12 months time, and
*the Chef API will be difficult to use in a multi-threaded kitchen simulation.
(If this is what you meant by a "magic variable", then it is bad ... see above.)
A: Is hard to generalize on this example.
In this simple example, there is probably not a reason for chef to keep a reference to `makeFood()', so it should be returned directly. (And then getFood() can be removed)
But there are plenty of other scenarios where it The Right Thing to keep an internal state, like for instance a StringBuilder - or more complex "builder" , and then return the result when its fine.
The local variable usually ends up there when debugging.... It doesn't really matter.
A: Well this isn't a magic variable or anything of the sort, instead here:
chef.makeFood();
waiter.deliverFood(chef.getFood())
The first one requires less lines, and arguably could be better if you do not need the reference to the newly created Food object, However many could argue that even if you don't need the reference, the code below is more readable and clear:
chef.makeFood();
Food f = chef.getFood();
waiter.deliverFood(f);
In general you should always try to go with the more readable code, because you never know who will be maintaining that code later on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Manually Updating Model in Entity Framework I am new to .NET MVC (Learning). I have the following method in Controller(this is not clean code and I am learning)
[HttpPost]
public ActionResult Edit(ProductCategoryLocation viewModel)
{
if (ModelState.IsValid)
{
var product = viewModel.Product;
product.Category = db.Categories
.Where(c => c.ID == viewModel.CategoryID).Single();
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
The View Model Has Product, Location and Category Types and CategoryID and LocationID. In the POST method I am getting the category ID from the View Model, Update the Category of the Product and then Update the Model to the Database. Any changes to the properties of Products gets saved except the manually changed Category.
Is there a mistake / Am I missing something?
Is this the right way of doing update using View Model?
A: You can directly assign CategoryID of the view model to CategoryID of the product. This way you do not have to retrieve the category from the database.
[HttpPost]
public ActionResult Edit(ProductCategoryLocation viewModel)
{
if (ModelState.IsValid)
{
var product = viewModel.Product;
product.CategoryID = viewModel.CategoryID;
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
If you do not have a scalar property CatagoryID you have to define it in the Product class
public class Product
{
public int ID { get; set; }
//other properties
public int CategoryID { get; set; }
public virtual Category Category { get; set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Extract a string using regular expressions I'm probably not using the right search term, because I keep finding
'matching\validating' string with regex (returns boolean) while I want is to extract a string from an other string.
How can I extract some parts of a string using a regex pattern?
A: It's matching that you are looking for. The Regex.Match and Regex.Matches methods use a regular expression to find one or several parts of a string, and returns a Match or MatchCollection with the result.
Example:
string input = "Some string with 123 numbers in it. Yeah 456!";
MatchCollection result = Regex.Matches(input, @"\d+");
foreach (Match m in result) {
Console.WriteLine(m.Value);
}
Output:
123
456
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: NSAutoreleasePool and class variables I'm getting what looks like a crash due to overreleasing but as far as I can tell I'm not doing anything wrong, however I may have the wrong idea about AutoreleasePools and class variables.
If I have a class variable:
UIImageView *imageView;
and I allocate it in a thread like so:
- (void)setupThreaded {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage *image = [UIImage imageNamed:@"myimage.png"];
imageView = [[UIImageView alloc] initWithImage:image];
[self performSelectorOnMainThread:@selector(addViewOnMainThread) withObject:nil waitUntilDone:YES];
[pool release];
}
- (void)addViewOnMainThread {
[self.view addSubView:imageView];
}
I'm currently occasionally getting an error suggesting that either imageView was prematurely released OR that imageView's image is getting prematurely released.
What could be causing that?
A: It is extremely unusual to store a view in a class variable. Why are you doing this?
It is, in general, illegal to access UIView on background threads. The docs are a little dodgy on whether construction of a UIView is legal on a background thread, but once you dive into initWithImage:, it definitely is not explicitly supported and is probably not allowed.
If there is some reason you're creating the UIImage on a background thread, that's fine, but then just pass the UIImage itself to the main thread and create the view there. You don't need a class variable to pass it between the threads. Just pass it as the object to performSelectorOnMainThread:withObject.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I target every other iframe using css? I am trying to target every other iframe in the screenshot below.
Can I use nth-child for this? Maybe something like the code below (although this doesn't work)?
#main iframe:nth-child(2n+2)
A: With that exact HTML structure, you need this selector:
#main iframe:nth-child(4n+2)
If you'd prefer to start from the first iframe instead of the second, remove the +2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PHP AJAX Registration form submission tutorial Can anyone please help me in finding good tutorials for php/jquery/ajax form submission validating each of the fields from the php code(server side validation). I have seen many tutorials on the web, but most of them show validating errors as a group. I want each of the error to be displayed next to the form field in the result. I have tried using php arrays to pass results into ajax using json... but its not working.
Any help will be great.
Thanks in advance.
A: I would suggest using JSON, which is specially designed for AJAX.
On the server side:
$form_fields = array(); // Holds errors in the form
$form_fields['field1'] = true;
$form_fields['field2'] = 'Error bla bla';
header('Content-type: application/json');
echo json_encode($form_fields);
and in javascript:
// put into "data" the response from the server
var responseObj = $.parseJSON(data);
// Check field1
if(responseObj.field1 === true) alert("Field1 is valid!");
else alert('Field1 is not valid: "'+responseObj.field1+'"!');
// Check field2
if(responseObj.field2 === true) alert("Field2 is valid!");
else alert('Field2 is not valid: "'+responseObj.field2+'"!');
You can build it however you like and you can add more values to the json object on the server side or structure it however you want.
The server side will make a string like:
{"field1":true,"field2":"Error bla bla"}
Which is practically javascript, and then on the javascript side the browser decodes the string into a javascript object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Fixing a style sheet for IE 7 8 9 I’m not sure if it’s acceptable to ask this kind of thing but since I have no idea how to solve it:
I created an HTML5 CSS3 layout from scratch and it looks exactly how I want in Firefox 5, Safari 5.1 and Chrome 12 for Mac.
But when I use https://browserlab.adobe.com/ for the same browsers, it appears a little broken (footer in the middle, background repeat, sub menus visible).
That made me wonder if I could trust Adobe’s tool or not.
Then when I use browserlab or http://ipinfo.info/netrenderer/ to view it in IE it’s totally broken (to be expected).
• In IE9 the radial background is missing, menus are not styled or rotated and thrown to the far right, main content appears below the sidebar and its width is not respected (strange because in an older version of my layout it displayed just fine in IE9)
• In IE8 some times it’s the same thing with sidebar list taking all the space, sometimes it’s just a black page.
• In IE7 if it’s not the black or white page, it’s worse than in IE8 with the main content being unreadable.
I use two JS, one that fixes many IE issues and the other that brings HTML5 tags support but they seem to conflict or at least to be responsible for the black pages.
I do hope that it in fact displays fine in mozilla and webkit. I’m worried about IE because I have no idea how to fix it and 13% of my visitors use it (not negligible).
I would greatly appreciate any help as this is blocking me from launching the site (which is already overdue).
http://protostype.free.fr/index-sitepointversion4.php
EDIT1: validated HTML, CSS gives errors, not sure anything can be done about it
EDIT2: fixed biggest layout problems, new link
A: Firstly, as others have said, it seems that html5shiv isn't working properly for you. I had this same problem with html5shiv, and I could never work out why, but I found that replacing it with Modernizr did the trick for me (Modernizr includes the same functionality plus a bunch of other good stuff; see their site for more info).
That may well fix a lot of the issues.
Stuff like the radial background and border-radius on the tabs might be fixable using CSS3Pie.
You're using transparent in your stylesheets. I'm fairly sure this isn't supported, at least in IE7 (not sure about IE8?). There are a number of work-arounds for IE to support stuff like this, but none of them are particularly great.
The position of your rotated menus is wrong because of differences in the way IE rotates elements compared with other browsers. IE's filter style uses a different point of origin for the rotation: it rotates around the top-left corner, whereas CSS3-compliant browsers default to rotating around the centre point.
The easiest way to fix this is to use the CSS3 transform-origin style to get the CSS3 browsers to act the same as IE (I'd prefer to change IE's origin point, but it's much more painful to change it in IE).
You're using CSS selectors like this:
.ul_nav_main li a:not(:last-child):after
That won't work in IE8. Neither :not nor :last-child are supported by IE8 or earlier, and :after isn't supported in IE7. You're also using some complex attribute selectors, which won't work in older IEs either.
I think that deals with most of the issues I could see. If you're still having problems once you've gone through all that lot, I'd suggest asking again (but make your question more specific next time! it'll be easier to answer)
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Localisation on a SAAS application Scenario
We have a SAAS product that has an Admin back-end with a public front-end. We want to give the user the option to change what language their front-end displays. There will be the option of 7+ different languages. Our product is built on C# and MVC3. The front-end only contains about 400 words. What is the best way to handle this? Could I store the different languages in resx files and have a flag in the DB to say which language the admin has chosen?
So the admin selects his language from a dropdown list and then all his public facing side will convert to that language.
I have never done anything like this before so any advice on potential pitfalls would be greatly appreciated.
Thanks
A: Resource files are the most common way to solve it. And storing the language choice in a database is a good idea.
I would use OnActionExecuting in your base controller to set the current language (Thread.CurrentUICulture)
Update
Specify the correct culture in the beginning of each request (in your base controller)
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
var cultureId = ((YourUserObj)Session["CurrentUser"]).PreferedLanguage;
var userCulture = new CultureInfo(cultureId);
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = userCulture;
}
Then let .NET load the correct resource files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Different images in table View? I am quite new to the forum and id love some assistance. I have a table view and im able to add cells to it via different buttons on a seperate page. I want to have each button add a new cell but with a different image. So for example. Button 1 will add a cell and an image named @"button1.png" button two will add a cell with an image named @"button2.png" and so on. But im having trouble adding the image to the cell. I can do it in the cellForRow, but not in a button method. Could somebody please help me? I have tried this in the buttons:
EDIT
button used to add cell and image:
- (IBAction)outlet1:(id)sender {
[cart.cells addObject:@"1"];
[cart.cell.imageView setImage:[UIImage imageNamed:@"paddle1.png"]];
}
cellForRow
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
//cell.imageView.image = [UIImage imageNamed:@"paddle1.png"];
[myTableView reloadRowsAtIndexPaths:indexPath.row
withRowAnimation:UITableViewRowAnimationNone];
cell.textLabel.text = [cells objectAtIndex:indexPath.row];
return cell;
}
A: The way UITableView renders is that it asks for a cell for a row whenever it is about to render that row, generates the pixels that it needs, and then forgets about the cell. Since most of the structure of a cell doesn't change from row to row, there is the capability to re-use the same cell object for rendering multiple rows and just (eg) change label text or an imageView's image.
Hence, changing a cell after a row has been rendered doesn't change the appearance of the row. You need to tell the table to re-render that row:
[myTable reloadRowsAtIndexPaths:indexPathArray withRowAnimation:foo];
This will cause the OS to call the tableView's Data Source delegate cellForRowAtIndexPath: message, which then needs to create and/or modify a cell, which then gets rendered.
Cells aren't rows. Cells are objects used to render rows.
A: If I understand the problem, you want a cart object to display its picture in a table cell. If this is true, then why don't you add an UIImage view to the cart object. At an appropriate time (somewhere where the object is select by the user) store the image of the item to your UIImage view of the object. Then when you go to set the cart object into your table, you have then objects name (presumably) and it's image in your object and you can then easily set the cell's image = to your objects image. Don't try to have the logic of which image to display inside the "cellForRowAtIndexPath" method. Store the image and all attributes with your object and use the objectAtIndex to point to your complete object and set your cell based on your objects attributes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use EJB 3.1 Singleton Bean as Client to Multiple Remote Stateful Session Beans I'm very new to EJB 3.1 and am trying to solve a server side problem; perhaps someone could offer some guidance.
I have a state machine that represents the shared state of multiple users in my application. I'm attempting to model this state machine as a Stateful Session Bean; since there are multiple users represented by this State Machine, I introduced a Singleton Session bean that is the actual Client of the StateMachine and all of the users end up being "Clients" to the Singleton bean. My problem arises when I want to lifecycle multiple StateMachines throughout the life of the Application.
I would like my Singleton bean (the "Manager") to handle client requests and distribute to the appropriate StateMachine - how would I access specific instances of that Stateful bean? To add further complexity, I'm trying to access these StateMachine beans remotely (if it were local, I'd just create instances of these things as members of the Manager).
Anyway, I hope this is clear. I feel like I'm missing some fundamental point of EJB design; y'all will tell me if that's the case.
A: Singletons have been introduced in EJB 3.1 providing the ability to share state between multiple instances as described in A Sampling of EJB 3.1.
Singletons
A long-standing omission in the EJB API has been the ability to easily
share state between multiple instances of an enterprise bean component
or between multiple enterprise bean components in the application. By
contrast, the Java EE web application programming model has always
provided this type of capability through a ServletConfig object. In
EJB 3.1, this omission has been addressed with the introduction of
singleton beans, also known as singletons.
A singleton is a new kind of session bean that is guaranteed to be
instantiated once for an application in a particular Java Virtual
Machine (JVM)*. A singleton is defined using the @Singleton
annotation, as shown in the following code example:
@Singleton public class PropertiesBean {
private Properties props;
private int accessCount = 0;
public String getProperty(String name) { ... }
public int getAccessCount() { ... }
} Because it's just another flavor of session bean, a singleton can
define the same local and remote client views as stateless and
stateful beans. Clients access singletons in the same way as they
access stateless and stateful beans, that is, through an EJB
reference. For example, a client can access the above PropertiesBean
singleton as follows:
@EJB private PropertiesBean propsBean;
...
String msg = propsBean.getProperty("hello.message"); Here, the
container ensures that all invocations to all PropertiesBean
references in the same JVM are serviced by the same instance of the
PropertiesBean. By default, the container enforces the same threading
guarantee as for other component types. Specifically, no more than one
invocation is allowed to access a particular bean instance at any one
time. For singletons, that means blocking any concurrent invocations.
However, this is just the default concurrency behavior. There are
additional concurrency options that allow more efficient concurrent
access to the singleton instance.
Have a look at Java EE6 Events about how to send notifications using events.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image flicker in a JFrame I'm very frustrated because I used knowledge I gained from a book on Java to set up and paint to a JFrame for my program, but it seems like no one else in the universe sets it up the same way and the only way to fix it would be a large amount of recoding. So help!
I get horrific image flicker with my program. I have no idea how to get rid of it. I know how to double buffer an applet, but this is not an applet so it does me no good. I have one "set" of images that never changes (P1_xxx) and then I have a "Background" (not sure that's the right terminology) image that changes when other variables change. Namely, when the player completes laps. They both flicker. A lot. Here's the code.
Everything I've read almost answers my question but is intended for the JFrame being set up a different way, within a JPanel or something else like that.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Game extends JFrame {
//all images
URL url1=null, url2=null, url3=null, url4=null, urlhome1=null;
Image img1,img2,img3,img4,home1;
//screen width
final int WIDTH = 1080, HEIGHT = 726;
//car
Rectangle p1 = new Rectangle(390,620,WIDTH/35,WIDTH/35);
//constructor
public Game() {
//create the JFrame
super("Racer Doom Squared");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//load the urls
try {
url1 = this.getClass().getResource("Images/P1_Up.png");
url2 = this.getClass().getResource("Images/P1_Right.png");
url3 = this.getClass().getResource("Images/P1_Down.png");
url4 = this.getClass().getResource("Images/P1_Left.png");
urlhome1 = this.getClass().getResource("Images/Home1.png");
}
catch(Exception e){}
//attach URLs to Images
img1 = Toolkit.getDefaultToolkit().getImage(url1);
img2 = Toolkit.getDefaultToolkit().getImage(url2);
img3 = Toolkit.getDefaultToolkit().getImage(url3);
img4 = Toolkit.getDefaultToolkit().getImage(url4);
home1 = Toolkit.getDefaultToolkit().getImage(urlhome1);
public void paint(Graphics g){
super.paint(g);
if(p1Laps==0) {
//home1
g.drawImage(home1,0,0,WIDTH,HEIGHT,this);
}
int scale = (WIDTH/HEIGHT)*3;
//Up
int p1width1 = img1.getWidth(this);
int p1height1 = img1.getHeight(this);
int w1 = scale*p1width1;
int h1 = scale*p1height1;
//Right
int p1width2 = img2.getWidth(this);
int p1height2 = img2.getHeight(this);
int w2 = scale*p1width2;
int h2 = scale*p1height2;
//Down
int p1width3 = img3.getWidth(this);
int p1height3 = img3.getHeight(this);
int w3 = scale*p1width3;
int h3 = scale*p1height3;
//Left
int p1width4 = img4.getWidth(this);
int p1height4 = img4.getHeight(this);
int w4 = scale*p1width4;
int h4 = scale*p1height4;
if(p1Direction==UP) {
g.drawImage(img1,p1.x,p1.y,(int)w1,(int)h1,this);
}
if(p1Direction==RIGHT) {
g.drawImage(img2,p1.x,p1.y,(int)w2,(int)h2,this);
}
if(p1Direction==DOWN) {
g.drawImage(img3,p1.x,p1.y,(int)w3,(int)h3,this);
}
if(p1Direction==LEFT) {
g.drawImage(img4,p1.x,p1.y,(int)w4,(int)h4,this);
}
}
A: What you are reading is telling to draw in the paintComponent method of a JPanel, not in a JFrame. Otherwise you lose the benefits of double buffering and other Swing goodies, so I'd believe it and follow it. Then add the JPanel to your JFrame.
If this still confuses, please ask, but also supply more information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Should displaying an unsigned char* & an signed char* output exactly the same result I am unsure if I am correctly translating/converting a unsigned char* to a regular signed char*?
The unsigned char* is a string that has been hashed. Does the following code correctly convert an unsigned char* to signed char*?
std::string message = "to be encrypted";
unsigned char hashMessage[SHA256_DIGEST_SIZE];
SHA256::getInstance()->digest( message, hashMessage );
// is this conversion correct
char* hashMessageSigned = reinterpret_cast<char*>(hashMessage);
printf("Unsigned Char Hash: %s\n", hashMessageSigned); // The 2 printf's print out exactly the same strings is that correct?
printf("Signed Char Hash: %s\n", hashMessage);
A: You're not converting anything here. Both printfs are instructed to treat the data as printable strings.
Signed or unsigned is a matter of interpretation. 0xFF can be 255 or -1, depending on how you interpret that. The "sign" of the type is the instruction that helps the compiler to interpret the data.
But in this case you don't treat the data as numbers at all, you treat it as strings, and then the interpretation is totally different: 0xFF is the character at the place 255 of the ASCII table. There's no sign there.
Just to be sure you got it: reinterpret_cast<char*> doesn't convert the data, it converts the way the compiler treats the pointer. The %s instructs how the printf should treat the pointer, and is unrelated to what the compiler was instructed to do before (and is done during run time).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to interpret the function type in Haskell? My code is the following
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving (Show)
f x = x + 1
myTree = Node (Node (Leaf 2) (Leaf 3)) (Leaf 4)
maptree f (Leaf a)= Leaf (f a)
maptree f (Node xl xr ) = Node (maptree f xl) (maptree f xr)
which can add one to the Leaf element in the tree.
I further look at the function type which are
*Main> let maptree f (Leaf a)= Leaf (f a)
maptree :: (t -> a) -> Tree t -> Tree a
*Main> let maptree f (Node xl xr ) = Node (maptree f xl) (maptree f xr)
maptree :: t -> Tree t1 -> Tree a
What do t, a, and t1 mean over here? Is there any reference that I can read for those stuffs?
Thanks.
A: Identifiers beginning with a lower case letter, like t, a and t1, are type variables when used in a type context. They are placeholders which can be specialized to any type. See this answer for more information on how to read type signatures.
Also note that in GHCi, your example will first define one function which only handles the Leaf case, and then replace it with another which only handles the Node case, unlike in Haskell source files where they will be two cases of the same function. To specify multiple equations for a function in GHCi, separate them with a semicolon:
*Main> let maptree f (Leaf a) = Leaf (f a); maptree f (Node xl xr) = Node (maptree f xl) (maptree f xr)
or use multiline mode:
*Main> :{
*Main| let maptree f (Leaf a) = Leaf (f a)
*Main| maptree f (Node xl xr) = Node (maptree f xl) (maptree f xr)
*Main| :}
A: We'll start with the first signature:
(t -> a) -> Tree t -> Tree a
This essentially says, "Given a function that takes something of type t and produces an a and also a Tree containing items of type t, produce a Tree containing elements of type a.
t and a are completely arbitrary names that GHCi generated; we could have easily said:
(originalType -> newType) -> Tree originalType -> Tree newType
Although most programmers would write:
(a -> b) -> Tree a -> Tree b
Now, the second signature:
t -> Tree t1 -> Tree a
This signature's strange because, like Hammar pointed out, the two maptree definitions you wrote in GHCi are completely independent. So let's look at the second definition all by itself:
maptree f (Node xl xr) = Node (maptree f xl) (maptree f xr)
Here, the type of f does not matter as you don't apply it to any arguments and you only pass it to maptree, which recursively doesn't care what type f is. So let's give f type t, as it doesn't matter.
Now, similarly, there's no constraint on xl and xr, as they are only passed to maptree which doesn't know their types except that it should be a Tree. Thus, we might as well call their type Tree t1.
We know this function will return a Tree because of the Node constructor, but the previous two types we looked at have no bearing on the type of elements in the tree, so we may as well call it Tree a.
As an example, let's see what happens when we expand the following:
maptree True (Node (Leaf 0) (Leaf 1))
= Node (maptree True (Leaf 0)) (maptree True (Leaf 1))
Which then fails because there's no way for maptree to expand a Leaf in this case.
However, the types work out:
True :: t
Node (Leaf 0) (Leaf 1) :: Tree t1
0 :: t1
1 :: t1
So that signature was very odd, but it does make sense. Remember to not overwrite definitions, I guess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I set the camera preview size to fullscreen with Android API? I am very new to Android development, and I am trying to get a simple camera application setup. So far I have a working camera application that has "switch camera" and "take picture" buttons inside the menu which are working fine.
The only problem I am having, is I am trying to figure out how to get the display to be fullscreen. Right now, the camera is only showing up in the very middle of the screen, and is only taking up about 1/4 of the screen.
MainActivity Code
package assist.core;
import android.app.Activity;
import android.app.AlertDialog;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends Activity {
private final String TAG = "MainActivity";
private Preview mPreview;
Camera mCamera;
int numberOfCameras;
int cameraCurrentlyLocked;
//The first rear facing camera
int defaultCameraId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Create a RelativeLayout container that will hold a SurfaceView,
//and set it as the content of our activity.
mPreview = new Preview(this);
setContentView(mPreview);
//Find the total number of cameras available
numberOfCameras = Camera.getNumberOfCameras();
//Find the ID of the default camera
CameraInfo cameraInfo = new CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if(cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
defaultCameraId = i;
}
}
}
@Override
protected void onResume() {
super.onResume();
//Open the default i.e. the first rear facing camera.
mCamera = Camera.open();
cameraCurrentlyLocked = defaultCameraId;
mPreview.setCamera(mCamera);
}
@Override
protected void onPause() {
super.onPause();
//Because the Camera object is a shared resource, it's very
//Important to release it when the activity is paused.
if (mCamera != null) {
mPreview.setCamera(null);
mCamera.release();
mCamera = null;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate our menu which can gather user input for switching camera
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.camera_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Handle item selection
switch (item.getItemId()) {
case R.id.switchCam:
//Check for availability of multiple cameras
if (numberOfCameras == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(this.getString(R.string.camera_alert)).setNeutralButton("Close", null);
AlertDialog alert = builder.create();
alert.show();
return true;
}
//OK, we have multiple cameras.
//Release this camera -> cameraCurrentlyLocked
if (mCamera != null) {
mCamera.stopPreview();
mPreview.setCamera(null);
mCamera.release();
mCamera = null;
}
//Acquire the next camera and request Preview to reconfigure parameters.
mCamera = Camera.open((cameraCurrentlyLocked + 1) % numberOfCameras);
cameraCurrentlyLocked = (cameraCurrentlyLocked + 1) % numberOfCameras;
mPreview.switchCamera(mCamera);
//Start the preview
mCamera.startPreview();
return true;
case R.id.takePicture:
mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Called when shutter is opened
*/
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
}
};
/**
* Handles data for raw picture when the picture is taken
*/
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
}
};
/**
* Handles data for jpeg picture when the picture is taken
*/
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// Write to SD Card
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",
System.currentTimeMillis()));
outStream.write(data);
outStream.close();
}
catch (FileNotFoundException e) {
Log.e(TAG, "IOException caused by PictureCallback()", e);
}
catch (IOException e) {
Log.e(TAG, "IOException caused by PictureCallback()", e);
}
}
};
}
Preview Class Code
package assist.core;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import java.io.IOException;
/**
*
* @author cmetrolis
*/
class Preview extends ViewGroup implements SurfaceHolder.Callback {
private final String TAG = "Preview";
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;
Preview(Context context) {
super(context);
mSurfaceView = new SurfaceView(context);
addView(mSurfaceView);
//Install a SurfaceHolder.Callback so we get notified when the
//underlying surface is created and destroyed.
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void setCamera(Camera camera) {
mCamera = camera;
if(mCamera != null) {
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
requestLayout();
}
}
public void switchCamera(Camera camera) {
setCamera(camera);
try {
camera.setPreviewDisplay(mHolder);
}
catch (IOException exception) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
}
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
camera.setParameters(parameters);
}
/**
* Called to determine the size requirements for this view and all of its children.
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//We purposely disregard child measurements because act as a
//Wrapper to a SurfaceView that centers the camera preview instead of stretching it.
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if(mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
/**
* Called when this view should assign a size and position to all of its children.
* @param changed
* @param l
* @param t
* @param r
* @param b
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if(changed && getChildCount() > 0) {
final View child = getChildAt(0);
final int width = r - l;
final int height = b - t;
int previewWidth = width;
int previewHeight = height;
if(mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
// Center the child SurfaceView within the parent.
if(width * previewHeight > height * previewWidth) {
final int scaledChildWidth = previewWidth * height / previewHeight;
child.layout((width - scaledChildWidth) / 2, 0, (width + scaledChildWidth) / 2, height);
}
else {
final int scaledChildHeight = previewHeight * width / previewWidth;
child.layout(0, (height - scaledChildHeight) / 2, width, (height + scaledChildHeight) / 2);
}
}
}
/**
* This is called immediately after the surface is first created
* @param holder
*/
public void surfaceCreated(SurfaceHolder holder) {
try {
if(mCamera != null) {
mCamera.setPreviewDisplay(holder);
}
}
catch (IOException e) {
Log.e(TAG, "IOException caused by setPreviewDisplay()", e);
}
}
/**
* This is called immediately before a surface is being destroyed
* @param holder
*/
public void surfaceDestroyed(SurfaceHolder holder) {
//Surface will be destroyed when we return, so stop the preview.
if(mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
}
/**
* This is called immediately after any structural changes (format or size) have been made to the surface
* @param holder
* @param format
* @param w
* @param h
*/
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setDisplayOrientation(90);
requestLayout();
mCamera.setParameters(parameters);
mCamera.startPreview();
}
/**
* Returns the best preview size
* @param sizes
* @param w
* @param h
* @return Size
*/
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio = (double) w / h;
if (sizes == null) return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
for(Size size : sizes) {
double ratio = (double) size.width / size.height;
if(Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
if(Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
if(optimalSize == null) {
minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if(Math.abs(size.height - targetHeight) < minDiff) {
optimalSize = size;
minDiff = Math.abs(size.height - targetHeight);
}
}
}
return optimalSize;
}
}
camer_menu.xml code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<item android:id="@+id/switchCam"
android:title="@string/switch_cam" />
<item android:id="@+id/takePicture"
android:title="@string/take_picture"
android:onClick="snapPicture"
android:layout_gravity="center" />
</menu>
UPDATE
I tried changing the code in the Preview constructor to the following.
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.setLayoutParams(lp);
mSurfaceView = new SurfaceView(context);
mSurfaceView.setLayoutParams(lp);
addView(mSurfaceView);
This did not crash, but it also did not make the camera fullscreen.
A: Since you're using setContentView with your custom Preview class that derives from ViewGroup, just pass a ViewGroup.LayoutParams telling it to fill it's parent.
Something like this:
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
Preview.setLayoutParams(lp);
A: I fixed it by removing the following code from the Preview class,
if(mPreviewSize != null) {
previewWidth = mPreviewSize.width;
previewHeight = mPreviewSize.height;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Update MySQL tables with PHP checkboxes Here's my table:
id | name | check
------------------
1 | Paul | no
2 | Bob | no
3 | Tom | no
id is an INT, name and check TEXT.
Here's the script:
<?php
include("database.php");
$dbc= new dbClass();
$query = $dbc->dbRunSql("select * from names order by name");
while ($result = mysql_fetch_array($query)){ ?>
<form method="POST" action="">
<input type="checkbox" name="names[]" value="yes"/><?php echo $result['name'];
} ?>
<br>
<input name="submit" type="submit" />
</form> <?php
if(isset($_POST["submit"])){
foreach ($_POST['names'] as $entry){
$dbc= new dbClass();
$query = $dbc->dbRunSql("update `names` set `check`='$entry';");
}
}
?>
This script works but updates all the rows, not the ones I check.
I have 2 questions:
1) What should I change to make it work correctly? (updating the ones that I check)
2) The ones that I don't check, how to update them in the "check" column as "no"
I hope you could understand what I meant.
Thanks in advance.
A: You should do a WHERE clause in your query. What you currently have updates every row because MySQL doesn't know what to update. This is a fix for that problem:
$query = $dbc->dbRunSql("update `names` set `check`='$entry' WHERE id='$id';");
$id needs to be defined by you correctly, with something like this:
<input type="checkbox" name="names[<?php echo $result['id']; ?>" value="yes"/>
and then in your foreach loop:
foreach ($_POST['names'] as $id => $entry){
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Error 'Program.Number' is a 'type' but is used like a 'variable Error 'Program.Number' is a 'type' but is used like a 'variable
i keep geting the above error when i try to run this program what am i doing wrong
using System;
class Program
{
enum Number{ standard = 1, express = 2, same = 3};
const int A = 1, B = 2;
const int Y = 3, N = 4;
static void Main()
{
double cost, LB;
int numValues, Number_of_items ;
Console.WriteLine("please enter the type of shiping you want");
Console.WriteLine("Enter 1:standard shipping.");
Console.WriteLine("Enter 2:express shipping.");
Console.WriteLine("Enter 3:same day shipping.");
switch ((Number))
{
case Numbers.standard:
Console.WriteLine("thankyou for chooseing standerd shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
{ if (A==A)
{
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 3 * Number_of_items;
Console.Write("is this shipment going to alaska or Hawaii? (y or n)");
if (Y==Y)
{
cost = cost + 2.50;
Console.WriteLine("Total cost is {0}." , cost);
}
else
Console.WriteLine("total cost is {0}." , cost);
}
else
Console.Write("please enter the weiht in pounds");
LB = double.Parse(Console.ReadLine());
cost = 1.45 * LB;
Console.WriteLine("is this shipment going to alaska or Hawaii? (y or n)");
}
if (Y==Y)
{
cost = cost + 2.50;
Console.WriteLine("Total cost is {0}." , cost);
}
else
Console.WriteLine("total cost is {0}." , cost);
break;
case Numbers.express:
Console.WriteLine("thankyou for chooseing Express Shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
{ if (A==A)
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 4 * Number_of_items;
{
Console.Write("is this shipment going to alaska or Hawaii? (y or n)");
if (Y==Y)
{
cost = cost + 5.00;
Console.WriteLine("Total cost is {0}." , cost);
}
else
Console.WriteLine("total cost is {0}." , cost);
}
if(B==B)
Console.Write("please enter the weiht in pounds");
LB = double.Parse(Console.ReadLine());
cost = 2.50 * LB;
Console.WriteLine("is this shipment going to alaska or Hawaii? (y or n)");
}
if (Y==Y)
{
cost = cost + 5.00;
Console.WriteLine("Total cost is {0}." , cost);
}
else
Console.WriteLine("total cost is {0}." , cost);
break;
case Numbers.same:
Console.WriteLine("thankyou for chooseing Same Day Shipping");
Console.WriteLine("please choose a catagory");
Console.Write("Type A or B to make your selection");
if (A == A)
Console.Write("please enter the number of items");
Number_of_items = int.Parse(Console.ReadLine());
cost = 5.50 * Number_of_items;
Console.Write("is this shipment going to alaska or Hawaii? (y or n)");
if (Y==Y)
{
cost = cost + 8.00;
Console.WriteLine("Total cost is {0}." , cost);
}
else
Console.WriteLine("total cost is {0}." , cost);
if (B==B)
Console.Write("please enter the weiht in pounds");
LB = double.Parse(Console.ReadLine());
cost = 3.00 * LB;
Console.WriteLine("is this shipment going to alaska or Hawaii? (y or n)");
if (Y==Y)
{
cost = cost + 8.00;
Console.WriteLine("Total cost is {0}." , cost);
}
else
Console.WriteLine("total cost is {0}." , cost);
break;
}
numValues = 1;
Console.ReadLine();
}//End Main()
}//End class Program
A: The error is here:
switch((Number))
I think you were about to cast something to Number but forgot to. So I'll assume you meant:
int input;
while(!int.TryParse(Console.ReadLine(), ref input) || input < 1 || input > 3) {
Console.WriteLine("Please enter a valid option!");
}
switch((Number)input)
A: You are switching on the type Number, must use an instance of Number.
for example:
switch ((Number)myNumber)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Doctrine2 ManyToMany doesn't execute listener events I have the following db structure:
User > UserRole < Role
UserId UserRoleId RoleId
Name UserId Name
RoleId
Active
CreationDate
And my doctrine2 classes are defined like this:
/**
* @var Roles
*
* @ORM\ManyToMany(targetEntity="SecRole")
* @ORM\JoinTable(name="SEC_USER_ROLE",
* joinColumns={@ORM\JoinColumn(name="SEC_USER_ID", referencedColumnName="SEC_USER_ID")},
* inverseJoinColumns={@ORM\JoinColumn(name="SEC_ROLE_ID", referencedColumnName="SEC_ROLE_ID")}
* )
*/
private $userRoles;
public function __construct() {
parent::__construct();
$this->userRoles = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addSecRole(\myEntity\SecRole $role)
{
$exists = $this->userRoles->exists(function($key, $elem) use($role) {
return isset($elem) && $elem->getSecRoleCode() == $role->getSecRoleCode();
});
return !$exists && $this->userRoles->add($role);
}
To add a new role to the user, I do:
$r = $rolerep->findOneBySecRoleCode('SystemAdmin');
$u = $userrep->findOneByUserLogin('sysadmin');
if (isset($r) && isset($u))
{
if ($u->addSecRole($r)) {
$em->flush();
}
}
And everything works fine EXCEPT for one thing. The lifecycle events are not being called for SecUserRole entity!. And my suspicion is that since Doctrine is "adding" the new SecUserRole record for itself, then it doesn't call the events for it.
I'm listening to prePersist, preUpdate, preDelete. Neither get the new record. I tried onFlush, but it seems it doesn't get it either.
Is there something I'm missing, how could I solve this? doing the inserts by myself? Sure that's a solution, but that leaves me to do also the queries myself, which is something I don't want to do.
Well, thanks in advance
KAT LIM
A: So far, haven't found the best way BUT seems that Doctrine assumes that your Join Table will be "autogenerated" so it assumes that it doesn't have nor need more than the two joining keys (UserId, RoleId).
What I did to solve it was to stop using a ManyToMany, but use a OneToMany relationship to SecUserRole table. So inside the addSecRole method, I inserted the new object and then flushed the EM on the outside (like the example above).
It seems that's the best way I could do. I got the idea from this http://www.zendcasts.com/ where there is one cast specially for ManyToMany mappings.
Well, hope this helps to all
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Turn a multidimensional PHP array into a bidimensional array I'm trying to achieve something I naively believed would be simple: flattening a multidimensional array (which could have many nested levels) but still having arrays as a result. Ideally I'm looking for a function that can iterate through 10+ nested levels and can handle different set of keys (not necessarily always the same).
In short, turning this:
Array
(
[0] => Array
(
[0] => Array
(
[index] => -1
[qty] => 77
[id] => 7
)
[1] => Array
(
[index] => -1
[qty] => 83
[id] => 8
)
)
[1] => Array
(
[0] => Array
(
[index] => -1
[qty] => 75
[id] => 13
)
[1] => Array
(
[index] => -1
[qty] => 60
[id] => 14
[msr] => g
)
)
[2] => Array
(
[index] => -1
[qty] => 10
[id] => 12
)
)
Into this:
Array
(
[0] => Array
(
[index] => -1
[qty] => 77
[id] => 7
)
[1] => Array
(
[index] => -1
[qty] => 83
[id] => 8
)
[2] => Array
(
[index] => -1
[qty] => 75
[id] => 13
)
[3] => Array
(
[index] => -1
[qty] => 60
[id] => 14
[msr] => g
)
[4] => Array
(
[index] => -1
[qty] => 10
[id] => 12
)
)
This is what I had and thought would work, but I end up with a flat array with no key information (and if I want keys, every iteration overwrites the previous values and I end up with just the last array of them all):
function flatten_multi_array(array $array){
$ret_array = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
$ret_array[] = $value;
}
return $ret_array;
}
A: function dig($source, &$out){
foreach ($source as $k => $v){
if (isset($v["index"]){
$out[] = $v;
} else {
dig($v, $out);
}
}
}
and that's it.
usage:
$out = array();
$source = array(); // your magic nested array
dig($source, $out);
and now $out has what you need.
A: If you're still looking for the RecursiveIteratorIterator approach, see the following:
foreach(new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($array)), RecursiveIteratorIterator::SELF_FIRST) as $value) {
if (isset($value['index']))
$ret_array[] = $value;
}
This should do it inside your function. See as well the demo.
Related: Quick Recursive search of all indexes within an array
A: Something like this untested code maybe...
$outArray = array();
foreach($originalArray as $nestedArray){
foreach($nestedArray as $innerArray){
$outArray[] = $innerArray;
}
}
print_r($outArray);
A: I see that this was just answered. Well, I thought I'd contribute my solution since I did it. :P
$newArray = array();
function isMulti($k,$v){
global $newArray;
if(is_array($v)){
foreach($v as $k2 => $v2){
if(!is_array($v2)){
$newArray[] = $v;
break;
}else{
isMulti($k2,$v2);
}
}
}
}
foreach($arrayInQuestion as $k => $v){
isMulti($k,$v);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: If domain specified not equal to then current URL apply this jQuery as well as pages with same domain The code below only shows <span> on http://example.com/ but wont show <span> on http://example.com/files/target.html so how can I get it to work on all pages with the specified domain? Please help.
<script type="text/javascript">
var myurl = "http://example.com/";
var currenturl = window.location
if(myurl != currenturl) {
$("<span style=font-size:200px;>big</span>").replaceAll("body"); // check replaceWith() examples
}
</script>
A: This should work:
<script type="text/javascript">
var myurl = "www.myurl.com";
var currenturl = window.location.hostname;
if(myurl != currenturl) {
$("<span style=font-size:200px;>big</span>").replaceAll("body"); // check replaceWith() examples
}
</script>
Per MDN Docs: https://developer.mozilla.org/en/window.location
A: What you wrote doesn't work because window.location returns a Location object, which is a host object. The variable myurl is a string. When comparing a string and an object using the equals operator, the string is compared with the result of calling the object's toString method.
Host objects don't necessarily have a toString method, so attempting to call it could throw an error. Even if the location object of the browser has a toString method, it could return a string that is the value of any one of those properties, or something else.
As it happens, in most browsers window.location.toString() will return the current URL (which is specified in Moziall's Gecko DOM Reference). However, myurl contains the string http://myurl.com/ and the URL usually contains more information, such as the current page being displayed.
To match myurl, you need the protocol (http:) separator (//), hostname (myurl.com) and a trailing "/" character, so:
var loc = window.location;
myurl = loc.protocol + '//' + loc.hostname + '/';
Or you could format myurl to match one of the properties of the location object to make the comparison simpler.
PS. HTML5 is the first attempt at standardising the window object across browsers, so expect it to be a little different in different browsers—program defensively and test widely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I validate the format of a MAC address? What's the best way to validate that an MAC address entered by the user?
The format is HH:HH:HH:HH:HH:HH, where each H is a hexadecimal character.
For instance, 00:29:15:80:4E:4A is valid while 00:29:804E4A is invalid.
A: If you mean just the syntax then this regexp should work for you
import re
...
if re.match("[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", x.lower()):
...
it accepts 12 hex digits with either : or - or nothing as separators between pairs (but the separator must be uniform... either all separators are : or are all - or there is no separator).
This is the explanation:
*
*[0-9a-f] means an hexadecimal digit
*{2} means that we want two of them
*[-:]? means either a dash or a colon but optional. Note that the dash as first char doesn't mean a range but only means itself. This subexpression is enclosed in parenthesis so it can be reused later as a back reference.
*[0-9a-f]{2} is another pair of hexadecimal digits
*\\1 this means that we want to match the same expression that we matched before as separator. This is what guarantees uniformity. Note that the regexp syntax is \1 but I'm using a regular string so backslash must be escaped by doubling it.
*[0-9a-f]{2} another pair of hex digits
*{4} the previous parenthesized block must be repeated exactly 4 times, giving a total of 6 pairs of digits: <pair> [<sep>] <pair> ( <same-sep> <pair> ) * 4
*$ The string must end right after them
Note that in Python re.match only checks starting at the start of the string and therefore a ^ at the beginning is not needed.
A: I hate programs that force the user to think a like a computer.
Make it more friendly by accepting any valid format.
Strip the separator, whatever it is, then get the hex value that's left. That way if a user enters dashes or spaces it also works.
import string
allchars = "".join(chr(a) for a in range(256))
delchars = set(allchars) - set(string.hexdigits)
def checkMAC(s):
mac = s.translate("".join(allchars),"".join(delchars))
if len(mac) != 12:
raise ValueError, "Ethernet MACs are always 12 hex characters, you entered %s" % mac
return mac.upper()
checkMAC("AA:BB:CC:DD:EE:FF")
checkMAC("00-11-22-33-44-66")
checkMAC("1 2 3 4 5 6 7 8 9 a b c")
checkMAC("This is not a mac")
A: If you want to ensure that there is either '-' or ':' throughout but not both, you can use following in Python:
import re
def is_valid_macaddr802(value):
allowed = re.compile(r"""
(
^([0-9A-F]{2}[-]){5}([0-9A-F]{2})$
|^([0-9A-F]{2}[:]){5}([0-9A-F]{2})$
)
""",
re.VERBOSE|re.IGNORECASE)
if allowed.match(value) is None:
return False
else:
return True
A: I cheated and used combination of multiple answers submitted by other people. I think this is pretty clear and straight forward one liner. mac_validation should return True or False.
import re
mac_validation = bool(re.match('^' + '[\:\-]'.join(['([0-9a-f]{2})']*6) + '$', mac_input.lower()))
A: private static final String MAC_PATTERN = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
private boolean validateMAC(final String mac){
Pattern pattern = Pattern.compile(MAC_PATTERN);
Matcher matcher = pattern.matcher(mac);
return matcher.matches();
}
A: Dash-separated MAC addresses can also contain a '01-' prefix, which specifies it is an Ethernet MAC address (not token ring, for example ... who uses token ring?).
Here's something that is somewhat complete and easy to read in a logical step-through way:
def IsMac(S):
digits = S.split(':')
if len(digits) == 1:
digits = S.split('-')
if len(digits) == 7:
if digits[0] != '01':
return False
digits.pop(0)
if len(digits) != 6:
return False
for digit in digits:
if len(digit) != 2:
return False
try:
int(digit, 16)
except ValueError:
return False
return True
for test in ('01-07-09-07-b4-ff-a7', # True
'07:09:07:b4:ff:a7', # True
'07-09-07-b4-GG-a7', # False
'7-9-7-b4-F-a7', # False
'7-9-7-b4-0xF-a7'): # False
print test, IsMac(test)
A: import re
def MacValidator(inputMacList):
def MacParser(mac):
octets = re.split('[\:\-]', mac)
if len(octets) != 6:
return False
for i in octets:
try:
if int(i, 16) > 255:
return False
except:
return False
return mac
return [i.upper() for i in inputMacList if MacParser(i) != False]
macList = ["00-15-F2-20-4D-6B", "Kozel", "00:13:aa:00:00:01",
"00:13:AA:00:tr:01", "00-01-01-20-55-55", "00-01-01-20abc-55"]
validMacList = MacValidator(macList)
A: This Regex validates the following MAC format
"Ae:Bd:00:00:00:00"
"00-00-00-00-00-00"
"aaaa.bbbb.cccc"
private static final String MAC_PATTERN = "(([0-9A-Fa-f]{2}[-:.]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})";
public class MacRegExp {
private static final String MAC_PATTERN = "(([0-9A-Fa-f]{2}[-:.]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})";
static boolean validateMAC(final String mac){
Pattern pattern = Pattern.compile(MAC_PATTERN);
Matcher matcher = pattern.matcher(mac);
return matcher.matches();
}
}
Hope this helps
A: This works like a charm.
def isMAC48Address(inputString):
if inputString.count(":")!=5:
return False
for i in inputString.split(":"):
for j in i:
if j>"F" or (j<"A" and not j.isdigit()) or len(i)!=2:
return False
return True
A: #Just works Perfect
#validate the MAC addr
#!/usr/bin/python
import re
mac = "01-3e-4f-ee-23-af"
result = re.match(r"([0-9a-fA-F]{2}[-:]){5}[0-9a-fA-F]{2}$",mac)
if result:
print ("Correct MAC")
else:
print ("Incorrect MAC")
A: pattern = "^(([0-9]{2}|[a-f]{2}|[0-9][a-f]|[a-f][0-9])\:){5}([0-9]{2}|[a-f]{2}|[0-9][a-f]|[a-f]|[0-9])$"
valid_mac_check =re.search(pattern,"00:29:15:80:4E:4A",re.IGNORECASE)
print(valid_mac_check.group())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: How to select first value from array in a foreach loop when passing variable on same page? code:
$persons = array();
$tags = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
if(!isset($persons[$row["id"]])) {
$persons[$row["id"]]= $row;
$tags[ $row['id'] ] = array();
}
$tags[ $row['id'] ][] = $row['tag'];
}
foreach($persons as $pid=>$p){
$tag1 = $p["tag"];
$tag1ish = $tags[$p['id']];
}
A: foreach($persons as $pid=>$p){
$tag1 = $p["tag"];
$tag1ish = $tags[$p['id']];
/* to get the first tag, there are many options e.g.: */
$first_tag = $tag1ish[0]; // given u use [] syntax as above.
}
A: You could avoid calling a foreach and just use the first element
$tag1 = $persons[0]["tag"];
or use current:
$tag1 = current($persons);
A: I think the clarification didn't help much :P Anyway, I'd reccomend to order the tags by ID then (or at least alphabetically). So the order of the tags will be the same and accessing the first element of the array would return always the same tag.
A: if i understand well, you can use the reset() function. It received an array as argument and returns the first element.
A: foreach($persons as $pid=>$p){
// is this what you mean..?
$theTagYouWant = $tags[0];
$tag1 = $p["tag"];
$tag1ish = $tags[$p['id']];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: bulk loading data into a b+tree I have built a b+tree index of my own, with all the operations for insert/delete/search over the index. To accelerate the insertion of a huge dataset, I would like to implement bulk-loading as well to be able to experiment with large datasets.
What I have been trying to do is to sort the data and start filling the pages at the leaf level. keys are copied or pushed at the upper levels once necessary. I always keep track of the frontier of the index at various heights. For example, if my index is of height 3 (root, one level containing internal nodes and the leaves level), I only keep 3 pages in the memory and once they get full, or there is no more data, I write them to the disk.
The problem is how much data to write to each page to maintain the page limits of all individual nodes. These limits can be found here. I could not find any useful resource that has details on implementation of bulk loading or a good strategy for deciding what fill ratio to use in order to guarantee node limits.
Any ideas?
A: From the comments under the question I can tell that your concern is that the last page (or last pages if considering ones higher up in the tree) might not reach the minimum fill count.
As the number of such pages is bounded by log2(n) (the height of the tree) I suspect that the theoretical performance guarantees are unaffected.
Anyway, the guarantees you linked to are not required for correctness. They are sufficient for guaranteed bounds on running time. They are not necessary for guaranteed running time though (example: add one page with one row to the end of the b-tree - you still get the same guaranteed running times).
If you want to know how real b-trees operate, you might want to take a look at your favorite RDBMS (as a SQL Server user I know that SQL Server happily under-runs the 50% page-fullness guarantee without practical impact). I think you'll find that theoretical concerns are treated as not very meaningful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Apple Mach-O Linker (Id) error !! not sure what to do first I know this question has been posted alot of times on internet, but everytime people seem to give different solutions, and I tried a few and none worked for me.
so when I build my app I get this error :
Ld /Users/ahoura/Library/Developer/Xcode/DerivedData/Game-dkfwmqscuzprkpappmtrrrahhgtu/Build/Products/Debug-iphonesimulator/TinyWings.app/TinyWings normal i386
cd /Users/ahoura/Downloads/haqu-tiny-wings-e393aa3
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.3.sdk -L/Users/ahoura/Library/Developer/Xcode/DerivedData/Game-dkfwmqscuzprkpappmtrrrahhgtu/Build/Products/Debug-iphonesimulator -F/Users/ahoura/Library/Developer/Xcode/DerivedData/Game-dkfwmqscuzprkpappmtrrrahhgtu/Build/Products/Debug-iphonesimulator -filelist /Users/ahoura/Library/Developer/Xcode/DerivedData/Game-dkfwmqscuzprkpappmtrrrahhgtu/Build/Intermediates/Game.build/Debug-iphonesimulator/TinyWings.build/Objects-normal/i386/TinyWings.LinkFileList -mmacosx-version-min=10.6 -lz -Xlinker -objc_abi_version -Xlinker 2 -framework QuartzCore -framework OpenGLES -framework OpenAL -framework AudioToolbox -framework AVFoundation -framework UIKit -framework Foundation -framework CoreGraphics -o /Users/ahoura/Library/Developer/Xcode/DerivedData/Game-dkfwmqscuzprkpappmtrrrahhgtu/Build/Products/Debug-iphonesimulator/TinyWings.app/TinyWings
ld: duplicate symbol _screenWidth in /Users/ahoura/Library/Developer/Xcode/DerivedData/Game-dkfwmqscuzprkpappmtrrrahhgtu/Build/Intermediates/Game.build/Debug-iphonesimulator/TinyWings.build/Objects-normal/i386/pauseMenu.o and /Users/ahoura/Library/Developer/Xcode/DerivedData/Game-dkfwmqscuzprkpappmtrrrahhgtu/Build/Intermediates/Game.build/Debug-iphonesimulator/TinyWings.build/Objects-normal/i386/mainMenu.o for architecture i386
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/llvm-g++-4.2 failed with exit code 1
alot of people seem to say that it has something to do with a missing library or including a file in a special way!!!
NOTE I am using box2d, so C and C++ is mixed and the extension of the files are .mm
A: This has nothing to do with a missing library
You have defined the variable screenWidth in both pauseMenu and mainMenu. It should only be defined in one of these.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Parsing a .txt file as different data types So I have a text file that reads as the following
-9
5.23
b
99
Magic
1.333
aa
When I try to read it in using the following code, the GetType() function outputs it as strings:
string stringData;
streamReader = new StreamReader(potato.txt);
while (streamReader.Peek() > 0)
{
data = streamReader.ReadLine();
Console.WriteLine("{0,8} {1,15}", stringData, stringData.GetType());
}
Here then is the output:
-9 System.String
5.23 System.String
b System.String
99 System.String
Magic System.String
1.333 System.String
aa System.String
I understand that I asked the streamReader class to read it all in as strings.
My question is, how does one read it as the different different data types (i.e. string, int, double), and have it output as:
-9 System.int
5.23 System.double
b System.String
99 System.int
Magic System.String
1.333 System.double
aa System.String
A: You have to convert string to that types:
string stringData;
double d;
int i;
streamReader = new StreamReader(potato.txt);
while (streamReader.Peek() > 0)
{
data = streamReader.ReadLine();
if (int.TryParse(data, out i)
{
Console.WriteLine("{0,8} {1,15}", i, i.GetType());
}
else if (double.TryParse(data, out d)
{
Console.WriteLine("{0,8} {1,15}", d, d.GetType());
}
else Console.WriteLine("{0,8} {1,15}", data, data.GetType());
}
A: Normally you would know the types (the structure of the file).
If not, use RegEx to check for possible int and double values, return the rest as string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ResourceBundle not found for MessageSource I'm not able to locate the message source in my app. I have set the following configuration
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list><value>resources.dev</value></list>
</property>
</bean>
There will be more .properties files that will be added.
The dev.properties file is located at ROOT/resources/dev.properties where ROOT is the webapp
The dev.properties has to be in ROOT/resources/dev.properties
dev.properties contains
test.url="external.url.com"
In my controller I'm trying to access the message as
messageSource.getMessage("test.url", new Object[]{}, Locale.getDefault())
I'm getting the following exception
org.springframework.context.NoSuchMessageException: No message found under code 'test.url' for locale 'en_US'.
A: Try just using this in your XML:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="resources/dev"/>
</bean>
Then try putting your dev.properties file in ROOT/WEB-INF/classes/resources (where ROOT is the root directory of the exploded webapp).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Touch gesture recognition for phones without neural networks I'm developing a gesture recognition program for a phone. What I am trying to accomplish is for users to draw their own "patterns", and then afterwards have these patterns do different things.
Storing the pattern - the "pattern save" algorithm as I call it
This when the gesture is originally being drawn and recorded. This is also the algorithm I use for grabbing what the user draws, and to use it for comparison:
*
*The user starts drawing his pattern. For every 15 pixels, a point is placed in a list referred to as "the list".
*Once the pattern has been drawn, the first and last point is removed from the list.
*For each of the points now in the list, their connections are converted into a direction enumeration (containing 8 directions) which is then added to a list as well, now referred to as "the list".
*Filter 1 begins, going through 3 directions at a time in the list. If the left direction is the same as the right direction, the middle direction is removed.
*Filter 2 begins, removing duplicate directions.
*Filter 3 begins, removing assumed noise. Assumed noise is detected by pairs of duplicate directions occuring again and again. (as an example, "left upper-left left upper-left" is being turned into "upper-left" or "left").
*Filter 4 begins, removing even more assumed noise. Assumed noise is this time detected by (again) comparing 3 directions at a time in the list as seen in step 4 (Filter 1), but where directions are not checked for being entirely equal, only almost equal (as an example, left is almost equal to "upper-left" and "lower-left").
The list of directions are now stored in a file. The directions list is saved as the gesture itself, used for comparing it later.
Comparing the pattern
Once a user then draws a pattern, the "pattern save" algorithm is used on that pattern as well (but only to filter out noise, not actually saving it, since that would be stupid).
This filtered pattern is then compared with all current patterns in the gesture list. This comparison method is quite complex to describe, and I'm not that good at English as I should be.
In short, it goes through the gesture that the user typed in, and for each direction in this gesture, compares with all other gestures directions. If a direction is similar (as seen in the algorithm above), that's okay, and it continues to check the next direction. If it's not similar 2 times in a row, it is considered a non-match.
Conclusion
All of this is developed by myself, since I love doing what I do. I'd love to hear if there are anywhere on the Internet where I can find resources on something similar to what I am doing.
I do not want any neural network solutions. I want it to be "under control" so to speak, without any training needed.
Some feedback would be great too, and would work as well, if you have any way that I could do the above algorithm better.
You see, it works fine in some scenarios. But for instance, when I make an "M" and an upside-down "V", it can't recognize the difference.
Help would be appreciated. Oh, and vote up the question if you think I described everything well!
A: General ideas
*
*wouldn't M and V appear identical because you junk the first and last points? Junking the first and last points seemed a bit redundant since you operate on directions anyway (a list of three points already leads to a list of only 2 directions).
*Also, I'd recommend just prototyping stuff like this. You'll find out whether you'll be susceptible to noise (I expect not, due to 'for every 15 pixels').
Re: the comparison stage
I think you'll get some more generic ideas to matching 'closely related' movements by reading Peter Norvigs excellent 16-line spellchecker article. here
A: You're basically using a Markovian(ish) FSM based on gesture orientations to calculate "closeness" of shapes. You shouldn't. An M looks the same whether it's drawn left-to-right or right-to-left. (Maybe I misunderstood this detail.)
You should compare shapes using something like openCV. In particular, cvMatchShapes(). This function uses Hu moments (a well-established metric) to compare "closeness" of binary shapes. Hu moments are used for comparing protein binding sites and as part of more complicated shape-recognition algorithms like SURF. It should be good enough for what you're trying to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: UIButton highlight state images I've a UIButton and I set it with:
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *imageNormal = [UIImage imageNamed:@"normal.png"];
UIImage *imageNormalHover = [UIImage imageNamed:@"normalHover.png"];
UIImage *imageSelected = [UIImage imageNamed:@"selected.png"];
UIImage *imageSelectedHover = [UIImage imageNamed:@"selectedHover.png"];
[myButton setImage:imageNormal forState:UIControlStateNormal];
[myButton setImage:imageSelected forState:UIControlStateSelected];
if (boolVar) {
[myButton setSelected:YES];
[myButton setImage:imageSelectedHover forState:UIControlStateHighlighted];
} else {
[myButton setImage:imageNormalHover forState:UIControlStateHighlighted];
}
The issue is when the state is normal and I try to press the button I see correctly the image normalHover.png but when the state is selected and I try to press the button I see still normalHover.png and not the selectedHover.png. It seems that with UIButton I'm unable to change the highlighted image. Do you how to solve?
A: You need to set the image for the UIControlStateSelected | UIControlStateHighlighted combined state:
[myButton setImage:imageSelectedHover forState:(UIControlStateSelected | UIControlStateHighlighted)];
Because both states are on when the button is selected and you hignlight it by tapping on it.
A: In swift this is done with union:
myButton.setImage(imageSelectedHover, forState: UIControlState.Selected.union(UIControlState.Highlighted))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GNU Gettext and wide characters I'm developing a game (actually I'm porting it from Gosu to SFML) in C++. I'm using GNU Gettext as the i18n system. As you know, gettext returns char * strings using the local encoding, usually UTF8. The problem is that I need to use wide strings for SFML to recognize the special characters such as áéíüñ.
So the question would be: how do I create a proper wstring from the output of gettext? It would be great if there were some kind of wchar_t * w_gettext() function, but there's not. I have tried some options, such as creating a wstring from the original string by passing the iterators, but obviously it does not work.
A: To convert between the system's narrow, multibyte encoding and its wide character set (agnostic of any encoding specifics), use the mbstowcs() and wcstombs() standard C functions, found in <cwchar>. Here's a previous post of mine on the subject, and here's some sample code.
A: You can convert your multi-byte UTF-8 string to wide char.
On Windows, use MultiByteToWideChar. On Unix, use libiconv.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL compare two tables with common id Given the following tables stored in SQL database
Table person
id username phone
1 james 555-666-777
2 gabriel 666-555-777
3 Lucas 222-888-999
4 Marta 555-444-777
Table room_booking
id person_id room time
1 2 A2 13:00
2 4 B5 09:00
3 1 C1 20:00
By only getting the room_booking id number 2
I would like the output to be:
Output table
id username phone
4 Marta 555-444-777
I know INNER JOIN can do the job but I got fields from the table room_booking included with SELECT *.
A: As others have said, the answer is to not include the unwanted columns. Since you want all of the columns from one table, and none of the columns from the other table, the solution is to use person.*
Select distinct p.*
from person p
Inner join room_booking r
On r.person_id = p.id
I include the distinct because given your structure, you're likely to have more than one booking per person eventually.
Alternate syntax for achieving the same goal...
/*using sub select*/
Select * from person where id in (select person_id from room_booking);
/*using cte, distinct and inner join*/
; pids as(select distinct person_id from room_booking)
Select person.*
from pids
Inner join person on person_id = id;
/*using cte and subquery with explicit column list */
; pids as(select person_id from room_booking)
Select id, username, phone
from person
Where id in (select person_id from pids)
A: select
p.id,
p.username,
p.phone
from Person p
inner join room_booking rb
on p.id = rb.person_id
where rb.id = 2
Alternatively you could select p.* but you shouldn't do that in prod code.
A: You only get all fields included if you use the asterisk in the query. Try selecting only the fields you want to get:
SELECT person.id, username, phone
FROM person JOIN room_booking ON person.id = room_booking.person_id
WHERE room_booking.id = 2
A:
I know INNER JOIN can do the job but I got fields from the table
room_booking included.
Don't select them and you won't get them:
select p.id ,p.username ,p.phone from Person p
inner join room_booking rb
on rb.person_id=p.id
A: Both Return The Same Result
======================1
SELECT C.CountryName,C.ZipCode,P.Population
FROM tbl_Country C, tbl_Population P
WHERE C.ID= P.ID
======================2
SELECT C.CountryName,C.ZipCode,P.Population
FROM tbl_Country C inner join tbl_Population P
on C.ID= P.ID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java Interface implements Object? Does any Java Interface implicitly implements java.lang.Object?
This question arose when I did something like this:
public static String[] sizeSort(String[] sa) {
Comparator<String> c = new Comparator<String>() {
public int compare(String a, String b) {
if (a.length() > b.length()) return 1;
else if (a.length() < b.length())
return -1;
else
return 0;
}
};
// more code
}
It worked fine even though I did not implement equals method of this interface.
Your answers clears this up. But does any one know if above is anonymous local inner class or named local inner class?
A: Sort of. Citing the Java Language Specification:
If an interface has no direct
superinterfaces, then the interface
implicitly declares a public abstract
member method m with signature s,
return type r, and throws clause t
corresponding to each public instance
method m with signature s, return type
r, and throws clause t declared in
Object, unless a method with the same
signature, same return type, and a
compatible throws clause is explicitly
declared by the interface. It is a compile-time error if the interface explicitly
declares such a method m in the case
where m is declared to be final in
Object.
Note that Object has a number of final and protected methods that all interfaces "inherit" this way, and you couldn't have those modifiers in an interface (which would be implied by your "implements java.lang.Object").
A: java.lang.Object is not an interface, so no interface will implicitly implement it.
However, any class that you create which implements any interface will extend Object, because all classes must extend it. Any instance which you (or indeed anyone else) can create will therefore have all of the methods defined on java.lang.Object.
A: Object is a class, not an interface, so it can't be "implemented" by other interfaces.
The whole point of an interface is that it contains no implementation details. If an interface could extend a class, it would inherit that class's implementation details, which would defeat the point.
A: Strictly speaking: How would you know the difference?
You will never have a reference to an interface, you will always having a reference to an actual instance with is an Object and implements the interface. This means that you can call methods from Object on any reference (not null of course) even if the declared type of the reference is an interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Access to getImageData from Greasemonkey script I want to implement a Greasemonkey script which scan each image on a page and makes some action depending on the image content. I'm going to use getImageData method of Canvas object to get the image content.
When I test my userscript with FireFox I get 'Security Error' exception which means that the userscript does not have access to original page's images.
Is there any workarounds?
What security context the user scripts are working in?
Thanks.
A: This is likely due to the same origin policy. If you're trying to manipulate images from domains other than the one the site is hosted on, you will receive security errors.
You can work around this by using a proxy web server to feed you the image data via a base64 encoded string. There's a jQuery plugin available here that uses Google by default to feed you the strings, but it's limited to a certain amount of traffic per day and thus is not reliable out of the box. You can use their code (linked at the bottom of the page) on your own server to bypass this, though (which I have done with great success).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Clustering a stateless Java EE application with Glassfish on Amazon AWS What's the best way to deploy a stateless Java EE 6 application in a distributed environment in order to achieve high availability and scalability? My application is stateless. Therefore, I don't need to replicate any session state (HTTP session, EJB stateful beans, etc.)
Specifically, I'd like to know the following:
*
*Do I need the clustering capabilities of Glassfish 3.1 (given that I don't need to replicate session state)?
*I'm heavily using JMS Queues and Message Driven Beans. How do I setup JMS to make it work in a clustered environment?
*I'm also using the EJB timer service. How does that work in a clustered environment? Is there anything I need to do besides using a shared DB for storing timers (and not the embedded Derby DB)?
I plan to use Amazon AWS (RDS with multi AZ deployment, elastic load balancing, EC2).
A: My perspective on your respective points:
1) session replication is a part of cluster management, its not the goal of creating clustered server environment. The benefits you get out of clustering are :
*
*Improved scalability
*Higher availability
*Greater flexibility
Side-effects of clustering are increase in infrastructure complexity, additional design and code requirements etc. So if you are thinking about clustering then your decision should be driven by the factors like how scalable, available and flexible you want your application to be.
2) You can use Apache ActiveMQ with you glassfish server to make your JMS thing working in clustered environment.
3) I think shared DB should suffice
A: I'm in a similar situation, and I'm currently discovering what GF clustering can / cannot do for me.
Re 1) Do I need the clustering capabilities of Glassfish 3.1
Since your EJBs are stateless, you don't need a GF cluster for session/state replication (as you say yourself). You could just setup multiple standalone instances and deploy your app to them individually. However, even in a stateless application, I find the benefits of a GF cluster very worthwhile - from an administrative point of view.
The GF Cluster will ensure that the configuration is automatically applied to all instances. JNDI is replicated automatically. Applications are deployed automatically. It's a single command to scale out and add an additional instance - a short while later, your cluster is extended and the new instance is configured, deployed, started and ready to go. For me, that's administrative heaven and reason enough to use a GF cluster whenever I have more than 1 instance!
One thing to consider (and I'm struggling with this badly at the moment) might be a distributed/coordinated L2 cache, in case your application is talking to a database.
Re 2) ... How do I setup JMS to make it work in a clustered environment?
Not sure I understand your question... If you want to have a high available message broker outside of GF, you'd need to set it up accordingly and manage it by yourself. For example, ActiveMQ has several ways of setting up clustering/HA/scale-out. If you use the GF-provided OpenMQ, setting up a GF-cluster also provides a clustered message broker. Out of the box.
But broker clustering is a topic in itself, and not to be underestimated. You might need to think about persistence and a shared message store and such - regardless of using an external or the GF-provided-and-clustered broker.
If JMS is such an integral part of your application, I'd recommend appropriate attention to the broker. I probably wouldn't use the GF-broker, but rather have a separate broker-cluster (separation of concerns; e.g. you can upgrade GF / broker independent of each other).
Re 3) EJB timer service ... Is there anything I need to do besides using a shared DB for storing timers?
If you require timers to automatically fire only once in your group of (appserver-)instances, I believe you do need GF clustering (plus the shared DB of course). Otherwise I do not see, how each instance should know if it should fire or not. However, this is easily tested...
tl;dr
*
*Use GF clustering to save on admin work
*Use an external, well-understood high-available message broker
*Use a shared DB for your EJB timers
A: You will probably will need a industrial grade EJB framework if you really want your application to run smoothly.... However, you certainly are not restricted to glassfish alone. The important thing to remember is that EJB is a specification which is not necessarily limited to any one implementation !
1) Do I need the clustering capabilities of Glassfish 3.1 (given that I don't need to replicate session state)?
NO you definetly do not. If your application is stateless, Glassfish won't be necessary.
2) I'm heavily using JMS Queues and Message Driven Beans. How do I setup JMS to make it work in a clustered environment?
JBoss is an option here. I JBOSS clustering services simply re-elect new master nodes to manage the messaging if one goes down, so availability is gauranteed.
3) I'm also using the EJB timer service. How does that work in a clustered environment? Is there anything I need to do besides using a
shared DB for storing timers (and not the embedded Derby DB)?
Timing can be transparently clustered if your using either weblogic OR the Jboss ejb implementations. In this case, I don't think you need an embedded database : The frameworks can handle this directly : http://community.jboss.org/wiki/DeployingEJB3TimersInCluster.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Maven GAE/Datanucleus uncertainties I been spending some time today, trying to produce my first maven managed Google app engine 1.5.4 + GWT 2.4.0 build.
I'm finally at a stage where everything compiles, and the gae:run goal works. Which was more work that I had imagines, but hey, its all good fun.
Anyways, my question now is, eventhough everything works, I get the following ERROR when the datanucleus enhancer runs.
[ERROR] --------------------
[ERROR] Standard error from the DataNucleus tool + org.datanucleus.enhancer.DataNucleusEnhancer :
[ERROR] --------------------
[ERROR] Oct 02, 2011 11:04:39 PM org.datanucleus.enhancer.DataNucleusEnhancer <init>
INFO: DataNucleus Enhancer : Using ClassEnhancer "ASM" for API "JDO"
Oct 02, 2011 11:04:39 PM org.datanucleus.plugin.NonManagedPluginRegistry resolveConstraints
INFO: Bundle "org.datanucleus" has an optional dependency to "org.eclipse.equinox.registry" but it cannot be resolved
Oct 02, 2011 11:04:39 PM org.datanucleus.plugin.NonManagedPluginRegistry resolveConstraints
INFO: Bundle "org.datanucleus" has an optional dependency to "org.eclipse.core.runtime" but it cannot be resolved
Oct 02, 2011 11:04:39 PM org.datanucleus.enhancer.DataNucleusEnhancer main
INFO: DataNucleus Enhancer (version 1.1.4) : Validation of enhancement state
Oct 02, 2011 11:04:40 PM org.datanucleus.jdo.metadata.JDOAnnotationReader processClassAnnotations
INFO: Class "net.kindleit.gae.example.model.Message" has been specified with JDO annotations so using those.
Oct 02, 2011 11:04:40 PM org.datanucleus.metadata.MetaDataManager loadClasses
INFO: Class "net.kindleit.gae.example.model.Messages" has no MetaData or annotations.
Oct 02, 2011 11:04:40 PM org.datanucleus.enhancer.DataNucleusEnhancer addMessage
INFO: ENHANCED (PersistenceCapable) : net.kindleit.gae.example.model.Message
Oct 02, 2011 11:04:40 PM org.datanucleus.enhancer.DataNucleusEnhancer addMessage
INFO: DataNucleus Enhancer completed with success for 1 classes. Timings : input=78 ms, enhance=15 ms, total=93 ms. Consult the log for full details
[ERROR] --------------------
What's going on there? What's with the [ERROR] blocks? It doesnt seem like there are any errors at all?
Additionally, I get the following warning, which I dont entirely understand
[WARNING] Could not transfer metadata asm:asm/maven-metadata.xml from/to local.repository (file:../../local.repository/trunk): No connector available to access repository local.repository (file:../../local.repository/trunk) of type legacy using the available factories WagonRepositoryConnectorFactory
And finally, how come all the dependencies are added to the datanucleus enchancer classpath?
There's a [INFO] message from datanucleus enhancer listing all the jars in its classpath and it seem to contain everything, how come? I would have thought only the JDO and persistence related libraries was needed there?
A: I have same error as you. Then I changed version to latest one. The errors are gone.
<properties>
<datanucleus.version>3.0.1</datanucleus.version>
<maven-datanucleus-plugin>3.0.0-release</maven-datanucleus-plugin>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!--datanucleus related dependencies-->
<dependency>
<groupId>com.google.appengine.orm</groupId>
<artifactId>datanucleus-appengine</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus.version}</version>
<scope>runtime</scope>
<exclusions>
<exclusion>
<groupId>javax.transaction</groupId>
<artifactId>transaction-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--jdo related dependencies-->
<dependency>
<groupId>javax.jdo</groupId>
<artifactId>jdo2-api</artifactId>
<version>2.3-ec</version>
<exclusions>
<!--
exclude the legacy javax.transaction:transaction-api and replace it
with javax.transaction:jta (it appears to be the same thing)
-->
<exclusion>
<groupId>javax.transaction</groupId>
<artifactId>transaction-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<build>
<plugins>
..........
<plugin>
<groupId>org.datanucleus</groupId>
<artifactId>maven-datanucleus-plugin</artifactId>
<version>${maven-datanucleus-plugin}</version>
<configuration>
<!--
Make sure this path contains your persistent classes!
-->
<mappingIncludes>**/db/*.class</mappingIncludes>
<verbose>true</verbose>
<enhancerName>ASM</enhancerName>
<api>JDO</api>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>enhance</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>${datanucleus.version}</version>
<exclusions>
<exclusion>
<groupId>javax.transaction</groupId>
<artifactId>transaction-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-rdbms</artifactId>
<version>${datanucleus.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-enhancer</artifactId>
<version>${datanucleus.version}</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jdo</artifactId>
<version>${datanucleus.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Change location if POST is 0 I got this variable:
$page = (int) $_REQUEST['page'];
I need some actions that will base on the above request. This will be used to the pagination script.
I mean:
if $page is 0 , then script will redirect the user to the another subpage.
The trick is that I need to redirect user ONLY in case if in his URL &page=0 is specified, otherwise, it won't do anything.
I've tried this:
if( $page == 0 ) {
header("Location; xxxx");
}
but it does redirect the user even if he did not specified (or POST the page).
So , how can I do that?
A: This checks if it is actually set by user, and it is 0
if (isset($_REQUEST['page']) && $_REQUEST['page'] === 0)
{
header('Location: xx');
}
Do 3: === to check if value is actually the number 0
A: use strict comparison:
if ($page === "0"){
...
}
updated.
well I would be more strict. I would use following approach
if (isset($_POST["page"])){
$page = (int) $_POST["page"];
/* do you assumptions here. this will definitely work */
}
A: See array_key_exists:
array_key_exists($_REQUEST, 'page'); // returns false if no 'page' parameter supplied.
A: You should compare the 0 as a string value, therefore you should read $page from $_REQUEST as a string value too...
<?php
$page = $_REQUEST['page'];
if( $page == "0" ) {
header("Location: ./?did-it");
}
?>
ps - I think Location; ... should be with colon like Location: ...
A: Change the semicolon to colon.
header("Location; xxxx");
should be:
header("Location: xxxx");
Now, additional info on comparison operators as I disagree with @jancha answer
===: TRUE if $a is equal to $b, and they are of the same type.
==: TRUE if $a is equal to $b after type juggling.
This is the same in JavaScript. An example of how this is useful is when you want different code to run on false/0 and on undefined (say for error handling), in this case we can do a much simpler test.
$page = (int) $_REQUEST['page']; //this is the line to change
change to
//this way you don't need to type cast it (which is only supported with php5.3+)
$page = (isset($_REQUEST['page']) && is_numeric($_REQUEST['page'])) ? $_REQUEST['page']:0;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does a Tool for the analyzation of JBoss log files exist? I have a JBoss 6 Server running which generates a big log file.
Does a tool exist, which allows me to analyse the log file (How often did a specific error occur? When did it occur? How many INFO / WARNING / ERROR messages are there, ...)?
I've heard of log4j, but it seems as if it would only allow me to set up a configuration for logging options. Am I right?
If no GUI tools, do you know a library/module/scripts for Python/PHP which helps me to parse the log file?
A: Take a look at Chainsaw and Log Parser
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Converting .TTF files to .EOT using PHP I want to convert .TTF font files to .EOT with PHP to make script like http://www.kirsle.net/wizards/ttf2eot.cgi
I searched a lot and I've got "NONE"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GLSL ES local variables crash? I'm trying to implement some shaders from online tutorials (lighthouse3d.com) in my OpenGL ES 2.0 engine.
The problem is that for some reason, ANY variables declared in the scope of main() causes the entire shader to fail. for example, this fails:
void main(){
vec4 color;
gl_FragColor = vec4(1.0, 0.5, 0.5, 1.0);
}
but this works perfectly:
void main(){
//vec4 color;
gl_FragColor = vec4(1.0, 0.5, 0.5, 1.0);
}
Same thing happens with my vertex shaders.(EDIT:nvm, only seems to happen with fragment shaders) The only way to use any type of non-constant value is to use attributes, varyings, uniforms, etc. for example, this works as you would expect:
uniform sampler2D texture;
varying lowp vec4 fragcol;
varying lowp vec2 texco;
void main(){
gl_FragColor = fragcol * texture2D(texture, texco);
}
Also, I'm having a hell of a lot of trouble trying to find documentation or resources specifically about GLSL ES (or whatever this version is called). All I've been able to find is this: http://old.siggraph.org/publications/2006cn/course16/KhronosSpecs/ESLanguageSpec1.10.11.pdf
This is all I could find related to variable declarations:
[snip]There are no default types. All variable and function declarations
must have a declared type, and optionally qualifiers. A variable is
declared by specifying its type followed by one or more names
separated by commas.[snip]
And that is exactly what I did:
declared type: vec4
followed by one or more names: color;
vec4 color
I'm clueless
EDIT:
GLES20.glGetError() gives error 1282
A: GLSL ES differs from traditional GLSL in that it requires precision modifiers in order to specify a full type. Have you tried, e.g.:
void main(){
lowp vec4 color;
gl_FragColor = vec4(1.0, 0.5, 0.5, 1.0);
}
You can also throw something like this into the top of a source file:
precision highp float;
To set the default precision, so you can omit it later on.
To get detailed information about an error compiling GLSL, you can use glGetProgramInfoLog (with assistance from glGetProgramiv). Most GL implementations return a meaningful error and a line number. I'm sadly backward with Java, but in C you might do:
glCompileShader(shader);
// check whether compilation was successful; if not
// then dump the log to the console
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if(!status)
{
GLint logLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0)
{
GLchar *log = (GLchar *)malloc(logLength);
glGetShaderInfoLog(shader, logLength, &logLength, log);
printf("Shader compile log:\n%s", log);
free(log);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can a ListView item be complex? I have a set of views that I need to present in a list-like manner. Every view is rather complicated, but each is a clone of the previous, just with different data. Now, there is a lot of data on any given view, so is a ListView/ListActivity still the right thing to use here? Or are those only intended for simple views that show just one or two text items?
A: ListViews can be used to display complex views as you seem to have. However, ListViews are especially useful if you don't know the number of views to display until runtime and have some datastore behind that is being displayed.
If you have a fixed number of views to display, a FrameLayout or other ViewGroup might be a better choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Joins vs multiple copies of the data: Performance I was just reading
http://s.niallkennedy.com/blog/uploads/flickr_php.pdf about Flickr's infrastructure
and this is what it said.
JOIN’s are slow
• Normalised data is for sissies
• Keep multiple copies of data around
• Makes searching faster
Is it true or its just their way of managing their DBs? If I just looking for performance that is it better to not normalise?
A: Joins become a performance issue on large data sets. It's not something to worry about if you are not experiencing slowness issues. There are big advantages to normalized data, but nobody ever goes to fifth normal form. Typical is second or third normal form.
When you have performance issues, then you should consider de-normalizing what you have and making copies of data optimized for retrieval. Especially data that doesn't change.
Flickr probably has few updates, so there is minimal overhead in keeping multiple copies of data. They also have the luxury of eventual consistency, data doesn't have to replicate in real time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dos command to move all files from all subdir to one folder i want to write 2 batch files.
1st:
move all files in subdirs to root dir.
eg:
Folder1
|_folder2
|___files.jpg
|_folder3
|___files.jpg
i want to move all files in folders of folder1 to folder1
2nd batch file is
eg:
Folder1
|_folder2
|___JPEG
|_____files.jpg
|_folder3
|___JPEG
|_____files.jpg
Need to Delete all files in sub dir then move files from JPEG one level up -to folder2 for example- and rename it to thumbnail.png for example.
i tryed
for /r %%f in (*) do ren "%%f" thumbnail.jpg
to rename all files but dont know how to delete all files in same folder that containe jpeg folder and how to move files one level up.
Thankx :D hope its not vey complex
A: Here's a solution to your first question, as I understand it:
@echo off
setlocal
set root=Folder1
for /f "delims=" %%f in ('dir /ad /b /s %root%') do @move "%%f\*.*" %root%
endlocal
As I've written it all files at any level are moved. If you only want first level subdirectory files moved, then get rid of the /s.
For your second problem, try a similar approach, but with
dir /a-d /b
to list all the entries that aren't sub-directories (ie, skip JPEG). This will let you construct the for statement that does the deletion, then do another statement that does the move and rename.
You might want to look at calling a sub-routine to do the move, rename, delete. You could then manipulate the filename to change the name. I'm a bit confused about exactly what you want to do in the second case. Also have a look a the help on the set and call commands if your not sure about extracting the filename and other string manipulations.
If you add comments or edit your question to show exactly what you want then I'm happy to help further.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How a user can have multiple likes? Well lately I'm making a script application. People can post and share stuff (let's call them object for the purpose of the question). Thing is, that a user can "bookmark an object" in his profile.
I have a table for users with unique uid (primary key) and a table for objects with a unique oid (primary key). I was thinking of making a new table in MySQL, calling it liked_objects which will have the following:
id - oid - uid
Each time I need to find all the object that user X liked I may run a query
SELECT * FROM liked_objects WHERE uid = userXid
My question is: Is there a most efficient way of doing this?
I'm using PHP 5 and MySQL Database.
Best regards
A: I think that's as efficient as you're going to get, just make sure your uid column in liked_objects is indexed to help speed up your queries.
A: It depends on how many times you're running that query. It doesn't get much simpler than that, but if you need to optimize things you could always cache the liked objects or even grab them in a join when you select the rest of the user information.
A: As far as I know, your proposed solution is exactly how you want to do it. Just make sure to add indexes on your new table to significantly speed that query.
A: You could remove the field "id" and take "oid" and "uid" as a compound primary key.
A: You don't need an id column for your liked_objects table. Assuming a user can only like each object once, you can just use two columns:
uid | oid
Make the Primary Key be both columns. Then to unlike an object you just:
DELETE FROM `liked_objects` WHERE uid = 'user_id' AND oid = 'object_id'
To like an object you:
INSERT INTO `liked_objects` (`uid`, `oid`) VALUES('user_id', 'object_id')
And you can select the liked objects the way you said.
A: i personally recommends you use your current idea. else
another approach :
Serialize
Serialize function help you store arrays into mysql field
use help of serialize function to story array of users that did like these objects to a field (users_liked.objects) on objects table.
and another array stored to user field with the objects that he did likes. (likes.users)
Pros:
When Showing object. just get users_liked.obj
When showing users likes.get likes.user
cons: when user likes, you have to add his id to users_liked.objects and object ID to likes.users
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL REPLACE statement to replace some numbers not all I am trying to use a T-SQL REPLACE statement to replace the middle 4 numbers under the DepartmentID column....
I understand the simple way of changing one set of DepartmentID numbers I want to be able to change all middle numbers under DepartmentID
SELECT REPLACE (DepartmentID,'000701280918','000799990918') AS DepartmentID
FROM Employees
Objective Select all the employees, replace 4 middle numbers with 9999 in DepartmentID:
---4-----4-----4
0007 0128 0918
4 char to the left
4 char to the right
4 char in the middle
Table: Employees
First Column in Table: EmployeeID
Column: DepartmentID
000701280918
000701782662
000702220442
000702118362
000702108487
000702109473
000702033600
000702275707
How would I write the statement
Thank You for your assistance
A: Check out the stuff function:
update YourTable
set DepartmentId = stuff(DepartmentId, 5, 4, '9999')
A: update YourTable
set DepartmentId = left(DepartmentId, 4) + '9999' + right(DepartmentId, 4)
This code would set the DepartmentId column to what is was before, except it would change the middle four numbers to all nines.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Number of column in a table MySQL
Possible Duplicate:
Find the number of columns in a table
I would like to know what is the query which enables to count the number of columns in a table in MySQL.
Something like :
SELECT COUNTNUMBEROFCOLUMN(*) FROM mytable
A: http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
Also
Find the number of columns in a table
Please read the questions before
A: The columns and information:
DESCRIBE my_table;
Using the "Data Dictionary" INFORMATION_SCHEMA to know the number of columns from a table:
SELECT COUNT(*) FROM `INFORMATION_SCHEMA.COLUMNS` WHERE TABLE_NAME='my_table'
Is that what you mean?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Conducting a diacritic sensitive search I've looked all over the web only to find ways to make searches insensitive to diacritic characters, but I need the opposite.
In my situation I need to be able to compare specifically symbols with superscript and subscript dots (i.e. ȧ & ạ) and some other more common acents (á, ã, etc), but these letters might be anything (ṡ, ṛ, ṫ, ḍ, ṅ, etc). The desired result would work like this: if I search for "a" I receive "a" only, and if I search for "ȧ", I receive "ȧ" only as a result and not "a" along with it (without the dot).
I've read that I need to use utf8_bin and have tried changing both my field collations, table collations and database collations to that with no success. Here's the code:
// "sound" is being passed in by an AJAX call
$sound = $_POST['sound'];
$query = "SELECT * FROM sounds WHERE 'sound' = '$sound'";
$result = mysql_query($query);
// This is then sent back to my page.
I've also looked into COLLATE with little success. I'm probably misunderstanding its prober usage:
// Attempting to covert the searched string into the utf8_bin format to match my db collations
$query = "SELECT * FROM sounds WHERE 'sound' = '$sound' COLLATE utf8_bin";
When I use utf8_general_ci or utf8_unicode_ci I get the excepted result of "a" or "ȧ" returning both "ȧ" and "a". However, If I use utf8_bin I get nothing when searching for either of these. I believe this is because in my database when using utf8_bin this - "ṅ(PH)" (one of my entries) - gets converted to this - "e1b98528504829". So Is there a way of converting my searches to that same format before querying them? Or just an all around better way of making this work?
Thank you!
A: My guess is that your data is not normalized. In order to use the utf8_bin collating sequence, you need to be working with normalized data. Both the data in the data base and the data in the query need to be normalized.
The byte sequence e1 b9 85 is the UTF-8 encoding of LATIN SMALL LETTER N WITH DOT ABOVE (U+1E45), but this can be decomposed into LATIN SMALL LETTER N (U+006E) + COMBINING DOT ABOVE (U+0307). The UTF-8 encoding of the decomposition would be 6e cc 87. The utf8_general_ci and utf8_unicode_ci collation sequences take care of this automatically, but utf8_bin does not.
On a separate note--you should not be constructing the query by directly interpolating $sound. This opens up a huge security hole in your system by making it vulnerable to SQL injection attacks. Instead, use a prepared statement and parameter binding. (The php docs have an example of how to do this.)
A: Okay, with a little help from a friend I got it working. Turns out it works just fine with utf8_general_ci collations as well.
My first issue was with how I had entered my data into my database. I had used phpMyAdmin to do this, which for some reason didn't encode the data properly and all my bins were turning out wrong. This was fixed by just writing my own sql to enter the values.
Second, I ended up using the PHP function iconv() to encode the data coming from the web page. These two solutions put together got matching values and the entire script works great.
Thanks all for the help and suggestions... really appreciated, and believe me, did not go to waste. I spent a long time fiddling with all of them.
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: html/css : margin and padding values keep applying to entire div instead of just the text I'm having an issue trying to center a piece of text inside a grey box, every time I move the text the entire grey box moves. I can't seem to figure this out. The problem is with the "show-collections-box" and the link to the collection text inside it. Thanks for any help.
Edit: So I made a div id="show-collections-box" which creates a grey box 228px by 50px. Inside the div I have a link, I wrpapped the link inside another div tag with class="margin". When I apply the margin class, instead of only moving the link inside the div class="margin" down, the entire grey box, div id="show-collections-box", plus the link is moved down 20px.
Here's a jsfiddle of it, you can see the 20px margin-top is pushing the entire grey box down 20px instead of just the word 'collections'.
http://jsfiddle.net/bfU3v/
HTML
<div id="show-collections-box">
<div class="margin"><a href="www.example.com">Collections</a></div>
</div>
CSS
#show-collections-box {
border-bottom: solid 1px #ececec;
border-left: solid 1px #ececec;
background: #faf9f9;
width: 228px;
height: 50px;
}
.margin {
margin-top: 20px;
}
A: I'm not certain I know exactly what you're specific problem could be so this answer is based only on the limited information posted so far.
...every time I move the text the entire grey box moves.
This really sounds like you may be confused about how to apply margins & paddings to elements.
If you apply a margin to a div, that margin is located to the outside of the div thereby moving it around on the page. The margin is not applied to the contents of the div.
If you apply padding to a div, that padding is located just inside the boundaries of the div thereby pushing its contents away from the div's boundaries. The padding is not applied to the contents of the div.
The problem is with the "show-collections-box" and the link to the
collection text inside it.
You have not explained what the problem is. Once you provide a more detailed explanation of exactly what you'd like to achieve, I'll edit this answer accordingly.
EDIT:
I believe there is probably a better way to achieve your goal but to answer your specific question, all I did was remove the inner div entirely and add the 20 pixels as top padding to the outer div. (It should be noted that padding will add to the size of the div. i.e., A 50 pixel high div with 20 pixels of top padding will end up being 70 pixels high)
http://jsfiddle.net/bfU3v/5/
EDIT 2:
If you only have one line of text that will not wrap and you know the height of the div, just add a line-height that equals the height of the div. The text will always be vertically centered.
http://jsfiddle.net/bfU3v/7/
A: Add display: inline-block; to the container.
If for some reason you need the container to not be inline-block, add a second interior wrap with width: 100%; and display: inline-block;.
A: here is a working fiddle
http://jsfiddle.net/kasperfish/bfU3v/3/
no need to use 2 divs for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a checklist on developing a web application from start to finish?
*
*Gather requirements
*Figure out which programming language/DB to use
*Ask mgr if it's okay
*Design the database tables
*Ask mgr if it looks okay
*Mgr says to work with DBA
*DBA says okay
*I code a prototype
*Senior developers, tell me how I should of coded it
*I rework
*Prototype almost finished
*I present my progress to customer, they are happy so far, can I still meet the deadline? Yeah I say.
*Mgr wants to see my progress
*Mgr says I shouldn't use unique seq_key as unique identifier, use emp id, rename foreign keys, add columns, etc..
*I rework db tables
*I rework code and components to reflect db column changes
*Now await mgr review, assuming more rework
*Now I will not make my deadline with customer
Does this happen to the majority of developers?. What am I doing wrong, how can i streamline this process, how can I be more efficient?
A: Well, you can make this more efficient by always be working on three different things.
*
*What you'll show your manager to show you're 'making progress'
*What you'll show your customers to show you're 'making progress'
*What you're actually working on.
Neither your customer nor your manager have time to work out that the example you show them is bogus. Instead, they will be happy to see you making progress. Managers like to see diagrams. Customers like to see pretty interfaces. Make a few of those for your meetings, then spend spending time running everything you do by someone and more time actually working on the product.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How to set the frame of an animation in cocos2d I have made a CCAnimationHelper class that performs the following. You give it a fileName, a frameCount, and a Delay and it will give you back an animation. The thing I want to know is how to set the frame of the animation so instead of starting at frame 1, it will start at frame 10 instead. Here is my code
// Creates an animation from sprite frames.
+(CCAnimation*) animationWithFrame:(NSString*)frame frameCount:(int)frameCount delay:(float)delay
{
// load the ship's animation frames as textures and create a sprite frame
NSMutableArray* frames = [NSMutableArray arrayWithCapacity:frameCount];
for (int i = 1; i < frameCount; i++)
{
NSString* file = [NSString stringWithFormat:@"%@%i.png", frame, i];
CCSpriteFrameCache* frameCache = [CCSpriteFrameCache sharedSpriteFrameCache];
CCSpriteFrame* frame = [frameCache spriteFrameByName:file];
[frames addObject:frame];
}
// return an animation object from all the sprite animation frames
return [CCAnimation animationWithFrames:frames delay:delay]; //Is there another method I should be using here to set the frame
}
A: There isn't a built in funcion that does that, but you can simply create your animation and pass it the NSArray starting at the frame you want:
CCAnimation *animation = [CCAnimation animation];
NSArray *offset = [NSArray arrayWithObjects:frame3, frame4, nil];
[animation initWithFrames:offset];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python HTTP Server available for Multiple Requests I have been doing a lot of studying of the BaseHTTPServer and found that its not that good for multiple requests. I went through this article
http://metachris.org/2011/01/scaling-python-servers-with-worker-processes-and-socket-duplication/#python
and I wanted to know what is the best way for building a HTTP Server for multiple requests
->
My requirements for the HTTP Server are simple -
- support multiple requests (where each request may run a LONG Python Script)
Till now I have following options ->
- BaseHTTPServer (with thread is not good)
- Mod_Python (Apache intergration)
- CherryPy?
- Any other?
A: I have had very good luck with the CherryPy web server, one of the oldest and most solid of the pure-Python web servers. Just write your application as a WSGI callable and it should be easy to run under CherryPy's multi-threaded server.
http://www.cherrypy.org/
A: Indeed, the the HTTP servers provided with the standard python library are meant only for light duty use; For moderate scaling (100's of concurrent connections), mod_wsgi in apache is a great choice.
If your needs are greater than that(10,000's of concurrent connections), You'll want to look at an asynchronous framework, such as Twisted or Tornado. The general structure of an asynchronous application is quite different, so if you think you're likely to need to go down that route, you should definitely start your project in one of those frameworks from the start
A: Tornado is a really good and easy-to-use asynchronous event-loop / webserver developed by FriendFeed/Facebook. I've personally had very good experiences with it. You can use the HTTP classes as in the example below, or only the io-loop to multiplex plain TCP connections.
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
application = tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: java send email using annotations and aop I want to send emails only if they have an annotation in the method, using spring AOP. But how do I get the values in objects using annotation. For example, I have the following method. By using AOP, I can track when placeOrder is called. But how do I get ordernumber, user email address and items ordered from AOP code.
@SendEmail()
public void placeOrder(){
//ordernumber
//user email address
//items ordered
}
Is it possible to have objects in annotations and the methods can set the objects. For example
@SendEmail(order=<order instance>, user=<user instance>, items=<list of item instance>)
public void placeOrder(){
Order order;
User user;
List<Item> items;
}
A: in an annotation you can use only primitives, String, Class, enums, annotations, and arrays of the preceding types. You can obtain the same behaviour using the AOP advice. If you wanna to access to the method objects args or obtain the advise target you can write an advisor like this:
@Aspect
public class AOPSampleAdvice {
.....
@AfterReturning("execution(* *..YorServiceInterface.placeOrder(..))")
public void afterReturning(JoinPoint joinPoint) {
/*Use this if the order is passed in the method signature*/
//Object[] args = joinPoint.getArgs();
//Order order = (Order) args[0];
/**/
Object target = joinPoint.getTarget();
List<Item> items = ((YorServiceInterface) target).getItems();
User user = ((YorServiceInterface) target).getUser();
//Your business
}
Every time the placeOrder method is called when this method return start this advise. You can use:
@Before
@AfterReturning
@AfterThrowing
@After (finally)
@Around
To register this advise in your applicationContext.xml write this:
<!-- enable aop -->
<aop:aspectj-autoproxy/>
<bean id="adviseAspect" class="com.foo.acme.AOPSampleAdvice"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I convert Hex values to 32-bit MIPS instructions? I need to convert these Hex values to MIPS instructions:
I converted them to binary first, but not sure if it is necessary.
Hex: 0x0000 0000 - Binary: 0000 0000 0000 0000 0000 0000 0000 0000
Hex: 0xAFBF 0000 - Binary: 1010 1111 1011 1111 0000 0000 0000 0000
Hex: 0x3424 001E - Binary: 0011 0100 0010 0100 0000 0000 0000 0000
Please explain the process so I can do it in the future.
I have this MIPS reference data sheet
A: The MIPS instruction encoding is very simple and it was explained in every MIPS documents including the sheet you read above. Just get the opcode field and determine if that's an R, I or J-type instruction to get the remaining parameters correctly. If the opcode is 0 then it's always R type, in that case look up the function field
For the first instruction 0x00000000:
6-bit opcodes = 000000: R type
6-bit funct: 000000 ==> sll
rs, rd, rt = 0
==> sll $0, $0, $0 or nop
The second instruction 0xAFBF0000:
opcode: 101011 = 0x2B => sw
The last one 0x3424001E:
opcode: 001101 = 0x0D => ori
If you use some disassembler like ODA you'll see the result like this
.data:0x00000000 00000000 nop
.data:0x00000004 afbf0000 sw ra,0(sp)
.data:0x00000008 3424001e ori a0,at,0x1e
A: Are you looking for a MIPS disassember? Here's one:
http://acade.au7.de/disasmips.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Wrapper functions for IndexedDB I need to build an offline HTML5 web app for a iPad/tablet device where the user can download a dataset (table of data) from the server and store it on the device. The user could then disconnect from the server and view/edit the data locally on the device. This is for people who work out in remote areas where there's no cellular coverage and need to collect/update data. When they come back into the office they can sync/upload the data back to the server. The reason it needs to be HTML5 is so it's platform agnostic, ie can run it on iOS, Android etc as long as it has a modern web browser that supports HTML5.
Now I've already built the system using HTML5 local storage (for the data) and the HTML5 offline application cache (for the pages/css/js/images) and it works reasonably well with small datasets (I can view, edit and save while offline and load/sync while online). Now I need to scale up to 10,000 rows of data. It works but it's pretty slow and hangs the browser for 10secs while loading on an Intel quad core 8GB machine.
So I've been researching a few better alternatives than local storage:
1) WebSQL: Would be able to query the data using SQL language and do joins etc. Problem is it's now deprecated an won't be supported any longer so I don't want to invest time building something for it.
2) IndexedDB: Uses an object store (which technically I'm already storing objects using local storage API and storing using JSON). Potentially is faster as it uses indexes with the SQL lite backend. There's lots of boilerplate code to do simple tasks like creating the database, adding to it, reading from it, iterating over it. I just want to do a simple query like select(xyc, abc).where(abc = 123).limit(20) but instead have to write a lot of JavaScript code to do it. How does one write their own code to do joins between tables, any examples anywhere?
I've found one jQuery plugin that might make life simpler. Are there any other ones around or other libraries that ease the pain of using IndexedDB?
Many thanks!
A: I have an open source web database wrapper which supports both IndexedDB and WebSql.
Version migration is handled behind sense. The following code migrates (or initialize) to version 2.
schema_ver2 = {
version: 2,
size: 2 * 1024 * 1024, // 2 MB
stores: [{
name: 'ydn_obj',
keyPath: 'id.value',
indexes: [{
name: 'age',
type: 'INTEGER' // type is require for WebSql
}]
}]
}
db = new ydn.db.Storage('db name', schema_ver2)
Query is very flexible and powerful. For example:
q = db.query('customer').when('age', '>=', 18 , '<', 25).where('sex', '=', 'FEMALE')
young_girls = q.fetch(10, 2); // limit and offset
Again with more efficient key range query if age is indexed:
q = db.query('customer', 'age').bound(18, 25, true).where('sex', '=', 'FEMALE')
It also support transaction.
p123 = db.tkey('player', 123);
db.runInTransaction(function() {
p123.get().success(function(p123_obj) {
p123_obj.health += 10;
p123.put(p123_obj);
});
}, [p123]);
A: Try linq2indexeddb. It has the query interface you want + with the indexeddb shim for websql the WebSQL API is also supported.
A: Have you considered [Lawnchair][1]? It provides a nice abstraction from the underlying storage, there are also plugins for querying, aggregating and paginating data. As an example of querying:
// basic searching
this.where('record.name === "brian"', 'console.log(records)')
this.where('record.name != ?', username, 'console.log(records)')
// sorting results
this.where('name === "brian"').asc('active', 'console.log(records)')
The only potential drawback I can see is that it doesn't appear to handle migrations and being generic doesn't appear to have a way of creating indexes etc.
With regards to joins, IndexedDB is designed to be a document oriented (No SQL) store not a relational database, however given this is a common scenario it appears there are two options:
1) Cursor iterate over the data items
2) If the above is too slow, you could also create a dedicated key value object store which could then be used to do an indexed lookup in the relevant store. Depending on the number of join requirements you have, this could be a chore.
A: I think JsStore will work for you.
Lets say your query looks something like this in sql -
select * from table_name where column1='abc' limit 20
In JsStore - It will be
var Connection = new JsStore.Instance("YourDbName");
Connection.select({
From: "table_name"
Where: {
Column1: 'abc',
},
Limit:20,
OnSuccess:function (results){
console.log(results);
},
OnError:function (error) {
console.log(error);
}
});
So you can write sql like query using JsStore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Dynamic Linking/Referencing of Classes at Runtime on Android I am wondering is there is a simple and clean way of achieving the desired functionality below:
I have a main APK that provides the core functionality of my application, which contains an abstract class to be extended. There are various other APKs, each containing a unique subclass of the abstract class and overriding some of its methods in order to provided extended functionality. When these subclasses are instantiated, they require decoding of resources contained in their respective APKs. I chose to have these subclasses in separate APKs to allow the user to install only the desired components without having to modify the main APK, which will provide a list of all available components on launch.
My main questions:
Is there a way to reference a class in another APK without duplicating code like my subclasses are trying to accomplish?
Is it possible to reference or pass the instantiated subclasses back to my main application where the overridden methods will be called with only knowledge of the original abstract class?
Thanks.
A: If all the APKs are signed with the same certificate, you can use the method outlined in this answer:
Android: how to share code between projects signed with the same certificate
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get values of all checkboxes in child elements all im tryin to do is get the values of all checkboxes in child elements, i have seen this question: How to retrieve checkboxes values in jQuery but cant successfully get it working on child elements
My code is this:
<ul id="menu3" class="side_menu expandfirst noaccordion">
<li>
<div class="refine_att"><a href="#" name="Expand/Collapse">Price</a></div>
<ul class="check">
<li><input onclick="updateTextArea()" id="_1" type="checkbox"><a href="#"> £0.00 - £9.99 </a></li>
<li><input onclick="updateTextArea()" id="_2" type="checkbox"><a href="#"> £10.00 - £99.99 </a></li>
<li><input onclick="updateTextArea()" id="_3" type="checkbox"><a href="#"> £100.00 - £249.99 </a></li>
<li><input onclick="updateTextArea()" id="_4" type="checkbox"><a href="#"> £250.00 - £499.99 </a></li>
<li><input onclick="updateTextArea()" id="_5" type="checkbox"><a href="#"> £500.00 - £999.99 </a></li>
</ul>
</div>
</li>
</ul>
There could also be multiple 'refine_att' lists, ive shown just one here
function updateTextArea() {
var allVals = [];
$('#menu3').find(":checked").each(function() {
allVals.push($(this).val());
});
$('#t').val(allVals)
}
A: You could try the following:
function updateTextArea() {
var vals = $('#menu3 input:checkbox:checked').map(
function(){
return this.id + ': ' + $(this).val();
}).get().join(', ');
$('#t').text(vals);
}
$('input:checkbox').change(
function(){
updateTextArea();
});
JS Fiddle demo.
A: Shouldn't you be checking any data of your checkbox values, rather than checking the inner html of your tags? Also, I would get rid of the onclick, and do a jquery search on ALL checkboxes inside the ul. Like (notice that I added an id, and added values to the checkboxes):
<ul class="check" id="ul_check">
<li><input id="_1" type="checkbox" value="0"><a href="#"> £0.00 - £9.99 </a></li>
<li><input id="_2" type="checkbox" value="10"><a href="#"> £10.00 - £99.99 </a></li>
<li><input id="_3" type="checkbox" value="100"><a href="#"> £100.00 - £249.99 </a></li>
<li><input id="_4" type="checkbox" value="250"><a href="#"> £250.00 - £499.99 </a></li>
<li><input id="_5" type="checkbox" value="500"><a href="#"> £500.00 - £999.99 </a></li>
</ul>
jQuery:
$('#ul_check input:checkbox').change(
function(){
var strSelectedVals = $('#ul_check input:checkbox:checked').map(
function(){
return $(this).val();
}).get().join(',');
$('#t').val(strSelectedVals );
});
The jQuery makes all click-changes on checkboxes within the element with id="ul_check", to get all elements of type checkboxes that are checked WITHIN the id="ul_check" element, then create an appended ('glued') string with a comma ',' in between the values. Without the onClick in each checkbox, you are separating jQuery/javascript from HTML, so it all becomes cleaner and overseeable. Also, the jQuery could work on class="check", but it would then check other elements with that class, so ID is better for this jQuery suggestion. I am assuming that you have a element, instead of a textarea? If textarea, use:
$('#t').text(strSelectedVals);
strSelectedVals will contain something like "0,10,100" depending on which checkboxes you selected. (With PHP, you can, if you wish, then do an explode(",", $POST["[...]"]) to get all values, etc...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Algorithm for finding intersections of straight lines there's this problem about line crossings I saw somewhere and was trying to solve.
There's a 64x64 grid of 8 bit pixels and it has a bunch of 1 pixel wide vertical and horizontal lines of different colors on it. All parallel lines have at least one space between them. The problem is to find the number of line crossings that each set of colored lines makes (e.g. all green line crossings count towards one sum). And find which set of lines had the fewest amount of crossings. Also, all vertical lines of a color are the same size and all horizontal lines of the same color are the same size.
I had a few ideas but they all seem pretty inefficient. It would involve going through every pixel in the grid, if you run into a color determine if it's a vertical or horizontal line, and then go in the direction of the line all the while checking adjacent sides for different colors.
I'm trying to decide if first counting the length of the horizontal and vertical lines for each color would speed up the process. Do you guys have any brilliant ideas for how to do this?
Here are two examples. Notice that parallel lines always have a space in between them.
A: Scanning a pixel grid is actually very fast and efficient. It's standard for computer vision systems to do that kind of thing. A lot of these scans produce a FIR filtered versions of images that emphasize the kinds of details being searched for.
The main technical term is "convolution" (see http://en.wikipedia.org/wiki/Convolution). I think of it as a kind of weighted moving average, though weights can be negative. The animations on Wikipedia show convolution using a rather boring pulse (it could have been a more interesting shape), and on a 1D signal (like a sound) rather than a 2D (image) signal, but this is a very general concept.
It's tempting to think that something more efficient can be done by avoiding calculating that filtered version in advance, but the usual effect of that is that because you haven't precalculated all those pixels, you end up calculating each pixel several times. In other words, think of the filtered image as a lookup-table based optimisation, or a kind of dynamic programming.
Some particular reasons why this is fast are...
*
*It is very cache-friendly, so accesses memory efficiently.
*It is exactly the kind of thing that vector instructions (MMX, SIMD etc) are designed to support.
*These days, you may even be able to offload the work onto your graphics card.
Another advantage is that you only need to write one image-filtering convolution function. The application-specific part is how you define the filter kernel, which is just a grid of weight values. In fact you probably shouldn't write this function yourself at all - various libraries of numeric code can supply highly optimised versions.
For handling the different colours of lines, I'd simply generate one greyscale image for each colour first, then filter and check each separately. Again, think of this as the optimisation - trying to avoid generating the separate images will likely result in more work, not less.
*
*On second thoughts, I may have understood the requirement. It may make more sense to generate a black-and-white image from the black-and-colours, filter that, and the find all intersections from that. Once you have the intersection points, then refer back to the original black-and-colours image to classify them for the counting. The filtering and intersection-finding remains very efficient per pixel. The classifying isn't so efficient per pixel, but is only done at a few points.
You could do a convolution that based on the following FIR filter kernel...
.*.
***
.*.
Dots are zeros (pixel irrelevant) or, possibly, negative values (prefer black). Asterisks are positive values (prefer white). That is, look for the three-by-three crosses at the intersections.
Then you scan the filtered result looking for greyscale pixels that are brighter than some threshold - the best matches for your pattern. If you really only want exact crossing points, you may only accept the perfect-match colour, but you might want to make allowances for T-style joins etc.
A: On the grid with your lines look for 2 types of 3x3 squares:
1).a. 2).a.
bab bbb
.a. .a.
"." represents background (always black?), "a" and "b" represent 2 different colors (also different from the background color). If found, bump up by 1 the counts for a-colored line intersections and b-colored line intersections.
A: Is your only input the 64x64 grid? If so, then you're looking at something with a 64x64 flavor, since there's no other way to ensure you've discovered all the lines. So I will assume you're talking about optimizing at the operation level, not asymptotically. I seem to remember the old "Graphics Gems" series had lots of examples like this, with an emphasis on reducing instruction count. I'm better at asymptotic questions myself, but here are a few small ideas:
The grid cells have the property that grid[i,j] is a green intersection if
(grid[i,j] == green)
&&
(grid[i+1,j]==green || grid[i-1,j]==green)
&&
(grid[i,j+1]==green || grid[i, j-1]==green)
So you can just scan the array once, without worrying about explicitly detecting horizontal and vertical lines ... just go through it using this relationship and tally up intersections as you find them. So at least you're just using a single 64x64 loop with fairly simple logic.
Since no two parallel lines are directly adjacent, you know you can bump your inner loop counter by 2 when you pass a populated cell. That'll save you a little work.
Depending on your architecture, you might have a fast way to AND the whole grid with offset copies of itself, which would be a cool way to compute the above intersection formula. But then you still have to iterate through the whole things to find the remaining populated cells (which are the intersection points).
Even if you don't have something like a graphics processor that lets you AND the whole grid, you can use the idea if the number of colors is less than half of your word size. For example, if you have 8 colors and a 64-bit machine, then you can cram 8 pixels into a single unsigned integer. So now you can do the outer loop comparison operation for 8 grid cells at a time. This might save you so much work it's worth doing two passes, one for a horizontal outer loop and one for a vertical outer loop.
A: Simple way to find straight intersection
def straight_intersection(straight1, straight2):
p1x = straight1[0][0]
p1y = straight1[0][1]
p2x = straight1[1][0]
p2y = straight1[1][1]
p3x = straight2[0][0]
p3y = straight2[0][1]
p4x = straight2[1][0]
p4y = straight2[1][1]
x = p1y * p2x * p3x - p1y * p2x * p4x - p1x * p2y * p4x + p1x * p2y * p3x - p2x * p3x * p4y + p2x * p3y * p4x + p1x * p3x * p4y - p1x * p3y * p4x
x = x / (p2x * p3y - p2x * p4y - p1x * p3y + p1x * p4y + p4x * p2y - p4x * p1y - p3x * p2y + p3x * p1y)
y = ((p2y - p1y) * x + p1y * p2x - p1x * p2y) / (p2x - p1x)
return (x, y)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to show my javascript counter result in 2 divs on the same page? I have a javascript counter (named clock because it counts seconds) where the results are displayed in a div:
<div id="right">Time: <input id="clock" type="text" value="00:00" style="text-align: left; background:transparent; border-style: none; color:#ffbe5e; margin: 0px; font: 20px shanghai; width:60px;" readonly /></div>
This all works and it's displays counting the seconds. Now I want the same display results shown in a sec div at the same page, but how to do this? Simply copy and paste the code again doesn't work.
Any suggestions?
Kind regards,
ps I didn't post the javascript code cause it's a bit too big to copy/paste it in here. If you need it, let me know
A: As dgvid suggested above, please make sure to have separate ids for each counter you have.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Representing Data Types With Variable Variables I am attempting to represent formulae with variables ranging over, for instance, either formulae or variables and constants:
R(a,b) -> Q [Q takes formulae as substitutions]
R(x,b) v P(b) [x takes constants or variables as substitutions]
Functions over formulae have class constraints specifying which variable type is being considered. For instance, classes of terms, variables and substitutions might have the following structure:
class Var b where ...
class (Var b) => Term b a | b -> a where ...
class (Term b a) => Subst s b a | b a -> s where ...
There are many algorithms dealing with syntactic term manipulation for which parameterizing term types on variable types would be beneficial. For instance, consider a generic unification algorithm over formulae of some term type having different variable types:
unify :: (Subst s b a) => a -> a -> s b a
unify (P -> F(a,b)) ((Q v R) -> F(a,b)) = {P\(Q v R)} -- formulae
unify (P(x,f(a,b))) (P(g(c),f(y,b))) = {x\g(c),y\a} -- variables and constants
What is the best way to represent such variable variables? I have experimented with a variety of methods, but haven't settled on a satisfactory solution.
A: Maybe your question would be clearer if you said what was wrong with the following simple minded representation of terms and formulas? There are a million ways of doing this sort of thing (the possibilities much expanded by {-LANGUAGE GADTs-})
{-#LANGUAGE TypeOperators#-}
data Term v c = Var v
| Const c deriving (Show, Eq, Ord)
data Formula p v c = Atom p
| Term v c := Term v c
| Formula p v c :-> Formula p v c
| Not (Formula p v c)
| Subst v (Term v c) (Formula p v c)
| Inst p (Formula p v c) (Formula p v c)
deriving (Show, Eq, Ord)
update f v c v' = case v == v' of True -> c; False -> f v'
one = Const (1:: Int)
zero = Const (0 :: Int)
x = Var 'x'
y = Var 'y'
p = Atom 'p'
q = Atom 'q'
absurd = one := zero
brouwer p = (((p :-> absurd) :-> absurd) :-> absurd) :-> (p :-> absurd)
ref :: (v -> c) -> Term v c -> c
ref i (Var v) = i v
ref i (Const c) = c
eval :: (Eq c , Eq v , Eq p) => (v -> c) -> (p -> Bool) -> Formula p v c -> Bool
eval i j (Atom p) = j p
eval i j (p := q) = ref i p == ref i q
eval i j (p :-> q) = not ( eval i j p) || eval i j q
eval i j (Not p) = not (eval i j p)
eval i j q@(Subst v t p) = eval (update i v (ref i t)) j q
eval i j q@(Inst p r s) = eval i (update j p (eval i j r)) s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Assign Common ID to multiple row insert from MySQL array I have a PHP script that inserts rows into a table based on selected rows from a MySQL array.
the code to insert the rows into the new table is:
$sql="insert into loaddetails (CaseNo,GrossMass,CaseStatus,Customer)
select `case no`,`gross mass`,`case status`, customer from
availablestock where `case no` = '$val'";
I want to assign all the inserted rows the same ID so that multiple stock items share the same LoadID.
How can I modify my code to do this so all the inserted records share the same ID and the ID is unique to the load.
I thought I could use the code below to get the max id and increment it by one
SELECT max(loadid)+1 from loaddetails
How can I acheive this? I realise my PHP code is not perfect but it is functional, I just need to add the functionality to allow for the rows to be inserted with a common ID to produce a result as below:
Thanks in advance for the assistance.
Regards,
Ryan Smith
Complete code is:
<?php
mysql_connect("localhost", "user", "password")or die("cannot connect");
mysql_select_db("databasename")or die("cannot select DB");
$sql="SELECT `case no`,`customer`,`gross mass`, `case status` from availablestock where transporttypename= 'localpmb'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table border=1>
<tr>
<td>
<form name="form1" method="post">
<table>
<tr>
<td>#</td>
<td>Case Number</td>
<td>Customer</td>
<td>Weight</td>
<td>Status</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><input type="checkbox" name=check[] value="<?php echo $rows['case no']; ?>"></td>
<td><?php echo $rows['case no']; ?></td>
<td><?php echo $rows['customer']; ?></td>
<td><?php echo $rows['gross mass']; ?></td>
<td><?php echo $rows['case status']; ?></td>
</tr>
<?php
}
?>
<tr>
<td><input name="planlocalpmb" type="submit" id="planlocalpmb" value="planlocalpmb"></td>
</tr>
<?php
$check=$_POST['check'];
if($_REQUEST['planlocalpmb']=='planlocalpmb'){
{
$sql="insert into loaddetails (CaseNo,GrossMass,CaseStatus,Customer) select `case no`,`gross mass`,`case status`, customer from availablestock where `case no` = '$val'";
foreach($check as $key=>$value)
{
$sql="insert into loaddetails (CaseNo,GrossMass,CaseStatus,Customer) select `case no`,`gross mass`,`case status`, customer from availablestock where `case no` = '$value'";
$final=mysql_query($sql);
if($final)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=php.php\">";
} }
}
}
// Check if delete button active, start this
// if successful redirect to php.php
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
A: INSERT INTO loaddetails (LoadID, CaseNo, GrossMass, CaseStatus, Customer)
SELECT (SELECT MAX(loadid)+1 FROM loaddetails) LoadID, CaseNo, GrossMass, CaseStatus, Customer
FROM availablestock WHERE CaseNo = '$val'
Make sure LoadID has an index!
You may need to lock the table first. I'm not sure.
I didn't check the rest of your code, but I do notice you have an SQL Injection vulnerability there.
A: You can also try:
INSERT INTO loaddetails
(LoadID, CaseNo, GrossMass, CaseStatus, Customer)
SELECT m.NewLoadId, CaseNo, GrossMass, CaseStatus, Customer
FROM availablestock
CROSS JOIN
( SELECT MAX(loadid)+1 AS NewLoadId
FROM loaddetails
) AS m
WHERE CaseNo = '$val'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: validating parameters under script tag i need to include codes for "value must be nonnegative" when a negative number is entered. i have already included codes for "value must be a number."
<script type="text/javascript">
function test_ifinteger(testcontrol, nameoffield) {
var x = 0;
var isok = true;
var teststring = testcontrol.value;
if (teststring.length == 0)
return true;
else {
while (x < teststring.length) {
if (teststring.charAt(x) < '0' || teststring.charAt(x) > '9')
isok = false;
x++;
} //end while
if (!isok) {
alert(nameoffield + " must be a number!");
testcontrol.focus();
} //end else if(ok)
return isok;
}//end else if (teststring.length==0)
} //end function
</script>
A: You can check the first char of the string, it will be "-" if its a negative number.
Use this:
var negative = "-1234";
if (negative[0] == '-')
MessageBox.Show("Negative Number");
or add to your code:
while (x < teststring.length) {
if (x == 0 && teststring.charAt(x) == '-')
MessageBox.Show("Negative Number - Do what you want");
if (teststring.charAt(x) < '0' || teststring.charAt(x) > '9')
isok = false;
x++;
Also, if its either negative or not a number, consider breaking the loop to avoid unnecessary loop iterations.
use the "break" command.
if (x == 0 && teststring.charAt(x) == '-')
{
MessageBox.Show("Negative Number - Stopping loop");
break;
}
A: Try,
<script type="text/javascript">
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function test_ifinteger(testcontrol, nameoffield) {
var teststring = testcontrol.value;
if(isNumber(teststring)) {
var no=parseFloat(teststring); // or use parseInt
if(no<0) {
//negative
}
}
else {
//not a number
}
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to 'follow' foreign keys in a SQL client I am currently using Sequel Pro to view my database. I find much of my time spent on 'following' foreign keys. For example, if an entry in table A links to table B, I find myself writing down the id number, then clicking the other table, scrolling down to find that id, etc. It becomes quite tedious.
Is there a way in Sequel Pro or in another SQL client to link to the FK (e.g., double click the FK and it takes you to that entry)?
A: You can benefit from the foreign key lookup editor for easy editing of fields referencing other tables in dbForge Studio for MySQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7629772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits