text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Wordpress: Parameter for Shortcode function I am trying to create a shortcode in Wordpress, in which the function that is called with the shortcode tag gets the shortcode tag as parameter.
So say I have
<?php
var $shortcode = 'my_shortcode_tag';
add_shortcode( $shortcode, 'my_shortcode_function');
?>
then I want 'my_shortcode_function' to know the shortcode tag by it was called. I know that I could use attributes as in [my_shortcode_tag tag='my_shortcode_tag'] when I call the shortcode in my actual post, but I want to be able to just write [my_shortcode_tag] and my function to know that it was called by that tag. Is there a way to do this?
A: This is sent in as the third argument to a shortcode function (as mentioned in the Shortcodes API).
for example:
add_shortcode( 'shortcode1', 'my_shortcode_function');
add_shortcode( 'shortcode2', 'my_shortcode_function');
function my_shortcode_function($atts, $content, $sc) {
return $sc;
}
this will output the name of the shortcode called for that function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I generate a Webservice Client in IntelliJ IDEA? I have to set up a connection to a webservice that I don't own, all I have is a link to the WSDL file. The webservice has only one method, and I need access to it. I'm trying to use the standard "Generate Java Code from Wsdl or Wadl" (or create New->Web Service Client, which ends up in the same spot)
When I enter the URL I have, the status line says "Wsdl url connection exception". If I put the url in a browser, it nicely displays the xml file, so the URL works. I have a similar problem trying to generate the code in eclipse, where it also refuses to acknowledge the URL.
It's the first time I do anything webservice related and it's driving me mad, how do I fix this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Cognos like cubes What are the various options to have a cube designer in Java other than Cognos?
Basically I need to see a multi-dimensional cube and the user must be able to select the columns to filter by.
A: You probably want to take a look at Pentaho
It's a very comprehensive BI solution, open source, Java based.
There's an online demo of some of the features: http://demo.pentaho.com
There is "some assembly required" to the extent that it is more of a toolkit for building BI solutions than an "out of the box" product. But it is very capable and mature, probably the best solution available if you don't want to buy an expensive proprietary tool like Cognos.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: error: requestFeature() must be called before adding content - Still won't work I know that similar questions have been asked in the past but I can't seem to get this working at all even with the suggestions.
I get the above abend on the "show()" command.
public void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.submitscoredummylayout);
scoreloopInit();
AlertDialog whatToUploadDialog;
whatToUploadDialog = new AlertDialog.Builder(YanivSubmitScoreActivity.this).create();
whatToUploadDialog.setContentView(R.layout.submitscoreprompt);
whatToUploadDialog.setTitle(R.string.uploadedScoreTitle);
whatToUploadDialog.setCancelable(false);
((CheckBox)whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setChecked(settings.getUploadToSL());
((CheckBox)whatToUploadDialog.findViewById(R.id.ckbFacebook)).setChecked(settings.getUploadToFB());
((CheckBox) whatToUploadDialog.findViewById(R.id.ckbScoreloop)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) {
settings.setUploadToSL(isChecked,true);
findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToFB());
}
});
((CheckBox) whatToUploadDialog.findViewById(R.id.ckbFacebook)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton ckBox, boolean isChecked) {
settings.setUploadToFB(isChecked,true);
findViewById(R.id.btnYes).setEnabled(isChecked||settings.getUploadToSL());
}
});
whatToUploadDialog.findViewById(R.id.btnYes).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
submitScore(SUBMIT_UPLOAD_TO_SL);
whatToUploadDialog.dismiss();
}
});
whatToUploadDialog.findViewById(R.id.btnNo).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
whatToUploadDialog.dismiss();
finish();
}
});
whatToUploadDialog.show();
}
Logcat:
W/System.err(14969): android.util.AndroidRuntimeException: requestFeature() must be called before adding content
W/System.err(14969): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:184)
W/System.err(14969): at com.android.internal.app.AlertController.installContent(AlertController.java:198)
W/System.err(14969): at android.app.AlertDialog.onCreate(AlertDialog.java:251)
W/System.err(14969): at android.app.Dialog.dispatchOnCreate(Dialog.java:307)
W/System.err(14969): at android.app.Dialog.show(Dialog.java:225)
W/System.err(14969): at ui.YanivSubmitScoreActivity.onCreate(YanivSubmitScoreActivity.java:105)
W/System.err(14969): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
W/System.err(14969): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
W/System.err(14969): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
W/System.err(14969): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
W/System.err(14969): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
W/System.err(14969): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(14969): at android.os.Looper.loop(Looper.java:123)
W/System.err(14969): at android.app.ActivityThread.main(ActivityThread.java:4627)
W/System.err(14969): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(14969): at java.lang.reflect.Method.invoke(Method.java:521)
W/System.err(14969): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
W/System.err(14969): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
W/System.err(14969): at dalvik.system.NativeStart.main(Native Method)
A: Substitude the following line:
whatToUploadDialog.setContentView(R.layout.submitscoreprompt);
with:
whatToUploadDialog.setView(R.layout.submitscoreprompt);
A: I experienced the same problem. I found that the problem only occurs if I do both of the following things:
*
*I don't use activity managed dialogs (activity.showDialog() ->
activity.onCreateDialog()/onPrepareDialog())
*I do dialog.findViewById() (and this is indeed the line difference
between success or the requestFeature exception!).
final Builder dialogBuilder = new AlertDialog.Builder(activity);
b.setView(rootView);
b.setIcon(android.R.drawable.ic_dialog_info);
b.setTitle(R.string.message_of_the_day_title);
b.setCancelable(false);
dialog = b.createDialog();
dialog.findViewById(R.id.myid); // this is the problem
The dialog.findViewById() causes the problem because it calls
dialog.getWindow().getDecorView()
and the method javadoc of getDecorView() says:
Note that calling this function for the first time "locks in" various
window characteristics as described in {@link #setContentView(View,
android.view.ViewGroup.LayoutParams)}.
Isn't that nice, findViewById() has a side effect which causes seemingly correct applications to crash. Why there's a difference between Activity managed dialogs and normal dialogs I do not know, but I guess getDecorView() does some magic for Activity managed dialogs.
I did the above because I moved from using Activity managed dialogs to handling dialogs myself.
The solution for me is to manipulate the rootView, using rootView.findViewById(), instead of manipulating the dialog.
A: Try calling
.setTitle(R.string.uploadedScoreTitle);
before
.setContentView(R.layout.submitscoreprompt);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how can i pass perl variable in sql file in perl script here i have 3 variable in perl and i m passing those variable in one db.sql file in sql query line then executing that db.sql file in same perl file but it's not fetching those variable.
$patch_name="CS2.001_PROD_TEST_37987_spyy";
$svn_url="$/S/B";
$ftp_loc="/Releases/pkumar";
open(SQL, "$sqlfile") or die("Can't open file $sqlFile for reading");
while ($sqlStatement = <SQL>)
{
$sth = $dbh->prepare($sqlStatement) or die qq("Can't prepare $sqlStatement");
$sth->execute() or die ("Can't execute $sqlStatement");
}
close SQL;
$dbh->disconnect;
following is the db.sql file query
insert into branch_build_info(patch_name,branch_name,ftp_path)
values('$patch_name','$svn_url','$ftp_loc/$patch_name.tar.gz');
pls help me how can i pass the variable so that i can run more the one insert query at a time.
A: If you can influence the sql-file, you could use placeholders
insert into ... values(?, ?, ?);
and then supply the parameters at execution:
my $ftp_path = "$ftp_loc/$patch_name.tar.gz";
$sth->execute( $patch_name, $svn_url, $ftp_path) or die ...
That way you would only need to prepare the statement once and can execute it as often as you want. But I'm not sure, where that sql-file comes from. It would be helpful, if you could clarify the complete workflow.
A: there's a few problems there - looks like you need to read in all of the SQL file to make the query, but you're just reading it a line at a time and trying to run each line as a separate query. The <SQL> just takes the next line from the file.
Assuming there is just one query in the file, something like the following may help:
open( my $SQL_FH, '<', $sqlfile)
or die "Can't open file '$sqlFile' for reading: $!";
my @sql_statement = <$SQL_FH>;
close $SQL_FH;
my $sth = $dbh->prepare( join(' ',@sql_statement) )
or die "Can't prepare @sql_statement: $!";
$sth->execute();
However, you still need to expand the variables in your SQL file. If you can't replace them with placeholders as already suggested, then you'll need to either eval the file or parse it in some way...
A: You can use the String::Interpolate module to interpolate a string that's already been generated, like the string you're pulling out of a file:
while ($sqlStatement = <SQL>)
{
my $interpolated = new String::Interpolate { patch_name => \$patch_name, svn_url => \$svn_url, ftp_loc => \$ftp_loc };
$interpolated->($sqlStatement);
$sth = $dbh->prepare($interpolated) or die qq("Can't prepare $interpolated");
$sth->execute() or die ("Can't execute $interpolated");
}
Alternately, you could manually perform replacements on the string to be interpolated:
while ($sqlStatement = <SQL>)
{
$sqlStatement =~ s/\$patch_name/$patch_name/g;
$sqlStatement =~ s/\$svn_url/$svn_url/g;
$sqlStatement =~ s/\$ftp_loc/$ftp_loc/g;
$sth = $dbh->prepare($sqlStatement) or die qq("Can't prepare $sqlStatement");
$sth->execute() or die ("Can't execute $sqlStatement");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disable scrolling the webview
Possible Duplicate:
Disable UIWebView default scrolling behavior using objective-c
I want to disable my webview scrolling, I have checked all property but I could not find any property which is useful for me , if this is possible please help me.
Thanks.
A: Check this code which may be helpful
UIView* row = nil;
for(row in webView.subviews){
if([row isKindOfClass:[UIScrollView class] ]){
UIScrollView* scrollRow = (UIScrollView*) row;
scrollRow.scrollEnabled = NO;
scrollRow.bounces = NO;
scrollRow.backgroundColor=[UIColor clearColor];
}
}
A: try this...
for(UIView *scrl in webView.subviews){
if([row isKindOfClass:[UIScrollView class] ]){
UIScrollView* scrollView = (UIScrollView*) scrl;
// stop scrolling
scrollView.scrollEnabled = NO;
//stop bounceback of webView..
scrollView.bounces = NO;
}
}
A: Use this it works fine; webDescription is a UIWebView object.
[[webDescription.subviews lastObject] setScrollEnabled:NO];
A: Try this
[[[yourWebViewObject subviews] lastObject] setScrollEnabled:NO];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to check if data is being sent to a Port with C# UdpClient I have a program whereby Data is being sent from one computer to another via UDP. The problem is that data may not always be sent by the sending program and I want my receiving program's receive functionality to be enabled ONLY when something is being sent to a specified port (5000 in this case), otherwise when the user tries to receive data on the port using UdpClient the program crashes. For example:
private const int listenPort = 5000;//receiving port
UdpClient listener = new UdpClient(listenPort);//udclient instance
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
public string received_data;
public byte[] receive_byte_array;
private void receiveButton_Click(object sender, RoutedEventArgs e)
{
receive_byte_array = listener.Receive(ref groupEP);
received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
textBox1.Text = received_data.ToString();
}
My problem here is when there is no data being sent and the User clicks receiveButton on the main window my whole program crashes. To be specific the problem is here:
receive_byte_array = listener.Receive(ref groupEP);
I've tried to fix the problem by putting the above line of code in a try catch statement but even then the program crashes! It seems merely trying to receive data on the IPEndpoint port when there is none raises hell.
Any ideas as to how I can first check if data is being sent to the port and only then allow the user to receive data? Thanks in advance.
A: based on your comment I'd say the program is freezing because it is waiting for data to receive. your user interface freezes because you've started listening for data synchronously from the UI thread and it is now preoccupied with listening for data and not repainting or processing input. to fix this put the listening bit in a separate thread or use the async BeginReceive method to receive the data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET Visitors counter I am creating a counter for my webpage. What wan't to achieve is that every time user visits my asp.net application, it stores his data into database. I am using Global.asax and event Application_Start. Here is my code .
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
WebpageCounter.SaveVisitor(new WebpageVisitor()
{
VisitorIP = HttpContext.Current.Request.UserHostAddress,
VisitedOn = DateTime.Now
});
}
But it never stores anything into database. The function SaveVisitor has been tested and it is functional.
Any suggestions ?
A: Application_Start() is only called once for the lifetime of the application domain - not for every request to your site. Also see "ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0"
A:
Code for the code behind:
C#
protected void Page_Load(object sender, EventArgs e)
{
this.countMe();
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}
private void countMe()
{
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());
hits += 1;
tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();
tmpDs.WriteXml(Server.MapPath("~/counter.xml"));
}
VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
Me.countMe()
Dim tmpDs As New DataSet()
tmpDs.ReadXml(Server.MapPath("~/counter.xml"))
lblCounter.Text = tmpDs.Tables(0).Rows(0)("hits").ToString()
End Sub
Private Sub countMe()
Dim tmpDs As New DataSet()
tmpDs.ReadXml(Server.MapPath("~/counter.xml"))
Dim hits As Integer = Int32.Parse(tmpDs.Tables(0).Rows(0)("hits").ToString())
hits += 1
tmpDs.Tables(0).Rows(0)("hits") = hits.ToString()
tmpDs.WriteXml(Server.MapPath("~/counter.xml"))
End Sub
XML file will look like this:
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
A: Application_Start is runs only when process created - not every visit.
You can use Application_BeginRequest instead.
A: This information can be logged by IIS, and then queried/transformed using the excellent logparser. You could also put Google Analytics on your site - its free version is sufficient for all but the busiest sites. If you still feel the need to do this yourself, then Application_BeginRequest is a better place to record this.
EDIT: You could implement it as a module, like the MSDN Custom Module Walkthrough and then your app could be a little more modular
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AutoTab to Next TabPage in TabControl C# .Net fw 3.5, in winform in TabControl,
when the user tab out of the last control on a TabPage, then focus should moves to the next page, and focuses the first control in that page, how can i do it?
this is necessary for me because, in a master entry form, there is some compulsory questions which is placed out side of tabcontrol, and some controls which is not necessary all in tabcontrol,
if user visiting each control sequentially then focus should automatically move to next pages, if user want to fill only neccessory infos, then he can submit by clicking save button.
is any suggestion about this.
A: your question is not accurate
"C# .Net fw 3.5, in winform in TabControl, when the user tab out of the last control on a TabPage, then focus should moves to the next page, and focuses the first control in that page?"
is this a statement or question. I didnt understand. And what is the goal you need ?
If you want the user consequently visit the controls inside the consequent tabs by pressing tab key you can do it by keypressed event in tab control. In the keypressed event you can change the tab programatically.
hope it helps.
The code should be something like this.
Generate keypress event for your tabcontrol and monitor the press of TAB key.
private void tabControl1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.ToString().Equals("TAB") // I dont know what tab key returns. But is hould be something like this
{
tabControl1.SelectedTab = tabControl1.TabPages[1] ;
// now tabpage 2 has the focus
// You can also focus any control you want in here as follows:
tabControl1.TabPages[1].Control["control key"].Focus();
}
}
hope its clear enough
A: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
namespace CSBSSWControls
{
// Class inhertis TabControl
public class bssTabControl : TabControl
{
private bool AutoTab_;
[DefaultValue(false)]
public bool AutoTab { get { return AutoTab_; } set { AutoTab_ = value; } }
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
//property which determines auto change tabpages
if (AutoTab)
{
switch (keyData)
{
case Keys.Tab | Keys.Shift:
{
return SetNextTab(false);
}
case Keys.Tab:
{
return SetNextTab(true);
}
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
private bool SetNextTab(bool Forward)
{
// getting cuurent active control
ContainerControl CC = this.FindForm();
Control ActC = null;
while (CC != null)
{
ActC = CC.ActiveControl;
CC = ActC as ContainerControl;
}
//checking, current control should not be tabcontrol or tabpage
if (ActC != null && !(ActC is TabPage) && !(ActC is bssTabControl))
{
//getting current controls next control if it is tab page then current control is surely that last control on that tab page
//if shift+tab pressed then checked its previous control, if it is tab page then current control is first control on the current tab page.
TabPage NC = ActC.FindForm().GetNextControl(ActC, Forward) as TabPage;
if (NC != null)
if (this.TabPages.Contains(NC))
if (Forward)
{
//selecting next tab page
this.SelectedTab = NC;
return true;
}
else
{
if (this.TabPages.IndexOf(NC) > 0)
{
//selecting pervious tab page
this.SelectedIndex = this.TabPages.IndexOf(NC) - 1;
return true;
}
}
}
return false;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What does (array) do in php? Does this code do anything? Somehow I made a mistake and wrote this code. However, this mistake turned out to be a boon. This solved my problem :D
$arr_centres = (array) $centres_array[0];
But I want to know what this does. The centres_array is like this:
stdClass Object (
[ExampleCentre] => Array (
[0] => stdClass Object (
[ID] => 14
[Name] => mycity
[Code] => exm
[Email] => example.web@example.com
[FB] =>
[Address1] => Exm, example
[City] => Hakuna Matata
[PostCode] => 000000
[County] =>
[Fax] => Fax
[Telephone] => 000222888
[Location] => 01.000000,-0.00004
[URL] => /holla/hakuna/example
)
A: It casts your stdClass object as an array.
More info: http://php.net/manual/en/language.types.type-juggling.php
A: It'll create an array with single index whose value will be value of $centres_array[0đ which is your stdClass object.
A: If you have a stdClass object casting it to an array will produce an array with object public properties as keys => values. For instance the following code
$obj = new stdClass;
$obj->foo = 'value1';
$obj->bar = 'value2';
var_dump((array) $obj);
will give you
array(2) {
["foo"]=>
string(6) "value1"
["bar"]=>
string(6) "value2"
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sharing layout information between Jade and Javascript I have a Node.js/Jade-based site and I'm trying to add some interactivity with some simple bits of Javascript.
In particular, I'm trying to set up a button that adds a new row to a table.
The table rendering is currently done in Jade, and I'm planning on using JQuery to set up the callback to add the row.
My template looks something like:
tbody#my_body
- each foo in foos
tr
td= foo.blah
td= foo.hello
td
a( ... complex link stuff etc. )
And I'm thinking my JS callback will be
$("a#add_row").click(function(){
$("#my_body").append( ??? );
});
I could rewrite the whole layout stuff in HTML in the append body, but that seems stupid. Every time I change one I'd have to change the other.
Is there a way of sharing the layout code between the Jade template and the Javascript?
A: I mean, you have access to the server-side variables when you are writing the view. You could also do a dump of your models/variables to json and use that. Finally, you could look at Backbone.js and reuse the same models on the client/server. See this post.
A: So... I don't think I fully understand what you're asking. Do you want the table to be static between sessions or just within the context of a single session or refresh?
If it's the latter then you just add the table row via jquery like you would a site that was full html. By the time you're calling the jquery function express has already rendered the jade templates out to full html.
If you want that row to persist then you need to include a call to the server that adds that new row's data to your data collection for foo, then whenever the page renders again the server will pass foo back with all the prior rows + the one you just added.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to access id of control from ascx page to cs page This is my ascx Code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Demo.ascx.cs"
Inherits="Demo" %>
<asp:HiddenField ID="hidden" runat="server" Value="" />
And the aspx:
<%@ Register TagName="Hidden" TagPrefix="CRS" Src="~/Demo.ascx" %>
<div>
<CRS:Hidden ID="hid" runat="server" />
</div>
Now How to access Hidden variable ID From ascx page to this cs page backend
A: Do you mean the actual ID? or the Value within the hidden field?
You can access the value using the FindControl method
HiddenField hf = (HiddenField)this.hid.FindControl("hidden");
string theValue = hf.Value;
Not sure if this is exactly what you are looking for.
Alternatively, you can declare some public properties in the UserControl in which you can access directly
In the ascx code:
public string theValue { get; set; }
In the aspx code:
string theValue = this.hid.theValue;
A: To access the HiddenField inside the UserControl from the asp.net web page you will need to wire up something called a Public Property.
This code should be added to the UserControl ascx.cs code behind:
public string Value
{
get { return hidden.Value; }
set { hidden.Value = value; }
}
You could then write code like this in your asp.net page:
string SomeHiddenValue = hid.Value;
hid.Value = "Its a secret!";
Note: I haven't compiled this so I am not sure if the public property name of Value will compile. I am also not sure if the second value in set { hidden.Value = value; } needs capitalising. Try changing these two values if you encounter problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: hOW can i add external jars in my build.xml hOW can i add external jars in my build.xml.
i am getting compilation error while running my build.xml.some jars are missing.how can i add them in my build.xml.
my build.xml looks like this
<project name="HUDSONSTATUSWS" default="dist" basedir=".">
<description>
Web Services build file
</description>
<!-- set global properties for this build -->
<property name="src" location="src"/>
<property name="build" location="build"/>
<property name="dist" location="dist"/>
<property name="webcontent" location="WebContent"/>
<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>
<target name="compile" depends="init"
description="compile the source " >
<!-- Compile the java code from ${src} into ${build} -->
<javac srcdir="${src}" destdir="${build}"/>
</target>
<target name="dist" depends="compile"
description="generate the distribution" >
<!-- Create the distribution directory -->
<mkdir dir="${dist}/lib"/>
<!-- Put everything in ${build} into the MyProject-${DSTAMP}.jar file -->
<jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/>
</target>
<target name="war" depends="compile"
description="generate the distribution war" >
<!-- Create the war distribution directory -->
<mkdir dir="${dist}/war"/>
<!-- Follow standard WAR structure -->
<copydir dest="${dist}/war/build/WEB-INF/" src="${webcontent}/WEB-INF/" />
<copydir dest="${dist}/war/build/WEB-INF/classes/" src="${build}" />
<jar jarfile="${dist}/war/HelloWorld-${DSTAMP}.war" basedir="${dist}/war/build/"/>
</target>
<target name="clean"
description="clean up" >
<!-- Delete the ${build} and ${dist} directory trees -->
<delete dir="${build}"/>
<delete dir="${dist}"/>
</target>
</project>
A: You just need to specify the classpath for javac, using the classpath or classpathref attribute, or a nested classpath element.
See http://ant.apache.org/manual/Tasks/javac.html for details. The ant documentation is very well written, exhaustive, and full of examples. It's there to be read.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to get DateTimePicker checkstate value of DataGridView? I have a DataGridview in which there is a DataTimePickerColumn, and it's DateTimePickerCell contain checkstate. How do I get the checkstate value after editing the checkstate?
A: Create a control inheriting from DateTimePicker and handle the DTN_DATETIMECHANGE notification. Then handle your DataGridView's EditingControlShowing event to add a handler for your DateTimePicker's new CheckedChanged event, or even you can create your own DataGridViewColumn and Cell type with DateTimePickerEx as EditingControl:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class DateTimePickerEx : DateTimePicker
{
private bool _checked;
private const int WM_REFLECT = 0x2000;
public event CheckedChangedEventHandler CheckedChanged;
public delegate void CheckedChangedEventHandler(object sender, System.EventArgs e);
public DateTimePickerEx()
{
this._checked = this.Checked;
}
private void WmDateTimeChange(ref Message m)
{
NMDATETIMECHANGE nmdatetimechange = m.GetLParam(typeof(NMDATETIMECHANGE));
if (nmdatetimechange.dwFlags == GetDateTimeValues.GDT_NONE) {
if (this.ShowCheckBox && !this.Checked) {
this._checked = false;
if (CheckedChanged != null) {
CheckedChanged(this, EventArgs.Empty);
}
}
} else {
if (this.ShowCheckBox && this.Checked && !this._checked) {
this._checked = true;
if (CheckedChanged != null) {
CheckedChanged(this, EventArgs.Empty);
}
}
this.Value = SysTimeToDateTime(nmdatetimechange.st);
}
m.Result = IntPtr.Zero;
}
private bool WmReflectCommand(ref Message m)
{
if (m.HWnd == this.Handle) {
long code = NMHDR.FromMessage(m).code;
switch (code) {
case FWEx.Win32API.DateTimePickerNotifications.DTN_DATETIMECHANGE:
this.WmDateTimeChange(ref m);
return true;
}
return false;
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg != 71 && m.Msg != 513) {
switch ((WindowsMessages)m.Msg) {
case WindowsMessages.WM_NOTIFY + WM_REFLECT:
if (!this.WmReflectCommand(ref m)) {
break;
}
return;
break;
}
}
base.WndProc(m);
}
private System.DateTime SysTimeToDateTime(SYSTEMTIME st)
{
return new System.DateTime(st.Year, st.Month, st.Day, st.Hour, st.Minute, st.Second);
}
/// <summary>
/// This structure contains information about a change that has taken place in a date and time picker (DTP) control.
/// This structure is used with the DTN_DATETIMECHANGE notification message.
/// </summary>
/// <remarks></remarks>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct NMDATETIMECHANGE
{
/// <summary>
/// NMHDR structure that contains information about the notification message.
/// </summary>
public NMHDR nmhdr;
/// <summary>
/// Specifies if the control was set to no date status (for DTS_SHOWNONE only).
/// Also specifies whether the contents of the st member are valid and contain current time information.
/// </summary>
public GetDateTimeValues dwFlags;
/// <summary>
/// SYSTEMTIME structure that contains information about the current system date and time.
/// </summary>
public SYSTEMTIME st;
}
/// <summary>
/// This structure contains information about a message.
/// The pointer to this structure is specified as the lParam member of the WM_NOTIFY message.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct NMHDR
{
/// <summary>
/// Window handle to the control sending a message.
/// </summary>
public IntPtr hwndFrom;
/// <summary>
/// Identifier of the control sending a message.
/// </summary>
public IntPtr idFrom;
/// <summary>
/// Notification code. This member can be a control-specific notification code or it can be one of the common notification codes. The following values are supported if you include mouse support in your device platform:
/// - NM_RCLICK
/// - NM_RDBCLICK
/// </summary>
public int code;
public static NMHDR FromMessage(System.Windows.Forms.Message msg)
{
return (NMHDR)msg.GetLParam(typeof(NMHDR));
}
}
/// <summary>
/// Specifies a date and time, using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
/// The time is either in coordinated universal time (UTC) or local time, depending on the function that is being called.
/// </summary>
/// <remarks>
/// It is not recommended that you add and subtract values from the SYSTEMTIME structure to obtain relative times.
/// </remarks>
public struct SYSTEMTIME
{
/// <summary>
/// The year. The valid values for this member are 1601 through 30827.
/// </summary>
public short Year;
/// <summary>
/// The month.
/// </summary>
public short Month;
/// <summary>
/// The day of the week. Sunday = 0.
/// </summary>
public short DayOfWeek;
/// <summary>
/// The day of the month. The valid values for this member are 1 through 31.
/// </summary>
public short Day;
/// <summary>
/// The hour. The valid values for this member are 0 through 23.
/// </summary>
public short Hour;
/// <summary>
/// The minute. The valid values for this member are 0 through 59.
/// </summary>
public short Minute;
/// <summary>
/// The second. The valid values for this member are 0 through 59.
/// </summary>
public short Second;
/// <summary>
/// The millisecond. The valid values for this member are 0 through 999.
/// </summary>
public short Milliseconds;
}
public enum GetDateTimeValues
{
/// <summary>
/// Error.
/// </summary>
GDT_ERROR = -1,
/// <summary>
/// The control is not set to the no date status.
/// The st member contains the current date and time.
/// </summary>
GDT_VALID = 0,
/// <summary>
/// The control is set to no date status.
/// The no date status applies only to controls that are set to the DTS_SHOWNONE style.
/// </summary>
GDT_NONE = 1
}
public enum WindowsMessages
{
/// <summary>
///Sent by a common control to its parent window when an event has occurred or the control requires some information.
/// </summary>
WM_NOTIFY = 0x4e
}
public enum DateTimePickerNotifications
{
DTN_FIRST = -740,
DTN_LAST = -745,
DTN_FIRST2 = -753,
DTN_LAST2 = -799,
DTN_DATETIMECHANGE = DTN_FIRST2 - 6,
DTN_USERSTRING = DTN_FIRST2 - 5,
DTN_WMKEYDOWN = DTN_FIRST2 - 4,
DTN_FORMAT = DTN_FIRST2 - 3,
DTN_FORMATQUERY = DTN_FIRST2 - 2,
DTN_DROPDOWN = DTN_FIRST2 - 1,
DTN_CLOSEUP = DTN_FIRST2
}
}
Handle the DateTimePickerEx.CheckedChanged on DataGridView.EditingControlShowing:
private void dgv_EditingControlShowing(System.Object sender, System.Windows.Forms.DataGridViewEditingControlShowingEventArgs e)
{
switch (this.dgv.CurrentCellAddress.X) {
case 0: // your DateTimePickerEx column number
DateTimePickerEx dtp = e.Control as DateTimePickerEx;
if (dtp != null) {
dtp.CheckedChanged += (object sen, EventArgs ea) => {
//TODO: Add your code here
};
}
break;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Having a GPS location and my GPS location, ¿how to calculate the direction (0-360º from north) to the location from my location? I tried to do with BearingTo(), but i don't know how to use it. myLocation.bearingTo(BuildingLocation) gives me 0º if i am facing the Building and North direction, gives me 90º if i am facing the Building and East Direction, gives me -180º if i am facing the Building and South direction. Then bearingTo doesn't works for my needs.
I need to do that because i need to calculate when the phone camera is facing the object...
A: Try this link:
http://www.movable-type.co.uk/scripts/latlong.html
Edit-- This would be the example, use locations or get the long/lat in other ways
Location destination;
Location from;
double dLon = Math.abs(destination.getLongitude()-from.getLongitude()); //Delta Longitude
double y = Math.sin(dLon) * Math.cos(destination.getLatitude());
double x = Math.cos(from.getLatitude())*Math.sin(destination.getLatitude()) -
Math.sin(from.getLatitude())*Math.cos(destination.getLatitude())*Math.cos(dLon);
double brng = Math.atan2(y, x);
double brngdegrees = Math.toDegrees(brng);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to parse SOAP XML in ruby? <?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="https://extranet.mcs.be/DEV_QUALITY_API/modules/quality/services/soap/quality.php"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:getQuestionnairesListResponse>
<return SOAP-ENC:arrayType="ns1:QuestionnaireListItem[34]"
xsi:type="ns1:ArrayOfQuestionnaireListItem">
<item xsi:type="ns1:QuestionnaireListItem">
<ID xsi:type="xsd:string">0000000022</ID>
<Code xsi:type="xsd:string">Interest PubTransp</Code>
<Reference xsi:type="xsd:string">Check Employees Interest in Public
Transport</Reference>
</item>
<item xsi:type="ns1:QuestionnaireListItem">
<ID xsi:type="xsd:string">0000000008</ID>
<Code xsi:type="xsd:string">CS SRE North 2003</Code>
<Reference xsi:type="xsd:string">Customer Satisfaction SRE North 2003</Reference>
</item>
<item xsi:type="ns1:QuestionnaireListItem">
<ID xsi:type="xsd:string">0000000006</ID>
<Code xsi:type="xsd:string">CS SRE South 2003</Code>
<Reference xsi:type="xsd:string">Customer Satisfaction SRE South 2003</Reference>
</item>
.
.
.
I want to parse the above soap String (I actually want to get items from the above soap). How could I do this?
A: There's a gem called Savon that's specifically made for dealing with SOAP in Ruby.
There's good documentation on the web site, once you looked into that and have more specific questions I'm sure we can help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Questions about Sencha Touch I have done some project using Sencha Touch -> www.estof.net/sencha (php + sencha). I want to ask you guys some questions:
a) I want to create app using sencha and upload to iPad. My app will work only if i connected to wifi or whatever internet?
b) For example i did some application, draw icon. Can I put it on iPad? Then click on icon and my application will work? (will be nice if app tried even to connect to Internet, but APP ICON will be on iPad)
c) Or sencha using only as a web-site?
A: *
*Sencha apps can work in offline mode. This is done by using a manifest file to cache the required files. This will explain more about it. This is another tutorial using phone gap.
*Yes you can create app icons for your apps. In this link, you can see an attribute named 'icon' which specifies the images to be used as the icon. In safari when you take your site, and press the option button on the bottom, there is an option to 'ADD to Home Screen'. This option will add the icon to the home screen.
*If you go to the sencha forums and check their showcase section you can see many apps that are actually sold in the app store.
The upcoming version of Sencha is said to have their own api's to access native feature of a phone os. Its more detailed on their website.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Codeigniter Signup Controller code review I just started using a MVC framework, especially Codeigniter and i am having some trouble maintaining my code and where to place my functions(controller or model).
For now i am building a sign up system and i have a controller with the name signup.php
This is my code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Signup extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$this->load->view("register/index");
}else{
$this->submitRegistration();
}
}
public function ajaxup(){
if ($this->input->isAjaxRequest()){
header('Content-type: application/json');
$error = false;
$message = '';
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|max_length[32]');
if ($this->form_validation->run() == false){
$message = validation_errors();
$error = true;
}else{
$this->_submitRegistration();
$message = 'Successfully registered.';
}
$return = array(
'error' => $error,
'message' => $message
);
$return = json_encode($return);
echo $return;
}
}
public function _submitRegistration(){
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = $this->input->post('password');
$data = array(
'username' => $username,
'email' => $email,
'password' => $password
);
$this->load->model('users_model');
$this->users_model->register_user($data);
}
public function check_valid_username($username){
$this->load->model('users_model');
if (!$this->users_model->is_valid_username($username)){
$this->form_validation->set_message('check_valid_username', 'The %s field should contain only letters, numbers or periods');
return false;
}
return true;
}
}
Is there anything i could write better to maintain my code and be readable?
*NOTE:*the function ajaxup is used when a user clicks the button and does an ajax call.
Thanks
A: Looks pretty good to me. Here are few ideas/suggestions for future improvements:
*
*In index() you are calling $this->submitRegistration() but I think you want to be calling $this->_submitRegistration().
*Since you are using the same validation rules in both the index() and ajaxup() methods you could pull pull them out into an array and either make them a property of your controller or put them into a config file.
For documentation see here and here.
$validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback_check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
Then in your methods you would do something similar to $this->form_validation->set_rules($validation_rules).
*
*Think about reordering your validation rules. For example, let's take a look at the rules for the username field. If check_valid_username() is making a call to the database (through the user model) then it would probably be better to validate the length requirements before. There's no use making an expensive call to the database if we can determine if the username is invalid.
*Make your callback methods private. Right now check_valid_username() is a public method and could potentially be accessed through the URL. Prefix it with an underscore (_check_valid_username()) and then in your validation rules use callback__check_valid_username. Note the two underscores.
*If you find yourself needing to use check_valid_username() in multiple controllers you could extend the native form validation library and put it there.
A: This looks fine to me. You seem to have all the relevant functions located in the user model and you are using the controller to access them. All I can suggest is read up on MVC theory if you feel unsure.
This is a good article:
http://www.codinghorror.com/blog/2008/05/understanding-model-view-controller.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RESTful route add new post method My routes file looks like this one with my new restful post action:
resources :projects do
post 'addpartner'
end
And in my view:
<%= link_to '[Add]', project_addpartner_url(@project,partner) ,
confirm: 'Are you sure?',
method: :post %>
Now the problem is project_addpartner_url generates the path with the default formatting. For my case it is something like:
/projects/1/addpartner.16
But my expected formatting is something like:
/projects/1/addpartner/16
How can I achieve this?
A: It seems to me that your link is setup as a GET methods, that's why you get
/projects/1/addpartner.16
But the way you want is seems like GET
/projects/1/addpartner/16
So try changing your link as
<%= link_to '[Add]', project_addpartner_url(@project,partner) ,
confirm: 'Are you sure?',
method: :get %>
But normally add/update/delete should be POST methods.
A: Try use another route, like:
resources :projects do
member do
post 'addpartner'
end
end
Or, maybe:
resources :projects do
collection do
post 'addpartner'
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: storing records in mysql db in sorting order of date I want to store some records in mysql database. records have a date column. i want to store them in sorting order of that date column.
For example, record having date 27/sep/2011 get stored as first row on the top of record having date 26/sep/2011 as:
id_1,name_1,27/sep/2011
id_2,name_2,26/sep/2011
if new records come on future dates they would get inserted on the top.
I DONT want to order them while using select by using order by desc .
i want they get inserted into db directly in sorted order.
how to do this???
thanks...
A: I am always surprised when people want to determine physical order of storing records.
Basically, it's a terrible idea for multiple reasons.
1) How the record is physically stored should not be of your concern.
2) How the record is presented should be of your concern. That's why we have ORDER BY built in.
3) Determining physical storage should be done by experts in the field, since it has performance implications - which is a topic in its own and I won't go into details.
Basically, worry about getting the data out in the sorted order, not getting it in in the sorted order.
Reason why it's a bad idea is because you'll be tampering with the primary key which is never, ever a good idea. On top of that, you'll have to reorder the records every time you insert something. Just don't reinvent hot water.
A: You could do this by adding another table - inserting all of the records into that table (the current and the new ones) then doing and insert as follows :
INSERT into newtable
select * from temptable
order by temptable.date
Why do you need to do this ? why not just use orderby on the query ?
As pointed out in the comments below - you would need to truncate the newtable each time
A: You cannot choose where to insert your row.
Here's one possible solution: MySQL syntax for inserting a new row in middle rows?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Horizontal navigation does not appear in a horizontal line in another machine Hello I have a django app which has a horizontal navigation. What happen recently, I decide to connect from my windows machine to use my app. This is what my horizontal nav looked like below.
For some reason, backup data and help are moved into a new line. But I want these two tabs to be in the same horizontal nav line. I tried using a different web browsers and the menu still looked the same.
One thing I can think of why this has happen is might be my resolution but I am not sure. My windows machine has a screen resolution of 1440 X 900 wile my linux machine has a resolution of 1024 x 768.
I wonder if there to make all my tabs stay in the same line. Might need to add some css to do it.
base_menu.html
<ul id="toc">
<li><a href="{% url mmc.views.return_clients %}"><span>Home</span></a></li>
<li><a href="{% url mmc.views.quote_step1 %}"><span>Create quote/order</span></a></li>
<li><a href="{% url mmc.views.search_item %}"><span> Item Search</span></a></li>
<li><a><span>Service orders</span></a><br/>
<ul class="subnav">
<li><a href="{% url mmc.views.order_list %}"><span>Storage orders</span></a></li>
<li><a href="{% url mmc.views.order_list_service 1 %}"><span>Delivery orders</span></a></li>
<li><a href="{% url mmc.views.order_list_service 2 %}"><span>Collection orders</span></a></li>
</ul>
</li>
<li><a><span>Collection/Delivery</span></a><br/>
<ul class="subnav">
<li><a href="{% url mmc.views.service_list 1 %}"><span>Delivery list</span></a></li>
<li><a href="{% url mmc.views.service_list 2 %}"><span>Collection list</span></a></li>
</ul>
</li>
<li><a href="{% url mmc.views.invoice_list %}"><span>Export for invoicing</span></a></li>
<li><a href="{% url mmc.views.dbbackup %}"><span>Backup data</span></a></li>
<li><a href="{% url mmc.views.help_index %}" target="_blank" onclick="return showAddAnotherPopup(this);"><span>Help</span></a></li>
</ul>
Update: base.css file
ul#toc {
height: 2em;
list-style: none;
margin-left: 200px;
padding: 0;
position relative;
}
ul#toc li{
background:#ffffff url(../images/tab.png);
float: left;
margin: 0 1px 0 0;
}
ul#toc span {
background: url(../images/tab.png) 100% 0;
display: block;
line-height: 2em;
padding-right: 10px;
}
ul#toc a {
color: #000000;
height: 2em;
float: left;
text-decoration: none;
padding-left: 10px;
}
A: Seems to me that you may need to add a width attribute to the navigation. That should help keep it from resizing when the display sizes change.
ul#toc {
/*width: ###px;*/
/*adding a width attribute to your div will give the ul a boundary*/
height: 2em;
list-style: none;
margin-left: 200px;
padding: 0;
position relative;
}
A:
My windows machine has a screen resolution of 1440 X 900 while my linux
machine has a resolution of 1024 x 768.
Are you sure this isn't reversed?
Your problem would make more sense if your windows resolution was smaller.
If that's the case, one thing you can do is to set a specific pixel width for the nav.
Then, if the resolution is smaller than the viewport, you will have a horizontal scroll but the nav will all be one line.
EDIT
From the comment below How would I set up a specific width on my nav?
If ul#toc is the nav container, then
ul#toc {
height: 2em;
list-style: none;
margin-left: 200px;
padding: 0;
position relative;
width:1440px; //OR SOME OTHER #
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple collisions not working I am experimenting collision detection using onTriggerEnter. On collision with other object(tower) direction changes and object moves. I have created one more similar object (tower) and placed both far from each other. Now for the first collision it is working fine, but at other collision it is not working, if I placed both closer to each other it works! .. I am unable to understand this phenomena, pl help Here is my code:
void OnTriggerEnter(Collider obj) {
collideCount++;
Debug.Log(collideCount);
Quaternion target = Quaternion.Euler(0, 90, 0);
tf.rotation = Quaternion.Slerp(tf.rotation, target, Time.deltaTime * speed);
tf.Translate(0,6,0);
}
A: I would recommend try record a collision count for each of the other collider methods such as OnTriggerStay and OnTriggerExit
This way you can identify if the engine is raising the event correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hide div on clientside click Trying to get this div to disappear, does not seem to doing what I expect it to do, where am I going wrong?
It does not disappear.
Javascript:
<script type="text/javascript">
function Show_Hide_Display() {
var div1 = document.getElementById("checkAvailability");
if (div1.style.display == "" || div1.style.display == "block") {
div1.style.display = "none";
}
else {
div1.style.display = "block";
}
return false;
}
</script>
HTML:
<div runat="server" id="checkAvailability">
<asp:LinkButton OnClientClick="Show_Hide_Display()" ID="lbtnCheckAvailability" runat="server" CausesValidation="true" OnClick="lbtnCheckAvailability_Click">Check availability
</asp:LinkButton>
</div>
I want the button to pretty much hide itself.
A: Change your line to:
var div1 = document.getElementById("<%=checkAvailability.ClientID%>");
The reason is that when the checkAvailability control is rendered on the client side it may or may not have the same id (checkAvailability) since asp.net will prepend its id with that of the container control or some other logic.
This <%=checkAvailability.ClientID%> will always give you the actual id on the client side.
A: I think you will be better of looking at some jQuery here. For example, your code could look like:
$(document).ready(function(){
$('#yourbutton').click(function(){
$(this).toggle();
});
});
Of course, in your case you can also hide the wrapping div if you want that for some reason. It's about the same approach.
A: In addition to what @Icarus has posted, modify your code as such.
OnClientClick="return Show_Hide_Display()"
this will stop a post back from happening. i'm guessing you don't want a postback to occur since your div/button will be visible after a postback.
A: the problem is linkbutton causes postback, thus div visibility, set by JS, after postback will be restored to it's default value. i.e. style.display will not be saved. a simple solution will be just add simple html button. like this
<input type="button" value="hide the div" onclick="Show_Hide_Display()" />
this just triggers JS, not causing postback, and your div visibility will alter as expected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to efficiently filter datetime column for extracting data? I am usng sqlite to log data every 5 minutes to a column that is time stamped with and integer in Unix time. The user interface uses php code to extract data in various user selectable time frames which is then plotted using javascript. Charts typically have 12 data/time points and I need to extract data for plotting over different periods of say 1Hr/12Hr/24Hr/12days/month/year. So only need to extract 12 data rows per search. So for a 24Hr plot I need to only extract data at houly intervals (when minutes = 0) similarly for 12day plots at daily intervals (when mins=0 && hours=0) etc.
My php code for 1Hr works fine since the data is logged every 5min giving me 12 rows of data between search start time and end time. What is an efficient way of extracting data for the longer periods when number of rows between start time and end time is greater than 12? I need to further filter the search to efficiently extract only the data I need?
any suggestions - most appreciated - frank
$db = new MyDB(); // open database
$t=time(); // get current time
$q1 = "SELECT TimeStamp,myData FROM mdata WHERE ";
$q2 = " AND TimeStamp <=".$t; // end time
$q3 = " AND TimeStamp >=".($t-3600); // start time 1 hour earlier
$qer = $q1.$q2.$q3; // my search query form above parts
$result = $db->query($qer);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}
echo json_encode($json); // data is returned as json array
$db->close(); // close database connection
A: I think you should use WHERE date BETWEEN in your search query?
This kind of search could take up a lot of time once data builds up?
A: Since you already know the exact times you're interested in, you should probably just build an array of times and use SQL's IN operator:
$db = new MyDB(); // open database
$timeStep = 300; // Time step to use, 5 minutes here - this would be 3600 for hourly data
$t = time(); // get current time
$t -= $t % $timeStep; // round to the proper interval
$query = "SELECT TimeStamp,myData FROM mdata ";
$query .= "WHERE TimeStamp IN "
$query .= "(" . implode(",", range($t, $t + $timeStep * 12, $timeStep)) . ")";
$result = $db->query($query);
$json = array();
while ($data = $result->fetchArray(SQLITE_NUM)) {
$json[] = $data;
}
You'll need to do some different math for monthly data - try constructing 12 times with PHP's mktime() function.
Here are the references for the PHP implode() and range() functions I used.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the syntax enabling patterns in C#? There are several pattern-features of C# language, i.e. classes need not derive from a specific interface; but rather implement a certain pattern in order to partake in some C# syntax/features.
Let's consider an example:
public class MyCollection : IEnumerable
{
public T Add(T name, T name2, ...) { }
public IEnumerator GetEnumerator() { return null; }
}
Here, TYPE is any type. Basically we have a class that implements IEnumerable and has a method named Add() with any number of parameters.
This enables the following declaration of a new MyCollection instance:
new MyCollection{{a1, a2, ...}, {b1, b2, ...} }
Which is equivalent to:
var mc = new MyCollection();
mc.Add(a1, a1, ...);
mc.Add(b1, b2, ...);
Magic! Meanwhile, recently (I believe during the BUILD event) Anders Hejlsberg let slip that the new await/async will be implemented using patterns as well, which lets WinRT get away with returning something other than Task<T>.
So my question is twofold,
*
*What is the pattern Anders was talking about, or did I misunderstand something? The answer should be somewhere between the type WinRT provides, something to the effect of IAsyncFoo and the unpublished specification.
*Are there any other such patterns (perhaps already existing) in C#?
A: The draft specification is published - you can download it from the Visual Studio home page. The pattern for async is the one given in driis's answer - you can also read my Eduasync blog series for more details, with this post being dedicated to the pattern.
Note that this pattern only applies to "what you can await". An async method must return void, Task or Task<T>.
In terms of other patterns in C# beyond the collection initializer you mentioned originally:
*
*foreach can iterate over non-IEnumerable implemenations, so long as the type has a GetEnumerator method returning a type which has MoveNext() and Current members
*LINQ query expressions resolve to calls to Select, Where, GroupBy etc.
A: For async, it works on the awaiter pattern, which I think is described best here, by Stephen Toub:
"The languages support awaiting any instance that exposes the right method (either instance method or extension method): GetAwaiter. A GetAwaiter needs to return a type that itself exposes three members:"
bool IsCompleted { get; }
void OnCompleted(Action continuation);
TResult GetResult(); // TResult can also be void
As an example of this, in the Async CTP, Task’s GetAwaiter method returns a value of type TaskAwaiter:
public struct TaskAwaiter
{
public bool IsCompleted { get; }
public void OnCompleted(Action continuation);
public void GetResult();
}
If you want all the details of async, start reading Jon Skeets posts about async. They go into great detail about the subject.
Besides collection initializers, which is pattern based as you mention, another pattern based feature in C# is LINQ: For the LINQ keywords, all that is required is that overload resolution finds an instance or extension method with the correct name and signature. Have a look at Eric Lipperts article about the subject. Also, foreach is pattern based - Eric also describes the details on this pattern in the linked article.
A: Another pattern you can use is the using keyword.
If you have a class that implements IDisposable then you can say:
using(Resource myResource = GetResource())
{
}
Which translates to something akin to::
Resource myResource;
try
{
myResource = GetResource();
}
finally
{
var disposable = myResource as IDisposable;
if(disposable != null) disposable.Dispose()
}
While I suppose it is less "magical" than foreach or the query operators it is a relatively nice bit of syntax.
Also a bit more in the same vein you can use the yield return to automatically implement an iterator for you.
public struct SimpleBitVector32 : IEnumerable<bool>
{
public SimpleBitVector32(uint value)
{
this.data = value;
}
private uint data;
public bool this[int offset]
{
get
{
unchecked
{
return (this.data & (1u << offset)) != 0;
}
}
set
{
unchecked
{
this.data = value ? (this.data | (1u << offset)) : (this.data & ~(1u << offset));
}
}
}
public IEnumerator<bool> GetEnumerator()
{
for (int i = 0; i < 32; i++)
{
yield return this[i];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Displaying image in MFC method that is not ONPaint I am trying to display an image in a dialog dynamically, it works no problem if I put the code in the on paint method and use the dc from there, I can't do this though I need to display after the window is shown, the code I am using is as follows, I am getting the dc of the client window creating the bitmap from a resource and "trying" to display it in the window but nothing displays, Any suggestions what might be wrong?
void CProcessSteps::OnShowWindow(BOOL bShow, UINT nStatus)
{
CDialog::OnShowWindow(bShow, nStatus);
SetupInstructions();<-----------------Call To Method
}
void CProcessSteps::OnPaint()
{
CPaintDC dc(this);
}
void CProcessSteps::SetupInstructions()
{
CDC *pDC = new CDC();<------------------------------Problem starts here
CFontUtil cfu;
cfu.SetFont(&LineFont,30);
CDC memDC;
memDC.CreateCompatibleDC(pDC);
int stepTop = 10;
int stepEnd = 230;
int imageLeft = 30;
STEP_STRUCT* step;
CBitmap iconImage;
iconImage.LoadBitmap ( IDB_TID_CHECK );
memDC.SelectObject(&iconImage);
CRect iconRect;
BITMAP bmInfo;
iconImage.GetObject ( sizeof ( bmInfo ), &bmInfo );
iconRect.SetRect ( imageLeft, stepTop, imageLeft+bmInfo.bmWidth, stepTop+bmInfo.bmHeight );
pDC = this->GetDC();
pDC->BitBlt(imageLeft, stepTop, imageLeft+bmInfo.bmWidth, stepTop+bmInfo.bmHeight, &memDC, 0, 0, SRCCOPY);
//RedrawWindow();<-------- tried this here no luck
int stepCount = m_pageStructure->PageSteps.GetCount();<----------------------------Bellow this works correctly
POSITION pos = m_pageStructure->PageSteps.GetHeadPosition();
while (pos)
{
step = m_pageStructure->PageSteps.GetNext(pos);
CStatic *label = new CStatic;
label->Create(_T( step->StepInstruction ),WS_CHILD | WS_VISIBLE, CRect(80, stepTop, 480, stepEnd), this);
label->SetFont(&LineFont, true);
label->GetWindowRect(rect);
ScreenToClient(rect);
pDC = label->GetDC();
pDC->SelectObject(&LineFont);
pDC->DrawText(step->StepInstruction, &rect, DT_CALCRECT|DT_WORDBREAK);
label->ReleaseDC(pDC);
label->MoveWindow(rect);
stepTop += rect.Height();
stepTop += 30;
stepEnd += rect.Height();
}
}
A: Reasons why you can't use OnPaint() are not clear.
The usual strategy when one needs to redraw all or part of a window upon some event is to call InvalidateRect().
Windows will in turn send WM_PAINT (handled by your OnPaint() method) to your app, specifying which part of the window should be redrawn.
A: I think there's more in the BeginPaint-function than just giving you the CDC. And BeginPaint can only be called from the OnPaint-method.
To solve your problem, use the Invalidate-functions to force a repaint from your "SetupInstructions" method. Then do the drawing inside the OnPaint function.
A: I suppose CProcessSteps derives from CWnd, perhaps a CDialog?
If you want to draw in the client area of a CWnd derived class you have to get the DC using the CWnd GetDC method. I don't understand why you create your own CDC, you should get the CWnd DC at the beginning of SetupInstructions and use this DC everywhere, also to create your memDC.
Also you should be careful when you allocate memory (new CStatic) if you don't call delete for this variables you will have memory leaks. If you really need to create this CStatics dynamically you will have to keep a pointer to all of them in order to delete them before closing the dialog/view.
As people suggested, I don't think you are following the right way by drawing using OnShowWindow. You should use OnPaint to make your drawing stuff, if you don't want to draw the image until the window is fully initialized you should use a member variable of the window (for instance a bool) initialized to false in the constructor and set it to true when you are ready to draw the image. Then calling Invalidate will draw the image. Something like:
In the .h:
class CProcessSteps : CDialog
{
...
private:
bool m_bReadyToDraw;
};
In the .cpp:
CProcessSteps::CProcessSteps() : CDialog()
{
m_bReadyToDraw = false;
}
BOOL CProcessSteps::OnInitDialog()
{
CDialog:OnInitDialog();
m_bReadyToDraw = true;
return TRUE;
}
void CProcessSteps::OnPaint()
{
CPaintDC dc(this);
if(m_bReadyToDraw)
{
CFontUtil cfu;
cfu.SetFont(&LineFont,30);
CDC memDC;
memDC.CreateCompatibleDC(&dc);
...
}
}
Hope it helps.
Javier
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to release property of static class i have a static class witch has two property,like below ...
@interface Global : NSObject
{
BarcodeScanner* scanner;
NSInteger warehouseID;
}
@property(assign) BarcodeScanner* scanner;
@property(assign) NSInteger warehouseID;
+(Global *)sharedInstance;
@end
#import "Global.h"
@implementation Global
@synthesize scanner,warehouseID;
+ (Global *)sharedInstance
{
static Global *globalInstance = nil;
if (nil == globalInstance) {
globalInstance = [[Global alloc] init];
globalInstance.scanner = [[BarcodeScanner alloc] init];
globalInstance.warehouseID = 1;
}
return globalInstance;
}
-(void) dealloc
{
[super dealloc];
}
@end
now when i analyze project in Xcode i got warning for memory leak for scanner and warehouseID properties , and when i try to release them in dealloc method like ...
[[[Global sharedInstance] scanner]release];
i got warning "incorrect decrement of the reference count of an object..."
how should i resolve this problem.
so thanks for any help.
A: The warning is because your code does not match the rules Analyzer uses. To avoid the warning
*
*make the scanner property retain
*change the the instantiation or BarcodeScanner to be autorelease
*add a release for scanner in dealloc
Example (reformatted just to save space):
@class BarcodeScanner;
@interface Global : NSObject {
BarcodeScanner* scanner;
NSInteger warehouseID;
}
@property(retain) BarcodeScanner* scanner;
@property(assign) NSInteger warehouseID;
+(Global *)sharedInstance;
@end
@implementation Global
@synthesize scanner,warehouseID;
+ (Global *)sharedInstance {
static Global *globalInstance = nil;
if (nil == globalInstance) {
globalInstance = [[Global alloc] init];
globalInstance.scanner = [[[BarcodeScanner alloc] init] autorelease];
globalInstance.warehouseID = 1;
}
return globalInstance;
}
-(void) dealloc {
[scanner release];
[super dealloc];
}
@end
A: just leave it to autorelease pool
globalInstance.scanner = [[[BarcodeScanner alloc] init] autorelease];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make a Spring form:checkbox to readonly using javascript I want to make spring form:checkbox tag to readonly using java script. I can make it to disable using
document.getElementById('id').disabled = true;
But then it doesn't set value to command object.
A: A disabled form input field is indeed not submitted. You could do one of the following:
*
*make the checkbox readonly rather than disabled.
*add a hidden input field with the same name as the checkbox and with the checkbox's value, when disabling the checkbox. Just make sure to remove this hidden field when re-enabling the checkbox again.
*re-enable the disabled checkboxes at submit time, using JavaScript
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Restoring animation where it left off when app resumes from background I have an endlessly looping CABasicAnimation of a repeating image tile in my view:
a = [CABasicAnimation animationWithKeyPath:@"position"];
a.timingFunction = [CAMediaTimingFunction
functionWithName:kCAMediaTimingFunctionLinear];
a.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
a.toValue = [NSValue valueWithCGPoint:CGPointMake(image.size.width, 0)];
a.repeatCount = HUGE_VALF;
a.duration = 15.0;
[a retain];
I have tried to "pause and resume" the layer animation as described in Technical Q&A QA1673.
When the app enters background, the animation gets removed from the layer.
To compensate I listen to UIApplicationDidEnterBackgroundNotification and call stopAnimation and in response to UIApplicationWillEnterForegroundNotification call startAnimation.
- (void)startAnimation
{
if ([[self.layer animationKeys] count] == 0)
[self.layer addAnimation:a forKey:@"position"];
CFTimeInterval pausedTime = [self.layer timeOffset];
self.layer.speed = 1.0;
self.layer.timeOffset = 0.0;
self.layer.beginTime = 0.0;
CFTimeInterval timeSincePause =
[self.layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
self.layer.beginTime = timeSincePause;
}
- (void)stopAnimation
{
CFTimeInterval pausedTime =
[self.layer convertTime:CACurrentMediaTime() fromLayer:nil];
self.layer.speed = 0.0;
self.layer.timeOffset = pausedTime;
}
The problem is that it starts again at the beginning and there is ugly jump from last position, as seen on app snapshot the system took when application did enter background, back to the start of the animation loop.
I can not figure out how to make it start at last position, when I re-add the animation. Frankly, I just don't understand how that code from QA1673 works: in resumeLayer it sets the layer.beginTime twice, which seems redundant. But when I've removed the first set-to-zero, it did not resume the animation where it was paused. This was tested with simple tap gesture recognizer, that did toggle the animation - this is not strictly related to my issues with restoring from background.
What state should I remember before the animation gets removed and how do I restore the animation from that state, when I re-add it later?
A: I used cclogg's solution but my app was crashing when the animation's view was removed from his superview, added again, and then going to background.
The animation was made infinite by setting animation.repeatCount to Float.infinity.
The solution I had was to set animation.isRemovedOnCompletion to false.
It's very weird that it works because the animation is never completed. If anyone has an explanation, I like to hear it.
Another tip: If you remove the view from its superview. Don't forget to remove the observer by calling NSNotificationCenter.defaultCenter().removeObserver(...).
A: I write a Swift 4.2 version extension based on @cclogg and @Matej Bukovinski answers. All you need is to call layer.makeAnimationsPersistent()
Full Gist here: CALayer+AnimationPlayback.swift, CALayer+PersistentAnimations.swift
Core part:
public extension CALayer {
static private var persistentHelperKey = "CALayer.LayerPersistentHelper"
public func makeAnimationsPersistent() {
var object = objc_getAssociatedObject(self, &CALayer.persistentHelperKey)
if object == nil {
object = LayerPersistentHelper(with: self)
let nonatomic = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
objc_setAssociatedObject(self, &CALayer.persistentHelperKey, object, nonatomic)
}
}
}
public class LayerPersistentHelper {
private var persistentAnimations: [String: CAAnimation] = [:]
private var persistentSpeed: Float = 0.0
private weak var layer: CALayer?
public init(with layer: CALayer) {
self.layer = layer
addNotificationObservers()
}
deinit {
removeNotificationObservers()
}
}
private extension LayerPersistentHelper {
func addNotificationObservers() {
let center = NotificationCenter.default
let enterForeground = UIApplication.willEnterForegroundNotification
let enterBackground = UIApplication.didEnterBackgroundNotification
center.addObserver(self, selector: #selector(didBecomeActive), name: enterForeground, object: nil)
center.addObserver(self, selector: #selector(willResignActive), name: enterBackground, object: nil)
}
func removeNotificationObservers() {
NotificationCenter.default.removeObserver(self)
}
func persistAnimations(with keys: [String]?) {
guard let layer = self.layer else { return }
keys?.forEach { (key) in
if let animation = layer.animation(forKey: key) {
persistentAnimations[key] = animation
}
}
}
func restoreAnimations(with keys: [String]?) {
guard let layer = self.layer else { return }
keys?.forEach { (key) in
if let animation = persistentAnimations[key] {
layer.add(animation, forKey: key)
}
}
}
}
@objc extension LayerPersistentHelper {
func didBecomeActive() {
guard let layer = self.layer else { return }
restoreAnimations(with: Array(persistentAnimations.keys))
persistentAnimations.removeAll()
if persistentSpeed == 1.0 { // if layer was playing before background, resume it
layer.resumeAnimations()
}
}
func willResignActive() {
guard let layer = self.layer else { return }
persistentSpeed = layer.speed
layer.speed = 1.0 // in case layer was paused from outside, set speed to 1.0 to get all animations
persistAnimations(with: layer.animationKeys())
layer.speed = persistentSpeed // restore original speed
layer.pauseAnimations()
}
}
A: Hey I had stumbled upon the same thing in my game, and ended up finding a somewhat different solution than you, which you may like :) I figured I should share the workaround I found...
My case is using UIView/UIImageView animations, but it's basically still CAAnimations at its core... The gist of my method is that I copy/store the current animation on a view, and then let Apple's pause/resume work still, but before resuming I add my animation back on. So let me present this simple example:
Let's say I have a UIView called movingView. The UIView's center is animated via the standard [UIView animateWithDuration...] call. Using the mentioned QA1673 code, it works great pausing/resuming (when not exiting the app)... but regardless, I soon realized that on exit, whether I pause or not, the animation was completely removed... and here I was in your position.
So with this example, here's what I did:
*
*Have a variable in your header file called something like animationViewPosition, of type *CAAnimation**.
*When the app exits to background, I do this:
animationViewPosition = [[movingView.layer animationForKey:@"position"] copy]; // I know position is the key in this case...
[self pauseLayer:movingView.layer]; // this is the Apple method from QA1673
*
*Note: Those 2 ^ calls are in a method that is the handler for the UIApplicationDidEnterBackgroundNotification (similar to you)
*Note 2: If you don't know what the key is (of your animation), you can loop through the view's layer's 'animationKeys' property and log those out (mid animation presumably).
*Now in my UIApplicationWillEnterForegroundNotification handler:
if (animationViewPosition != nil)
{
[movingView.layer addAnimation:animationViewPosition forKey:@"position"]; // re-add the core animation to the view
[animationViewPosition release]; // since we 'copied' earlier
animationViewPosition = nil;
}
[self resumeLayer:movingView.layer]; // Apple's method, which will resume the animation at the position it was at when the app exited
And that's pretty much it! It has worked for me so far :)
You can easily extend it for more animations or views by just repeating those steps for each animation. It even works for pausing/resuming UIImageView animations, ie the standard [imageView startAnimating]. The layer animation key for that (by the way) is "contents".
Listing 1 Pause and Resume animations.
-(void)pauseLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
layer.speed = 0.0;
layer.timeOffset = pausedTime;
}
-(void)resumeLayer:(CALayer*)layer
{
CFTimeInterval pausedTime = [layer timeOffset];
layer.speed = 1.0;
layer.timeOffset = 0.0;
layer.beginTime = 0.0;
CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
layer.beginTime = timeSincePause;
}
A: Just in case anyone needs a Swift 3 solution for this problem:
All you have to do is to subclass your animated view from this class.
It always persist and resume all animations on it's layer.
class ViewWithPersistentAnimations : UIView {
private var persistentAnimations: [String: CAAnimation] = [:]
private var persistentSpeed: Float = 0.0
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func didBecomeActive() {
self.restoreAnimations(withKeys: Array(self.persistentAnimations.keys))
self.persistentAnimations.removeAll()
if self.persistentSpeed == 1.0 { //if layer was plaiyng before backgorund, resume it
self.layer.resume()
}
}
func willResignActive() {
self.persistentSpeed = self.layer.speed
self.layer.speed = 1.0 //in case layer was paused from outside, set speed to 1.0 to get all animations
self.persistAnimations(withKeys: self.layer.animationKeys())
self.layer.speed = self.persistentSpeed //restore original speed
self.layer.pause()
}
func persistAnimations(withKeys: [String]?) {
withKeys?.forEach({ (key) in
if let animation = self.layer.animation(forKey: key) {
self.persistentAnimations[key] = animation
}
})
}
func restoreAnimations(withKeys: [String]?) {
withKeys?.forEach { key in
if let persistentAnimation = self.persistentAnimations[key] {
self.layer.add(persistentAnimation, forKey: key)
}
}
}
}
extension CALayer {
func pause() {
if self.isPaused() == false {
let pausedTime: CFTimeInterval = self.convertTime(CACurrentMediaTime(), from: nil)
self.speed = 0.0
self.timeOffset = pausedTime
}
}
func isPaused() -> Bool {
return self.speed == 0.0
}
func resume() {
let pausedTime: CFTimeInterval = self.timeOffset
self.speed = 1.0
self.timeOffset = 0.0
self.beginTime = 0.0
let timeSincePause: CFTimeInterval = self.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
self.beginTime = timeSincePause
}
}
On Gist:
https://gist.github.com/grzegorzkrukowski/a5ed8b38bec548f9620bb95665c06128
A: I was able to restore the animation (but not the animation position) by saving a copy of the current animation and adding it back on resume. I called startAnimation on load and when entering the foreground and pause when entering the background.
- (void) startAnimation {
// On first call, setup our ivar
if (!self.myAnimation) {
self.myAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
/*
Finish setting up myAnimation
*/
}
// Add the animation to the layer if it hasn't been or got removed
if (![self.layer animationForKey:@"myAnimation"]) {
[self.layer addAnimation:self.spinAnimation forKey:@"myAnimation"];
}
}
- (void) pauseAnimation {
// Save the current state of the animation
// when we call startAnimation again, this saved animation will be added/restored
self.myAnimation = [[self.layer animationForKey:@"myAnimation"] copy];
}
A: After quite a lot of searching and talks with iOS development gurus, it appears that QA1673 doesn't help when it comes to pausing, backgrounding, then moving to foreground. My experimentation even shows that delegate methods that fire off from animations, such as animationDidStop become unreliable.
Sometimes they fire, sometimes they don't.
This creates a lot of problems because it means that, not only are you looking at a different screen that you were when you paused, but also the sequence of events currently in motion can be disrupted.
My solution thus far has been as follows:
When the animation starts, I get the start time:
mStartTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
When the user hits the pause button, I remove the animation from the CALayer:
[layer removeAnimationForKey:key];
I get the absolute time using CACurrentMediaTime():
CFTimeInterval stopTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
Using the mStartTime and stopTime I calculate an offset time:
mTimeOffset = stopTime - mStartTime;
I also set the model values of the object to be that of the presentationLayer. So, my stop method looks like this:
//--------------------------------------------------------------------------------------------------
- (void)stop
{
const CALayer *presentationLayer = layer.presentationLayer;
layer.bounds = presentationLayer.bounds;
layer.opacity = presentationLayer.opacity;
layer.contentsRect = presentationLayer.contentsRect;
layer.position = presentationLayer.position;
[layer removeAnimationForKey:key];
CFTimeInterval stopTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
mTimeOffset = stopTime - mStartTime;
}
On resume, I recalculate what's left of the paused animation based upon the mTimeOffset. That's a bit messy because I'm using CAKeyframeAnimation. I figure out what keyframes are outstanding based on the mTimeOffset. Also, I take into account that the pause may have occurred mid frame, e.g. halfway between f1 and f2. That time is deducted from the time of that keyframe.
I then add this animation to the layer afresh:
[layer addAnimation:animationGroup forKey:key];
The other thing to remember is that you will need to check the flag in animationDidStop and only remove the animated layer from the parent with removeFromSuperlayer if the flag is YES. That means that the layer is still visible during the pause.
This method does seem very laborious. It does work though! I'd love to be able to simply do this using QA1673. But at the moment for backgrounding, it doesn't work and this seems to be the only solution.
A: It's surprising to see that this isn't more straightforward. I created a category, based on cclogg's approach, that should make this a one-liner.
CALayer+MBAnimationPersistence
Simply invoke MB_setCurrentAnimationsPersistent on your layer after setting up the desired animations.
[movingView.layer MB_setCurrentAnimationsPersistent];
Or specify the animations that should be persisted explicitly.
movingView.layer.MB_persistentAnimationKeys = @[@"position"];
A: I use cclogg's solution to great effect. I also wanted to share some additional info that might help someone else, because it frustrated me for a while.
In my app I have a number of animations, some that loop forever, some that run only once and are spawned randomly. cclogg's solution worked for me, but when I added some code to
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
in order to do something when only the one-time animations were finished, this code would trigger when I resumed my app (using cclogg's solution) whenever those specific one-time animations were running when it was paused. So I added a flag (a member variable of my custom UIImageView class) and set it to YES in the section where you resume all the layer animations (resumeLayer in cclogg's, analogous to Apple solution QA1673) to keep this from happening. I do this for every UIImageView that is resuming. Then, in the animationDidStop method, only run the one-time animation handling code when that flag is NO. If it's YES, ignore the handling code. Switch the flag back to NO either way. That way when the animation truly finishes, your handling code will run. So like this:
- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
if (!resumeFlag) {
// do something now that the animation is finished for reals
}
resumeFlag = NO;
}
Hope that helps someone.
A: I was recognizing the gesture state like so:
// Perform action depending on the state
switch gesture.state {
case .changed:
// Some action
case .ended:
// Another action
// Ignore any other state
default:
break
}
All I needed to do was change the .ended case to .ended, .cancelled.
A: iOS will remove all animations when view disappears from the visible area (not only when app goes into background). To fix it I created custom CALayer subclass and overrided 2 methods so the system doesn't remove animations - removeAnimation and removeAllAnimations:
class CustomCALayer: CALayer {
override func removeAnimation(forKey key: String) {
// prevent iOS to clear animation when view is not visible
}
override func removeAllAnimations() {
// prevent iOS to clear animation when view is not visible
}
func forceRemoveAnimation(forKey key: String) {
super.removeAnimation(forKey: key)
}
}
In the view where you want this layer to be used as main layer override layerClass property:
override class var layerClass: AnyClass {
return CustomCALayer.self
}
To pause and resume animation:
extension CALayer {
func pause() {
guard self.isPaused() == false else {
return
}
let pausedTime: CFTimeInterval = self.convertTime(CACurrentMediaTime(), from: nil)
self.speed = 0.0
self.timeOffset = pausedTime
}
func resume() {
guard self.isPaused() else {
return
}
let pausedTime: CFTimeInterval = self.timeOffset
self.speed = 1.0
self.timeOffset = 0.0
self.beginTime = 0.0
self.beginTime = self.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
}
func isPaused() -> Bool {
return self.speed == 0.0
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
}
|
Q: Cannot validate xml against a xsd. Error "cvc-elt.1: Cannot find the declaration of element 'systems'" I am having trouble validating an XML using an XSD via code. I can't figure out what I'm missing
XML:
<?xml version="1.0" encoding="UTF-8"?>
<systems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="test.namespace">
<system address="test" id="test" name="test" systemNr="test">
<mandant mandant="test"/>
</system>
<system address="test2" name="test2" systemNr="test2" id="test2">
<mandant mandant="test2"/>
<mandant mandant="test2"/>
</system>
<system id="test3" address="test3" name="test3" systemNr="test3">
<mandant mandant="test"/>
</system>
</systems>
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test.namespace">
<xs:element name="systems">
<xs:complexType>
<xs:sequence>
<xs:element name="system" maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:sequence>
<xs:element name="mandant"
maxOccurs="unbounded" minOccurs="1">
<xs:complexType>
<xs:attribute name="mandant"
type="xs:string" use="required">
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required">
</xs:attribute>
<xs:attribute name="name" type="xs:string" use="required">
</xs:attribute>
<xs:attribute name="address" type="xs:string" use="required">
</xs:attribute>
<xs:attribute name="systemNr"
type="xs:string" use="required">
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
And here is the code snippet:
File systemsFile = new File(LocalFileSystemManager.getDefaultPath() + "Systems.xml");
File schemaFile = new File(LocalFileSystemManager.getDefaultPath() + "SystemsSchema.xsd");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document systemsDocument = db.parse(systemsFile);
systemsDocument.getDocumentElement().normalize();
SchemaFactory factory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(new DOMSource(systemsDocument));
Thanks in advance!
Lori
A: This instance should validate. Your attributes belong to the schema so you need to mark them as such with a namespace:
<?xml version="1.0" encoding="UTF-8"?>
<systems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="test.namespace">
<system a:address="test" a:id="test" a:name="test" a:systemNr="test" xmlns:a="test.namespace">
<mandant a:mandant="test"/>
</system>
...
</systems>
I am assuming you have attributeFormDefault="qualified" and elementFormDefault="qualified" in your <schema /> element?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Transfer Resources to fresh installation I have live website running on MODx Revolution 2.1.3pl. Some days back I had to restore my entire site from backup. This messed up some file ownerships (for packages installed and images uploaded etc.) because in my server PHP runs as 'nobody' user which is different from my cPanel user.
Now I can't change much things on the server(like installing suPHP because its a shared server) and I don't know which all files are created by PHP, I decided to wipe the site clean and perform a clean install. My site has a large number of already published resources which is impossible to be posted into the new site individually.
Is there any way that I can transfer those resources to the new installation?
A: Why don't you create a mysql dump of your old site (with phpmyadmin or the like) and import this into a new database, which you use to run your new site from?
A: I've not tried it myself but provisioner seems to do (or at least claim to) what you need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eclipse+FindBugs - exclude filter files doesn't work I'm using Windows and Eclipse 3.7 Classic with ADT plugin for Android development.
I've just installed FindBugs and it have found a bug in auto-generated R.java class.
I want to exclude this class from FindBugs checks.
I've found that I can define exclude filters for FindBugs in xml file, so I've created a file D:\Projects\eclipse\FindBugsExculde.xml with text
<FindBugsFilter>
<Match>
<Class name="com.android.demo.notepad3.R$attr" />
</Match>
</FindBugsFilter>
I've added this file to Eclipse -> Window -> Preferences -> Java -> FindBugs -> Filter files -> "Add..." button near the "Exclude filter files" section.
But when I right-click on my project and select "Find Bugs" -> "Find Bugs" I still see the error
The class name com.android.demo.notepad3.R$attr doesn't start with an upper case letter
I have even tried to replace
<Class name="com.android.demo.notepad3.R$attr" />
with
<Class name="~.*" />
but still the error is there.
I tried to restart Eclipse - no luck. I even thought that maybe there is a Bug in FindBugs so it doesn't use the file specified but Procmon.exe from SysinternalsSuite shows that it do use it each time I execute FindBugs:
ProcessName Operation Path Result
javaw.exe QueryOpen D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
javaw.exe QueryOpen D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
javaw.exe CreateFile D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
javaw.exe CreateFile D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
javaw.exe QueryFileInternalInformationFile D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
javaw.exe CloseFile D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
javaw.exe ReadFile D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
javaw.exe CloseFile D:\Projects\eclipse\FindBugsExculde.xml SUCCESS
What am I doing wrong? Please help me!
A: Following the directives from Jenkins I created a findbugs-exclude.xml in my android workspace and added it via Eclipse -> Window -> Preferences -> Java -> FindBugs -> Filter files -> "Add..." button near the "Exclude filter files" section to findbugs. My first error was that I ticked the first checkbox (the include filter :-) section).
Then I started manually findbugs and everything was ok. The content of my file is:
<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
<Match>
<Class name="~.*\.R\$.*"/>
</Match>
<Match>
<Class name="~.*\.Manifest\$.*"/>
</Match>
</FindBugsFilter>
I am using eclipse 3.7.1 and findbugs 1.3.9. Hope that helps.
A: Filter file may be ignored silently when path to file is incorrect or when XML file is not valid. Try to validate filter using XSD from https://raw.githubusercontent.com/findbugsproject/findbugs/master/findbugs/etc/findbugsfilter.xsd .
Had this problem on Eclipse 4.4.2.
A: I just want to remind newbie that "Default Settings" is apply on new project, so you can't just exclude your filter in "Default Settings" if you want to apply it in current project:
instead you should exclude your filter in "Settings":
btw, once plugin installed and restart, Android Studio may pop up dialog on right bottom, you just have to click that link Add R.class File Filter, it will automatically generate the correct xml code for you.
A: Please delete the error manually. Select the error and right click, select Delete. Then rebuild your project.
It could be that findbugs is ignoring the file correctly, but that doesn't mean that the errors it has previously raised on the file get deleted, they still exist, and you have to delete them manually.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to run background service on web application - DotNetNuke I made dnn scheduler and set to run it on every 1 min. It works when I do something on site. But I need to run some actions when I am not on the site. For example insert record to database with currenct time. Is this possible?
A: In Host Settings, use Scheduler Mode = Timer Method
This will make the scheduler run in a separate thread that is not triggered by page requests.
If the scheduler runs in the timer method, it won't have access to the current HttpContext.
You will also have to make sure that DNN is kept alive, and IIS doesn't shut down the application due to inactivity. Setting the application pool idle timeout appropriately, and pinging the /Keepalive.aspx should take care of this. Nevertheless, using the DNN scheduler for critical tasks is not a good idea.
See Also:
*
*Creating DotNetNuke Scheduled Jobs
*DotNetNuke Scheduler
Explained
A: If you just want database related things, such as inserting a record, you can use database jobs. You didn't mention what dbms you use but almost every database have almost same functionality under different names.
A: Doing the equivalent of a Cron job is still a pain in the butt on Windows.
The DNN Scheduler will work if you aren't super concerned about when it runs. What you may need to do is have more logic on your end... if it only runs every 10 minutes, or every hour or whatever you may have to look at your database tables, determine last time it ran and then do whatever it needs to do to 'catch up.' In your case add 60 minutes of info versus every minute.
I'm struggling to think of an example of why I would just write to a table every minute or on some interval. If I needed it for a join table or something convenient to report off of you should generate them in larger chunks.
The other option is to write a small .NET windows service which isn't that hard and have it run every minute. That would be more reliable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Map View on Tab Bar project I've got a tab-bar project in Xcode 4 and I'm trying to implement a map view on one of the tabs.
I've followed this tutorial: http://www.youtube.com/watch?v=ZrePrrHgXYA but I'm getting an error: Program received signal: "SIGBART" whenever I click the tab.
How come? Is it because the tutorial is only for view based projects? And if so, how do I get around it?
A: Error SIGBART can be shown when you don't import a Framework (like mapkit), o you try to use an object that has been released. Is a common error occurred when you badly connect (in IB o in code) with link pages or objects. You surely have done a big error in the code that prevent your app to run! Try to redo the last steps before the app stopped!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP unsetting all variables with 'tmp' at the front I'm simply looking to loop through all current session variables and if the session variable name begins with 'tmp' then I want to unset the variable.
I would do it as follows:
foreach($session as $sv){
if(substr($sv,0,3)=='tmp'){
unset($sv);
}
}
Just not sure how to get all the current session variables into an array to start with.
Thanks in advance!
A: $_SESSION holds every session variable
foreach(array_keys($_SESSION) as $sv){
if(substr($sv, 0, 3) === 'tmp'){
unset($_SESSION[$sv]);
}
}
is correct
A: Simply use $_SESSION
A: What's the problem with
foreach (array_keys($_SESSION) as $key) {
if (substr($key,0,3) == 'tmp') {
unset($_SESSION[$key]);
}
}
?
A: Solution with suitable example
<?php session_start();
$_SESSION['var1']='var 1 value';
$_SESSION['var2']='var 2 value';
$_SESSION['var3']='var 3 value';
$_SESSION['tmpvar1']='tmp var 1 value';
$_SESSION['tmpvar2']='tmp var 2 value';
$_SESSION['tmpvar3']='tmp var 3 value';
print_r($_SESSION);
foreach($_SESSION as $key=>$value)
{
if(substr($key,0,3)=='tmp'){
unset($_SESSION[$key]);
}
}
print_r($_SESSION);
?>
A: If your are actually trying unset variables to do with a session) you would loop through $_SESSION.
If by session variables you mean "all variables declared in the scope of the current script" you would loop through $GLOBALS for all variables in the global scope, or the result of get_defined_vars() for all variables in the current scope, e.g. the scope of the current function.
The code you have to actually do the loop and unset the variables is correct.
A: Session itself is a big array, of arrays of arrays etc... so you need to make some recursive function which would search all the levels ($_SESSION["a"] can be an array whcih have some temps inside like $_SESSION["a"]["tmp_b"] ..)
So:
function resetTemps($arr)
{
foreach( $arr as $key => $value )
{
if( is_array( $value ) )
{
resetTemps($value);
}
else
{
if( substr($key,0,3)=='tmp' )
{
unset( $arr[$key] );
}
}
}
}
And then call it like
resetTemps($_SESSION);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Splitviewcontroller with two tableviews, delegate problem I have, what seems to be a basic requirment. I am making a splitview iPad app using xcode 4's template. I want my root view controller to be a table view populated with languages and my detail view to be another tableview that gets re-populated every time the user selects a language on the left. The problem is, when a user selects a language on the left in the rootview, my [tableView reloadData]; function in the detailview doesn't work ie. the tableView delegates do not get called. I need it so that when the user selects a language the tableView gets refreshed.
Here is the code I have now:
RootViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetailViewController *detObj = [[DetailViewController alloc] init];
detObj.detailItem = [self.tableArray objectAtIndex: indexPath.row];
NSLog(@"Selected Item %@", [self.tableArray objectAtIndex: indexPath.row]);
}
DetailViewController.m
- (void)setDetailItem:(id)newDetailItem
{
NSLog(@"setDetailItem Called");
if (_detailItem != newDetailItem) {
[_detailItem release];
_detailItem = [newDetailItem retain];
self.title = _detailItem;
NSLog(@"Detail Item %@", _detailItem);
// Update the view.
//[self testAction:self];
[self configureView];
}
if (self.popoverController != nil) {
[self.popoverController dismissPopoverAnimated:YES];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
[tableView setDataSource:self];
[tableView setDelegate:self];
NSLog(@"Configure");
[self.tableView reloadData];
}
#pragma mark - Split view support
- (void)splitViewController:(UISplitViewController *)svc willHideViewController:(UIViewController *)aViewController withBarButtonItem:(UIBarButtonItem *)barButtonItem forPopoverController: (UIPopoverController *)pc
{
barButtonItem.title = @"Languages";
NSMutableArray *items = [[self.toolbar items] mutableCopy];
[items insertObject:barButtonItem atIndex:0];
[self.toolbar setItems:items animated:YES];
[items release];
self.popoverController = pc;
}
// Called when the view is shown again in the split view, invalidating the button and popover controller.
- (void)splitViewController:(UISplitViewController *)svc willShowViewController:(UIViewController *)aViewController invalidatingBarButtonItem:(UIBarButtonItem *)barButtonItem
{
NSMutableArray *items = [[self.toolbar items] mutableCopy];
[items removeObjectAtIndex:0];
[self.toolbar setItems:items animated:YES];
[items release];
self.popoverController = nil;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(@"DETAIL numberOfSectionsInTableView Called");
#warning Potentially incomplete method implementation.
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
// Return the number of rows in the section.
if(section == 0){
return 2;
}
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (section == 0) {
return @"Documents";
}
else if (section == 1){
return @"Video";
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = @"Cell";
return cell;
}
By the way all those logs are working correctly (except for the one in the tableView delegate method) and I have set the delegates for both tableViews in IB, in the .h and in the .m. As a test I set up a button in the detailView nib file with an IBAction as follows:
- (void)testAction:(id)sender {
NSLog(@"Test CAlled");
[self.tableView reloadData];
}
and it works. What is going on?
A: In - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath you should update current DetailViewController and not making new one. It is approach that you should follow when using split view.
So you should replace alloc+init :
DetailViewController *detObj = [[DetailViewController alloc] init];
with
DetailViewController *detObj = self.currentDetailViewController;
where self.currentDetailViewController should point on current left view in split view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Different DataTemplates in one TreeView? is it possible to use two different DataTemplates in one WPF TreeView?
Maybe the first and second flat with yellow Background and the thirt flat with red Background.
Where is the right place for the distinction - in Code or in XAML?
Thanks for your ideas.
A: Different templates are possible in more than one ways...
*
*Templates at various hierarchy levels.
*Templates using selector.
*One template with multiple data triggers setting various backgrounds.
A: Sure, if you use HierarchicalDataTemplate you will see that these also have an ItemTemplate field where you can supply another HierarchicalDataTemplate for the sub children, where you can provide another look for the items. Also you can use implicit DataTemplates, or use an ItemTemplateSelector. It more or less depends on your actual needs.
I'm not sure, but maybe it is also possible, if you just want to change the color, which can be used with a trigger, to use the AlternationCount property, but i never used it myself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Loading Dialog Box for Webview This things sending me crazy. My app loads webview and shows a loading dialog on the initial load. I want the loading dialog to appear each time a link is clicked or each time webview is loading. This is not happening.
Eclipse tells me onPageStarted() is not used locally, although onPageFinished() works fine!?
Can anyone see what's going wrong, I've pasted all my activity below:
package com.jeh.myapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyActivity extends Activity {
WebView myWebView;
public static final String TAG = "Main";
public ProgressDialog progressBar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar as we already have it in the web app
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Point to the content view defined in XML
setContentView(R.layout.main);
//Configure the webview setup in the xml layout
myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
//Yes, we want javascript, pls.
webSettings.setJavaScriptEnabled(true);
progressBar = ProgressDialog.show(MyActivity.this, "Diag Title", "Loading...");
//Make sure links in the webview is handled by the webview and not sent to a full browser
myWebView.setWebViewClient(new WebViewClient() {
//this bit causes problems, if I add @Override here it says to remove, where as the current code marks onPageStarted yellow and says it's not used locally!? - yet onPageFinsihed() below works fine?
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.show();
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
//Load URL:
myWebView.loadUrl("http://www.google.com");
}
A: Easy.
There are no
void onPageStarted(WebView view, String url)
method in a WebViewClient, simply use :
@Override
void onPageStarted(WebView view, String url, Bitmap favicon)
These errors are easy to make and difficult to find. You should use @Override keyword wherever you know you're overriding a method (which would have flagged an error in your case).
Try to modify your source this way:
//Make sure links in the webview is handled by the webview and not sent to a full browser
myWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.show();
}
@Override
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Join columns with certain values (and replace) Consider a table that looks like this:
**************************
* Col1 *** Col2 *** Col3 *
--------------------------
* 0 *** 1 *** 0 *
* 0 *** 0 *** 0 *
* 1 *** 1 *** 0 *
* 1 *** 1 *** 1 *
**************************
How could I join (for example) the last row with each field containing "1" translated into something?
So for the first row, it would return something like: "Yes" (omitting the ones that isn't "1"). Or for the last row: "Yes, Yes, Yes".
A: SELECT IF(Col1=1,'Yes', 'No'), IF(Col2=1,'Yes', 'No'), IF(Col3=1,'Yes', 'No') FROM tbl;
Replace 'NO' with 0 if you don't want No.
ANSWER MODIFICATION TO REFLECT QUESTION:
SELECT CONCAT_WS(',', IF(Col1=1,'Yes',NULL), IF(Col2=1, 'Yes', NULL), IF(Col3=1, 'Yes', NULL) ) as formatedText FROM tbl;
A: Try something like this:
SELECT
REPLACE(TRIM(CONCAT(IF(Col1=1,'Yes ',''), IF(Col2=1,'Yes ',''), IF(Col3=1,'Yes ',''))), ' ', ', ') AS translation
FROM
oneyes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How is new application launched on Mac? I am looking for process & a system call which is responsible for starting every new process on Mac.
I believe it should be something like CreateProcess() and which returns process id of newly created process.(This is a guess)
I am interested in internal details like a flow responsible for launching new application.
Any help is appreciated. Even some references to look after might help.
A: OS X is a variety of Unix. New processes are created with the fork() system call. This creates an almost identical copy of the process that makes the call (the difference is that fork returns 0 in the child and the pid of the child in the parent). It's then normal to use one of the exec() syscalls in the child to transform the child into a process running a different executable.
Edit
Since the question is tagged [Cocoa], I should mention there is a Cocoa class called NSTask that wraps the above.
A: Normally on Mac OS X LaunchD is parent of all the processes. So, LaunchD is launching them. How?? First it fork() and then posix_spawn().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the cheapest way to build an Erlang server farm (for a hobby project)? Let's say we have an 'intrinsically parallel' problem to solve with our Erlang software. We have a lot of parallel processes and each of them executes sequential code (not number crunching) and the more CPUs we throw at them the better.
I have heard about CUDA bindings for Erlang, but after watching the Kevin Smith's presentation I am not sure that it is the solution: the whole purpose of pteracuda buffer is to assign a difficult number crunching task to the buffer and get the result back. It is not possible to use GPU's processors to serve Elrang's processes. (Am I right?).
On the other side multicore CPUs are really expensive (8 cores CPU prices start at $300). So, to build a 10-machine Erlang parallel processing 'cluster' you have to spend at least $3000 on CPUs only.
So, the question is:
What kind of affordable CPU or GPU can be used to build a 'server cluster' for a parallel Erlang software?
A: There was a student project at Uppsala University in 2009 called LOPEC that had this aim, in cooperation with Erlang Solutions (then still called Erlang Training & Consulting, or ETC for short).
I couldn't find any slides from their final project report, but this is a poster they showed at the Erlang User Conference in 2009: http://www.it.uu.se/edu/course/homepage/projektDV/ht09/ETC_poster.pdf
Parts of the code seems to live on here: https://github.com/burbas/LoPECv2 (the user burbas was one of the students), but strangely incomplete. You could ask burbas for more info.
There is of course also the Disco project by Nokia: http://discoproject.org/
In both cases, I think you'll need to write a C or Python stub to run on the clients to talk to the GPU (or you might run Erlang with CUDA bindings on the clients); the above frameworks just help you distribute the workload and gather results.
A: I would check into Amazon EC2. You can rent servers for very cheap, and can spin the servers up close to instantly if there is work to be done. You can also bid on very cheap spot instances. This would at least give you a great way to test your code on multiple boxes, and allow for some testing if you want to buy the hardware at a later date. They also have GPU instances available as well (for a more expensive rate), which have Tesla GPU's and quad core hyper threaded processors. Here is a list of all the types available.
Here is a simple guide I found to help you get started setting up a master node that can spin up additional nodes if needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Boost PropertyTree: check if child exists I'm trying to write an XML parser, parsing the XML file to a boost::property_tree and came upon this problem. How can I check (quickly) if a child of a certain property exists?
Obviously I could iterate over all children using BOOST_FOREACH - however, isn't there a better solution to this?
A: Include this:
#include <boost/optional/optional.hpp>
Remove the const:
boost::optional< ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
// child node is missing
}
A: optional< const ptree& > child = node.get_child_optional( "possibly_missing_node" );
if( !child )
{
// child node is missing
}
A: Here's a couple of other alternatives:
if( node.count("possibliy_missing") == 0 )
{
...
}
ptree::const_assoc_iterator it = ptree.find("possibly_missing");
if( it == ptree.not_found() )
{
...
}
A: One other way which can be used is to used in case you don't want to check some potential missing child/nodes. Try using iterators:
if (node.begin() != node.end()) { // Node does have child[ren]
// Code to process child nodes
}
A: You can check if a tag is present or not using count()
typedef boost::property_tree pt;
pt::ptree tree;
pt::read_xml(filename, tree);
int bodyCount = tree.count( "body" );
if( bodyCount == 0 )
{
cout<<"Failed : body tag not found"<<endl;
return -1;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: Micro-benchmark comparing Scala mutable, immutable collections with java.util.concurrent.* collections Are there any published micro-benchmarks that compare the Scala mutable and immutable collections with each other and the collections in java.util.concurrent, in multi-threaded environments? I am particularly interested in cases where readers far outnumber writers, like caching HashMaps in server-side code.
Micro-benchmarks of the Clojure collections would also be acceptable, as their algorithms are similar to those used in the Scala 2.8 persistent collections.
I'll write my own if there are none already done, but writing good micro-benchmarks is not trivial.
A: There are some results comparing Java hash maps, Scala hash maps, Java concurrent hash maps, Java concurrent skip lists, Java parallel arrays and Scala parallel collections here (at the end of the technical report):
http://infoscience.epfl.ch/record/165523/files/techrep.pdf
There is a more detailed comparison of concurrent skip lists and Java concurrent hash maps here (also at the end of the main part of the report, before the appendix):
http://infoscience.epfl.ch/record/166908/files/ctries-techreport.pdf
These micro benchmarks are focused on testing the performance of one single operation. If you plan to write your own benchmarks, this will probably be useful:
http://buytaert.net/files/oopsla07-georges.pdf
A: Li Haoyi's Benchmarking Scala Collections is a detailed and comprehensive study that addresses your query. It is way too long to quote here.
A: Why don't you try using java.util.concurrent.ConcurrentHashMap then? that way you don't have to synchronize, and your million reads will be much faster (as well as the one write).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: initialisation of const member of base class into derive class public:
const int x;
base():x(5){}
};
class der : public base {
public:
der():x(10){}
};
der d;
My aim is when instance of base class is created it will initialise x as 5 and when instance of der class is created it will initialise x as 10. But compiler is giving error.
As x is inherited from class base, why is it giving error?
A: You can make this work with a little adjustment...
#include <cassert>
class base
{
public:
const int x;
base()
:x(5)
{
}
protected:
base(const int default_x)
:x(default_x)
{
}
};
class der: public base
{
public:
der()
:base(10)
{
}
};
struct der2: public base
{
der2()
:base()
{
}
};
int main()
{
base b;
assert(b.x == 5);
der d;
assert(d.x == 10);
der2 d2;
assert(d2.x == 5);
return d.x;
}
This provides a constructor, accessible by derived classes, that can provide a default value with which to initialise base.x.
A: You can't initialize a base class member in the initializer list for a constructor in the derived class. The initializer list can contain bases, and members in this class, but not members in bases.
Admittedly, the standardese for this isn't entirely clear. 12.6.2/2 of C++03:
Unless the mem-initializer-id names a nonstatic data member of the
constructor’s class or a direct or virtual base of that class, the
mem-initializer is ill-formed.
It means "(a nonstatic data member of the constructor's class) or (a direct or virtual base)". It doesn't mean "a nonstatic data member of (the constructor's class or a direct or virtual base)". The sentence is ambiguous, but if you took the second reading then you couldn't put bases in the initializer-list at all, and the very next sentence in the standard makes it clear that you can.
As for why it's not allowed, that's a standard rationale question and I'm guessing at the motives of the authors of the standard. But basically because it's the base class's responsibility to initialize its own members, not the derived class's responsibility.
Probably you should add an int constructor to base.
A: This works.
class base {
public:
static const int x = 5;
};
class der : public base {
public:
static const int x = 10;
};
If you want to change x depending on your constructor, you have to make it non-static.
A non-static const is the same as a non-const variable once compiled. If you want to enforce a member variable to be read-only, use non-static const. If you want to set a constant whose scope is restricted to a single class, use static const.
A: This may be over-engineered compared the original question, but please consider:
template <typename T, class C, int index=0>
// C and index just to avoid ambiguity
class constant_member {
const T m;
constant_member (T m_) :m(m_) {}
};
class base : virtual public constant_member<int, base> {
public:
base () : constant_member<int, base>(5) {}
int x () const { return constant_member<int, base>::m; }
};
class der : public base {
public:
der () : constant_member<int, base>(10) {}
};
class der2 : public der{
public:
der2 () {} // ill-formed: no match for
// constant_member<int, base>::constant_member()
};
Comment: This is verbose, non-obvious (maybe impossible to understand for beginners), and it will be very inefficient to convert to virtual base class just to read a member variable. I am not really suggesting this as a real world solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to Get Correct co-ordinates after zooming? im using finger paint turtorial with
class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor = detector.getScaleFactor();
mScaleFactor = Math.max(1f, Math.min(mScaleFactor, 5.0f));
return true;
}
}
but after zooming canvas,my lines are not drawing at correct position on canvas?
A: you have create logic like when you zooming then increase your canvas size also
like canvasHeight=(canvasHeight*mScaleFactor);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to merge two excel files into one with their sheet names? For merging of two excel sheet, I am using below code.
using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace MergeWorkBooks
{
class Program
{
static void Main(string[] args)
{
Excel.Application app = new Excel.Application();
app.Visible = true;
app.Workbooks.Add("");
app.Workbooks.Add(@"c:\MyWork\WorkBook1.xls");
app.Workbooks.Add(@"c:\MyWork\WorkBook2.xls");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
int count = app.Workbooks[i].Worksheets.Count;
app.Workbooks[i].Activate();
for (int j=1; j <= count; j++)
{
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
ws.Select(Type.Missing);
ws.Cells.Select();
Excel.Range sel = (Excel.Range)app.Selection;
sel.Copy(Type.Missing);
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing
);
sheet.Paste(Type.Missing, Type.Missing);
}
}
}
}
}
This code is working good for me for merging excel workbook. But at the time of merging I am not getting the excel sheet names. Here I need that when the excel is merging at the same time the sheet names should also go to the merged excel sheet.
A: The following worked fine for me, including copying the name and where the name clashed it kindly even handled the Sheet1(2) etc.
Excel.Application app = new Excel.Application();
app.Visible = true;
app.Workbooks.Add("");
app.Workbooks.Add(@"c:\MyWork\WorkBook1.xls");
app.Workbooks.Add(@"c:\MyWork\WorkBook2.xls");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
for (int j = 1; j <= app.Workbooks[i].Worksheets.Count;j++ )
{
Excel.Worksheet ws = app.Workbooks[i].Worksheets[j];
ws.Copy(app.Workbooks[1].Worksheets[1]);
}
}
A: Error Free and Improve Answer
create result2.xlsx file as same location and you find final excel sheet as you want
class Program
{
static void Main(string[] args)
{
Application app = new Application();
app.Visible = true;
Workbook w1 = app.Workbooks.Add(@"D:\MyDownload\result2.xlsx");
Workbook w2 = app.Workbooks.Add(@"D:\MyDownload\merge1.xlsx");
Workbook w3 = app.Workbooks.Add(@"D:\MyDownload\merge2.xlsx");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
for (int j = 1; j <= app.Workbooks[i].Worksheets.Count; j++)
{
Worksheet ws = (Worksheet)app.Workbooks[i].Worksheets[j];
ws.Copy(app.Workbooks[1].Worksheets[1]);
}
}
app.Workbooks[1].SaveCopyAs(@"D:\MyDownload\result2.xlsx");
w1.Close(0);
w2.Close(0);
w3.Close(0);
app.Quit();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Cast List to List I'm writing a piece of code in java and would like to encapsulate my object and only return interfaces.
Now in short this is my problem I have a class containing a list, and I have a getter which returns a List. How can I return a list of the interface ?
Without getting this error warning :
List is a raw type. References to generic type List should be parameterized
To give you a clear picture this piece of code is an example of my problem :
public class Employee{
private List<MyObject> myObjects;
public List<MyInterface> getMyObjects(){
return myObjects;
}
}
where MyObject implements MyInterface and return myObjects gives the problem.
Thanks in advance.
A: If MyObject implements MyInterface you could change the return type to List<? extends MyInterface>.
class Employee{
private List<MyObject> myObjects;
public List<? extends MyInterface> getMyObjects(){
return myObjects;
}
}
Note that in this case the compiler won't allow you to call add(...) on the returned list, except you'd cast here. However, since you're returning interfaces only, I guess you're not planning to add anything to the returned list, so you should be fine.
A: Simply declare a list of your interface as your instance variable.
private List<MyInterface> myObjects;
A: I'd simply define the instance attribute the way you need it:
public class Employee{
private List<MyInterface> myObjects;
public List<MyInterface> getMyObjects(){
return myObjects;
}
}
A: Even though MyObject implements MyInterface, it is not true that List<MyObject> extends List<MyInterface> - see this excellent document for more info. In order to inform the compiler of your intentions, specify the method signature like so:
public List<? extends MyInterface> getMyObjects{
...
A: Use
checkedCollection(Collection c, Class type)
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Collections.html#checkedCollection(java.util.Collection, java.lang.Class)
A: You cannot cast List<MyObject> to List<MyInterface>. So try to define myObjects as List<MyInterface> or use the following:
public class Employee{
private List<MyObject> myObjects;
public List<MyInterface> getMyObjects(){
List<MyInterface> result = new ArrayList<MyInterface>(myObjects.size());
result.addAll(result);
return result;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In Django, can I exclude a field in ModelForm sub-subclass? I have a “generic” InternForm that inherits from ModelForm and defines common messages, widgets, etc.
I defined a subclass called ApplyInternForm for application form that is accessible to everyone and I want to hide some of the “advanced” fields.
How can I override exclude setting in the form's subclass?
class InternForm(ModelForm):
# ...
class Meta:
model = Intern
exclude = ()
class ApplyInternForm(InternForm):
def __init__(self, *args, **kwargs):
super(ApplyInternForm, self).__init__(*args, **kwargs)
self.Meta.exclude = ('is_active',) # this doesn't work
A: Defining a Meta class in the subclass worked for me:
class InternForm(ModelForm):
# ...
class Meta:
model = Intern
class ApplyInternForm(InternForm):
class Meta:
model = Intern
exclude = ('is_active',)
A: Not in this way, no. When you subclass a form the fields you want to exclude are already there. You can however remove them from self.fields after calling super() in your __init__().
A: You can change widget to hidden:
class ApplyInternForm(InternForm):
class Meta:
widgets = {
'is_active': forms.HiddenInput(required=False),
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any way to implement unscrollable header for UISplitViewController RootViewController? What it did in RootviewController of UISplitViewController -
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 0)];
[searchBar setPlaceholder:@"Search within application"];
searchBar.delegate = self;
[searchBar sizeToFit];
searchBar.tintColor=[[UIColor alloc] initWithRed:212.00/255 green:236.00/255 blue:256.00/255 alpha:1.0 ];
self.tableView.tableHeaderView = searchBar;
[searchBar release];
It's working fine but when we scroll tableview searchbar is also moving with tableview rows.
I want to implement searchbar which will always visible to the user.
I can try with SearchDisplayController but in UISplitViewController we are not getting .xib file for RootViewController.
Please help me out on this.
A: You can add your search bar to the navigation controller's navigation bar. Here are the steps:
*
*change the frame of the navBar by adding the height of the search bar to its frame.origin.height.
*add the search bar as a subview
*change the class of the controller's view to UIView (assuming it is now a table view) and add a new subview UITableView, adjusting the frame according to your search bar height.
*reconnect the new tableView with the controller (delegate, datasource, tableView outlet).
This worked for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gridview Dynamic linkButton event not fired I'm creating a GridView with dynamic controls(including itemtemplates).
Here is the html code.
<asp:GridView ID="gvItems" runat="server"
AutoGenerateColumns="False" CellPadding="4"
GridLines="None"
Width="95%" EmptyDataText="Records Not Found!!!!"
onselectedindexchanged="gvItems_SelectedIndexChanged"
onrowdatabound="gvItems_RowDataBound" onrowcommand="gvItems_RowCommand"
onselectedindexchanging="gvItems_SelectedIndexChanging">
<RowStyle CssClass="GVRowStyle" />
<Columns>
</Columns>
<PagerStyle CssClass="gridPager" />
<SelectedRowStyle BackColor="#DCCDDA" Font-Bold="true" ForeColor="#510030" />
<HeaderStyle CssClass="Gheader" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
<EditRowStyle BackColor="#7C6F57" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
</asp:GridView>
Here is the class for Adding ItemTemplate...................................
public class GridViewTemplate : ITemplate
{
ListItemType _templateType;
string _columnName;
public GridViewTemplate(ListItemType type, string colname)
{
_templateType = type;
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
Label lbl = new Label();
lbl.Text = _columnName;
container.Controls.Add(lbl);
break;
case ListItemType.Item:
LinkButton Lb1 = new LinkButton();
Lb1.CommandName = "Select";
Lb1.DataBinding += new EventHandler(tb1_DataBinding);
container.Controls.Add(Lb1);
break;
case ListItemType.EditItem:
break;
case ListItemType.Footer:
CheckBox chkColumn = new CheckBox();
chkColumn.ID = "Chk" + _columnName;
container.Controls.Add(chkColumn);
break;
}
}
void tb1_DataBinding(object sender, EventArgs e)
{
LinkButton LinkData = (LinkButton)sender;
GridViewRow container = (GridViewRow)LinkData.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
LinkData.Text = dataValue.ToString();
LinkData.ForeColor = System.Drawing.Color.Red;
LinkData.CommandName = "Select";
}
}
}
Here is the page code.........................................
for (int i = 0; i < dtGrid.Columns.Count; i++)
{
string columnName = dtGrid.Columns[i].ColumnName;
BoundField bField = new BoundField();
TemplateField tField = new TemplateField();
if (i == 0)
{
tField.HeaderTemplate = new GridViewTemplate(ListItemType.Header, columnName);
tField.ItemTemplate = new GridViewTemplate(ListItemType.Item, columnName);
tField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
tField.ItemStyle.ForeColor = System.Drawing.Color.Red;
gvItems.Columns.Add(tField);
}
else
{
bField.DataField = columnName;
bField.HeaderText = columnName;
bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
gvItems.Columns.Add(bField);
}
Now Problem is when i click on linkbutton it disappear and no event other than rowdatabound is raised.
A: Since you're creating these columns dynamically, you'll need to recreate the controls at every postback. As for the event handler not firing, make sure you create the columns early enough in the page lifecycle. I would suggest creating the dynamic columns OnInit, and see if that fixes the problem.
A: Are you re-binding the data on postbacks?
Please make sure that your data-binding logic is surrounded with if(!IsPostback).
The re-binding of the grid means re-creation of your button, and therefore no events are fired.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TextBox Column In DataGridView I have added TextBox control inside the grid: I want my DataGridView TextBox column to hold numbers without any decimal values. How can I do it?
A: From: http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/919b059c-dba9-40d2-bac7-608a9b120336
You can handle the DataGridView.EditingControlShowing event to cast
the editing control to TextBox when editing in the column you want to
restrict input on, and attach KeyPress event to the TextBox, in the
KeyPress event handler function, we can call the char.IsNumber()
method to restrict the key board input, something like this:
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("c1", typeof(int));
dt.Columns.Add("c2");
for (int j = 0; j < 10; j++)
{
dt.Rows.Add(j, "aaa" + j.ToString());
}
this.dataGridView1.DataSource = dt;
this.dataGridView1.EditingControlShowing +=
new DataGridViewEditingControlShowingEventHandler(
dataGridView1_EditingControlShowing);
}
private bool IsHandleAdded;
void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if (!IsHandleAdded &&
this.dataGridView1.CurrentCell.ColumnIndex == 0)
{
TextBox tx = e.Control as TextBox;
if (tx != null)
{
tx.KeyPress += new KeyPressEventHandler(tx_KeyPress);
this.IsHandleAdded = true;
}
}
}
void tx_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b'))
{
e.Handled = true;
}
}
A: public Form1()
{
InitializeComponent();
dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing;
}
private void dataGridView1_EditingControlShowing(object sender , DataGridViewEditingControlShowingEventArgs e)
{
// Convert the editing control to a TextBox to register for KeyPress event
TextBox txt_edit = e.Control as TextBox;
if(txt_edit != null)
{
// Remove any existing handler
txt_edit.KeyPress -= TextBoxKeyPressed;
// Add the new handler
txt_edit.KeyPress += TextBoxKeyPressed;
}
}
private void TextBoxKeyPressed(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Test for numeric value or backspace in first column
// Change this to whatever column you only want digits for
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
// If its a numeric or backspace, display it. Not a numeric, ignore it
e.Handled = (!Char.IsDigit(e.KeyChar) && (e.KeyChar != (char)Keys.Back));
}
}
A: Try this:
Convert.ToInt32(textBox1.Text)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Start windows service automatically when system reboots I have installed a windows service in a server with automatic mode.But when system reboots its not starting automatically.It is still in start state only. Manually i am starting the service. Please suggest me how can the service get started when system reboots.Service is working fine.No dependencies.
A: Check the system logs (run compmgmt.msc , under "Performance Logs and Alerts"), for any error messages. It seems like you service is not starting for a good reason, most likely a dependency.
A: I got the solution for my problem.By setting property of service to local system its working fine.
A: Just set the preference to Automatic and the service would automatically run
A: Go to start
type services.msc and press enter.
On the services list that opens up, right click on the service and select Properties. The dialog that opens has an option 'Automatic' for starting your service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to pass generic parameters to multiple delegates. 2 Delegates with generic parameters I have a method which accepts two delegates as parameters.
method1(Delegate delegate1,Delegate delegate2,params Object[] parameters)
{
// There is lot of other code, I haven't put here. To make it clear.
string key = delegate1.DynamicInvoke(parameters);
object instance = delegate2.DynamicInvoke(parameters);
// Getting errors here, as parameters mismatch.
}
// Code from the Calling class
// There are many other classes in my project, which are calling Method1,
// but the number of parameters of method2 and method3 always vary.
private string Method2(object[] paramsObject)
{
string key = string.Empty;
foreach (object obj in paramsObject)
{
key += obj.ToString() + "|";
}
return key.Trim(new char[]{'|'});
}
private object Method3(object[] paramsObject)
{
object object1 = paramsObject[0];
object object2 = paramsObject[1];
object object3 = paramsObject[2];
object object4 = GetObjectUsingParameters(object1,object2,object3);
return object4;
}
Func<string, string, string> Method2Delegate = Method2;
Func<object1,object2,object3,object4> Method3Delegate = Method3;
//Calling Method1
Method1(Method2Delegate,Method3Delegate,string str1,string str2,object object1,Object object2,Object object3);
I am getting an error in Method1 when invoking the delegates, parameters mismatch error.
As we can have only one one params parameter as input for a method at the end.
Could you please let me know, how can I bind the parameters to the same delegate or how can I resolve this issue?
Thanks inadvance.
A: You need to create a delegate with the next signature:
delegate void MyCustomDelegate (params object[] params);
And then to define Method2Delegate and Method3Delegate as MyCustomDelegate type.
A: what about doing it like this:
method1(Func<object[],string> delegate1,Func<object[], object> delegate2,params Object[] parameters)
{
// There is lot of other code, I haven't put here. To make it clear.
string key = delegate1(parameters);
object instance = delegate2(parameters);
// Getting errors here, as parameters mismatch.
}
and at the caller just
Method1(Method2,Method3,string str1,string str2,object object1,Object object2,Object object3);
this way you don't need to define delegates that dynamically invoked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using Python String Formatting with Lists I construct a string s in Python 2.6.5 which will have a varying number of %s tokens, which match the number of entries in list x. I need to write out a formatted string. The following doesn't work, but indicates what I'm trying to do. In this example, there are three %s tokens and the list has three entries.
s = '%s BLAH %s FOO %s BAR'
x = ['1', '2', '3']
print s % (x)
I'd like the output string to be:
1 BLAH 2 FOO 3 BAR
A: For just filling in an arbitrary list of values to a string, you could do the following, which is the same as @neobot's answer but a little more modern and succinct.
>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'
If what you are concatenating together is already some kind of structured data, I think it would be better to do something more like:
>>> data = {"blah": 1, "foo": 2, "bar": 3}
>>> " ".join([f"{k} {v}" for k, v in data.items()])
'blah 1 foo 2 bar 3'
A: Following this resource page, if the length of x is varying, we can use:
', '.join(['%.2f']*len(x))
to create a place holder for each element from the list x. Here is the example:
x = [1/3.0, 1/6.0, 0.678]
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x)
print s
>>> elements in the list are [0.33, 0.17, 0.68]
A: Here is a one liner. A little improvised answer using format with print() to iterate a list.
How about this (python 3.x):
sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))
Read the docs here on using format().
A: Since I just learned about this cool thing(indexing into lists from within a format string) I'm adding to this old question.
s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print (s.format (x=x))
Output:
1 BLAH 2 FOO 3 BAR
However, I still haven't figured out how to do slicing(inside of the format string '"{x[2:4]}".format...,) and would love to figure it out if anyone has an idea, however I suspect that you simply cannot do that.
A: You should take a look to the format method of python. You could then define your formatting string like this :
>>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'
A: print s % tuple(x)
instead of
print s % (x)
A: This was a fun question! Another way to handle this for variable length lists is to build a function that takes full advantage of the .format method and list unpacking. In the following example I don't use any fancy formatting, but that can easily be changed to suit your needs.
list_1 = [1,2,3,4,5,6]
list_2 = [1,2,3,4,5,6,7,8]
# Create a function that can apply formatting to lists of any length:
def ListToFormattedString(alist):
# Create a format spec for each item in the input `alist`.
# E.g., each item will be right-adjusted, field width=3.
format_list = ['{:>3}' for item in alist]
# Now join the format specs into a single string:
# E.g., '{:>3}, {:>3}, {:>3}' if the input list has 3 items.
s = ','.join(format_list)
# Now unpack the input list `alist` into the format string. Done!
return s.format(*alist)
# Example output:
>>>ListToFormattedString(list_1)
' 1, 2, 3, 4, 5, 6'
>>>ListToFormattedString(list_2)
' 1, 2, 3, 4, 5, 6, 7, 8'
A: x = ['1', '2', '3']
s = f"{x[0]} BLAH {x[1]} FOO {x[2]} BAR"
print(s)
The output is
1 BLAH 2 FOO 3 BAR
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "139"
}
|
Q: Using Maven, how do I run specific tests? I have thousands of unit tests in my project, and I'd like to choose one or a couple of them to run from the command line. What's the command to do that?
A: Please read this piece of the maven surefire plugin manual. Basically you can do the following:
mvn -Dtest=*PerformanceTest clean test
Which only runs all the test classes ending in PerformanceTest.
A: +1 to the above answers, and... make sure you're in the same directory of the module where the test you're trying to run lives.
I ran into this issue, because I normally work in multi-module projects and run mvn clean install from the root of the project... but for this use case, you need to cd into the module of the test you're trying to run.
A: You can run all the tests in a class, by passing the -Dtest=<class> flag to Maven:
mvn clean test -Dtest=xxxxTest
Since Surefire 2.8, you can also run an individual test, say a method testA within your unit tests, using the same flag:
mvn clean test -Dtest=xxxxTest#testA
More examples for running multiple tests, by name pattern or name lists, can be found in the Maven Surefire documentation > Running a Single Test.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "71"
}
|
Q: My custom javascript is conflict with sharepoint javascript (sharepoint 2010) I am using custom javascript file([mootools-1.2-core.js][1]) in custom application page in sharepoint(2010).I get type mismatch error in wpadder.js(Sharepoint Javascript file which resides in 14/layouts).Could anyone provide a solution for this issue ?
A: I would recommend a google search for type mismatch error wpadder.js - first link = http://labs.steveottenad.com/type-mismatch-on-wpadder-js/
A: I stumbled upon this question today because I had the same error. The link pointed by Brian Brinley (http://labs.steveottenad.com/type-mismatch-on-wpadder-js/) actually helped, because it mentions that:
Sharepoint (and possibly IE in general) has issues with any
plugins/scripts that try to extend the Array Prototype.
The code I was working on had extended Array.prototype to include an indexOf method.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, start) {
for (var i = (start || 0); i < this.length; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
The error in wpadder.js disappeared as soon as I removed the above bit from the code.
As a substitute for the indexOf method, I wrote this:
// this function returns the index of the first occurrence
// of the given item in a simple array
function indexOf(array, item, start) {
for (var i = (start || 0); i < array.length; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
}
and replaced all array.indexOf(item) in the code with indexOf(array, item).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do i test www to non-www forwarding? I'm using html5 boilerplate and I'm trying to test if my htaccess is working properly. When I type in www.domain.com into chrome or firefox it does not redirect. I'm thinking maybe this is just some browser gimmick though, similar to how Chrome hides the http:// even though its there.
I have checked using chrome dev tools and firebug, and under the request headers it shows whatever I enter in as the "Host"... both with www. and without it... so I dont really know if its working
# ----------------------------------------------------------------------
# Suppress or force the "www." at the beginning of URLs
# ----------------------------------------------------------------------
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
A: The rule is OK.
Please check the following:
*
*Did you enabled mod_rewrite in your .htaccess via RewriteEngine On?
*Is mod_rewrite module loaded in Apache at all? Try moving your instructions outside of <IfModule mod_rewrite.c> to see if it will generate any server errors (indication that mod_rewrite is not loaded).
*Check if .htaccess is allowed to be used.
As to www or non -- see these topics on Webmasters part of StackExchange:
*
*https://webmasters.stackexchange.com/questions/507/should-i-include-www-in-my-canonical-urls-what-are-the-pros-and-cons
*https://webmasters.stackexchange.com/questions/11925/to-www-or-not-to-www
*https://webmasters.stackexchange.com/questions/14457/what-does-www-do
*https://webmasters.stackexchange.com/questions/11560/seo-preference-for-www-or-http-protocol-redirection-do-www-websites-rank-bett
*https://webmasters.stackexchange.com/questions/8964/is-was-seo-the-only-reason-to-force-the-www-on-domain-names
*https://webmasters.stackexchange.com/questions/15290/does-it-matter-that-our-website-cant-be-found-without-the-www
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create a UIView from NIB I have created a custom class that subclasses UIView. I want to do my layout in IB, so have set outlets. The problem is how do I initialise my view so that I get it from the NIB? Any help would be greatly appreciated.
A: Something like this:
UIView *info = [[[NSBundle mainBundle] loadNibNamed:@"InfoWeather" owner:self options:nil] objectAtIndex:0];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Oracle group data I have table, MyTable, in Oracle 11GR2:
COL1 VARCHAR2
COL2 VARCHAR2
COL3 VARCHAR2
COL4 NUMBER
with data
COL1 COL2 COL3 COL4
A B C 1
A D E 2
F G H 3
F I J 4
K L M 8
How do I get results with SQL:
COL1 COL2 COL3 COL4
K L M 8
K Total 8
F I J 4
F G H 3
F Total 7
A D E 2
A B C 1
A Total 3
Grand Total 18
I tried with roolup function:
SELECT m.col1, m.col2, m.col3, sum(m.col4)
FROM MyTable m
group by rollup(m.col1, (m.col2, m.col3))
I don't know how to sort to get results sorted by col4 like example above.
Thanks
A: I don't use ROLLUP often, but the difficulty seems to be that once the ROLLUP is applied, there is no connection between the summary rows and the detail rows, so you can't easily sort them as groups within the overall result set, which is what I think you want to do.
I think this will get what you want, but it could be inefficient on large data sets; it essentially calculates the subtotal values twice, once with rollup, and once with an analytic function.
select *
from (select m.col1,
m.col2,
m.col3,
sum(m.col4) sum_c4
from mytable m
group by rollup(m.col1, (m.col2, m.col3))
)
order by case when col1 is null then 1
else 0
end asc, -- put grand total line at end of entire set
sum(sum_c4) over (partition by col1) desc, -- sort subgroups by descending subtotal
col1, -- tiebreaker for subgroups with same total
case when col2 is null then 1
else 0
end asc, -- put subtotal line at end of each group
sum_c4 desc -- put detail lines in descending order
A: There are three functions that provide information about the superaggregate rows that are returned. These functions are group_id grouping and grouping_id.
I think the one you want to use here is grouping. This function will tell you if it is summed on a given column. Calling the function for superaggregate rows will return 1 and other non-superaggregate rows will return 0. Details on the grouping function can be found in the Oracle documentation.
The query that you want is shown below:
select case when grouping_col1 = 1 then 'Grand Total'
else col1
end as col1,
case when grouping_col1 = 0 and grouping_col2 = 1 then 'Total'
else col2
end as col2,
col3,
sum_col4,
grouping_col1,
grouping_col2
from (select col1,
col2,
col3,
sum(col4) as sum_col4,
grouping(col1) as grouping_col1,
grouping(col2) as grouping_col2
from mytable
group by rollup(col1, (col2, col3))
)
order by grouping_col1,
sum(sum_col4) over (partition by grouping_col1, grouping_col2, col1) desc,
grouping_col2,
sum_col4 desc
A: Append
ORDER BY sum(m.col4) DESC
to your query.
A: you can run following query -
SELECT COL1 ,COL2, COL3, COL4 FROM
(
SELECT COL1 ,COL2, COL3, COL4 FROM MyTable
UNION ALL
SELECT COL1,'Total', NULL, SUM(COL4) FROM MyTable
GROUP BY COL1
ORDER BY 1,3 -- line to change for case discussed below
)
UNION ALL
SELECT 'GRAND TOTAL',NULL,NULL,SUM(COL4) FROM MyTable
I have tested above query on my machine and it is working fine.
By any chance if you will get 'Total' row before main table's row then edit last line as -
ORDER BY 1,3 DESC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Deleting local commit when is calling git pull I've made a commit with an error (program isn't compiled) and after made: git push (I).
My colleague done: git pull (She)
and got uncompiled state of repository. After that added some commits (about project documentation - for the compiling wasn't critical) and done again: git push (She)
After that we've got following state of repository:
*
*Some her commit
*Some her commit
*My commit with error
*My another commit
I wanted exactly to delete commit 3. And for that I've made
git-rebase --onto <sha of commit 4> <sha commit 3> master
git push --force
Now we have correct state of repository (without commit 3), but with all another changes.
But, if she do
git pull
git push
she will make merge with her local commit #3 and then pull it to repository. How can I make that someone (not only she) after git pull will correct state of repository - with all changes, but without commit #3?
Notes:
Probably she added (in another case - feature) local commits above last. And her local repository newer than server's repository.
A: You have discovered the problem with changing public history: everyone who has seen the change must agree to change it the same way. In this simple case, they can likely get the new proper version by also doing the same rebase command that you did:
git-rebase --onto <sha of commit 4> <sha commit 3> master
This will update their local master to agree with the remote master branch again and they can continue as normal.
There is no way to automatically cause this to happen. The easiest way for people who were simply tracking master, or had pushed all changes they made when you did this rebase, may be to execute git reset --hard origin/master but this will erase any local commits made on the current branch that weren't in master when you did your rebase.
An alternate way to achieve the same thing is with git revert. This will simply add a new commit which is the inverse of a different commitish. This doesn't edit history, it simply adds to it in such a way as to undo it. This causes the problem commit to still show up in git log and related commands, but doesn't cause issues for everyone else.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery animate slider onClick event I am creating a slider using jquery animate function. The first image is moving to left and is working fine.But the next image is not quickly following the first image. It displays a blank screen for a while. This is what I have tried so far:
$('.next').live('click',function() {
$('.ac_bgimage').animate({
left:"-80em"
}, 1500 , function(){
test();
});
});
function test() {
$('.ac_bgimage').attr('src','images/2.jpg');
$('.ac_bgimage').css('left','0em');
}
I am stuck at this point. Please help. Thanks in advance.
A: Try this easy slider jquery plugin. This will solve your purpose.
A: In your jsfiddle.net/cSVWv, you have two errors, because you have you div with 'next' class hidden, as thats is not possible to trigger the 'click' event. The other is, in image with 'ac_bgimage' class you need to the position relative to works.
See my example here: http://jsfiddle.net/expertCode/tvaMK/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: observer design pattern question i am creating a oop system in php and would like to implement more observer patterns into it as i have heavy coupling between my classes that i wish to reduce.
my question is this.
in relation to best practice in design for this pattern is it ok for one class to add an observer to another class, that class is working with.
or should i keep the observer adding to the top most level of the chain?
example: (assume other methods called, but not included in the class, exist but are not important for this example.)
class orderItem extends observable {
public function pick($qty, $user){
$this->setUser($user);
$position = new position($this->getPositionID());
$position->addObserver(new ProductObserver()); // is this the best option ? ?
$position->setQty($position->getQty() - $qty);
$position->save();
$this->notify(self::EVENT_PICK); // notify observers
}
}
class orderProductObserver implements observer {
public function update($orderitem){
$position = new position($orderitem->getPositionID());
$product = new product($position->getProductID());
if($product->getQty() < $product->getMinimum()) {
$alert = new minProductAlert($product);
}
}
}
class ProductObserver implements observer {
public function update($position){
$product = new product($position->getProductID());
if($product->getQty() < $product->getMinimum()) {
$alert = new minProductAlert($product);
}
}
}
$order = new orderItem(123);
$order->addObserver(new orderProductObserver()); // or is this the best option ??
$order->pick(2, 'bill');
Or alternatively if both methods are wrong i am very interested in your input.
would this example be the most ideal by removing dependency between orderitem and position ?
class OrderItem extends Observable {
public function pick($qty, $user){
$this->setUser($user);
$this->setPickedQty($qty);
$this->save();
$this->notify(self::EVENT_PICK); // notify observers
}
}
class OrderItemPickObserver implements Observer {
public function update($orderitem){
$position = new Position($orderitem->getPositionID());
$position->addObserver(new ProductPositionObserver());
$position->setQty($position->getQty() - $orderItem->getPickedQty());
$position->save();
}
}
class ProductPositionObserver implements Observer {
public function update($position){
$product = new product($position->getProductID());
if($product->getQty() < $product->getMinimum()) {
$alert = new minProductAlert($product);
}
}
}
$pickQty = 2;
$orderitem = new OrderItem(123);
$position = new Position($orderitem->getPositionID());
if($position->getQty() >= $pickQty)
{
$orderitem->addObserver(new OrderItemPickObserver()); // or is this the best option ??
$orderitem->pick($pickQty, 'bill');
}
A: I would use your second method .... its a lot clearer to read and understand than the first (dependency injection)- good examples (although an old document) are given here -> http://www.ibm.com/developerworks/library/os-php-designptrns/
A: The second example looks good, but I'm not sure if creating new Position object inside update method of OrderItemPickObserver class. Instead, what I would suggest is to keep a Position object as a property of OrderItem class so that you can set it from outside.
class OrderItem extends Observable {
private $_position;
public function setPosition($position){
$this->_position = $position;
}
public function getPosition(){
return $this->_position;
}
}
Then update OrderItemPickObserver class:
class OrderItemPickObserver implements Observer {
public function update($orderitem){
$position = $orderitem->getPosition());
$position->setQty($position->getQty() - $orderItem->getPickedQty());
$position->save();
}
}
And your calling code:
$orderitem = new OrderItem(123);
$position = new Position();
$position->addObserver(new ProductPositionObserver());
$orderitem->setPosition($position);
This way you can decouple OrderItemPickObserver and Position classes.
EDITED:
If your business logic doesn't allow you to have a Position object in OrderItem class, you can move the same to OrderItemPickObserver since this is the class which actually uses the Position object.
class OrderItemPickObserver implements Observer {
private $_position;
function __construct($position){
$this->_position = $position;
}
public function update($orderitem){
$position = $this->_position;
$position->setId($orderitem->getPositionID());
$position->setQty($position->getQty() - $orderItem->getPickedQty());
$position->save();
}
}
And your calling code:
$orderitem = new OrderItem(123);
$position = new Position();
$position->addObserver(new ProductPositionObserver());
...
...
$orderitem->addObserver(new OrderItemPickObserver($position));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the best way of coding DWR based classes? What is the best way to code DWR (Direct Web Remoting - Ajax for Java) based logic in a web application?
I have listed 3 types of disciplines.
*
*Use of single class to code DWR based implementations
eg: For all scenarios use DWRUtil.java (contains all logic related to several actions in many pages, for example Order placing related Ajax calls, customer registration related Ajax calls)
*Use separate DWR based class for each scenario(there can be several JSPs sharing same java script generated by DWR)
eg: For customer registration - CustomerRegisterUtil.java, for order processing utility methods - OrderProcessUtil.java
*Use separate DWR based class for each page
eg: For customer registration page- CustomerRegisterUtil.java, for order processing page - OrderProcessUtil.java
A: The answer depends on your project. In my opinion, you should split up your DWR classes in such a way that it's obvious to developers which class contains which functionality.
So if you have very few DWR calls, put them in the one DWR class. Other developers will then know exactly where to go for all DWR code.
But for most projects you'll need quite a number of calls, so putting them in one file will make them hard to find. Then it's up to you to split them up in an appropriate way. You'll probably find that creating one DWR class for each scenario is the best, rather than one per page. That's because a particular DWR method might be useful on a number of pages, so all the pages in that scenario can use the one method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android toast class parameter I had doubt in android Toast class. We have a static method in android called makeText
and have to use it as
Toast.makeText(Context context , CharSequence text, int duration);
and we can use getBaseContext() as one of the options among getBaseContext() , getParent() and getApplicationContext().
Please anyone can explain me the purpose and usage of getBaseContext()
Thank you........
A: To be able to show the message you need to have some reference to the context. Toast is static class you can call Toast from any activity, broadcast receiver or any class that have context
In general there are two type of classes. Ones that extend ContextWrapper class (Activity, Service, Application) and those that do not extend it (like View).
If class extends ContextWrapper then you can use this as Context. Such classes normally do not have getContext() method.
Those classes that do not extend ContextWrapper but still save and use Context normally expose getContext() function. And you cannot use this as Context in such cases.
And these two cases are mutually exclusive. At least I don't recall classes that extend ContextWrapper and have getContext at the same time.
this for more details What's the difference between the various methods to get a Context?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Image/Text Pulsating Glow Effect (Graphics) How would I make an Image have a pulsating effect to it? I already know how to draw an Image to the screen, so I just need to know how I can add a pulsating glow effect. Would I need to use tons of threads?
Also, how would I make some text have the same pulsating glow effect?
I want to be able to draw this to the screen so this needs to be a graphics object (g.drawString(glowingText, x, y);).
Thanks in advance!
A: AlphaTest shows one approach using Alpha Composite; FlashTest shows another using getHSBColor(). You can infer which is more popular.
Addendum: To get a pulsating glow behind some text or image, you'll want to vary the background alpha instead of the foreground. There's a related example here. I often use this utility to preview the effects of different composite modes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jquery DatePicker Some Display Changes I am using the jquery datepicker. I have to change some display showing the calendar.
I don't have enough reputation to post an image so i have posted in jquery forum. Kindly look over it and guide me and how to implement this.
A: IF you simply want to show the current month plus any days in incomplete weeks - days from other months, you can do this as such:
$(function() {
$( "#datepicker" ).datepicker({
showOtherMonths: true,
selectOtherMonths: true
});
});
If you wish to show the next months incomplete week, PLUS one more week, you will need to do this differently.
The selectOtherMonths: true portion above sets if the OTHER months dates are selectable (true) or not (false), the current months days are more bold visually but ALL are selectable if this is true.
EDIT: The question remains then, if you want the EXTRA week of dates listed from the NEXT month? IF that last is true, I think perhaps we are looking at the need for custom code or another plug-in to use.
A: Use following option to show other months
$( "#datepicker" ).datepicker({
showOtherMonths: true,
selectOtherMonths: true
});
To change the styling override the following css class
.ui-priority-secondary
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Getting value from JS to PHP
Possible Duplicate:
How to pass value from Javascript to PHP and get return of PHP back to Javascript
how to get value from
JS:
var vars="";
and add it into PHP
$vars="";
Vars contains only digits.
A: You'll have to send that variable with ajax or another kind of request to your server.
For example:
(JS):
var vars="123";
$.get('get_that_Variable.php?vars='+vars);
(PHP):
<?php
$vars = $_GET['vars'];
A: Its impossible for us to pass JS variable values to PHP variables cause PHP is a server side language and JavaScript is client side. Please understand that when your browser is running the JS codes PHP has already completed executing.
The only way that you will be able to do this is using AJAX. But thats a different story altogether.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Eclipse+Vaadin: Could not start XULRunner (version 1.9 or higher required) When I am trying to open java file with Vaadin Editor, I am getting the following error:
Could not start XULRunner (version 1.9 or higher required)
OS: Windows 7 Prof x64
Eclipse: Indigo
XULRunner: 6.0, it is just unpacked into some folder, not installed; PATH added.
So, how to either install XULRunner for Eclipse Vaadin plugin, or how to tell Vaadin plugin where XULRunner is located?
P.S. I have tried to install xulrunner 1.9 and it din't help. So the problem persists.
A: This plugin seems to assume a system-wide installation of XULRunner. As mentioned in XULRunner Error: couldn't parse application.ini., this is no longer supported starting with XULRunner 5.0 but you could pass in a XULRunner path explicitly. This is only one part of the problem however, chances are that newer XULRunner versions simply won't work. You might actually have to download the ancient XULRunner 1.9.0 instead of XULRunner 6.0.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can one change the name of a tag? I have made a tag in mercurial:
hg tag release_123
Later on I found out that the name was wrong, it should be release_124. Is it possible to simply rename the tag or do I have to create a new one?
A: You should be able to edit regular tags in the .hgtags file (and commit it)
A "regular" tag (with no special specifier) is revision controlled, does propagate with other changes, and lives in the .hgtags file in a repository.
This old thread mentions you need to do this in all HEADS of a repo though.
A: I would do it by removing the tag and then adding a new tag with the new name
The Mercurial tag wiki explains how to remove a tag:
How do I remove a tag?
Either by
*
*hg tag --remove tagname
(this being the nearest equivalent to cvs tag -d)
*
*adding tagname 0000000000000000000000000000000000000000 to the end
of .hgtags
*removing all references to tagname in .hgtags (but this might
confuse the multiple-head tag collision resolution algorithm)
A: Like what @matt-ellen has said, but in reverse. Because I like to be sure the revision is tagged properly before I delete the old tag.
Here I create an example of a repo with 4 revisions.
*
*View the log
*View the tags (none, and tip)
*Create a tag at revision #2 (using the hash)
*View tags (now there is one, and tip)
*Create new tag name
*View tags (now there are two, and tip)
*Remove bad tag name
*View tags (now there is one, and tip)
Example:
$ hg log
changeset: 3:271cb2836c23
user: user <you@example.com>
date: Sat Mar 01 13:49:55 2014 -0600
summary: Very important things.
changeset: 2:3c953ee62faf
user: user <you@example.com>
date: Wed Feb 26 00:17:55 2014 -0600
summary: Did some changes.
changeset: 1:54e2275eed1e
user: user <you@example.com>
date: Tue Feb 25 01:34:31 2014 -0600
summary: So, lots of things here.
changeset: 0:3f3e1aee4e14
user: user <you@example.com>
date: Sat Feb 22 00:42:29 2014 -0600
summary: Inital project checkin.
$ hg tags
tip 3:271cb2836c23
$ hg tag -r 3c953ee62faf release_123
$ hg tags
tip 3:271cb2836c23
release_123 2:3c953ee62faf
$ hg tag -r 3c953ee62faf release_124
$ hg tags
tip 3:271cb2836c23
release_123 2:3c953ee62faf
release_124 2:3c953ee62faf
$ hg tag --remove release_123
$ hg tags
tip 3:271cb2836c23
release_124 2:3c953ee62faf
A: I've been looking for a solution to same issue: I found this command which creates another tag with copied from the previous one with a new name. But it does not remove the old one. It has to be deleted manually.
Rename a tag :
hg tag -f -r
To delete the old tag:
hg tag --remove
A: If you are using TortoiseHg, its pretty simple:
case#1 if it's a local tag: right click a tagged change-set|tag...|Select tag |Options |Replace existing tag | Done < local tag will disappear>
case#2 if its global tag: right click a tagged change-set|tag...| Select tag| Options | Replace existing tag | Remove
Now select change-set and create new tag (its like a renamed tag). Not in one click though :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: how to add dynamic button to push notification alert box and redirect to the desired UIView in iphone? I have a task to create application with push notification when the notification send at that time it redirect user to the different user page without login in the application.
I have to work with the local notification in which i have to create custom alertbox. in which i have to customize the button title and redirect it to the different pages without login view.
Is it possible to set the user custom uialertbox with custom name button. and it redirect to the uiview without loading first view for login.
Please help me. And provide some sample for it.if possible.
A: UILocalNotification are handled by the system and are not UIAlertViews.
You can set the button title for pushnotiftcaion or UILocalNotification by setting the alertAction property.
The notification has a userInfo property which you can fill with a NSDictionary, then in your appdelegate you can check the userInfo when you app launches and navigate the user to the view.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Your normal code here.
[self.window makeKeyAndVisible];
// Check for a UILocalNotification
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification ) {
// handle the notification
}
return YES;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Missing dlls on 64 bit Win I have a .net application that uses some vc++ compiled Win32 dlls. It works great on a 32 bit Win, but on 64 bit there is a problem: "Unable to load DLL 'xyz': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"
Using dependency walker I found it misses the following dlls: MSVCP100.DLL, MSVCR100.DLL, GDIPLUS.DLL, GPSVC.DLL, IESHIMS.DLL
How can I install them to my 64 bit Win? Where should I put them? Should I register them? Or...?
Note, my project is compiled for x86 platform and it is ran from Program Files (x86) folder as a 32 bit app. My dlls are comiled as Win32 via Visual C++ in Visual Studio 2010.
Note, that it is mission impossible to get 64 version of my dlls because of some other reasons, so it would not be a solution.
Thanks!
A: As ALex Farber noted, you have to install some runtime dlls on the target machine:
*
*The .NET runtime with the right version, here the 4.0,
*Visual Studio redistributable package (I'm not sure of this one, it should be for C++ applications only but may be worth a try if .NET is not enough)
A: The whole process should be 32 or 64 bit. If you cannot compile all dependency libraries in 64 bit, you need to run .NET project in 32 bit. To do this, create x86 configuration (default is Any CPU) and build .NET project in this configuration.
You also need to install VC++ 2010 redistributable package on destination computer, with correct bitness, in your case - x86. This package can be downloaded from Microsoft WEB site.
If your program has installation package, VC++ redistributable should be added to it as single file or as merge modules.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Problems using URL Rewrite in IIS7 for friendly URLs I'm trying to make some rewrite rules in my IIS7 server using URL Rewrite.
For example, I have the url mydomain.com/data.php?id=1 and I want to convert it to mydomain.com/archive/1
Currently I have:
<rule name="Ugly to friendly" stopProcessing="true">
<match url="^data\.php$" />
<conditions>
<add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
<add input="{QUERY_STRING}" pattern="^([^=&]+)=([^=&]+)$" />
</conditions>
<action type="Redirect" url="archive/{C:2}" appendQueryString="false" />
</rule>
<rule name="Friendly to ugly" stopProcessing="true">
<match url="archive/(.+)" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="data.php?id={R:1}" />
</rule>
but it doesn't work (read as "page shows fine without that rule, but when rule is added no css/imgs are shown).
Weird, as firebug tells me that everything is ok (200 OK) (maybe it gets confused too?)
Regards
A: Sorry, the code is just fine. My page (data.php) is wrong. Instead of having all imgs/css using relative paths from the php file, I should have wrote those using relative paths from the root.
I mean, instead of "img src="../../test.jpg" I should have wrote "img src="/folder1/fol".
Note the "/" at the beggining of the path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Binding Listbox/CheckedListBox's SelectedValue using ObjectDataSource when Multiselect is enabled I do not have code at the moment for explaining my question in the best way. So there might be some syntax mistakes, might leave some datasource related binding.
Scenario.
I have a class as Customer that contains some of the properties
eg.
class Customer
{
int CustomerId{get;set;} //primary key
int age{get;set;}
string name{get;set;}
Collection<BooksPurchased> booksCollection{get;set;}
}
I used a function say GetCustomer() which returns Collection
public Collection<Customer> GetCustomer();
This function is bound with GridView using ObjectDataSource control.
i.e.
<asp:GridView DataKey="CustomerId">
<columns>
<asp:TemplateField>
<ItemTemplate><%# Eval('age') %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate><%# Eval('name') %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Listbox DataSourceId="availableBooks" SelectedValue='<%# Bind("booksCollection") %>' />
<asp:ObjectDataSource SelectMethod="GetBooksCollection" TypeName="Books">
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This Grid is again binded to a ObjectDataSource control which tables GetCustomer() function to bind the grid.
Problem
is I want to display/Update and all the selected items binded in Listbox control.
i.e. If Listbox has 10 items and booksCollection contains 3 items.
Then these 3 items should be displayed as selected. And when user chages selection these should get reflected in the collection itself.
A: Personally, I stay away from performing this sort of operation in the ASP markup. Because of that, I'm not sure if you can bind your full list of books and select the books for each customer in the markup alone -- certainly, the SelectedValue property is not the way to do this.
Here's how I would do something like this:
Markup:
<asp:GridView ID="customers" DataKey="CustomerId">
<Columns>
<asp:TemplateField>
<ItemTemplate><%# Eval('age') %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate><%# Eval('name') %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Listbox ID="books" DataSourceId="availableBooks" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected override OnInit(EventArgs e)
{
base.OnInit(e);
customers.RowDataBound += new GridViewRowEventHandler(customers_RowDataBound);
}
void customers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Customer currentCustomer = (Customer) e.Row.DataItem;
Listbox books = (ListBox) e.Row.FindControl("books");
books.DataSource = GetBooksCollection();
books.DataBind();
foreach (BooksPurchased currentBook in currentCustomer.booksCollection)
{
if (books.Contains(currentBook))
{
books.Selected = true;
}
}
}
}
This code isn't pretty, and needs some details filled in (such as the structure of the BooksPurchased object), but it should get you on the right path to displaying each customer's selected books.
It's a bit more complicated to manage adding and removing books when the user selects different items in the ListBox, and each option depends on implementation details (for instance: how are you storing the customer, if at all? Are you instantly updating the database, or caching changes until the user clicks a submit button?). If you can provide some more detail about this part, I might be able to help on it, too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to send a Int[] to an Oracle Stored Procedure using OleDb Is it possible to send an int[] from a c# application using OleDb to an Oracle Stored Procedure?
I was wondering if there is a specific way of setting up both c# OleDbType and the type in the Oracle stored procedure. At the moment I am using this kind of setup.
C#
int[] intArray = new int[] { 1, 2};
cmd.Parameters.Add(new OleDbParameter("var_name", intArray));
cmd.Parameters[i].OleDbType = OleDbType.Variant
cmd.Parameters[i].Size = 20;
Oracle
TYPE intArray IS TABLE OF NUMBER;
PROCEDURE proc(var_name IN intArray);
Thankyou in advance - Ankou
A: Managed to fix my own problem.
Seeing as no one has came up with a solution I decided to fix this problem by sending in a string of CSV, then created a split method in order to add each value to TABLE OF VARCHAR2(30) INDEX BY BINARY_INTEGER; which could then be used elsewhere.
So have a solution and a String Split function too :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Editable Console Output Here is a portion of some code I am trying to write:
//Choice Based Menu
#include <iostream.h>
#include <conio.h>
int main()
{
char choice;
cout<<"Menu"<<endl<<endl;
cout<<"A. Option A"<<endl;
cout<<"B. Option B"<<endl;
cout<<"C. Option C"<<endl;
cout<<"Q. Quit"<<endl;
cout<<endl<<"Choice:\t";
do
{
choice=getch();
cout<<choice<<"\r";
switch(choice)
{
case 'A':
{
cout<<endl<<"Option A!";
break;
}
case 'B':
{
cout<<endl<<"Option B!";
break;
}
case 'C':
{
cout<<endl<<"Option C!";
break;
}
case 'Q':
{
return 0;
}
default:
{
cout<<endl<<"Invalid Choice! Please try again.";
break;
}
}
}while(1);
}
Since the loop continues indefinitely, it waits for another input option after executing the code of the previously chosen option.
Menu
A. Option A
B. Option B
C. Option C
Q. Quit
Choice: A
Option A!
I want the line "Choice: A" to update with the most recently entered option every single time. And I want the output of the previously selected option (Option A!) to be replaced with the output from a newly chosen option.
I tried using '\r' as you may have noticed. That does not work because it gives me a carriage return i.e. it moves back to the beginning of the line. I want it to move back only by one character, and not to the beginning of the line.
A: This this:
#include <iostream.h>
#include <conio.h>
int main()
{
char choice;
cout<<"Menu"<<endl<<endl;
cout<<"A. Option A"<<endl;
cout<<"B. Option B"<<endl;
cout<<"C. Option C"<<endl;
cout<<"Q. Quit"<<endl;
do
{
choice=getch();
cout << "\r" << "Choice:\t"; // Moved into the loop
switch(choice)
{
case 'A':
{
cout << "Option A!"; // No more endl
break;
}
case 'B':
{
cout << "Option B!";
break;
}
case 'C':
{
cout << "Option C!";
break;
}
case 'Q':
{
return 0;
}
default:
{
cout << "Invalid Choice! Please try again.";
break;
}
}
}while(1);
cout << endl; // New sole endl
}
This is not exactly what you want, but it's the closest one can get with minimal rework.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Stored procedure reading xml, any way better to do it? SQL SERVER 2008 I do something like this:
CREATE PROCEDURE [dbo].[InsertStudents]
(
@students nvarchar(max)
)
AS
DECLARE @studentstable TABLE
(
RowIndex int,
FirstName nvarchar(50),
LastName nvarchar(50),
Number nvarchar(20),
IdSchool int
)
DECLARE @xmldata xml
SET @xmldata = @students
INSERT INTO @studentstable
SELECT S.Stud.query('./RowIndex').value('.','int') RowIndex,
S.Stud.query('./FirstName').value('.','nvarchar(50)') FirstName,
S.Stud.query('./LastName').value('.','nvarchar(50)') LastName,
S.Stud.query('./Number').value('.','nvarchar(50)') Number,
S.Stud.query('./IdSchool').value('.','int') IdSchool,
FROM @xmldata.nodes('/Students/Student') AS S(Stud)
DECLARE @totalrows int
DECLARE @currentrow int
DECLARE @totalinserts int
DECLARE @currentfirstname nvarchar(50)
DECLARE @currentlastname nvarchar(50)
DECLARE @currentnumber nvarchar(20)
DECLARE @currentidschool int
DECLARE @insertresult int
SET @totalinserts = 0
SET @totalrows=(SELECT COUNT(*) FROM @studentstable)
SET @currentrow=0
WHILE(@currentrow<@totalrows) BEGIN
SELECT @currentfirstname = FirstName, @currentlastname = LastName, @currentnumber = Number, @currentidschool = IdSchool
FROM @studentstable
WHERE RowIndex=@currentrow
EXEC @insertresult = InsertStudent @currentfirstname, @currentlastname, @currentnumber, @currentidschool
IF @insertresult=0 BEGIN
SET @totalinserts=@totalinserts+1
END
SET @currentrow = @currentrow + 1
END
SELECT @totalinserts
InsertStudent returns 0 if insert worked or 1 if there is already a student with that number.
Isn't there any way to do it without messing with that variable table?
A: Something like this using merge.
merge Student
using (select S.Stud.query('./RowIndex').value('.','int') RowIndex,
S.Stud.query('./FirstName').value('.','nvarchar(50)') FirstName,
S.Stud.query('./LastName').value('.','nvarchar(50)') LastName,
S.Stud.query('./Number').value('.','nvarchar(50)') Number,
S.Stud.query('./IdSchool').value('.','int') IdSchool
from @xmldata.nodes('/Students/Student') as S(Stud)) as SXML
on Student.Number = SXML.Number
when not matched then
insert (FirstName, LastName, Number, IdSchool)
values (SXML.FirstName, SXML.LastName, SXML.Number, SXML.IdSchool);
select @@rowcount
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Get the document id of all documents in couchdb database I have a simple question, How should I retrieve the document ids of all documents from a given database in couchdb.
I have written this code which retrieves all the documents-
docs=CouchRest.get("http://localhost:5984/competency1/_all_docs?include_docs=true")
puts docs.to_json
The above code displays the entire details of the database.I want to be able to list only the document id's.
I really appreciate your help.
Thanks.
A: From HTTP Document API about retrieving all documents:
To get a listing of all documents in a database, use the special
_all_docs URI. ... Will return a listing of all documents and their
revision IDs, ordered by DocID (case sensitive)
In other words, get /competency1/_all_docs without the ?include_docs=true part. This is the best solution for several reasons.
*
*Like a map/reduce view, it supports limit, startkey,endkey` options.
*But unlike a map/reduce view, it does not use any additional disk space or CPU.
*Other people (or you in the future) will immediately recognize this query's purpose.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How can I maintain focus on text box being validated without locking other text boxes? Here is an example of a validation method I am using:
if(currentFieldCategory=='e')
{
var atpos=currentFieldValue.indexOf("@");
var dotpos=currentFieldValue.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=currentFieldValue.length)
{
echo('Please enter a valid email address');
currentField.focus();
return 'Please enter a valid email address';
}
}
If the user does not enter a valid email then an error message is triggered. Using currentField.focus(); the focus stays on the current text box being validated, but all other text boxes are locked until the correct data is entered.
I am wondering if there is a way of maintaining the focus on the current text box without locking the other text boxes (i.e. the user can still click in other text boxes). Because my validation works both on user entry and form submission, it is OK for users to click in other text boxes even if the current text box doesn't contain the correct data.
Could someone help with this?
Thanks,
Nick
A: Your requirement seems contradictory: you can't "maintain focus" in one input and simultaneously allow users to click into other inputs.
A more common validation technique is onchange or onblur if a particular field fails validation set its background to a different colour, and/or display the error message beside it or something. Then the user knows which fields they need to come back to but they're still free to enter other fields first.
Having said that, if you're really keen on the focus idea, maybe you can set focus only the first time the user tries to leave the field. If they try to leave the field again allow it.
// global (or at least a higher scope variable) to keep track of which
// fields have failed; I assume your fields all have IDs set
var invalidFields = {};
// within your validation function
if(currentFieldCategory=='e')
{
var atpos=currentFieldValue.indexOf("@");
var dotpos=currentFieldValue.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=currentFieldValue.length)
{
echo('Please enter a valid email address');
// NEW IF TEST
// only set focus if this field didn't already fail validation
if (!invalidFields[currentField.id]) {
invalidFields[currentField.id] = true;
currentField.focus();
}
return 'Please enter a valid email address';
}
invalidFields[currentField.id] = false;
}
Note: the expression in the new if test, !invalidFields[currentField.id], will be true if invalidFields doesn't have a key defined (yet) for the currentField's id, or if it does have a key defined with a corresponding value of false. I.e., if it has never previously been validated, or if the last time it was validated it passed.
(By the way, you should look into validating format with regular expressions rather than manually comparing the position of the first "@" with the last ".".)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What broadcast / multicast method should we use? We are creating a mobile App that will benefit from knowing the ID of another entity on the same network (presuming the two mobile phones are on the same WiFi network).
We would like the “master” App to send out an ID that the “slave” App’s can pick up and store. Regardless of when the “slave” logs on to the network it should identify the Master (get the ID of the Master) and use it until it gets a new one (from another network and a new master).
We require that the implementation is feasible under iOS and Android (preferably also under J2ME) and that the method most likely is available in normal network configurations (including public WiFi set-ups as long as the clients both have proper network access).
What broadcast / multicast method should we use?
A: Usability on public WiFi connections pretty much precludes IP-layer multicast.
If you are only interested in Apps within the same subnet, you might be able to do a broadcast. I think base-stations tend to have all connected machines on the same sub-net, whereas 3G networks tend to block all broadcasts between dongles.
If that fails, then an alternative approach is to have a hierarchy of masters, much like MSN. Basic idea is that a higher-level masters act as directories for local masters. Of course you have to make allowances for things like IP addresses changing, but as a general rule the longer-running an App, the more likely it will have built up a list of who else is nearby. Masters could also notice that some of its slaves have similar IP addresses (hazard: NAT), and get them to make speculative contact..
All this requires fairly generic TCP/UDP functionality, which even J2SE should have.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Running Android application on device via ethernet I have a problem concerning my Android device. I use a ethernet cable to connect my Android tablet to my PC. I don't see any new devices detected by my PC. Is there some configuration which needs doing? Additionally, how can I run my app on device itself using Eclipse.
A: Make sure you have debugging turned on in the settings of the phone. Make sure debugging is set to true in the project manifest and make sure you have the correct drivers for the device.
A: if you are win user you need to install driver if you are linux user than
cat /etc/udev/rules.d/51-android.rules
and add the the ids
SUBSYSTEM=="usb", SYSFS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", SYSFS{idVendor}=="0fce", MODE="0666"
SUBSYSTEM=="usb", SYSFS{idVendor}=="04e8", MODE="0666"
complete list here
A: 1.Check whether the cable is working fine by using it to connect other devices.
2.Install the correct drivers for the device.
- Cancel windows update install if you have already downloaded a set of drivers needed.
3.Once the phone gets detected from the PC Wait for 5 min (till the time eclipse recognizes it) and then run it selecting the device as a target.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: saving images in documents folder with high resolution in iphone I want to save image which is draw on iphone screen in the documents folder with high resolution. Here I am able to save images in documents folder but the resolution is very low .
Can anyone tell me how to achieve this task.
Here is my Code
UIImage *image = [[UIImage alloc]init];
double resolution = 50;
//CGSize pageSize = CGSizeMake(612, 792);
// CGRect boundsRect = CGRectMake(50, 50, 512, 692);
CGRect boundsRect = CGRectMake(0, 0, 612, 792);
double imageWidth = image.size.width * image.scale * 72 / resolution;
double imageHeight = image.size.height * image.scale * 72 / resolution;
double sx = imageWidth / boundsRect.size.width;
double sy = imageHeight / boundsRect.size.height;
// At least one image edge is larger than maxBoundsRect
if ((sx > 1) || (sy > 1)) {
double maxScale = sx > sy ? sx : sy;
imageWidth = imageWidth / maxScale;
imageHeight = imageHeight / maxScale;
}
// Put the image in the top left corner of the bounding rectangle
CGRect bounds = CGRectMake(boundsRect.origin.x, boundsRect.origin.y + boundsRect.size.height - imageHeight, imageWidth, imageHeight);
CGSize size = bounds.size;
// UIGraphicsBeginImageContextWithOptions(size,NO,10.0f);
UIGraphicsBeginImageContext(size);
{
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
}
A: Try this:
- (UIImage *)screenshotImage {
UIView* screen = self.view;
CGSize imageSize = screen.bounds.size;
UIGraphicsBeginImageContext(imageSize);
CGContextRef imageContext = UIGraphicsGetCurrentContext();
[screen.layer renderInContext: imageContext];
UIImage* screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return screenshotImage;
}
After receive image and save it:
UIImage *screenshotImage = [self screenshotImage];
UIImageWriteToSavedPhotosAlbum(screenshotImage,nil,nil,nil);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Type error in application I'm trying to get this piece of haskell code to work, however I keep getting this error message:
> ERROR file:.\4.hs:9 - Type error in application
> Expression : fact n div (fact m * fact (n - m))
> Term : fact
> Type : Int -> Int
> Does not match : a -> b -> c -> d
Here's the code:
fact :: Int -> Int
fact q
| q == 1 = 1
| otherwise = q * fact(q-1)
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = ((fact n) div ((fact m) * (fact (n - m))))
Any idea how to fix it?
A: The problem is div in the last line.
When you want to make a function infix, you have to write it between `. So, simply change the last line to:
| otherwise = ((fact n) `div` ((fact m) * (fact (n - m))))
A: You are using div as infix, but it is not an operator so you have to write it like this:
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = fact n `div` (fact m * fact (n - m))
or like this:
comb :: Int -> Int -> Int
comb n m
| n < m = error "undefined as n < m"
| otherwise = div (fact n) (fact m * fact (n - m))
A: You have
| otherwise = ((fact n) div ((fact m) * (fact (n - m))))
but it should be
| otherwise = ((fact n) `div` ((fact m) * (fact (n - m))))
(at least)
Basically, you are using an infix operator, you'll have to mark it using back-quotes.
However, in this case, to reduce the number of parantheses, I'll rewrite it as
| otherwise = div (fact n) $ (fact m) * (fact (n - m))
Edit: s/inline/infix
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What's the advantage and use of prepared statements in PHP
Possible Duplicate:
PHP PDO prepared statements
prepared statements - are they necessary*
Recently, heard about php prepared statements. Nearly all hi-rep php developers use php prepared statements. Can anyone explain me what's the main advantage and use of php prepared statements?
A: Prepared statements allow you to make multiple similar queries more efficiently. You can prepare (for example) an insert statement, then loop over it with multiple bits of data and get a performance boost as the database has less work to do as it doesn't have to set it up each time.
As a side effect, people using prepared statements tend to use bound parameters too, and these provide protection from SQL injection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to count the number of rows when using SQL joins and group by I have the following query:
SELECT a.HotelID,a.Hotelname,GROUP_CONCAT(DISTINCT b.OperatorName) AS Operators
FROM hotels AS a
INNER JOIN operators AS b
ON a.HotelID = b.HotelID
GROUP BY a.HotelID
ORDER BY a.HotelID
LIMIT 100
I need this query for a simple search function. The result Table should contain Paging. So what I did was I runned this query (without LIMIT) to get the number of rows (which I need to calculate the pages and so on) and then I rerun that query with the LIMIT.
In fact the query itself takes 4-5sec (against 300k table, with indexes on all the fields) which means it currently takes 10sec to load because it runs two times.
I am wondering if there is a SQL Statement I can simply use to get the number of rows and which might be faster. I thought I can use COUNT(a.HotelID) but this not works.
A: update
select count(*) from (
SELECT distinct b.HotelID
FROM hotels AS a
INNER JOIN operators AS b
ON a.HotelID = b.HotelID
)
can this be faster?
A: give this a try:
SELECT *
FROM (
SELECT a.HotelID,a.Hotelname,GROUP_CONCAT(DISTINCT b.OperatorName) AS Operators, COUNT(a.HotelID) AS total
FROM hotels AS a
INNER JOIN operators AS b
ON a.HotelID = b.HotelID
GROUP BY a.HotelID
) AS a
ORDER BY a.HotelID
LIMIT 100
also, for the speed you should make sure your indexes are in order.
A: Clearly described in the manual:
SQL_CALC_FOUND_ROWS tells MySQL to calculate how many rows there would
be in the result set, disregarding any LIMIT clause. The number of
rows can then be retrieved with SELECT FOUND_ROWS(). See Section
11.13, “Information Functions”.
If you follow the link to Section 11.13, there's then an example:
FOUND_ROWS()
A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward:
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
The second SELECT returns a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause.
In the absence of the SQL_CALC_FOUND_ROWS option in the most recent successful SELECT statement, FOUND_ROWS() returns the number of rows in the result set returned by that statement. If the statement includes a LIMIT clause, FOUND_ROWS() returns the number of rows up to the limit. For example, FOUND_ROWS() returns 10 or 60, respectively, if the statement includes LIMIT 10 or LIMIT 50, 10.
Please, use the documentation as your first port of call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I use Log4Perl across modules in Perl? I'm planning to use Log4Perl in my modules for logging.
My code structure goes like this
I have Start.PL which validates some parameters. I have several modules (PM) file which are interlinked (used across these PL and PM files)
I have a Logger.PM in which I have a method InitiateLogger() which creates the log object
$log = Log::Log4perl->get_logger("MyLog");
I call this method Logger::InitiateLogger(); in the Start.pl
Here are my questions
*
*How can I use the same $log across the modules (PM files)
*Do I need to use same package name for this?
Would be nice if someone clarifies me these points.
A: You may declare $log as a package variable with our and use the instance wherever you need, using its verbose fully qualified name:
Package::Name::$log->info( 'test' );
In place of fully qualified name you can use an alias after a typeglob assignment:
#!/usr/bin/env perl
package Package::Name;
use strict;
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init( $ERROR );
our $log = get_logger();
package main;
use v5.12;
use strict;
*log = $Package::Name::log;
say $log;
which yields:
Log::Log4perl::Logger=HASH(0x230ff20)
In your case, the fully qualified name of logger object in Start.pl is $main::log.
You can make an alias in every package where the logger is needed with *log = $main::log.
A: Actually, the way Log4perl works (it's a singleton), get_logger() will return the exact same object wherever in your program it's called from
use Log::Log4perl qw(:easy);
Log::Log4perl->easy_init( $ERROR );
print Log::Log4perl->get_logger("MyLog"), "\n";
package Some::Other::Package;
print Log::Log4perl->get_logger("MyLog"), "\n";
This prints (for example):
Log::Log4perl::Logger=HASH(0x15a9d48)
Log::Log4perl::Logger=HASH(0x15a9d48)
So if you want to use the same $log across all your modules, you could just call get_logger("MyLog") in each of those modules.
But a better way, if you want to be able to turn logging on or off in one particular module, might be to just call get_logger() without arguments. That will return you a logger tied to the current package name, so you could turn that package's logger on or off in your config file.
A: Use global variables like,
$main::log = Log::Log4perl->get_logger("MyLog");
So you can access the variable $main::log anywhere across the modules. Because it will be maintained in the namespace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can the expect script continue to execute other command after "interact"? I am writing a script to run ssh so as to login a remote host, after all the operation is done, I type exit and log off. But I want the script to continue running and write log on the local host. The script is something like:
#!/usr/bin/expect
spwan ssh qwerty@remote_host
expect {
"password:" {
send "123123\r"
}
}
interact;
send "echo $(date) >> login_history.log\r"
But the last command "send ..." always failed with the error message like
"send: spawn id exp4 not open ..."
When I log off from the remote host, can the expect script continue to work as it is running on the local host?
A: YES, processing can continue after an [interact].
Short answer: change the last {send ...} to {exec date >> login_history.log}
There are several concepts you'll want to understand to achieve the control flow you're after. First, http://www.cotse.com/dlf/man/expect/interact_cmd_desc.htm provides a succinct synopsis and example of intermediate [interact] use.
Second: why did you see the message "... spawn id ... not open ..."? Because the spawn id is not open. The script you wrote said, in effect, "interact, then, after interact is over, send a new command to the ssh process." If you've already logged out, then, of course that id for a defunct process is no longer available.
Third: how do you achieve what you want? I'm unsure what you want. It sounds as though it would be enough for you simply to transform the [send] as I've described above. How does that look to you?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Slicing an Array I am having trouble finding a matlab function to slice an element out of an array.
For example:
A = [1, 2, 3, 4]
I want to take out on element of this array, say the element 3:
B = [1, 2, 4]
Is there a matlab function for this or would I have to code the algorithm to construct a new array with all the elements of A except 3?
A: Do this:
index_of_element_to_remove = 3;
A(index_of_element_to_remove) = [];
now A will be [1 2 4]
If you want to remove more elements at the same time you can do:
index_of_element_to_remove = [1 3];
A(index_of_element_to_remove) = [];
now A will be [2 4]
A: By value, which will remove all elements equal to 3
A(find(A==3)) = []
Or by index
A(3) = []
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP output in the textfield/text i have a little problem about PHP
there is two input for num1 and num2
and another input answer,,can the output in the php be putted in the input text answer??
<input type="text" name ="num1">
<input type="text" name ="num2">
<input type="text" name ="answer">
A: <?php
//get the values and calc..
$answer = $_GET['num1'] + $_GET['num2'];
//more secure, $answer = floor($_GET['num1']) + ...
?>
<html><body>
<form method="get" action=".">
<input type="text" name ="num1">
<input type="text" name ="num2">
<input type="text" name ="answer" value="<?php echo $answer;?>">
<input type="submit">
</form>
...
A: Try something like this:
<?php
if(!empty($_POST['num1'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2']
$answer = $num1 + $num2;
}
?>
<form action="yourpage.php" method="post">
<input type="text" name ="num1" value="<?=@$num1?>">
<input type="text" name ="num2" value="<?=@$num2?>">
<input type="text" name ="answer" value="<?=@$answer?>">
<br/>
<input type="submit" id="btnSubmit" value="POST ME" />
</form>
Not tested btw...
A: The jQuery answer that was suggested by riky has shown up on SO before. Try:
How to update the value in one text box based on the value entered in another text box?
As per the OP's request for an fleshed out version of the jQuery answer, modifying the linked to answer gives something like:
$('#num1').change(function() {
var txtAmtval = $('#num1').val() + $('#num2').val();
$('#answer').val(txtAmtval);
});
$('#num2').change(function() {
var txtAmtval = $('#num1').val() + $('#num2').val();
$('#answer').val(txtAmtval);
});
Is that what you had in mind?
Obviously you'd need to include jQuery too.
Please see code in action here: http://jsfiddle.net/9KEsY/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual Studio 2010 settings file location I've got a small problem concerning my settings and a virtual machine. Recently I setup a VM so that I can perform clean checkouts and builds of the code once every week or so. However, my documents folder lives on the company network (thanks IT department!) so my settings are shared between my real machine, and my virtual machine.
Obviously this causes never ending conflicts and is super annoying. I feel like there should be some easy way to point the VM to a different location where it can store and use its settings internally. Does anyone know how to do this?
A: I figured it out, the option is actually hiding in plain sight. Start by navigating to:
Tools > Import and Export Settings
Now when you select any of the options (import / export / reset) you have the option to specify the directory where you want settings to be stored. I chose 'reset', made a copy of the current settings, and re-imported them when the reset operation was complete. It is probably just easier to change the directory and hit 'export' though.
I changed this value on both of the machines to something local (to them) and now I no longer have a conflict.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Compare NSString with Chinese letters ios Does anyone know if it works well to compare NSStrings with chinese letters?
A: Yes, it works well.
NSString *chnString = @"中文, 汉语";
if ([chnString isEqualToString:@"中文, 汉语"]){
NSLog(@"Equal");}
else
NSLog(@"NOT Equal");
if ([chnString isEqualToString:@"中文, 汉"])
NSLog(@"Equal");
else
NSLog(@"NOT Equal");
And results are:
2011-09-27 15:08:14.527 iProj-iPad[3716:207] Equal
2011-09-27 15:08:14.528 iProj-iPad[3716:207] NOT Equal
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Insert if there are available rooms using mySQL If in a mysql table RESERVATIONS there are ROOM_NUMBER, DATE_ARRIVAL and DATE_DEPARTED
With this I find the today free rooms
SELECT RPOM_NUMBER
FROM RESERVATIONS
WHERE (CURRENT_DATE() < DATE_ARRIVAL) OR (CURRENT_DATE() > DATE_DEPARTED)
How do I insert a record in RESERVATIONS if there is an available room in my preferable date of arrival and departure?
A: SELECT RPOM_NUMBER
FROM RESERVATIONS
WHERE (CURRENT_DATE() < DATE_ARRIVAL) OR (CURRENT_DATE() > DATE_DEPARTED)
If this query returns more than 0 rows, there are free rooms available.
Then just use INSERT statement like this
INSERT INTO reservations SET room_number = ROOM_NUMBER_FROM_PREVIOUS_QUERY, [other fields of reservation table...]
A: What you want is a conditional insert...look at this: http://forums.mysql.com/read.php?97,164551,164551
A: SQL generally does only part of the job you want to do. You want to write a program that will find available rooms then create a reservation for one of those rooms. SQL can do the finding part (with SELECT) and the creating part (with INSERT). But the part where you offer the list of rooms to the user, let the user select a room, and make a decision whether to create the reservation usually happens in some procedural language that issues SQL statements to affect the database.
What other language are you using in this project?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the difference between @Inject and @Autowired i am just wondering what is the difference between @Inject & @Autowired
when to use each one ?, or they are doing the same thing ?
and if i have a spring bean which have a scope:
@Service
@Scope("singleton")
can i make dependency injection for it with both with no problems ?
thanks in advance.
A: From what I know, they do the same. @Inject is an annotation from javax.inject, which is only the API for dependency injection. In Spring you can use both, as I think Spring provides an implementation for @Inject which does the same thing as @Autowired in Spring environments.
Matthias Wessendorf blogged about this here: http://matthiaswessendorf.wordpress.com/2010/04/20/spring-3-0-and-jsr-330-part-2/
A: How about reading the documentation?
JSR 330's @Inject annotation can be used in place of Spring's
@Autowired in the examples below. @Inject does not have a required
property unlike Spring's @Autowired annotation which has a required
property to indicate if the value being injected is optional. This
behavior is enabled automatically if you have the JSR 330 JAR on the
classpath.
A: I think it is worth pointing out that, if you use @Autowired, you are creating a dependency on Spring, where using @Inject, you will be able to swap out another dependency injection framework that supports JSR 330.
A: First, @Autowired is defined by Spring Framework but @Inject came from "Dependency Injection for Java" (JSR-330)"
Second, @Inject doesn't take required attribute so if it fails to find any bean, it will fail with an error but @Autowired can come with required=false and will allow a nullable field.
Third, Advantage of @Inject annotation is that rather than inject a reference directly, you could ask @Inject to inject a Provider. The Provider interface enables, among other things, lazy injection of bean references and injection of multiple instances of a bean.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Some problem with NumberFormatter -(void)textFieldDidEndEditing:(UITextField *)textField
{
if(textField == self.nameField)
{
self.movie.name = self.nameField.text;
}
else if(textField == self.summaryField)
{
self.movie.summary = self.summaryField.text;
}
else if(textField == self.budgetField)
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
self.movie.budget = [formatter numberFromString:self.budgetField.text];
NSLog(@"%@",self.movie.budget);
[formatter release];
}
}
The Above code is from the Movie_LibraryEditorViewController.m file which is my second view in my project. In "self.movie.budget" it doesn't take the value, it takes as null.
In the First View i have labels in which the text is displayed.
Now "movie" object is of the class Movie_Library in which i have overridden the following method.
-(id)initWithTitle:(NSString *)newname budget:(NSNumber *)newbudget summary:(NSString *)newsummary
{
self = [super init];
if(nil!=self)
{
self.name = newname;
self.budget = newbudget;
self.summary = newsummary;
}
return self;
}
Now my question is Why the Null value? Am i doing smmin wrong here?
A: You need to type the currency code if you use NSNumberFormatterCurrencyStyle. Default code is "$". So, the string should look like this
[formatter numberFromString:@"$34"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wordpress: Strange whitespace under Admin bar I'm creating a Wordpress theme from scratch, and so far everything's going well (it's my first time). However, underneath the admin bar I have 18 pixels of whitespace that wasn't in my static HTML page before Wordpress-ing it up. See below for a screenshot:
The blue part is the header, which should be flush with the admin bar. Is there any obvious reason for this happening?
A: I've had a similar thing happen, and I believe your issue is white space in your html. Go through and remove any extra spaces which may be rendering, especially before (or after) your <?php ?> tags.
A: maybe you could give us some more css. That could have thousands of reasons. If you dont work with firebug or other developer tools you should defenitley check that out. With this tools you can click at the place with the css element you want to see and see the attributes...
https://addons.mozilla.org/de/firefox/addon/firebug/
or click at chrome on the preferences of the browser...than "tools" and then "developer tools"
If you don't find the answer with this tools, post us some css from your stylesheet
A: We're short on information here. We need to see your CSS for an accurate answer.
Either way, if you log out, is the margin still there? I'm pretty sure it is. I actually think you're having a margin-top or padding-top on your container/header/whatever element is on top.
If there is no margin, then your CSS is probably interfering with the admin bar. You probably set a margin-bottom on an element that matches either your class, tag or structure of the admin bar.
If you still don't see anything, there is a very slim chance that it could be browser-related. If the other solutions didn't work, try adding a CSS reset.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is this setTimeout not working & related question inside I have this script on a page of mine and the setTimeout function never fires. It's just an alert right now but i'm just testing it out. I'm doing a meta refresh on the page just after it if that's any clue, but i've also given that a 10 sec delay so the page isn't refreshed before it's supposed to trigger.
Also, the related question: If I run a javascript with a delay of, say, 10 seconds (with setTimeout) and in that javascript I try to modify a design element that's not on the page when the setTimeout is declared but will be by the time the script is fired. Will it work?
<script language=javascript>
var xmlhttp_get_memento;
function loop_alerte(){
setTimeout( function() {
alert("timeout");
}, 5000);
xmlhttp_get_memento = new XMLHttpRequest();
if (xmlhttp_get_memento==null)
{
alert ("Browser does not support HTTP Request (1)");
return;
}
var url="crm/ajax/get_mementos.php";
url=url+"?sid="+Math.random();
xmlhttp_get_memento.onreadystatechange=function() {
if (xmlhttp_get_memento.readyState == 4) {
alert(xmlhttp_get_memento.responseText);
schimbare_tip_cursor("default");
}
else{
schimbare_tip_cursor("progress");
}
};
xmlhttp_get_memento.open("GET",url,true);
xmlhttp_get_memento.send(null);
}
loop_alerte();
</script>';
A: Your setTimeout looks good, so there's probably something else that's wrong. Have you tried using a javascript debugger to see if you get any errors?
As for your second question, yes, that shouldn't be any problem, as the anonymous function inside the setTimout won't be evaluated until it runs. Live sample here: http://jsbin.com/afonup/2/edit Both with and without jQuery.
A: There is nothing wrong with your setTimeout, you will need to debug further
As for your second question -- the function will run, but whatever it is you were trying to do will not work.
A: Cleaning up your code would be a nice start. I can imagine a browser doesn't understand the tag <script language=javascript>. I suggest to use <script type="text/javascript"> and if you're lucky, your javascript might work!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Escape strings by array of chars I have a js simple array.
array('p','(',')','?');
According to that array values i need to escape strings in js, how can i do that?
for example string is = 'hey?' and in escape array i have '?'
A: Something like this should work:
//for old browsers...
Array.prototype.indexOf = Array.prototype.indexOf || function(o) {
for(var k = 0; k < this.length; ++k)
if(this[k] === o) return k;
return -1;
};
var escapes = ['p', '(', ')', '?'];
var array = 'hey?'.split('');
for(var i = 0; i < array.length; ++i) {
var escapeIndex = escapes.indexOf(array[i]);
if(escapeIndex > -1) {
array[i] = '\\' + array[i];
}
}
var newString = array.join('');
A: Not sure if this is the most efficient way to do it, but you could try something like this -
var text = "= 'hey?'";
var a = ['p','(',')','?'];
for (i=0;i<a.length;i++) {
text = text.replace(a[i],'\\' + a[i])
}
alert(text);
Demo - http://jsfiddle.net/aEysk/
A: Try this
for(var i=0;i<arr.length;i++){
var ind = strValue.IndexOf(arr[i])
if(ind>-1)
{
strValue.splice(ind,1)
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JSF Primefaces:redirect to specific page on p:tab click I would like to utilize p:tabView for horizontal site menu.
When tab is clicked,that user should be redirected in non-ajax style to the specific page.
Is it possible to inject to each tab (e.g. inside p:tab tag) href link ?
Or there is already some alternative to it?
A: You could put the p:tabView in a template and set the activeIndex property according to the view ID of the current page. It's an ugly hack, but certainly do-able. I did something similar, using a p:menu on the left for navigation in the control panel section of my site.
A: Primefaces 3.4 now has a p:tabMenu component that may be of use.
You will have to manage the active tab manually since this is an undeveloped feature.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Benchmarking symmetric and asymmetric cryptography In order to integrity protect a byte stream one can conceptually either use symmetric cryptography (e.g. an HMAC with SHA-1) or asymmetric cryptography (e.g. digital signature with RSA).
It is common sense that asymmetric cryptography is much more expensive than using symmetric cryptography. However, I would like to have hard numbers and would like to know whether there exist benchmark suites for existing crypto libraries (e.g. openssl) in order to gain some measurement results for symmetric and asymmetric cryptography algorithms.
The numbers I get from the built-in "openssl speed" app can, unfortunately, not be compared to each other.
Perhaps somebody already implemented a small benchmarking suite for this purpose?
Thanks,
Martin
A: I don't think a benchmark is useful here, because the two things you're comparing are built for different use-cases. An HMAC is designed for situations in which you have a shared secret you can use to authenticate the message, whilst signatures are designed for situations in which you don't have a shared secret, but rather want anyone with your public key be able to verify your signature. There are very few situations in which either primitive would be equally appropriate, and when there is, there's likely to be a clear favorite on security, rather than performance grounds.
It's fairly trivial to demonstrate that an HMAC is going to be faster, however: Signing a message requires first hashing it, then computing the signature over the hash, whilst computing an HMAC requries first hashing it, then computing the HMAC (which is merely two additional one-block hash computations). For the same reason, though, for any reasonable assumption as to message length and speed of your cryptographic primitives, the speed difference is going to be negligible, since the largest part of the cost is shared between both operations.
In short, you shouldn't choose the structure of your cryptosystem based on insignificant differences in performance.
A: All digital signature algorithms (RSA, DSA, ECDSA...) begin by hashing the source stream with a hash function; only the hash output is used afterwards. So the asymptotic cost of signing a long stream of data is the same as the asymptotic cost of hashing the same stream. HMAC is similar in that respect: first you input in the hash function a small fixed-size header, then the data stream; and you have an extra hash operation at the end which operates on a small fixed-size input. So the asymptotic cost of HMACing a long stream of data is the same as the asymptotic cost of hashing the same stream.
To sum up, for a suitably long data stream, a digital signature and HMAC will have the same CPU cost. Speed difference will not be noticeable (the complex part at the end of a digital signature is more expensive than what HMAC does, but a simple PC will still be able to do it in less than a millisecond).
The hash function itself can make a difference, though, at least if you can obtain the data with a high bandwidth. On a typical PC, you can hope hashing data at up to about 300 MB/s with SHA-1, but "only" 150 MB/s with SHA-256. On the other hand, a good mechanical harddisk or gigabit ethernet will hardly go beyond 100 MB/s read speed, so SHA-256 would not be the bottleneck here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I extend clojure.contribs json writer to serialize other classes I need to create JSON objects from clojure maps that store things like clojure vars. The base implementation throws this kind of error when it sees them:
java.lang.Exception: Don't know how to write JSON of class clojure.lang.Var
Can anybody point me to sample code on how to extend the capabilities of the JSON writer?
Thanks.
A: Well, I figured out the answer. There's another SO question that answers it partially: How to map clojure code to and from JSON?
But here's the code that worked for me:
(defn- write-json-clojure-lang-var [x #^PrintWriter out]
(.print out (json-str (str x))))
(extend clojure.lang.Var clojure.contrib.json/Write-JSON
{:write-json write-json-clojure-lang-var})
Note that all I wanted to do is just render a string version of which Var I'm referring to. You could, of course, do many other things...
A: An update to the answer from zippy for those of us using the newer clojure.data.json. This is code that will work with the updated/new library:
(defn- write-json-clojure-lang-var [x #^PrintWriter out]
(.print out (json-str (str x))))
(extend clojure.lang.Var clojure.data.json/JSONWriter
{:-write write-json-clojure-lang-var})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Data manipulating environment I am looking for something* to aid me in manipulating and interpreting data.
Data of the names, addresses and that sorts.
Currently, I am making heavy use of Python to find whether one piece of information relate to another, but I am noticing that a lot of my code could easily be substituted with some sort of Query Language.
Mainly, I need an environment where I can import data in any format, be it xml, html, csv, or excel or database files. And I wish for the software to read it and tell me what columns there are etc., so that I can only worry about writing code that interprets it.
Does this sound concrete enough, if so, anyone in possession of such elegant software?
*Can be a programming language, IDE, combination of those.
A: Have you looked at the Pandas module in Python? http://pandas.pydata.org/pandas-docs/stable/
When combined with Ipython notebook, it makes a great data manipulation platform.
I think it may let you do a lot of what you want to do. I am not sure how well it handles html, but it's built to handle csv, excel and database files
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7568783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.