text stringlengths 8 267k | meta dict |
|---|---|
Q: Placeholder in C# expression WPF Is it possible to use placeholders in C# expression? I have a expression for filtering records in a datagrid as follows:
view.Filter = item =>
{
OrdsRlsd vitem = item as OrdsRlsd;
if (vitem.OrderNo >= Convert.ToInt32(TxtCond1.Text) && vitem.OrderNo <= Convert.ToInt32(TxtCond2.Text))
{
return true;
}
return false;
};
In this expression, the the comparison operators and the TxtCond1 and TxtCond2 values are dynamic. Can we use a placeholder for that?
A: Yes you can pass those as Func<string> parameters. So say your function definition is like this
public void Filter(Func<string> string1, Func<string> string2)
{
var result = item =>
{
OrdsRlsd vitem = item as OrdsRlsd;
if (vitem.OrderNo >= Convert.ToInt32(string1.Invoke()) && vitem.OrderNo <= Convert.ToInt32(string2.Invoke()))
{
return true;
}
return false;
};
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL - Select 'n' greatest elements in group The SQL MAX aggregate function will allow you to select the top element in a group. Is there a way to select the top n elements for each group?
For instance, if I had a table of users that held their division rank, and wanted the top two users per division ...
Users
userId | division | rank
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 2 | 3
I would want the query to somehow return users 2,3,4
If it matters, I'm using MySQL.
A: select * from users as t1
where (select count(*) from users as t2
where t1.division = t2.division and t2.rank > t1.rank) <2
order by division,rank
A: Try this:
SELECT *
FROM (
SELECT *, row_number() OVER (PARTITION BY division ORDER BY rank DESC) as rn
FROM users
) as extended_users
WHERE rn <= 2
ORDER BY userId
A: SELECT * FROM (
SELECT u1.userid, u1.rank
FROM users u1
GROUP BY u1.division
HAVING u1.rank = MAX(u1.rank)
ORDER BY u1.rank DESC
UNION
SELECT u2.userid, u2.rank
FROM users u2
WHERE u2.id <> u1.id
GROUP BY u2.division
HAVING u2.rank = MAX(u2.rank)
ORDER BY u2.rank DESC
) ranking
ORDER BY ranking.userid
A: SELECT * from users u0
WHERE NOT EXISIS (
SELECT * FROM users u1
WHERE u1.division = u0.division
AND u1.rank >= u0.rank +2
);
BTW: most people count ranks starting from zero: poll-position gets rank=1, the second gets rank=2, et cetera. In that case you rank is 1+ the number of people before you in the ranking
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to merge two arrays with same id in PHP?
Possible Duplicate:
Merge arrays (PHP)
This is aray my array how i merge array with his 'panid'.
same 'panid' please see array and required output.
show below array the 2 array contain same 'panid' but it's ingredient are different.
so i will merge this 2 array in one array with merge his ingredient.
Array
(
[0] => stdClass Object
(
[userid] => 62
[panid] => 5
[recipeid] => 13
[ingredients] => 10 Kilos,1 Gram
[panname] => XYZ
)
[1] => stdClass Object
(
[userid] => 62
[panid] => 5
[recipeid] => 12
[ingredients] => 150 Gram,15 Pcs
[panname] => XYZ
)
[2] => stdClass Object
(
[userid] => 62
[panid] => 3
[recipeid] => 15
[ingredients] => 100 Gram,10 Pcs
[panname] => ABC
)
)
Require Output :
Array
(
[0] => stdClass Object
(
[userid] => 62
[panid] => 5
[ingredients] => 10 Kilos,1 Gram,150 Gram,15 Pcs
[panname] => XYZ
)
[1] => stdClass Object
(
[userid] => 62
[panid] => 3
[ingredients] => 100 Gram,10 Pcs
[panname] => ABC
)
)
A: PHP has some great datastructure classes you can use for this. Extending the SplObjectStorage class to override the attach method, you can update your list of recipes however you like. You will likely have to do more sanity checking than I've done, but here's a fairly simple example:
class RecipeStorage extends SplObjectStorage
{
/**
* Attach a recipe to the stack
* @param object $recipe
* @return void
*/
public function attach(object $recipe)
{
$found = false;
foreach ($this as $stored => $panid) {
if ($recipe->panid === $panid) {
$found = true;
break;
}
}
// Either add new recipe or update an existing one
if ($found) {
$stored->ingredients .= ', ' . $recipe->ingredients
} else {
parent::attach($recipe, $recipe->panid);
}
}
}
You can use all of the methods available in SplObjectStorage and add new recipes without having to think about merges.
$recipeBook = new RecipeStorage;
$recipeBook->attach($recipe1);
$recipeBook->attach($recipe2);
foreach ($recipeBook as $recipe => $id) {
echo 'Pan Name: ' . $recipe->panname;
}
This is completely untested, but it should give you some idea how to proceed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How to open a link from custom swf player which posted on wall I'm really wondering about how youtube or soundcloud flash player on facebook wall posts can open url on another tab/window. I tried many things from navigateToURL (both url and javascript) to ExternalInterface, but I couldn't get it work.
A: If you're using Flex, this worked for my onclick:
var urlReq:* = new URLRequest(YourURL);
navigateToURL(urlReq, "_blank");
Here's an example where the bottom link is opened in new window.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Update fails - pyodbc - informix Updates to an informix database via a python script using pyodbc are silently failing.
I am using the syntax as provided in the pyodbc wiki and tried manual commit as well as autocommit
cursor= conn.cursor()
cursor.execute("update eqpt set notes='BOB' where serialno='SAM'")
conn.commit()
conn.close()
I posted this question in the pyodbc group as well but unfortunately did not get an answer.
A: Two ideas:
*
*Check how many records was changed (it is retured by execute()), and how many records should be changed (using SELECT count(*) ... WHERE...:
cursor= conn.cursor()
rs = c.execute("SELECT count(*) FROM eqpt WHERE serialno='SAM'")
for txt in c.fetchall():
print('before %s' % (txt[0]))
rows_affected = cursor.execute("update eqpt set notes='BOB' where serialno='SAM'")
print('rows_affected: %d' % (rows_affected))
rs = c.execute("SELECT count(*) FROM eqpt WHERE serialno='SAM'")
for txt in c.fetchall():
print('after %s' % (txt[0]))
conn.commit()
conn.close()
*You can enable ODBC tracing and check what is returned by ODBC driver.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Authentication, CodeIgniter templates If the user is logged in
I want to show a different menu then if the user is not logged in.
Is the best way to accomplish this to make just two different views, and including them depending if the user is logged in or not (check in controller)
class Page extends CI_Controller {
protected $file = 'index';
public function index()
{
if ($this->auth->logged_in()) {
$this->file = 'logged_in';
}
$data['title'] = 'Hem';
$this->load->view('templates/header', $data);
$this->load->view('templates/menu/' . $this->file . '');
$this->load->view('home');
$this->load->view('templates/sidebar/' . $this->file . '');
$this->load->view('templates/footer');
}
}
That is my solution so far, how can Improve it?
A: If it's something as small as a header or a menu, I usually just break it into view partials and determine which one to display in the view. I also call all of the other view partials inside my main template view so it only requires a single $this->load->view(). That approach would give you this in your controller:
class Page extends CI_Controller {
public function index()
{
$view_data['main_content'] = 'home';
$this->load->view('templates/default');
}
}
and this in your view:
$this->load->view('templates/partials/header');
if ($this->auth->logged_in())
{
$this->load->view('templates/partials/menu');
}
else
{
$this->load->view('templates/partials/index');
}
$this->load->view($main_content);
$this->load->view('templates/partials/sidebar');
$this->load->view('templates/partials/footer');
This way you are always calling the same template and you can just set the $main_content which is the actual view you want to load and everything else that stays the same from page-to-page is already there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Make a list of words from text file and search these words by letters from input Ok, I'm a newbie so I appreciate any clues and hints. This is my first question here, so sorry about anything messy! I have found a lot of help with other types of lists and magic tricks, and some things, but not much, that I can use in this one.
I want to make a list from my little text file (containing all the words in the universe). First I want the user to write some letters, then I want to list words which contain these letters. The letters being "abcdeir" for example, the list would go "bad", "bar", "beard", etc.
Here is what I have so far:
file = open("allthewords.txt", "r")
A: I'd use sets for this:
letters = set("abcdeir")
with open("allthewords.txt", "r") as f:
for word in f:
if set(word) <= letters: # check that all letters of `word` are in `letters`
print word
You can tweak this as required.
A: You can simply write it out in pseudocode, and then execute it:
letters = "abcdeir" # Alternatively, letters = raw_input('Input letters: ')
with open("allthewords.txt", "r") as file:
for word in file:
if all(character in letters for character in word):
print(word)
A: You can use regexp if in your file some words would be in a same line.
import re
with open('your_file.txt','r') as f:
print re.findall(r"\b[abcdeir]+\b", f.read())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The right place for "io.sort.mb" in Hadoop? I am a bit confused, in the Hadoop cluster setup, in section "Real-World Cluster Configurations", an example is given where properties like io.sort.mb & io.sort.factor goes in core-site.xml. But in the default configuration files these properties appears in mapred-site.xml!!! which one I should follow? Am i free to put it anywhere? If yes, what is the difference between the three configuration file (core, mapred, and hdfs .xml)?
Is there any complete list of all possible properties?
Any help is much appreciated..
EDIT: Trial and error I found io.sort.mb belongs to mapred-site.xml.
A: core-default.html,
hdfs-default.html and
mapred-default.html have all the properties with their defaults.
According to the 'Hadoop : The Definitive Guide'
core-site.xml has 'Configuration settings for Hadoop Core, such as I/O settings that are common to HDFS and MapReduce.'
hdfs-site.xml has 'Configuration settings for HDFS daemons: the namenode, the secondary namenode, and the datanodes.'
mapred-site.xml had 'Configuration settings for MapReduce daemons: the jobtracker, and the tasktrackers.'
Find more information about the configuration files here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Reinterpret cast floating point number to integer This question is probably "unusual", but I need to cast a float Number to an integer Number, without modifying its binary representation.
For example, the float 37.5 is represented by the bytes 0x42160000 (according to IEEE 754).
I need to reinterpret 0x42160000 as an integer, i.e. the number 1108738048
How do I do this? I'm thinking there could be some bitwise tricks to accomplish this?
To be clear, I'm not looking for Math.round or parseInt.
A: Typed arrays can come in handy here: http://jsfiddle.net/rtYrM/.
// create array which is specialized for holding 1 float value
var floatArray = new Float32Array(1);
// set the float value
floatArray[0] = 37.5;
// use its buffer (4 bytes for 1 float) and pass it to an array
// specialized for integers
var intArray = new Int32Array(floatArray.buffer);
// the integer array will interpret the buffer bytes as an integer,
// which seems to be just what you want
intArray[0] === 1108738048; //true
intArray.buffer will hold the same bytes as floatArray.buffer, but by not accessing it with the buffer but with the array itself, it will read those bytes as the type specified by the typed array: as integers for Int32Array, and as floats for Float32Array.
In this case (in base 10):
*
*floatArray is set to the value [ 37.5 ].
*floatArray.buffer is automatically set to the values [ 0, 0, 22, 66 ].
*floatArray.buffer is passed to a new integer array, intArray.
*intArray.buffer therefore contains the values [ 0, 0, 22, 66 ] as well.
*intArray contains the value [ 1108738048 ], calculated with its buffer.
A: I don't believe Javascript includes any mechanism for doing this. There's a method java.lang.Float.floatBitsToIntBits() in Java, so depending on your intended environment you might be able to make use of that. If all else fails, you might have to send the data back to the server to be converted. Alternatively, I've seen attempts at Javascript methods to do this conversion, but never one that was 100% complete and correct.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Spring MVC Validation Model I'm a noobie in Spring MVC
To make Spring MVC 3 Validation fully work,
Must it be that the Model Class (e.g. User class) to have a commandName as 'user'?
can't it be changed?
Whenever i change the commandName (e.g. 'userx'), the error messages in the JSP does not show.
Is it a prerequisite that the commandName must have a naming convention for its Class name?
I'm sorry if this question is already answered in the Spring Docs or here in stackoverflow, it seems that I can't find the answer myself. Thanks
EDIT: Here is my form
Command name is "searchClientForm", thus the corresponding Class name is SearchClientForm.java
<form:form action="search.html" commandName="searchClientForm" method="post" class="tabform">
<h2>Client Maintenance</h2>
<div class="spacer"></div>
<div class="clear">
<label class="error"><c:out value="${errorMessage}"/></label>
</div>
<div class="spacer"></div>
<div class="clear">
<label for="fieldCode">Filter: </label>
<form:select path="fieldCode" items="${searchFields}" itemLabel="description" itemValue="key" id="fieldCode" />
<label for="searchValue">Search: </label>
<form:input path="search" id="searchValue" />
<input type="submit" value="Go"/>
<form:errors path="search" element="label" cssClass="error"/>
</div>
<div class="clear"></div>
</form:form>
A: The command name and class should be the same (command starts from lower case letter). You can extend the original class.
public class User extends SearchClientForm {} and place it in model as "user".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Invoking a Camel end point deployed in remote Server from JUnit test case I am a new to Camel and have to deliver a module in a very short notice. My question may be a very basic question but I would really appreciate if someone could guide me on it.
The requirement is to invoke a Camel endpoint service deployed in a Tomcat server from a jUnit test case. The Service has been injected with the CamelContext and it has got a set of exposed methods which needs to be called. We are using Spring 2.5 and Camel 2 in our project. The Spring config is below
<bean name="/DispatcherService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="dispatcherService">
<property name="serviceInterface" value="test.DispatcherService">
</bean>
<camelContext id="dispatcherCamelContext" trace="true" xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:dispatcherChannel" />
<!-- use comma as a delimiter for String based values -->
<recipientList delimiter=",">
<header>serviceEndpoints</header>
</recipientList>
</route>
</camelContext>
<bean id="dispatcherService" class="test.DispatcherServiceImpl">
<property name="context" ref="dispatcherCamelContext" />
</bean>
What I am not able to find is to find how can we call the end point URI direct:dispatcherChannel deployed in a tomcat server (http://someIP:8080) from a jUnit which uses Spring configuration.
A: You can't do that, as direct: endpoints represent direct method calls (i.e. you need to be in the same process as the application). In order to be able to call direct: endpoints from tests, you will need to start up the CamelContext in the tests themselves. Obviously, this is only usable when you need to test separate routes or your context is really small.
Tests interacting with an already deployed application should be regarded as integration/system tests. You can write JUnit tests for these scenarios, but you should interact with the application through the exposed interface (http: endpoints, etc.).
A: The "direct" endpoint is only accessible from within the same VM. If you need to access a route externally, you can do this with JMX or by wrapping it with another route using JMS or HTTP. Either approach will allow you to manually test/debug a deployed route...
*
*with JMX, you just need to go navigate to your Camel Context MBean (using jconsole, etc) and execute the sendBody("direct:dispatcherChannel","test message") operation
*to wrap the route with HTTP, just add this route, then go to this URL in a browser to invoke the route...
from("jetty:http://0.0.0.0:9001/invokeDispatcherChannel")
.to("direct:dispatcherChannel");
*if you need to send a payload, you might consider exposing the route via JMS (or WS, etc) and convert to the expected format before invoking the route. Then you can just drop a message in the queue (using JMX, AMQ web console, etc) to invoke the direct route.
from("activemq:queue:invokeDispatcherChannel")
.process(new MyMessageConverterProcessor())
.to("direct:dispatcherChannel");
A: As you already inject the camel context into the test.DispatcherServiceImpl, you just need to use the camel ProducerTemplate to send the request to the "direct:dispatcherChannel" like this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is Test Driven Development the same as Test Driven Design? I'm starting to learn about Test Driven Development. I've read quite a few articles that talk about TDD. Some refer to it as Test Driven Development. Others call it Test Driven Design. Are they the same thing? I get the impression they are the same, but if not, what are the main differences?
A: There are some of the TDD evangelists adocating that "Test Driven Development" is primarily a design technique, so they renamed it "Test Driven Design" some time ago. But this point of view has been seen very sceptical by others, read for example this former SO post
Does Test Driven Development take the focus from Design?
There is also an interesting german blog entry of Ralf Westphal discussing this topic:
http://ralfw.blogspot.com/2011/07/test-driven-unterstanding.html
(Here's a Google Translation if you don't understand German).
A: Test driven development is developing tests before writing what will be the production code. The goal behind this is to produce what are called "executable requirements" and it is all about writing just enough code to satisfy requirements.
If you use a Mocking framework like Moq you will be forced to construct your code based on Inversion of Control principles, using Dependency Injection, which is considered good practice as it reduces the "brittleness" of your code and promotes loose coupling at a fine grained aspect of your solution.
So to answer your question TDDevelopment is more about implementing requirements in code, using whatever tools you wish. TDDesign is the next step in the evolution of unit testing where you force good design by adopting Mocking frameworks such as Moq. Code that is produced with TDDesign is guaranteed to conform to the requirements of an IoC container such as spring.
TDDev is good ... TDDesign is better.
A: Test driven development refers to a practice describing how to write code.
Test driven design makes an additional claim: that following this practice will result in good (overall) design.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: using grails security model (acegi) outside of grails I have an existing grails application that was developed using the older acegi security plugin. I would like to develop additional applications (non-grails) that uses the same security model. I have two questions:
*
*Can I use the Spring Security project to achieve this?
*Can you provide an example of how I would authenticate?
Also, by 'security model' I really mean the existing database that has the users and roles.
A: Yes! the old acegi plugin is about spring security 2.x (new plugin is spring security 3.x). So be sure to download the right jar
as or code, be sure that your xml config for configuring match your database schema, for instance:
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT U.username, U.password, U.accountEnabled AS 'enabled' FROM User U where U.username=?"
authorities-by-username-query="SELECT U.username, R.name as 'authority' FROM User U JOIN Authority A ON u.id = A.userId JOIN Role R ON R.id = A.roleId WHERE U.username=?"/>
</authentication-provider>
more info at http://java.dzone.com/tips/pathway-acegi-spring-security-
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Limits for Multidimensional Arrays I just made a multidimensional array that was 1024 x 1024 x 1024. I get an OutOfMemory exception. What is the largest size multidimensional array that is safe to use? I'm doing this in VB.net so all .net answers are acceptable.
EDIT
When I said safe, I mean, a good size for just about any computer. What size would run smoothly on a 32bit operating system. I didn't realize that the 1024 size was 4G. I'm hoping for something a 16th of that.
A: Well, 1024 * 1024 * 1024 is a very large number. Assume you are using an integer array, then this corresponds to 4 GiB of memory, not counting the overhead of managing the multiple arrays.
Since no process may allocate more than 2 GiB of memory, you’ve surpassed the hard limit imposed by the operating system (not VB or .NET!). .NET itself has no real limit here since the machine limit is reached much faster.
A: This question is meaningless without at least two other details:
*
*Available memory on the computer
*Size of each memory
Get those number, then do the math. Assuming unboxed 32 bit integers, a 1024 * 1024 * 1024 array would consume roughly 4 GB (actually more, .NET arrays aren't C arrays and have some overhead; I don't know enough about their implementation to estimate how large the overhead is). You can use such an array, if you want to restrict use of the program to 64 bit computers with vast (more than 4 GB, at the very least because you program won't be the only one running) amounts of memory. Likely the computers you intend your program to run on aren't that powerful. Then you'll have to figure out the minimum you want/need to support and do some math to estimate how much memory you can comfortably consume.
A: .NET objects can't be larger than 2 gigabytes. Even then, on a 32-bit operating system it is very unlikely to find a hole in addressable virtual memory space large enough to fit such a large array. You can get about 600 megabytes right after your program starts, rapidly going down hill from there after the address space starts getting fragmented. Bombing on a 90 MB allocation when there's still half a gig free space is not terribly unusual.
You'll need to use jagged arrays and a 64-bit operating system. And a bit of introspection if you really need such a massive array. Arrays are kinda old school after System.Collections.Generic became available. With collection classes that are as fast as an array and only let you pay for what you actually use. Recommended.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using a 32bit- or 64bit specific dll depending on the process bitness I need to reference a DLL which is available in 2 versions (one for 32bit and one for 64bit).
My goal is to build an web application that works on both 32 and 64 bit systems.
I thought about referencing the 32bit assembly by default and using the AssemblyResolve event to load the 64bit version (if loading the 32bit version failed):
static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += _AssemblyResolve;
// Try LoadAssembly ...
}
static System.Reflection.Assembly _AssemblyResolve(object sender, ResolveEventArgs args)
{
var path = string.Format(@"...\lib_x64\{0}.dll", args.Name);
return Assembly.LoadFrom(path);
}
But even when a BadImageFormatException occurs, the _AssemblyResolve handler will not be called. Is there any other way to achieve the proposed behavior?
A: Most straightforward way but less flexible from my point of view is explicitly specify platform specific references in csproj file using Condition:
<ItemGroup Condition=" '$(Platform)' == 'x86' ">
<Reference Include="MyAssemblyx86">
Also you can do it dynamically using Assembly.Load(AssemblyName) method overload.
Parameter is of type AssemblyName which exposes the property AssemblyName.ProcessorArchitecture which could be set to None, MSIL, X86, X64, IA64, AMD64
One thing you also could look into is the Publisher Policy File feature and command line argument /platform:processorArchitecture
*
*Introduction to Publisher policy file
*How to: Create a Publisher Policy
A: See answers for dealing with this for System.Data.SQLite.
I think your proposed method should work but you need to move the 32-bit version so it can't be found by default, so _AssemblyResolve is always called for that dll. That's just a guess.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Editing all entries in the iPhone phonebook I have an idea and I want to know if it would be possible to implement on iPhone or not. Basically I want to access every entry on the iPhone phonebook, add a prefix before all numbers and then save it again, all without the asking the user to press save on every entry.
Is that possible?
A: Yes, that's possible. Read Address Book Programming guide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to transform 4 points to an xna matrix I want to develop my own AR-Library in C#. My problem is: I have the 4 corner points of my marker and want to show 3D cubes on the marker (it's a multi-marker lib), but I don't know how to get the matrices for xna.
A: The term you are looking for is called "3d pose estimation". Have a look at this link: http://www.aforgenet.com/articles/posit/ . It describes the POSIT algorithm and there's also a sample application including source code you can download. Conveniently for you, it's also written in C#.
A: This video shows how to translate a point touched on the screen to a point in an XNA matrix:
http://bit.ly/WPARBasic
You may also be interested in the SLARToolkit for Windows Phone:
http://slartoolkit.codeplex.com/
And the Geo AR Toolkit for Windows Phone:
http://gart.codeplex.com/
They all show how to take locations on the screen or in the real world and convert them to XNA matricies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mono 2.10.5 for CentOS / RHEL 5 Until now I used THIS to install/update mono on my CentOS machines, but it seems that it's not updated since 2.10.2 anymore (may because mono isn't part of novell anymore).
So is there a new location to get newer mono *.rpm from?
A: I've had pretty good luck with the scripts Nathan Bridgewater posts on his blog. You can get at the latest ones here: Mono Install Scripts. They're pretty easy to update your parallel environment settings or mono version if needed.
You can also install from github (see section C), but will need to get XSP and what not on your own:
git clone git://github.com/mono/mono.git
cd mono
./autogen.sh --prefix=/usr/local
make
make install
(select a branch/tag after cloning as needed)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Failing to install the latest version of Windows Service I am installing a Windows Service on my Desktop with a particular version. Then I revise my service and make some changes in the service.I upgrade my installer version.I make the property RemovePreviousVersion true and I do the following things below.In Custom Action I add NOT PREVIOUSVERSIONSINSTALLED and then I add below mentioned code.
System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("WinDbSync1");
if (serviceController.Status != System.ServiceProcess.ServiceControllerStatus.Running)
{
serviceController.Start();
}
I have got tha above solution from link Installing Higher Versions of existing Windows Service in VS 2008 following above steps ,It installs the windows Service but doesnot execute the business functionality written in Install event.Please let me know if I am missing any step.Also I am not changing the version of exe.I am simply changing version of Installer.
Regards,
Sachin K
A: There is no need for custom actions to install the service. Windows Installer has built in support.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa371634(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa371637(v=VS.85).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Too many php cookies Will having too many php cookies on a webpage slow it down a significant amount? On a site I've created I'm considering adding a feature, which would be nice, but require quite a few php cookies to be stored. Will this make the site slower?
A: It won't, but there is limit for cookie length. Save only necessary informations (security token) and take it from your server instead
A: HTTP Cookies are transmitted to the server for each http request your browser does.
If you have a few number of cookies, you won't see any difference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set start date and end date? How to set Start Date and End Date using jQuery Mobile?
For example, I selected one date (i.e start date) 24-5-2011 (May 24th,2011) then end date will be in less than or equal to 100 days from the start date.
A: Try this:
var start = new Date('5/24/2011');
var daysTillEnd = 100;
var isBetween = isBetween(start, daysTillEnd);
function isBetween(start,days){
var startTS = start.getTime();
var now = (new Date()).getTime();
var endTS = startTS + days*24*60*60*1000;
return now >= startTS && now <= endTS;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ninject and dynamic WithConstructor/WithMeta and RhinoMocks In my project I have an IoC container that gets initialized the usual way with a ServiceModule. When I write unit tests, I want to be able to bind to either a StrictMock, DynamicMock, PartialMock or Stub. In the past I had a FakeServiceModule that would bind everything to StrictMocks, but this is very restrictive, and I wanted to expand this to allow creating a mock type of my choosing.
To achieve this I created the following.
public class NinjectMocking
{
public Type TypeToMock { get; set; }
public MockType MockTypeToUse { get; set; }
public IBindingWithOrOnSyntax<Type> BindingWithOrOnSyntax { get; set; }
}
public enum MockType
{
Stub,
Strict,
Dynamic,
Partial
}
The idea is that I would initialise the fake service module like so:
foreach (var mockType in _mocks)
{
object ninjaMock;
switch (mockType.MockTypeToUse)
{
case MockType.Strict:
{
ninjaMock = _mockRepository.StrictMock(mockType.TypeToMock);
break;
}
case MockType.Dynamic:
{
ninjaMock = _mockRepository.DynamicMock(mockType.TypeToMock);
break;
}
case MockType.Partial:
{
ninjaMock = _mockRepository.PartialMock(mockType.TypeToMock);
break;
}
case MockType.Stub:
{
ninjaMock = _mockRepository.Stub(mockType.TypeToMock);
break;
}
default:
{
ninjaMock = _mockRepository.StrictMock(mockType.TypeToMock);
break;
}
}
if (mockType.BindingWithOrOnSyntax == typeof(ConstructorArgument))
Bind(mockType.TypeToMock).ToMethod(m => ninjaMock).w
.WithConstructorArgument(mockType.BindingWithOrOnSyntax);
else
Bind(mockType.TypeToMock).ToMethod(m => ninjaMock);
}
Having been initliazed with a list of mocks...
NinjectMocking ninjectMocking = new NinjectMocking();
ninjectMocking.TypeToMock = typeToAdd;
ninjectMocking.MockTypeToUse = MockType.Dynamic;
This all works perfectly. However, and here comes the question, some of our bindings need either .WithConstructorArgument or .WithMetaData as in
Bind<ISomeRepository>().ToMethod(m => someRepository)
.WithConstructorArgument("context", ctx => new TestDataContext());
and maybe some others in the future. That is why I have the BindingWithOrOnSyntax property in the NinjectMocking class. So my new initializer may look something like this:
NinjectMocking ninjectMocking = new NinjectMocking();
ninjectMocking.TypeToMock = typeToAdd;
ninjectMocking.MockTypeToUse = MockType.Dynamic;
ninjectMocking.BindingWithOrOnSyntax.WithConstructorArgument("context", constructorArgument);
The problem is I don't know how to make it use that in the binding. What I would like to do is something like
Bind(mockType.TypeToMock).ToMethod(m => ninjaMock).[WhatGoesHere]
I don't really know how to do it with the [WhatGoesHere] bit, or how else to define the Bind so that it uses whatever I pass in, in the BindingWithOrOnSyntax property. My last desperate attempt was to try force it via something like
if (mockType.BindingWithOrOnSyntax == typeof(ConstructorArgument))
Bind(mockType.TypeToMock).ToMethod(m => ninjaMock)
.WithConstructorArgument(mockType.BindingWithOrOnSyntax);
But that obviously doesn't work.
Any pointers in the right direction, or even if there is a better way to achieve this, would be greatly appreciated.
A: Don't use an IOC container during unit testing. An IOC container is to be used at runtime to inject your dependencies into your components. During unit testing, you create your components with mocked/stubbed dependencies. If your components are resolving dependencies directly from the IOC container, you're not using the container properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is -webkit-focus-ring-color? I want to reproduce the outline effect for focused input boxes in webkit to non-webkit browsers. I found here the default CSS used in webkit. The lines of interest are:
:focus {
outline: auto 5px -webkit-focus-ring-color
}
I tried making a search in the whole code for the definition -webkit-focus-ring-color here but could not find it anywhere.
A: The following code tries to find the closest solution to the system colors:
*:focus {
box-shadow: 0 0 1px 3px rgba(59, 153, 252, .7);
box-shadow: 0 0 0 3px activeborder; /* Blink, Chrome */
box-shadow: 0 0 0 3px -moz-mac-focusring; /* Firefox */
outline: auto 0 -webkit-focus-ring-color; /* Webkit, Safari */
}
A: FWIW:
Using Chrome on a Mac, I get a blue outline color when using normal browser mode. When I use the device view, I get a yellow/golden outline color.
Not sure why it changes - was actually very confusing. See examples below.
A: -webkit-focus-ring-color is defined in the WebKit codebase as focusRingColor in each RenderTheme class. That work was performed in June 2009 as part of this changeset by Jeremy Moskovich.
For instance, the default Mac theme (used by Safari) defines the colour in RenderThemeMac.mm (in a roundabout way) as:
[NSColor keyboardFocusIndicatorColor]
(Apple's very light documentation of that property is available online).
There is an override value for the Mac (called WebCore::oldAquaFocusRingColor) to be used for testing (near as I can tell it's for the code to be able to perform comparison between the browser rendering and a reference graphic; it is toggled using WebCore::usesTestModeFocusRingColor). It's defined in ColorMac.mm as the following (which apparently maps to Color(125, 173, 217)):
0xFF7DADD9
Chromium/Chrome defines the colour in RenderThemeChromiumSkia.cpp as:
Color(229, 151, 0, 255)
The default colour (specified in RenderTheme.h) is pure black:
Color(0, 0, 0)
A: Nowadays, the revert value has good browser support (yay!), which is used to roll back to the default UA styles, here's my 2020 "please let me have outlines" snippet (usually accompanied with !important declarations):
:focus {
outline: -webkit-focus-ring-color auto thin;
outline: revert;
}
Or if you wish to use longhand properties for the first instance of outline:
outline-color: -webkit-focus-ring-color;
outline-style: auto;
outline-width: thin;
outline: revert;
A: -webkit-focus-ring-color does not work in Firefox. You can use the system color Highlight as a replacement though.
:focus {
outline: auto 2px Highlight;
outline: auto 5px -webkit-focus-ring-color;
}
Also see this site on why resetting outline styles is usually a bad idea.
A: Use this jsFiddle. I got rgb(229, 151, 0) in Chrome 14 on Windows 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: OCaml: find value of specific type I have the list of some values where I need to find out which kind of value is first:
type my_types =
| MAlpha
| MBeta of int list
| MGamma of string * int
let find_first where what =
List.iter ( fun m ->
| MAlpha ->
(* iterate frough "what" to find if it was asked to look and return it if it was *)
| (* do the same for all other types *)
) where;
;;
let main =
let where_to_find = [MGamma, MAlpha, MBeta] in
let what_to_find = [MAlpha, MBeta] in
(match (first_found where_to_find what_to_find) with
| MAlpha ->
(* should return this *)
)
;;
Is there a way to do so without touching all types of MyType within find_first - is it possible to compare types of two values?
Thank you.
A: The code you have posted would not compile, but I think you are looking for the following information:
*
*It is possible to write so-called or-patterns, as in, for instance, (function MAlpha | MBeta _ -> ...).
*But patterns are not first-class citizens. You cannot build a pattern from a list (and by the way, [MGamma, MAlpha, MBeta] is one of the things that does not compile in your question), nor can you pass a pattern as argument to a function.
*However, you can build and pass around a function that matches for a pattern, so if you are willing to change your function find_first to take a function instead of a list for what, it will be more convenient to use.
A: Another way to look at this is that you have an equivalence relation for your type; i.e., you have some places where you want to treat all the MAlphas the same, all the MBetas the same, and all the MGammas the same. A standard handling for equivalence relations is to pick a representative element that represents the whole set of equivalent values (the equivalence class).
In your case you could use MAlpha to represent all the MAlphas (but there's only one of them), MBeta [] to represent all the MBetas and MGamma ("", 0) to represent all the MGammas. You would have a function to calculate the representative value from a given one:
let malpha = MAlpha
let mbeta = MBeta []
let mgamma = MGamma ("", 0)
let canonicalize =
function
| MAlpha -> malpha
| MBeta _ -> mbeta
| MGamma _ -> mgamma
let find_first where what =
canonicalize (List.find (fun x -> List.mem (canonicalize x) what) where)
let main () =
let where_to_find = [MGamma ("a", 3); MAlpha; MBeta [3; 4]] in
let what_to_find = [malpha; mbeta] in
try
let found = find_first where_to_find what_to_find
in
if found = malpha then (* what to do *)
else if found = mbeta then (* what to do *)
else (* what to do *)
with Not_found -> (* nothing was there *)
I have written code like this and it doesn't come out too bad. In your case it allows you to specify the what parameter a little bit naturally. One downside, though, is that you can't pattern match against malpha, mbeta, and mgamma. You have to do equality comparisons against them.
It may be that you wanted to find the specific value in the list, rather than the canonicalized value. I think the changes for that case should be pretty clear.
This also answers the second part of your question. The List.find function will stop as soon as it finds what it's looking for.
OCaml defines an ordering relation for all types that don't contain functional values in them. If this built-in (polymorphic) ordering doesn't do what you want, you have to define your own. You would certainly need to do this to compare values of two different types; but that is not what you're doing here.
If there's no element in the list that looks like what you said you wanted, this version of find_first will raise the exception Not_found. That's something else to think about.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Design Application with fragments I am starting developing a new application based on fragments. What I want to achieve is something similar to an activity group. Talking in fragments I was thinking to start create a FragmentActivity (call it TabActivity) that would manages different tabs. Every tab is compound of a ListFragment and I need to start different fragment based on the user input. My idea lets implement the TabActivity different CallBackListener (one for ListFragment) and, based on the call back called, create a new fragment. Could be this a correct solution? I found the documentation a bit confusing and a little frustrating...
TabActivity:
ListFragment1: fragment1 -> fragment2 -> fragment3
ListFragment2: fragment4 -> fragment5 -> fragment6
ListFragment3: fragment7 -> fragment8 -> fragment9
thanks in advance
EDIT: every ListFragment shares the same container in order to show their content
A: I have done something similar where I have an Activity that is just a controller/container for what Fragments will be viewable at any given time.
I have a method on the Activity that accepts enough information to determine what Fragment is to be shown, and the bundle it needs to populate the Fragment. Fragments can then tell the activity that it needs to change out, or add the new Fragment using that interface.
My particular case actually uses the same mechanism to control the content of several different "fragment containers" in the layout of the parent Activity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parsing Datetime with timezone offsets I have these datetimes which appear to me to be in an odd standard..
2004/05/17 21:27:16.162 GMT-7
2006/08/01 01:00:00 GMT-7
2010/11/05 13:00:38.844 US/Pacific
Any ideas on how I can parse them in C#? Or has anyone seen them before?
A: Maybe you could take a look at this topic it tells you how to format the datetime
DateTime Localization
But i think what you are looking for is the DateTimeOffset
Convertsion between DateTime and DateTimeOffset
A: 2010/11/05 13:00:38.844 US/Pacific is something which you cannot parse in pure .Net, at least not in localized form. For others, it really depends on whether you know format. If you do, you can use DateTime's ParseExact() method:
var dateString = "2004/05/17 21:27:16.162 GMT-7";
var anotherDateString = "2006/08/01 01:00:00 GMT-7";
DateTime firstResult;
var success = DateTime.TryParseExact(dateString, "yyyy/MM/dd HH:mm:ss.fff 'GMT'z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out firstResult);
if (success)
MessageBox.Show(firstResult.ToString());
DateTime anotherResult;
success = DateTime.TryParseExact(anotherDateString, "yyyy/MM/dd HH:mm:ss 'GMT'z", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out anotherResult);
if (success)
MessageBox.Show(anotherResult.ToString());
Please keep in mind, that I used InvariantCulture because I knew it is exactly the same as en-US. For correct results you would need to use valid CultureInfo.
Last, but not least: why you want to parse these invalid formats anyway? I would suggest to fix the source of the problem and use local default formats (depending on the culture as well as local time for current user's location) rather than creating your own. Special formats make understanding time harder as they are unnatural for end users.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to run Applet with dependencies jar file in HTML I have a jar file containing applet files which are dependent of below additional jar file.
Its running fine as standalone jar file. The applet uses:
*
*xmlrpc-2.0.jar
*commons-codec-1.3.jar
But when I tried to run in HTML as below, it's running, but attached additional jar files are not binding with it. How can I fix the problem?
<html>
<body>
<APPLET
CODE="MAIN.class"
WIDTH="100%" HEIGHT="100%"
ARCHIVE = "MAIN.jar,xmlrpc-2.0.jar,commons-codec-1.3.jar"
>
This example uses an applet.
</APPLET>
</body>
</html>
Manifest
Manifest-Version: 1.0
Main-Class: MAIN
Created-By: 1.3.0 (Sun Microsystems Inc.)
Class-Path: xmlrpc-2.0.jar commons-codec-1.3.jar
Name: MAIN.class
A: It should work as long as the jar files are in the same folder than your MAIN.jar. Can you see any classpath-related error in the Java console?
You can also try to use a manifest file as described here.
A: FatJar for Eclipse worked for me. Just be careful when you have multiple projects open, since it has a tendency to grab other stuff from non-related projects and roll that into your fatjar too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PersistenceSpecification and inverse I've already posted this in the Fluent NH group a long time ago, but didn't get any answers until today. SO, here's the problem: I've got a one-to-many relationship defined and the one side has the inverse flag set. the mapping code looks something like this:
public class MapeamentoReceita : ClassMap<Receita> {
public MapeamentoReceita() {
Table("Receitas");
Not.LazyLoad();
Id(rec => rec.Id, "IdReceita")
.GeneratedBy
.HiLo("TabelaHilo", "ProximoHi", "1000", "Tabela='receitas'")
.Default(0);
Version(rec => rec.Versao);
//other props go here
HasMany(rec => rec.Imagens)
.Access.CamelCaseField((Prefix.Underscore))
.AsBag()
.Cascade.All()
.KeyColumn("IdReceita")
.Not.LazyLoad()
.Inverse();
}
}
Now, Imagem's mapping looks like this:
public class MapeamentoImagem : ClassMap<Imagem> {
public MapeamentoImagem() {
Table("Imagens");
Not.LazyLoad();
Id(img => img.Id, "IdImagem")
.GeneratedBy
.HiLo("TabelaHiLo", "ProximoHi", "1000", "Tabela='imagens'")
.Default(0);
Map(img => img.Bytes)
.CustomSqlType("image")
.CustomType<Byte[]>()
.LazyLoad()
.Length(2000000000)
.Not.Nullable()
.Not.Update();
References(img => img.Receita)
.Column("IdReceita")
.Cascade.None();
}
}
And here's the code that tests the persistence of these classes:
new PersistenceSpecification<Receita>(sess)
.CheckList(rec => rec.Imagens,
_imagens,
(receita, imagem) => receita.AdicionaImagem(imagem))
.VerifyTheMappings();
Even though Inverse is "on", PersistenceSpecification tries to insert Imagem before inserting Receita. Since IdReceita is foreign key configured not to accept null, I end up with an exception. I've tried writing "real world code" that uses receita and it works (I've turned on SQL and I can see that in this case, Receita is inserted before Imagem as it should be).
Since nobody answered this question on FH group, I was wondering if someone can please confirm that this PersistenceSpecification behavior is a bug.
thanks.
A: Have you tried it this way?:
var receita = BuildMeAReceita();
var imagems = BuildSomeImagems();
foreach(var imagem in imagems){
receita.AdicionaImagem(imagem);
}
new PersistenceSpecification<Receita>(sess)
.VerifyTheMappings(receita);
A: Try:
References(img => img.Receita)
.Column("IdReceita")
.Not.Nullable();
My guess is that your real world code saves Recieta first so that the inserts are issued in the correct order. If you changed that code to save Imagem first you would get the same error because NHibernate would attempt to insert Imagem then update it with the foreign key.
A: You could change your mapping of Imagem
References(img => img.Receita)
.Column("IdReceita")
.Cascade.SaveUpdate();
This will persist Receita before Imagem
What I've found is that PersistanceSpecification works well for fairly straight forward relationships but if you have complex object graphs you have to have cascading turned on all of your objects. Your scenario is fairly simple though so this small change should allow you to test this using PersistanceSpecification.
Edit:
Also make sure in your AdicionaImagem function you are setting the parent of the image. Here is an example:
public virtual void AdicionaImagem(Imagem newImagem)
{
newImagem.Receita = this;
imagems.Add(newImagem);
}
A: There are two possible issues in your code.
*
*Imagem.Bytes property is lazy-loaded but lazy loading for Imagem
istself is disabled. It means no proxy is generated for Imagem
instances and Bytes cannot be lazy-loaded: mission impossible (at least it appears to me right now, not sure).
Simple load from database (session.Get<Imagem>(id);) leads to
exceptions like this:
Invalid Cast (check your mapping for property type mismatches); setter of Imagem.
Solution is to enable lazy-loading on Imagem or disable lazy loading on Bytes property.
*PersistenceSpecification loads tested entity from database as
another instance. It means that default equality comparer does not
work well. You need to provide your own equality comparer to solve
this issue (check this for more details).
Here is Receita and Imagem entities, implementation of IEqualityComparer and PersistentSpecification snippet. This code works well in NH3.1 and FNH 1.2. Please, let me know if your code differs somehow from these snippets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to call Java method from C++ (java returns String[])? As far as I know I can't call method from C++ that will return from Java string array, so only solution for this is loop call method that will return array elements on by one, but how can I store them in C++ array?
In Java I have method:
public static String getData(int index){ return arry[index]; }
and in C++:
char * args[10];
for (int i = 0; i < arrayLength; i ++) {
jmethodID mid = env->GetStaticMethodID(INF.cls_JSox, "getData",(I)Ljava/lang/String;");
jobject result = env->CallStaticObjectMethod(cls, mid, num, i);
const char *nativeString = env->GetStringUTFChars( (jstring) result, 0);
const size_t len = strlen(nativeString);
cout << "copying... \n";
strncpy(args[i], nativeString, len);
env->ReleaseStringUTFChars( (jstring)result, nativeString);
}
but when i = 1 I'm getting memory violation error in Java. How can I correctly copy data from received strings to the char * args[10]? The length of every string passed from Java is about 3-5 chars.
A: Assuming that the C++ code snippet you posted is complete, you are getting an access violation because you need to allocate args[i] before copying a value into it - a args[i] = new char[ len + 1 ] would do.
You can actually call a method from C++ that returns a Java string array, assume your method was:
public static String[] getData() { return array; }
Then on the native side you should be able to do something like:
jmethodID method = env->GetStaticMethodID( cls, "getData", "()[Ljava/lang/String;" );
jarray data = (jarray) env->CallStaticObjectMethod( cls, method );
// assumption: the result of getData() is never null
jsize const length = env->GetArrayLength( data );
// assumption: the String[] is always of length > 0
char** args = new char*[ length ];
for( jsize index(0); index < length; ++index )
{
jstring element = (jstring) env->GetObjectArrayElement( data, index );
// assumption: there are no null strings in the array
char const* nativeString = env->GetStringUTFChars( element, 0 );
jsize const nativeLength = strlen( nativeString );
args[index] = new char[ nativeLength + 1 ];
strncpy( args[index], nativeString, nativeLength );
env->ReleaseStringUTFChars( element, nativeString );
env->DeleteLocalRef( element );
}
I haven't tried to compile the above snippet so there might be an error or two, but it should be an ok starting point. I've left the code using a char* array and native strings, so at some point the code is going to have to call delete[] on each member of the array and on the array itself. It may end up ultimately simpler using std::vector and std::string for memory management depending on how the supplied strings are going to be used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: url?id=1 How do i GET the id using a PHP MYSQL function? I am learning how to use functions to organize my code better and cant seem to workout a mysql query that requires an external variable such as the url?id=1. How is a mysql query function to get a variable from the url done?
How do i achieve this?
My function:
function item() {
$itemid = $_GET['id'];
$t = "items";
$sql = mysql_query("SELECT * FROM $t WHERE id=$itemid") or die(mysql_error());
$r = mysql_fetch_array( $sql );
$id = $r['id'];
$date = $r['date'];
$title = $r['title'];
$location = $r['location'];
}
Now when i call that function inside another file like this:
<?php ### // no entry
item(); // get item function
?>
<h1>Item View</h1>
<?php echo $id;?>
<?php echo $date;?>
<?php echo $title;?>
<?php echo $location;?>
I get no result from the above, i did test the function to make sure it was being called by printing some html and it does get called. It only works if i move the query inside the view file.
I have a strange feeling im missing something important that is to do with a php class as well, but i have been racking my brain online trying to understand examples.
If someone could please elaborate with a very simple example of how this is achieved i would be very grateful :-)
Update:
function external_db_connect() {
$database_hostname = 'localhost';
$database_username = 'user';
$database_password = 'pass';
$database_name = 'table';
class DatabaseConnectClass {
public $database_hostname;
public $database_username;
public $database_password;
public $database_name;
public function databaseConnection($objDatabaseConnect) {
$this->_database_connection =
mysql_pconnect($this->database_hostname,
$this->database_username,
$this->database_password)
or trigger_error(mysql_error(),E_USER_ERROR);
return $this->_database_connection;
}
public function databaseConnectionSelect() {
$this->_database_connection_select =
mysql_select_db($this->database_name,
$this->_database_connection);
return $this->_database_connection_select;
}
public function databaseConnectionProcess($objDatabaseConnect) {
$objDatabaseConnect->databaseConnection($objDatabaseConnect);
$objDatabaseConnect->databaseConnectionSelect($objDatabaseConnect);
}
public function databaseConnectionMain($objDatabaseConnect) {
$objDatabaseConnect->databaseConnectionProcess($objDatabaseConnect);
}}
$objDatabaseConnect = new DatabaseConnectClass();
$objDatabaseConnect->database_hostname = $database_hostname;
$objDatabaseConnect->database_username = $database_username;
$objDatabaseConnect->database_password = $database_password;
$objDatabaseConnect->database_name = $database_name;
$objDatabaseConnect->databaseConnectionMain($objDatabaseConnect);
}
Thanks in advance.
Jonny
A: <?php
function item() {
$username="root";
$password="";
$database="test";
$host="localhost";
$itemid = $_GET['id'];
$t = "items";
mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$sql = mysql_query("SELECT * FROM items WHERE id=$itemid") or die(mysql_error());
echo "<h1> Item view </h1>";
while($row = mysql_fetch_array($sql))
{
echo "<h1>" . $row['title'] . "</h1>";
echo "<p>" . $row['location'] . "</p>";
}
mysql_close();
}
?>
<?php
item();
?>
This should give you an idea on how to accomplish a select. however this is against SRP and DRY.
A: You need to include first code into the second, or to send variables via form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Serialize class keyword benefits What can be the benefits of writing serialize keyword in below line of code ?
[Serializable]
public class Abc
{
}
A: If you don't know much about serialization, check this for a start. But as the other commented, the benefit is to be able to store the state of the object (for example, to a file), and retrieve it later. If you don't need that functionality, there's no benefit at all.
A: that you can transfer the object between processes? Can easily serialize them to files, streams, etc.?
There are a lot of good reasons to do this.
I do this all the time in combination with ISerializable this way I can implement the serialization of my objects without exposing to much or having to insert setters for immutable data.
You can even use WCF to transfer those objects but you have to make the types known or use TypeResolvers.
Just think of this as magically marking your object to be persistet or transfered.
A: MSDN SerializableAttribute
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Suggested Routes - Google Directions API I want to get a list of directions between two locations. Google Directions API says that the results are placed in routes array.
I tried directions using API and got only a single direction, but when searched in Google Maps with the search text as "Hall Bazar, Amritsar to Majitha Road, Amritsar", I got three route suggestions.
Please correct me if I misunderstood Google Directions API.
A: Check the documentation, you need to ask for alternatives
&alternatives=true
A: var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives:true
};
put provideRouteAlternatives:true
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UIPanRecognizer doesn't work. My view never redrawn I've made a UIPanRecognizer like this.
- (void)pan:(UIPanGestureRecognizer *)gesture
{
if ((gesture.state == UIGestureRecognizerStateChanged) ||
(gesture.state == UIGestureRecognizerStateEnded)) {
CGPoint translation = [gesture translationInView:self];
self.origin = CGPointMake(
self.origin.x+translation.x,self.origin.y+translation.y);
[gesture setTranslation:CGPointZero inView:self];
}
}
But my view never gets redrawn, that means... my drawRect wont be called again. Anybody ever tried this?
In my viewController I have this
UIGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self.graphView action:@selector(pan:)];
[self.graphView addGestureRecognizer:pan];
[self updateUI];
My updateUI is
- (void)updateUI { [self.graphView setNeedsDisplay]; }
A: You are calling your updateUI method when you attach the gesture recognizer to the view. You should be doing it in your callback method pan:.
Also, you are leaking memory. After allocating and adding the UIGestureRecognizer to the view you should release it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: Return max float instead of infs? I have several functions with multiple calculations that might return inf, like so:
In [10]: numpy.exp(5000)
Out[10]: inf
I'd rather it return the maximum float value:
In [11]: sys.float_info.max
Out[11]: 1.7976931348623157e+308
I could put in checks for every time an inf might pop up, or wrap each calculation in a function that rounds inf down to the desired float. However, I'd really like a simple hack at the beginning of every function, like:
inf = sys.float_info.max
Which obviously doesn't work. Is there a smart way to do this?
Thanks!
A: You can use a decorator:
import sys
def noInf(f):
def wrapped(*args, **kwargs):
res = f(*args, **kwargs)
if res == float('inf'):
return sys.float_info.max
return res
return wrapped
@noInf
def myMult(x, y):
return x*y
print(myMult(sys.float_info.max, 2)) # prints 1.79769313486e+308
A: I don't know about 'replacing' infinity value, but what about using min()?
Something like (assuming x yields your value):
return min ( [ x, sys.float_info.max ] )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Finding the regex for ///? This was posted to me
<*@google.com> wrote:
Hi Niklas,
If you just want to map this: /region/city/category/ supposing
its only
this valid characters: [a-zA-Z0-9_]
you can do the following:
- main.py
application =
webapp.WSGIApplication([('/([-\w]+)/([-\w]+)/([-\w]+)',
handler)],debug=True)
and on your handler:
class Handler(webapp.RequestHandler):
def get(self, region, city, category):
# Use those variables on the method
Hope this helps!
My webapp is suppossed to handle URI like <region>/<city>/<category> with optional city and category e.g.
/rio_de_janeiro/grande_rio_de_janeiro/casas? #<region>/<city>/<category>
/gujarat/ahmedabad/vehicles-for_sale #<region>/<city>/<category>
/rio_de_janeiro/grande_rio_de_janeiro/ #<region>/<city>
/delhi #<region>
Etc Now I want to enable a request handler that can take optional arguments divided by the separator /. If I use the regex '/(.*) and variables in the request handler the first varible becomes a/b and the second variable becomes b so that is nearly what I want but a and b as 2 different variables instead. The regex I tried for the request handler is
application = webapp.WSGIApplication([('/(.*)',MyPage),
And the function head of my request handler is
class MyPage(RequestHandler):
def get(self, location='frankfurt', category='electronics'):
To enable an HTTP query e.g. /frankfurt, /frankfurt/, /frankfurt/electronics, /madrid/apartments, /newyork, etc allowing all possible combinations. Can you advice me a regex that can achieve what I want? I want functionality like a mod_rewrite but for GAE.
Thanks
Clarification
It's just a question of "make the directory a variable" so to clarify here are some examples how it should behave
'/frankfurt', - put 'frankfurt' in variable 1
'/frankfurt/', - put 'frankfurt' in variable 1
'/frankfurt/electronics', - put 'frankfurt' in variable 1 and 'electronics' in virable 2
'/frankfurt/electronics/', same as above
'/eu/frankfurt/electronics', same as above i.e. only last 2 groups count
'/eu/frankfurt/electronics/', same as above
'toronto/lightnings', doesn't start with / so shan't work
'toronto/lightnings/', as above
'lima/cars/old', as above
'lima/cars/old/' as above
Typical cases I want to handle is /region/city/category i.e. if I apply the example to Brazil it could be /rio_de_janeiro/grande_rio_de_janeiro/casas? for /region/city/category or for India it could be /delhi/delhi/for_sale or /gujarat/ahmedabad/vehicles-for_sale
Solution
As far as I can tell the solution from the answer works for my purposes:
/(?:[^/]+)/?([^/]*)/?([^/]*)
A: After you have given more details, I can now propose another regex pattern:
import re
reg = re.compile('(?:/[^/]+(?=/[^/]+/[^/]+/?\Z)' # this partial RE matches the
# first of 3 groups, if 3
'|' # OR
')' # nothing is catched
'/([^/]+)' # the group always catching something
'(?:/([^/]+)?)?' # the possible second or third group
'/?\Z' ) # the end
for ss in ('/frankfurt', '/frankfurt/',
'/frankfurt/electronics', '/frankfurt/electronics/',
'/eu/frankfurt/electronics', '/eu/frankfurt/electronics/',
'toronto/lightnings', 'toronto/lightnings/',
'lima/cars/old', 'lima/cars/old/',
'/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena'):
mat = reg.match(ss)
print ss,'\n',mat.groups() if mat else '- No matching -','\n'
result
/frankfurt
('frankfurt', '')
/frankfurt/
('frankfurt', '')
/frankfurt/electronics
('frankfurt', 'electronics')
/eu/frankfurt/electronics/
('frankfurt', 'electronics')
toronto/lightnings
- No matching -
lima/cars/old/
- No matching -
/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena
- No matching -
But, you know, using a regex isn't absolutely necessary to solve your problem:
for ss in ('/frankfurt', '/frankfurt/',
'/frankfurt/electronics', '/frankfurt/electronics/',
'/eu/frankfurt/electronics', '/eu/frankfurt/electronics/',
'toronto/lightnings', 'toronto/lightnings/',
'lima/cars/old', 'lima/cars/old/',
'/rio_de_janeiro/grande_rio_de_janeiro/casas/Magdalena'):
if ss[0]=='/':
splitted = ss.rstrip('/').split('/')
if len(splitted)==2:
grps = splitted[::-1]
elif len(splitted) in (3,4):
grps = splitted[-2:]
else:
grps = None
else:
grps = None
print ss,'\n',grps if grps else '- Incorrect string -','\n'
The results are the same as above.
A: You can try
/(?:[^/]+)/?([^/]*)/?([^/]*)
which will put 'a/b' in variable 1, 'a' in variable 2 and 'b' in variable 3. Not sure if that is what you want.
A: A solution that may work for you, though you may find it too hardcoded:
Routes for your app structured like this:
routes = [
('/foo/([a-zA-Z]+)/?', TestHandler),
('/foo/([a-zA-Z]+)/([a-zA-Z]+)/?', TestHandler),
('/foo/([a-zA-Z]+)/([a-zA-Z]+)/([a-zA-Z]+)/?', TestHandler)
]
And in your handler you'd check len(args), something like:
class TestHandler(webapp.RequestHandler):
def get(self, *args):
if len(args): # assign defaults, perhaps?
A: If you just want to map this: (region)/(city)/(category)/ supposing its only this valid characters: [a-zA-Z0-9_]
you can do the following:
- main.py
application = webapp.WSGIApplication([
('/([-\w]+)/([-\w]+)/([-\w]+)', Handler)
],debug=True)
and on your handler:
class Handler(webapp.RequestHandler):
def get(self, region, city, category):
# Use those variables on the method
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Visual C++ - Unable to get Text value of listBox item, error C2872: 'Text' : ambiguous symbol myWarcraftRace->removeSkill( sysStringToCharArray( listBox_mySkills->SelectedItem->Text ) );
syStringToCharArray() does work, also the removeSkill() does work, problem is that I can't get the Text value of listBox_mySkills->SelectedItem
If I do as I did above, it gives me error:
1>d:\programming\vc++ projects\wcrace maker\MainForm.h(194): error C2872: 'Text' : ambiguous symbol
1> could be 'System::Drawing::Text'
1> or 'System::Text'
1>d:\programming\vc++ projects\wcrace maker\MainForm.h(194): error C2882: 'Text' : illegal use of namespace identifier in expression
And if I'll try to use it without text, it gives me error:
1>d:\programming\vc++ projects\wcrace maker\MainForm.h(194): error C2664: 'sysStringToCharArray' : cannot convert parameter 1 from 'System::Object ^' to 'System::String ^'
Which it obliviously is supposed to do, cause sysStringToCharArray() takes System::String^ parameter. So Problem is that I'm unable to use the Text property of the listbox item, anyone have any ideas why's that?
A: You are not getting a great error message here. The real problem is the type of the ListBox::SelectedItem property. It is Object, a listbox can store any kind of value or object. And Object doesn't have a Text property. The compiler now goes noddy when hunting for the "Text" identifier and finding a match in namespace names, more than one. Fix:
listBox_mySkills->SelectedItem->ToString()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Overflow to left and top? If an element has overflow: auto or overflow: scroll, and its contents overflow, then scrollbars are shown... but only if the content overflows to the right or off the bottom.
Is it possible for the overflow to apply scrollbars if content is overflowing to the left, or off the top?
A: What you ask is somewhat contradictionary. If you want to show the whole content of a larger box inside a smaller box, you must have a scrollbar position for each side's end. When you place content (with absolute position and/or negative margins) which overflows this "endpoint" in either direction, you essentially block yourself from using the scroll feature as it is intended to be. (this does not mean that I do not find it usefull sometimes :)
A: If content is overflowing to the left or to the top, then both scroll bars appears with overflow: auto or overflow: scroll
jsFiddle
With overflow: scroll scroll bars are always visible, even if content does not overflow.
With overflow: auto scroll bars are visible, only when content does overflow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: LazyLoad images to GalleyView - Android i've searched and didn't come across anything usefull on problem i'm facing.
I fetch images from remote location and store them in local cache as they are needed, when image has been downloaded i use lazy loading to update the ImageView that requested it. It all works fine, but when request comes from Gallery adapter and once the download is complete it does not seem to update only the imageView that requested it, but rather the whole GalleryView. It's really annoying as if the user scrolls through the gallery it will jump back to last known position when one of the reqeusted images is ready to be shown.
Same happens if i'm just dragging the gallery to one side and as the new image that has just came into view is ready it jumps back to last known position and i have to dragg all over again and so on and on...
So does anybody know any workaround to update just single imageView in the gallery without affecting user scrolling?
A: I have an example for you (which I wrote myself some time ago and abstracted here):
public class MyAdapter ... {
// you don't need a weak reference necessarily, in my case it was a more
// common solution so I had to do that
private List<WeakReference<ImageView>> mShownImageViews =
new LinkedList<WeakReference<ImageView>>();
public View getView(...) {
if (view == null) {
// create your view
mShownImageViews.add(new WeakReference(theImageViewToUpdate));
}
// set your data
// If you set null the image view will never be updated
// you have to set the image here then
imageView.setTag(imageAvailable ? null : "someUniqueIdForYourImage");
}
public void imageLoaded(String someUniqueIdForYourImage, Bitmap theImage) {
for (WeakReference<ImageView> r : mShownImageViews) {
ImageView iv = r.get();
if (iv != null && iv.getTag() != null
&& iv.getTag().equals(someUniqueIdForYourImage)) {
iv.setImageBitmap(theImage);
iv.setTag(null);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I get the TargetOutputs of an MSBuild task in a Rake/Albacore script? MSBuild can provide the list of project output if you define an Output element like below
<MSBuild Projects="YourSln.sln">
<Output ItemName="YourProjectOutputs" TaskParameter="TargetOutputs"/>
</MSBuild>
Can I get that list with Rake/Albacore?
A: I can't find any way to provide an Output parameter to MSBuild on the command line, except through a .csproj or .target file. So, I don't think it's something we can fix by introducing more features on the Albacore msbuild task (which just invokes msbuild in the shell).
You can still get the list of project/solution output using regular Ruby/Rake. It's not perfect, but start with a single msbuild OutputPath
msbuild :msbuild do |msb|
msb.solution = 'YourSln.sln'
msb.properties :configuration => :Debug, :outputpath => './bin/Debug'
msb.targets = [ :Clean, :Build ]
end
And define a FileList that takes in all the items from that directory (and sub-directories)
msbuild_output = FileList['./bin/Debug/**/*']
You could define just .exe or .dll files, but you wouldn't know if they were actually msbuild output or post-build copy events or content or whatever. That's the downside.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Redirect / URL to /homepage/index/en one using RewriteEngine I have a .hraccess that displays homepage and language in "/homepage/index/en" style.
I want to Redirect (Using 301 code) requests to "site.com" to "site.com/homepage/index/en" using RewriteEngine.
I tried this:
RewriteRule ^/$ /homepage/index/en [R]
But this doesn't work!
How can I do this?
Thanks
A: Try these one of these should work:
RewriteRule ^/?$ /homepage/index/en [R=301]
OR
RewriteRule ^/?$ homepage/index/en [R=301]
OR (the following one also works if there is a query string like site.com/?a=46&b=47
RewriteRule ^/?(\?.*)?$ homepage/index/en [R=301]
And If you want any query string following the site.com/ to be appended you can use the QSA flag:
RewriteRule ^/?(\?.*)?$ homepage/index/en [R=301,QSA]
By the way questions pertaining to server configuration are more suited for ServerFault.com
A: The problem was other RewriteRules !I added [L] flag and problem solved:
RewriteRule ^/$ /homepage/index/en [R,L]
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: table in the android I have two table in a data base:
1) student
#_id## name ##
1 Bill
2) students_mark
#_id# stud_id ## date ## marks
1 1 12 50
1 1 13 30
and I need to make this all came to the table with a title or not
marks should be changed and then overwritten in the database.
table should look like this:
name# # marks#
# 1 # 2 # 3 # 4 # <<<date
Bill # 60 # 43 # 30 # 23 #
tony # 34 # 34 # 33 # 32 #
etc
HOW DO THAT IN THE ANDROID? explain, please.
A: First Look at this tutorial:
http://developer.android.com/resources/tutorials/views/hello-tablelayout.html
After that put id of column & row set dynamic data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does the compiler benefit from C++'s new final keyword? C++11 will allow to mark classes and virtual method to be final to prohibit deriving from them or overriding them.
class Driver {
virtual void print() const;
};
class KeyboardDriver : public Driver {
void print(int) const final;
};
class MouseDriver final : public Driver {
void print(int) const;
};
class Data final {
int values_;
};
This is very useful, because it tells the reader of the interface something about the intent of the use of this class/method. That the user gets diagnostics if he tries to override might be useful, too.
But is there an advantage from the compilers point of view? Can the compiler do anything different when he knows "this class will never be derived from" or "this virtual function will never be overridden"?
For final I mainly found only N2751 referring to it. Sifting through some of the discussions I found arguments coming from the C++/CLI side, but no clear hint why final may be useful for the compiler. I am thinking about this, because I also see some disadvantages of marking a class final: To unit-test protected member functions one can derive a class and insert test-code. Sometimes these classes are good candidates to be marked with final. This technique would be impossible in these cases.
A: I can think of one scenario where it might be helpful to the compiler from an optimisation perspective. I'm not sure if it's worth the effort to compiler implementers, but it's theoretically possible at least.
With virtual call dispatch on a derived, final type you can be sure that there is nothing else deriving from that type. This means that (at least in theory) the final keyword would make it possible to correctly resolve some virtual calls at compile time, which would make a number of optimisations possible that were otherwise impossible on virtual calls.
For example, if you have delete most_derived_ptr, where most_derived_ptr is a pointer to a derived, final type then it's possible for the compiler to simplify calls to the virtual destructor.
Likewise for calls to virtual member functions on references/pointers to the most derived type.
I'd be very surprised if any compilers did this today, but it seems like the kind of thing that might be implemented over the next decade or so.
There might also be some millage in being able to infer that (in the absence of friends) things marked protected in a final class also effectively become private.
A: Virtual calls to functions are slightly more costly that normal calls. In addition to actually performing the call, the runtime must first determine which function to call, which oftens leads to:
*
*Locating the v-table pointer, and through it reaching the v-table
*Locating the function pointer within the v-table, and through it performing the call
Compared to a direct call where the address of the function is known in advance (and hard-coded with a symbol), this leads to a small overhead. Good compilers manage to make it only 10%-15% slower than a regular call, which is usually insignificant if the function has any meat.
A compiler's optimizer still seeks to avoid all kinds of overhead, and devirtualizing function calls is generally a low-hanging fruit. For example, see in C++03:
struct Base { virtual ~Base(); };
struct Derived: Base { virtual ~Derived(); };
void foo() {
Derived d; (void)d;
}
Clang gets:
define void @foo()() {
; Allocate and initialize `d`
%d = alloca i8**, align 8
%tmpcast = bitcast i8*** %d to %struct.Derived*
store i8** getelementptr inbounds ([4 x i8*]* @vtable for Derived, i64 0, i64 2), i8*** %d, align 8
; Call `d`'s destructor
call void @Derived::~Derived()(%struct.Derived* %tmpcast)
ret void
}
As you can see, the compiler was already smart enough to determine that d being a Derived then it is unnecessary to incur the overhead of virtual call.
In fact, it would optimize the following function just as nicely:
void bar() {
Base* b = new Derived();
delete b;
}
However there are some situations where the compiler cannot reach this conclusion:
Derived* newDerived();
void deleteDerived(Derived* d) { delete d; }
Here we could expect (naively) that a call to deleteDerived(newDerived()); would result in the same code than before. However it is not the case:
define void @foobar()() {
%1 = tail call %struct.Derived* @newDerived()()
%2 = icmp eq %struct.Derived* %1, null
br i1 %2, label %_Z13deleteDerivedP7Derived.exit, label %3
; <label>:3 ; preds = %0
%4 = bitcast %struct.Derived* %1 to void (%struct.Derived*)***
%5 = load void (%struct.Derived*)*** %4, align 8
%6 = getelementptr inbounds void (%struct.Derived*)** %5, i64 1
%7 = load void (%struct.Derived*)** %6, align 8
tail call void %7(%struct.Derived* %1)
br label %_Z13deleteDerivedP7Derived.exit
_Z13deleteDerivedP7Derived.exit: ; preds = %3, %0
ret void
}
Convention could dictate that newDerived returns a Derived, but the compiler cannot make such an assumption: and what if it returned something further derived ? And thus you get to see all the ugly machinery involved in retrieving the v-table pointer, selecting the appropriate entry in the table and finally performing the call.
If however we put a final in, then we give the compiler a guarantee that it cannot be anything else:
define void @deleteDerived2(Derived2*)(%struct.Derived2* %d) {
%1 = icmp eq %struct.Derived2* %d, null
br i1 %1, label %4, label %2
; <label>:2 ; preds = %0
%3 = bitcast i8* %1 to %struct.Derived2*
tail call void @Derived2::~Derived2()(%struct.Derived2* %3)
br label %4
; <label>:4 ; preds = %2, %0
ret void
}
In short: final allows the compiler to avoid the overhead of virtual calls for the concerned functions in situations where detecting it is impossible.
A: Depending how you look at it, there's a further benefit to the compiler (although that benefit simply redounds to the user, so arguably this isn't a compiler benefit): the compiler can avoid emitting warnings for constructs with uncertain behavior were a thing to be overridable.
For example, consider this code:
class Base
{
public:
virtual void foo() { }
Base() { }
~Base();
};
void destroy(Base* b)
{
delete b;
}
Many compilers will emit a warning for b's non-virtual destructor when the delete b is observed. If a class Derived inherited from Base and had its own ~Derived destructor, using destroy on a dynamically-allocated Derived instance would usually (per spec behavior is undefined) call ~Base, but it would not call ~Derived. Thus ~Derived's cleanup operations wouldn't happen, and that could be bad (although probably not catastrophic, in most cases).
If the compiler knows that Base can't be inherited from, however, then it's no problem that ~Base is non-virtual, because no derived cleanup can be accidentally skipped. Adding final to class Base gives the compiler the information to not emit a warning.
I know for a fact that using final in this way will suppress a warning with Clang. I don't know if other compilers emit a warning here, or if they take finality into account in determining whether or not to emit a warning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: Using mod_rewrite to re-order part of a url path alphabetically Any help using mod_rewrite to re-order part of a url path alphabetically would be greatly appreciated.
The Problem: I need any path parameters after mysite.com/check/ to be re-ordered alphabetically and ideally converted to lower case.
For example:
mysite.com/check/dog/Cat/rat
would become:
mysite.com/check/cat/dog/rat
Please note that the length of path parameters will vary so re-ordering is only required when there is more then one.
I'm thinking I need to somehow capture the string after check/, split/explode it into an array/list of some sort, re-order it then add it back to the url. Problem is I'm not sure this is even possible with mod_rewrite as so far my googling hasn't turned up much.
This is for a django (python) based project. The views.py handles the path parameters like so.
def check(request, *args):
for arg in args:
arg = arg.split('/')
arg = list(set(arg)) # Remove Duplicates
arg.sort()
for a in arg:
a = a.lower()
...
Please help you mod_rewrite experts!
A: You can have mod_rewrite call external program (with MapType set to prg). It can be e.g. python script with logic copied from django.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Implement Google direction in asp.net google map direction in asp.net.
How can we achive
How to Implement Google direction in asp.net
A: "Google Maps has a wide array of APIs that let you embed the robust functionality and everyday usefulness of Google Maps into your own website and applications, and overlay your own data on top of them."
http://code.google.com/apis/maps/index.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to structure this SQL query. Combining multiple tables? NOTE: This is not a duplicate of my other question . I have changed the table structure and need new help with a new query.
So basically I'm getting notifications of new content on my website. I have 4 tables -
*
*articles
*media
*updates
*comments
Each table has a set of its own columns (I can include these if anyone wants). In my new notification system I am designing, I determine the newest content, by its timestamp. The timestamp value is an integer formatted to Unix Time.
I have just changed my table structure, before, my tables all had columns that were similar. An example, both articles and media had the column id. The SQL code I was using was this -
SELECT a.*,m.*,u.*,c.* from articles AS a
LEFT JOIN media AS m ON (m.mediaTimestamp = a.timestamp)
LEFT JOIN updates AS u ON (u.updateTimestamp = a.timestamp)
LEFT JOIN comments AS c ON (c.commentTimestamp = a.timestamp)
ORDER BY a.timestamp desc LIMIT 30
However when doing this, the code would return multiple iterations of a column in the same row (it would return an id column for articles and media!). Obviously when I tried to get the data via code, it would give me data for different tables (instead of giving me the article id, it would give me the media id).
My solution to this was to 'pretty' up my code and name all columns in a table (such as articles) with their table prefix (so id would become articleID). However now the above SQL is producing errors. Could someone 'convert'/restructure this SQL for me.
A: try this:
SELECT a.*,m.*,u.*,c.* from articles AS a
LEFT JOIN media AS m ON (m.mediaTimestamp = a.articleTimestamp)
LEFT JOIN updates AS u ON (u.updateTimestamp = m.mediaTimestamp)
LEFT JOIN comments AS c ON (c.commentTimestamp = u.updateTimestamp)
ORDER BY a.articleTimestamp desc LIMIT 30
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to create a Python Distribution like ActivePython? How would I create a Python Distro like ActivePython?
Basically its only for linux (Centos 5) platforms.
Ideally it should work like ActivePython, as in I could just untar it on a location, e.g a nfs share /path/to/python, and get my scripts to use it?
This usually is a common scenario in enterprise environments, where they dont want you to touch the standard servers builds, e.g don't install anything using RPMs / pollute the /usr/local ... etc.
Sure, I could just download & use ActivePython, but I'm more interested in the process behind creating such distros.
EDIT: This is also the main reason I can't use the EPEL Python 2.6 Packages. sigh
A: Check out this Python build script from github https://github.com/wavetossed/pybuild
and run it on a Debian or Ubuntu VM. The Python tarball that results can be run on any Linux including Centos, but the build script itself, needs to be run on a Debian derived system.
Because the build uses RUNPATH/RPATH, it can be untarred into any folder, however one bit of fixup needs to be done to make it run, and that is to run the included patchelf tool to --set-interpreter to use the new path where the binaries live. This only affects the python binary and the patchelf binary, so untar it into /data1/packages/python272 first, run patchelf and then move it to where you want it in the directory tree.
Or, you could just change $TARG before you build it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Eclipse graphiti tutorials From where can I get the Eclipse Graphiti tutorials?
For more information on this software you can get here.
Also please let me know the knowledge of Eclipse plugin development and EMF is mandatory in better understanding of Graphiti?
Eclipse Graphiti Link
A: The tutorial is installed in the Eclipse help, together with the plugin. It's also accessible online in the global Eclipse online docs, it's accesible from here, clicking in "Graphiti online help" (I don't link it directly because the link changes over time). There are no other tutorials AFAIK.
And yes, you need to know the basics of Eclipse plugin development and EMF.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the best way to determine a clients Facebook User ID in PHP on first arrival? The situation: a random user who may or may not be registered with my site (at a different computer, lets say) signs into facebook in one tab. User then opens a new tab and goes to my website.
The problem: This is the first time that the user has ever been to my website on this computer. Therefore, there are no cookies, get variables, post variables, or anything of the sort.
Server side solution: redirect the client to facebook->getLoginStatusUrl() and then use the returned information. (If user is registered with app, call will succeed). Pros: no client code required. Cons: redirects all users who land at my site.
Client solution:Not exactly sure how exactly this would work, but something along the lines of "using js sdk to determine if logged in and if so get and store client auth token to cookie and reload page". Pros: if not logged into facebook there is no refresh, no redirect necessary. Cons: page reload, client code.
Is there a better solution? Also, anyone know more specifically how to make the client solution happen?
A: You get Userid and Username from Facebook when an user logged in to your site via Facebook.
You can get those via either Javascript SDK or PHP SDK.
At that time, you can query a table which is including logging in data with that userid.
If there is one then that user is not on first arrival.
If there is no results, then add that user to your table and that user is on first arrival.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is auto outline in Webkit? What does auto mean when I write:
:focus {
outline: auto 5px -webkit-focus-ring-color
}
It is not documented here and I cannot find documentation elsewhere.
A: You're using the shorthand for the outline-* properties; auto represents the value for outline-style and auto itself means that it's up to the browser to decide what to do based on the context of the element.
A: I would just like to point out that in IE auto doesn't show anything, and you'll have to explicitly declare what type of border you want to use. Alex K's link is a good demonstration of how other popular browsers work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: validates_confirmation_of :password doesn't get triggered I have a very basic Admin model:
class Admin < ActiveRecord::Base
has_secure_password
validates_uniqueness_of :email
attr_accessible :email, :password, :password_confirmation
end
According to the manual has_secure_password also adds a validates_confirmation_of :password. If I'm correct validates_confirmation_of should always error if :password and :password_confirmation do not match - even if :password_confirmation is nil.
I'm testing with RSpec and this test fails and tells me that admin is valid:
admin = Admin.new
admin.email = 'test@example.info'
admin.password = 'secret'
admin.should be_invalid
This one passes:
admin = Admin.new
admin.email = 'test@example.info'
admin.password = 'secret'
admin.password_confirmation = ''
admin.should be_invalid
So, what the heck am I doing wrong?
A: Here's the code for has_secure_password:
# File activemodel/lib/active_model/secure_password.rb, line 32
def has_secure_password
attr_reader :password
validates_confirmation_of :password
validates_presence_of :password_digest
include InstanceMethodsOnActivation
if respond_to?(:attributes_protected_by_default)
def self.attributes_protected_by_default
super + ['password_digest']
end
end
end
As you can see it never ensures that a password confirmation is sent. You could add that yourself however, and as long as you have the form field on your page an empty string will be sent if it is unfilled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: (Un/De)compress a string in bash? Is it possible to compress/decompress a string in bash using stdin/stdout ?
I tried this but apparently it is not supported ?
hey=$(echo "hello world" | gzip -cf)
echo $hey # returns a compressed string
echo $hey | gzip -cfd
gzip: stdin is a multi-part gzip file -- not supported
I'm not well versed in linux but I read other compression utilities man pages and couldn't find a solution?
A: When you do:
hey=$(echo "hello world" | gzip -cf)
You don't have same same bytes in variable hey as you have in /tmp/myfile created by:
echo "hello world" | gzip -cf > /tmp/myfile
You get "gzip: stdin is a multi-part gzip file -- not supported" error simply because you have broken compressed data which cannot be uncompressed.
The VAR=$(...) construction is designed for working with text. This is why you get extra trailing trim for example.
A: If 33% compression rate loss is acceptable for you, then you can store base64 encoded compressed data:
me$mybox$ FOO=$(echo "Hello world" | gzip | base64 -w0) # compressed, base64 encoded data
me$mybox$ echo $FOO | base64 -d | gunzip # use base64 decoded, uncompressed data
Hello world
It will work, but each 3 (compressed) bytes will be stored in 4 bytes of text.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Hidden int property validation I am trying to validate hidden integer property can you please suggest better way
public class Model
{
[Display(Name="Theme"),Required(ErrorMessage="Please choose your theme")]
public int ThemeId { get; set; }
}
In view
@Html.Hidden(m=>m.ThemeId)
And this output <input type="hidden" bbla bla value="0"/>
Problem is currently this field is valid because 0 is default value of int property so every required in property is default valid. So I have to make it invalid.
My Solution is
Simply using Range(1,int.MaxValue) attribute for that property.
I am just asking to know that is it best solution to this problem or not . If not can you please point better solution.
A: I've hit this same problem and haven't come up with a better solution.
It's perfectly valid as you are saying that the range of values for this property is 1..MaxInt.
The only other solution I can see is to make it a nullable integer and then testing that the value is not null. However, that would include the value zero and negative values so you still have to check that it's a positive integer.
A: There are two alternatives:
*
*Use Nullable properties (int? in this case)
*Use string to allow empty fields
For this scenario, the preferred way is to make the property in the ViewModel nullable, and mark it as required.
The question Should my viewmodel value type properties be nullable? also contains some information and opinions on both approaches.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ezSQL check affected rows With adodb i checked affected rows like this:
$user_data = get_login_name($user_name, $password);
//0 = id
//1 = username
//2 = password
if (!$myDB->Affected_Rows($user_data[1], $user_data[2])) {
echo "everything good";
} else {
echo "bad";
}
How to check it with ezSQL ?
A: Old question but I ended up here wanting the answer and I've just found it. This works in ezSQL.
$db->rows_affected;
A: Ech, kind sorted it my self:
$user_data = get_login_name($user_name, $password);
//$user_data[0]->id = id
//$user_data[0]->username = username
//$user_data[0]->password = password
}
if ($user_data[0]->username == null and $user_data[0]->password == null) {
$error = '1';
$error_message = 'Incorrect username or password.';
} else {
//do my stuff
}
If somebody know better solution, please post it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Zend framework - access controller or model from the view I need to give the front-end designer the ability to choose whether or not to display a single xml feed or an mash-up, from the view.phtml file
This means I need to be able to call a method from the controller or model which then returns a variable to the view containing the requested feed(s).
So how do I access methods of the controller or model from the view?
A: you don't call controller methods in view , but you can create an instance of model (for read only purposes) inside view and then call its public methods .eg
Foo.phtml
<?php $feedsTb = new Default_Model_Feeds() ?>
<?php $allFeeds = $feedsTb->fetchAll(); ?>
A: I don't know if i got your problem right, but this is something i'd probably do in a way like
Controller:
if($this->_getParam('single')) {
$this->view->data = $model->getFeedSingleData();
$this->render('single_feed.phtml');
} else { //mashup
$this->view->data = $model->getMashUpData();
$this-render('mashup_feed.phtml');
}
Though admittedly an example like this is better off with two different actions (singleAction() and mashupAction())
But i really don't know if i got your problem figured out at all :S You may explain it further
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android web server authentication with JsonRPC I've been doing some research and it seems my best option to go with an Android-Client/PHP-Server application is by using JsonRPC. My question is, How would an authentication mechanism work?
I'd use Zend for json server and Android-json-rpc as client. Or is there a better way to do a remote authentication?
A: just like browser works . Browser also sends session id in every request using cookies . You can build the similar functionality with your java REST client by appending that id to every request .Then in php code you can do
session_id($_GET('session_id'));
session_start();
your rest client will send this session_id in every request to be identified. This way you can use php sessions just like with browsers.
A: If you want to do a simple API key then in every JSON call, the client would pass the auth key and in each method on the php side would get the key and authenticate it.
If you wanted to do session type authentication, you would have to first call an authenticate method that would return the session_id to the client. The client would then send the session key in every subsequent method. Within the methods, the server could then check the session key.
I have looked for a way to cleanly abstract authentication out of the actual json RPC methods, but if you use Zend_Json_Server directly, there is no way to do it. You may be able to extend it, but to me, it wasn't worth the hassle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The multiples of 2 Condition is not working(Counter Problem) Technically this code of mine is a kettle simulation, but the problem now is that. when it reach that 20.00 , the code for it is not working
#include<stdio.h>
#include<stdlib.h>
#include<cstdlib>
#include<time.h>
//Global Declaration for waterTemperature
double nWaterTemp;
//Function for seconds :)
void wait ( int seconds ){
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {
}
}
//Function for increasing of hit of Kettle
void behaviourOn(){
int counter = 1;
while(nWaterTemp <=100.0){
wait(1);
printf("Ticking! %d\n",counter);
if( counter%2 == 0&& nWaterTemp >=20.0 ){
nWaterTemp+=1.5/2.0;
printf("The water temp is %.2f\n",nWaterTemp);
}else if(counter%3==0){
nWaterTemp+=2.0/3.0;
printf("The water temp is %.2f\n",nWaterTemp);
}else if(nWaterTemp == 20.0){
system("cls");
printf("THE KETTLE IS NOW ON!\n");
}
counter++;
}
}
//Function for Envinronment
void environment(){
int counter2 = 0;
system("cls");
printf("THE WATER IS NOW COOLING\n");
while(nWaterTemp>=0){
counter2++;
wait(1);
printf("Ticking! %d\n",counter2);
if(counter2%3==0){
nWaterTemp -=2.0/3.0;
printf("The water temp is %.2f\n",nWaterTemp);
}
}
}
//main
int main(void){
behaviourOn();
environment();
system("pause");
}
you see, if the water temp is not higher than 20.00, it will only increase every 2 seconds but in my code there are times that each 1 second its value is changing, and also there are times that every 2 seconds it is changing ... what are the errors in this code?
if( counter%2 == 0&& nWaterTemp >=20.0 ){//THe equation changes if it reach 20.00, and the heat increases every 2 seconds
nWaterTemp+=1.5/2.0;
printf("The water temp is %.2f\n",nWaterTemp);
That's the part where it is confusing me, as you see in the condition if should increase the value the temperature every 2 seconds but the thing is it's changing every 1 second and then sometimes changed every 1 second help please
A: You should write like this:
if( nWaterTemp >=20.0 ) {
if (counter%2 == 0) {
nWaterTemp+=1.5/2.0;
printf("The water temp is %.2f\n",nWaterTemp);
}
} else if ...
otherwise when counter % 2 != 0, it will do something wrong
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: @$() notation within a makefile I’ve to run a makefile (not written by me) that contains the following line:
$(JAVAC) -verbose -classpath $(MY_CLASSPATH) -d $(BUILD_TMP) @$(SOURCE_FILES);
Where SOURCE_FILES is previously defined as:
SOURCE_FILES =$(BUILD_DIR)/sourcefiles
"@$(SOURCE_FILES)" doesn't work on my machine. Obviously this notation (when it works!) is evaluated to the file contents (one Java source file per line in my case).
Is that a notation specific to makefile or is it specific to the underlying shell? I haven't found anything on the subject on the Internet.
Thanks for your help.
A: It is specific to javac. See the manual page for javac. On mine:
$ man javac|grep -A 2 '@.*list'
@argfiles One or more files that list source files. The -J
options are not allowed in these files.
$ javac -version
javac 1.6.0_26
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Verify contribution of client-server network latency in application performance We have a typical Flash+J2EE application that makes multiple requests from client to server (over Flex remoting), which is taking quite a long time on some client systems (and hence results in poor application performance on such systems).
Now, suspecting issues with network connectivity (latency) on such client system(s), we need to identify how far does it contribute to the slow response of the application (rather than performance issues in the application itself).
So, what are the best way(s) to diagnose this on a client system (Windows)?
Note that we have tried profiling our application, which does not indicate bottlenecks there, so we just need to clearly identify the possible network issues.
Thanks.
A: Consider the use of a network impairment solution to model these uncontrolled network characteristics for the user(s) who are complaining. The industry defacto solution set is from Shunra (http://www.shunra.com), but if all you want is single session to look at the behavior of one user, then you might consider an open source solution such as WanEm, (http://wanem.sourceforge.net).
This should allow you to model the network characteristics between a single client and the server over a congested network link to observe how the single user application performance changes with different network conditions. With WanEm you get to model one logical link between the two. With Shunra you could model your whole network if you so desired. Don't accept the default installation of WanEm on a virtual machine, timing is critical to network impairment and the clock will "float" inside of a virtual machine - Go ahead and stand up a single host for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I pass origin and destination co-ordinates to the Google Maps directions API? I'm using the google maps api for directions but i'm having problems when i try to send the origin and destination as coordinates.it says in the documentation that i can do that
http://code.google.com/apis/maps/documentation/directions/#RequestParameters
but i am not sure of the format because it keeps giving me errors
Uncaught Error: Invalid value for property <origin>: [object Object]
i tried like so:
{"Ja":27,"Ka":45}
{latitude:27,longitude:45}
And all of the possible combinations above but still gives error which is weird because the objects are identical with the ones i should be sending.
A: Just provide the latidute/longitude separated by a comma as textual value:
http://maps.google.com/maps/api/directions/json?origin=27.111,45.222&destination=28.333,46.444&sensor=false
A: Use Google distancematrix API:
https://maps.googleapis.com/maps/api/distancematrix/json?origins=-0.6566588,35.0881299&destinations=-0.6433411,35.094122&mode=driving
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Optimise MySQL ORDER BY RAND() on a filtered GROUP BY query to avoid temp/indexless join MySQL "join without index" counter is incrementing as shown in various analysis tools like mysql-tuner.pl etc, having tracked down to a query which selects a random product using RAND(), I would like to optimise to help avoid this increment.
The query looks like this:
select p.*, count(u.prodid) as count from prods p
left outer join usage u on p.prodid=u.prodid
where p.ownerid>0 and p.active=1
group by p.prodid
order by rand() limit 1;
I've tried using this style also...
select p.*, count(u.prodid) as count from prods p
left outer join usage u on p.prodid=u.prodid
where prodid in
(select prodid from prods
where ownerid>0 and active=1
group by prodid order by rand() limit 1);
but MySQL doesn't support a LIMIT in an 'in' subquery...
The explain/describe looks like this...
+----+-------------+-------+-------+---------------+---------+---------+------+------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+------+------+----------------------------------------------+
| 1 | SIMPLE | p | range | ownerid | ownerid | 4 | NULL | 11 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | u | index | NULL | userid | 8 | NULL | 52 | Using index |
+----+-------------+-------+-------+---------------+---------+---------+------+------+----------------------------------------------+
2 rows in set (0.00 sec)
Whilst some of you may think "so what if it performs an index-less join", perhaps it's more an annoyance than something that could be a problem, but I appreciate there may be a better way to achieve what is needed anyway particularly as the table row counts grow...
So any ideas welcome!
A: Usually it's faster to run several queries than sorting the table by rand(). Firstly get the random number of the row:
select floor( count(*) * rand() ) random_number
from prods
where ownerid > 0 and active = 1
And then get the particular row:
select p.*, count(u.prodid) as count
from prods p
left outer join usage u on p.prodid = u.prodid
where prodid = (
select prodid from prods
where ownerid > 0 and active = 1
limit {$random_number}, 1
)
By the way your subquery returns only one field, so you can use = instead of in operator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Gzip in asp.net for Response and Request? When I use Gzip, I put some code in global.asax which zip the reponse from the server to my client.
But my page contains a lot of text ( no view state - pure text).
When I save it - it uploads it all as a plain text.
Is there any way to zip the uploaded content ?
A: You can enable GZip on the server.
By doing it in your application, do you ever have a moment where you don't want it? Why wouldn't you want it on all the time?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Webkit CSS reset There are a few CSS resets out there, but I would like one that resets all browsers to "webkit style". (Hence the webkit browsers are unaffected, just the non-webkit browsers are changed.)
I've found the default webkit stylesheet here but I cannot naively copy that, since a lot of the property names and variables are webkit-specific.
A: Instead of painfully trying to recreate a Webkit CSS reset for other web browsers (with webkit recreation hacks), you should instead use the excellent YUI CSS Reset and then design your website from there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deploying Terminal Base Java Application I'm migrating from .net to java and I'm not yet used in java application deployment. I'm used in deploying console base application that acts as a stand alone application , a mixed of tcp and udp servers with custom protocol.
I have a requirement that my ported .net application to java must be deployed inside tomcat or glass fish ( no embedding stuff ). I really don't know what technology I must used. I've been searching the net but my understanding is that tomcat is like IIS and for web application only and glass fish is somewhat an application server for hosting web application too. Can I really run my java console base application inside tomcat or glass fish? Can someone point out a good tutorials for this kind of stuff? Thanks!
EDIT 1
Ok got the reason why I need to deploy my app in tomcat/glassfish. I need to provide a web ui for my application since I'm currently using the console for user input. Now my application will not just support a custom tcp/udp server inside but also web functionality for management. Any suggestion how I can implement this is greatly appreciated, I just don't know yet what java api/technology to start with.
A: I am not sure why your requirement says that you need to run an application using a servlet container . I don't think at least based on your description your application fits servlet container programming model.
As long as you create an entry point, I think you can launch your application from command line either using java or javaw,
But If you are unable to change the requirement on the deployment to tomcat, You can do this by using a servlet to launch your application, I would read up on these things
*
*Servlet
*Deploying Servlet to tomcat
Here is one way you could do using a servlet and deploy this to tomcat
public class LaunchServlet extends HttpServlet
{
private static final long serialVersionUID = 4277145689972356257L;
//this method is run as tomcat starts up this servlet
public void init() throws ServletException
{
try
{
System.out.println("Launching my application...");
new Thread(new ApplicationLauncher()).start();
System.out.println("Launched my application successfully. ");
}
catch(Exception e)
{
throw new RuntimeException("Fail Fast: Unable to launch exception.");
}
}
class ApplicationLauncher implements Runnable
{
public void run()
{
//start you applicaton here
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Warning: Pattern match(es) are overlapped when matching on strings I am trying to make a simple url route in Haskell and can't get around the warning:
Warning: Pattern match(es) are overlapped
In a case alternative: "/" -> ...
Ok, modules loaded: Main.
the snippet:
{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.Wai.Handler.Warp (run)
import Network.Wai.Middleware.Debug (debug)
import Network.HTTP.Types (statusOK, status404)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Char8 (unpack)
import Data.ByteString.Lazy.Char8 (pack)
import qualified Data.Text.Lazy as T
import Control.Monad.IO.Class (liftIO, MonadIO)
application req = do
case unpack $ rawPathInfo req of
"/items" -> itemsJSON
"/" -> indexPage
_ -> return $ responseLBS status404 [("Content-Type", "text/plain")]
"Not found"
indexPage = do
page <- liftIO $ L.readFile "templates/index.html"
return $ responseLBS statusOK [("Content-Type", "text/html; charset=utf-8")] page
itemsJSON =
return $ responseLBS statusOK
[("Content-Type", "application/json; charset=utf-8")] "hi"
main = do
run 3000 $ debug $ application
UPD:
replaced snippet with complete program, and
$ ghc -V
The Glorious Glasgow Haskell Compilation System, version 6.12.1
A: This is a bug, and is fixed in newer versions of GHC.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Multiple WndProc functions in Win32 This might be a dumb question, but can you register multiple WndProc functions in Win32? e.g. a framework catches some messages and my app is interested in other ones - how do I catch them without modifying the framework code?
A: If I understand your intention correctly, you can do that by setting a hook. Assuming you know the thread whose message loop you'd like to hook, you can do something along these lines (unchecked):
SetWindowsHookEx(WH_CALLWNDPROC, yourHOOKPROC, NULL, theThreadId);
A: You can chain multiple message handling functions by using the function CallWindowProc instead of DefWindowProc.
Here is an example:
pfOriginalProc = SetWindowLong( hwnd, GWL_WNDPROC, (long) wndproc1 ); // First WNDPROC
pfOriginalProc2 = SetWindowLong( hwnd, GWL_WNDPROC, (long) wndproc2); // Second WNDPROC, WILL EXECUTE FIRST!!
LRESULT wndproc1( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
switch ( uMsg )
{
...
default:
return CallWindowProc( pfOriginalProc, hwnd, uMsg, wParam, lParam );
}
}
LRESULT wndproc2( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
switch ( uMsg )
{
...
default:
return CallWindowProc( pfOriginalProc2, hwnd, uMsg, wParam, lParam );
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Creation Gadget for WSO2 BAM I am creation Gadget for WSO2 BAM dashboard. I need to add the data to the chart that gives service of monitored server as result. How can I make this data as values of charts?
A: The standard way to follow is,
*
*You need to first expose this data through a service. Ex: Can be done through a data service with WSO2 DSS, a back end carbon component on top of WSO2 Carbon, or just any web service
*Then, write a gadget to consume this service. Reference: gadget tutorial
PS. There is a new BAM that will make all these things extremely easy, without having to write code. It should be available towards the end of the year.
A: You can use the BAM2 alpha2 available in here for generating gadgets according to your requirement. It is now much easier to generate a gadget with drag and drop gadget IDE comes with BAM2.
You can find more information from documentation
A: This is available using GadgetGen tool feature under latest BAM version
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Generalized chaining of non-member functions in C++ I don't know if this can even be achivieable, but given these set of functions\class:
float plus1(float x) { return x+1; }
float div2(float x) { return x/2.0f; }
template <typename T>
class chain {
public:
chain(const T& val = T()) : val_(val) {}
chain& operator<<( std::function<float (float)> func ) {
val_ = func(val_);
return *this;
}
operator T() const {
return val_;
}
T val_;
};
I can chain functions operating on floats like this:
float x = chain<float>(3.0f) << div2 << plus1 << div2 << plus1;
However, I'd like to generalize\extend this to being able to convert between types and have functions with arguments. Unfortunately I'm not smart enough to figure out how, or if, this can be done.
Too be more specific I'd like to be able to do something like this (Where operator<< is just an arbitary choice, and preferably I dont even have to write "chain" at the beginning);
Also, these are just dummy examples, I do not intend to use it for arithmetics.
std::string str = chain<float>(3.0) << mul(2.0f) << sqrt << to_string << to_upper;
or
vec3d v = chain<vec3i>(vec3i(1,1,1)) << normalize << to_vec3<double>;
Any ideas?
A: I think i see why you want to do it. It's similar to the iostream manipulators.
You will always need to start with chain(...) (i.e you will never be able to magically do something like int x = 1 << plus(2) << times(2)), but you can overload the operator int, operator float, ... to allow for the implicit conversions.
You will also need to go back and define each type (like mul) and then implement the operator<< which takes a mul or a const mul, but as a whole it's doable (but a PITA)
A: In order to get conversions between types you would want to have everything return a proxy object, that could convert to any type. Something based on boost::variant, perhaps.
You could also rewrite your operator << as a template function to make it a bit more generic:
template <class UnaryFunction>
chain& operator<<(UnaryFunction func) { _val = func(_val); return *this;}
That would allow you to use any kind of function object as an argument.
To use functions with multiple arguments, you can use the bind function. This was in boost prior to C++11, however now it is in the standard and should be available on any C++11 compatible compiler.
A: A general and extendable solution using boost::proto :
#include <iostream>
#include <boost/proto/proto.hpp>
namespace bp = boost::proto;
// -----------------------------------------------------------------------------
// perform is a callable transform that take a function_ terminal and execute it
// -----------------------------------------------------------------------------
struct perform : bp::callable
{
template<class Sig> struct result;
template<class This, class Func, class In>
struct result<This(Func,In)>
: boost::result_of<typename boost::remove_reference<Func>::type(In)> {};
template<class Func, class In>
typename result<perform(Func &,In)>::type
operator()( Func& f, In& in ) const
{
return f(in);
}
};
// -----------------------------------------------------------------------------
// Grammar for chaining pipe of functions
// -----------------------------------------------------------------------------
struct pipeline_grammar
: bp::or_<
bp::when<
bp::bitwise_or<pipeline_grammar,pipeline_grammar>
, pipeline_grammar(
bp::_right
, pipeline_grammar(bp::_left,bp::_state)
)
>
, bp::when<
bp::terminal<bp::_>
, perform(bp::_value, bp::_state)
>
> {};
// -----------------------------------------------------------------------------
// Forward declaration of the pipeline domain
// -----------------------------------------------------------------------------
struct pipeline_domain;
// -----------------------------------------------------------------------------
// A pipeline is the top level DS entity
// -----------------------------------------------------------------------------
template<class Expr>
struct pipeline : bp::extends<Expr,pipeline<Expr>, pipeline_domain>
{
typedef bp::extends<Expr, pipeline<Expr>, pipeline_domain> base_type;
pipeline(Expr const &expr = Expr()) : base_type(expr) {}
// ---------------------------------------------------------------------------
// A pipeline is an unary callable object
// ---------------------------------------------------------------------------
template<class Input>
typename boost::result_of<pipeline_grammar(pipeline,Input)>::type
operator()(Input const& in) const
{
pipeline_grammar evaluator;
return evaluator(*this,in);
}
};
// -----------------------------------------------------------------------------
// the pipeline_domain make pipeline expression macthes pipeline_grammar
// -----------------------------------------------------------------------------
struct pipeline_domain
: bp::domain<bp::generator<pipeline>,pipeline_grammar>
{};
// -----------------------------------------------------------------------------
// Takes a PFO instance and make it a pipeline terminal
// -----------------------------------------------------------------------------
template<class Func>
typename bp::result_of::
make_expr<bp::tag::terminal, pipeline_domain,Func>::type
task( Func const& f )
{
return bp::make_expr<bp::tag::terminal,pipeline_domain>( f );
}
//--------------------------- Examples --------------------
struct return_value
{
template<class Sig> struct result;
template<class This, class T>
struct result<This(T)> : bp::detail::uncvref<T>
{};
return_value(int i = 1) : factor(i) {}
template<class T>
T operator()(T const& in) const
{
return in*factor;
}
int factor;
};
struct say_hi
{
typedef void result_type;
template<class T>
void operator()(T const& in) const
{
std::cout << "Hi from value = " << in << "\n";
}
};
int main()
{
return_value r1,r2(5);
(task(r1) | task(r2) | task(say_hi())) (7); // SHould print 35
float k = 10,r;
r = (task(r2) | task(r2) | task(r2) | task(r2))(k);
std::cout << r << "\n"; // Should print 6250
}
The basic idea is to wrap function objects as proto terminals, build a small | based grammar and let the proto system deals with the composition.
A: Here is my solution for C++17.
#include <type_traits>
#include <utility>
template <class F>
struct waterfall
{
waterfall(F&& f)
: fn(std::forward<F>(f))
{}
template <class... Args>
decltype(auto) operator()(Args&&... args) const {
return fn(std::forward<Args>(args)...);
}
template <class T>
auto then(T&& t) const & {
return then_impl(fn, std::forward<T>(t));
}
template <class T>
auto then(T&& t) const && {
return then_impl(std::move(fn), std::forward<T>(t));
}
private:
F fn;
template <class In, class Out>
static auto then_impl(In&& in, Out&& out)
{
auto fn = [in = std::forward<In>(in), out = std::forward<Out>(out)](auto&&... args)
{
using InRet = std::invoke_result_t<In, decltype(args)...>;
if constexpr (std::is_invocable_v<Out, InRet>) {
return out(in(std::forward<decltype(args)>(args)...));
}
else {
in(std::forward<decltype(args)>(args)...);
return out();
}
};
return waterfall<decltype(fn)>(std::move(fn));
}
};
And use it like this
int main()
{
// Create a chain
waterfall chain([](const char* s) {
return 42;
})
.then([](auto x) {
// x = 42 here
return x + 1;
})
.then([] {
// Ignoring value from previous function.
// Send double to next one.
return 3.14;
})
.then([](double value) {
// etc...
return true;
});
// chain signature is now bool(const char*)
// Now call our functions in chain
bool ret = chain("test");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Jquery Issue About ScrollTop coding if($('html, body').scrollTop().val() > 50){
$("#scrolltop").css("display", "block");
};
Those're my codes, but of course don't work.
How can I apply to it with "if" questioning.. ?
A: Im not quite sure what you mean.
Do you have an element "scrolltop" which you only want to display if the body has scrolled passed 50px?
If so, here is an example: http://jsfiddle.net/t52HN/4/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write dynamic INNER JOIN in PDO I want to write a dynamic function for INNER JOIN in pdo. I want send table name and condition to function and create dynamic query in function.
SELECT *
FROM :tbl
INNER JOIN :tbl2 ON :tbl1.id = :tbl2.id
WHERE :tbl2.id = :value;
I want to passed tbl, tbl2, tbl.id, tbl2.id, and WHERE condition to function and create dynamic query and biindParam with PDO then execute query.
How can I write this function?
A: you can't bind identifiers.
So, table and field names should be added into query directly.
However, if you need such a dynamic join, it's most likely because your database setup is wrong.
And you'd better normalize it. So, you will have more reliable database yet will be no need in such dynamical joins
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP counter using files I found a really innovative and decent counter which lets me put the counter code on the main index.php page and then view the counter through my back end system, however although it kind of works it breaks the main page because of PHP errors, becasue of the old code; I know some PHP but not enough to know what im looking to fix.
counter tutorial: counter tutorial link
count.db
0%0%0%0000 00 00%0
counter.php:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$file_ip = fopen('counter/ip.db', 'rb');
while (!feof($file_ip)) $line[]=fgets($file_ip,1024);
for ($i=0; $i<(count($line)); $i++) {
list($ip_x) = split("\n",$line[$i]);
if ($ip == $ip_x) {$found = 1;}
}
fclose($file_ip);
if (!($found==1)) {
$file_ip2 = fopen('counter/ip.db', 'ab');
$line = "$ip\n";
fwrite($file_ip2, $line, strlen($line));
$file_count = fopen('counter/count.db', 'rb');
$data = '';
while (!feof($file_count)) $data .= fread($file_count, 4096);
fclose($file_count);
list($today, $yesterday, $total, $date, $days) = split("%", $data);
if ($date == date("Y m d")) $today++;
else {
$yesterday = $today;
$today = 1;
$days++;
$date = date("Y m d");
}
$total++;
$line = "$today%$yesterday%$total%$date%$days";
$file_count2 = fopen('counter/count.db', 'wb');
fwrite($file_count2, $line, strlen($line));
fclose($file_count2);
fclose($file_ip2);
}
?>
showcounter.php
<table>
<tr>
<th colspan="2">Unique visitors</th>
</tr>
<tr>
<td><b>Today</b></td>
<td>
<?php
$file_count = fopen('counter/count.db', 'rb');
$data = '';
while (!feof($file_count)) $data .= fread($file_count, 4096);
fclose($file_count);
list($today, $yesterday, $total, $date, $days) = split("%", $data);
echo $today;
?>
</td>
</tr>
<tr>
<td><b>Yesterday</b></td>
<td>
<?php
echo $yesterday;
?>
</td>
</tr>
<tr>
<td><b>Total</b></td>
<td>
<?php
echo $total;
?>
</td>
</tr>
<tr>
<td><b>Daily average</b></td>
<td>
<?php
echo ceil($total/$days);
?>
</td>
</tr>
</table>
Thanks for all replies, much appreciated, and hopefully we can get this working again:)
EDIT: just crashed my browser to get you guys some error messages :P
Warning: fopen(ip.db) [function.fopen]: failed to open stream: No such file or directory in /counter/counter.php on line 4
Warning: feof(): supplied argument is not a valid stream resource in /counter/counter.php on line 5
Warning: fgets(): supplied argument is not a valid stream resource in /counter/counter.php on line 5
Warning: feof(): supplied argument is not a valid stream resource in /counter/counter.php on line 5
It does say, "no such file" but ip.db IS uploaded to /counter/
Contents of the /counter/ folder:
count.db
counter.php
ip.db
index.html
showcounter.php
ip and count.db, chmod'd to 666
A: You say your file is named countdb.php, but there is not one single reference to that filename in the code. Make sure you have your files named correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to convert a strongname public key (snk) to ? I have a file testpublic.snk which holds a public key. I have created it with sn -p c:\test.snk c:\testpublic.snk.
Now, how can I convert testpublic.snk to a string like
<RSAKeyValue><Modulus>z140GwiEJvuGOVqMQUxnojILR8rn2SFOViigoloku59H5eqzqca3Hdyl/jc+Acdb5ktzhBOOyGFElE0/Btlvw9cXVVW8zcT0MBOCaq25D1rSVYLGGM6nXzBrl1XsrBEadZbCgkcF5rw8GaYcYakijaltP1/hvxhbMOARM9VCQ50=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>
Thanks for your help.
A: Simply re-use the (MIT.X11 licensed) code from Mono.Security StrongName class, available in github, then call ToXmlString on it's RSA property. Something like:
Console.WriteLine (new StrongName (data).RSA.ToXmlString (false));
Where data is a byte[] containing the content of your snk file. Also you can use true if you want the private key in your XML (it will work if it was available fom your snk file).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to lock in one thread and wait until lock will be released in another thread I just want wait in main thread until some event in run.
How can I do it using java.util.concurency classes?
Thanks!
P.S.
Does my question realy explained bad o correctness check is shit? I mean this message
"Oops! Your question couldn't be submitted because:
Your post does not have much context to explain the code sections; please explain your scenario more clearly."?
public class LockingTest {
private Lock initLock = new ReentrantLock();
@Test
public void waiting(){
initLock.lock();
final Condition condition = initLock.newCondition();
long t1= System.currentTimeMillis();
Thread th = new Thread(new Runnable(){
@Override public void run() {
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {}
initLock.unlock();
}
});
th.start();
try {
condition.await(3000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {}
long t2= System.currentTimeMillis();
System.out.println(t2-t1);
}
}
A: you can use CountDownLatch( http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html ).
1. init countdownlatch with count value 1
2. start another thread (Thread A )
3. call await() in main thread
4. call countdown() in Thread A
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: ASP.NET Label Inside UpdatePanel Not Updating I am new to ASP.NET and I'm trying to get a Label to update with some information that is grabbed when I hit a button. The click function is called and returns just fine (I've debugged and stepped through the whole thing). The only thing that doesn't work is where I set the text of the Labels I'm trying to update.
This is the function that gets called on the button click:
Protected Sub submitbutton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbutton.Click
Dim res As String() = query(email1.Text)
If Not res Is Nothing Then
url1.Text = res(0)
date1.Text = res(1)
End If
End Sub
I know it goes into the if and tries to set the text but nothing happens on the client side.
This is the UpdatePanel I have:
<asp:UpdatePanel ID="UpdatePanelSettings" runat="server" UpdateMode="Always" >
<Triggers>
<asp:AsyncPostBackTrigger ControlID="submitbutton" EventName="click" />
</Triggers>
<ContentTemplate>
<table>
<tr>
<td>Emails</td><td>Url Parsed</td><td>Date Created</td>
</tr>
<tr>
<td>
<asp:TextBox runat="server" ID="email1" Width="300" />
</td>
<td>
<asp:Label runat="server" ID="url1" Text="-" />
</td>
<td>
<asp:Label runat="server" ID="date1" Text="-" />
</td>
</tr>
<tr>
<td colspan="3"><asp:Button ID="submitbutton" runat="server" Text="Submit" /></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
As I said, I know the trigger works because I've stepped through the code when it is called. I know that you also need a ScriptManager, which I have right inside the form element that comes in the Site.Master file (I really just stuck stuff in the default template. It's just a proof of concept project).
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
From all the articles I've found on the web, this should be all I need. One article mentioned having to do things with the Web.Config, but it said that for VS 2005 and I'm using 2010. It mentioned you didn't have to change anything in 2008, so I figured the same was true for 2010. What am I missing that I need to get the labels to update?
A: Can you try removing the section.
<Triggers>
<asp:AsyncPostBackTrigger ControlID="submitbutton" EventName="click" />
</Triggers>
Then change the UpdatePanel by add ChildrenAsTriggers="true" to it.
<asp:UpdatePanel ID="UpdatePanelSettings" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" >
In theory, this should be exactly the same as the way you have it above, but just trying to help you debug it.
A: I haven't worked with this for a while, but you may need to explicitly call:
UpdatePanelSettings.Update()
At the end of your command.
.
Give it a try anyway.
A: 1) Is it possible res is two blank items?
2) Is there any other code that touches the two labels (like when the form loads)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: height of wrapper div to inside floated items? I have a div 'a' ( simple div)
and div 'b' which is float:left;
I was wondering what is the correct method to set the height of div 'a' to be a perfect wrapper for div 'b' ( in terms of height).
i know there are some options :
1)set 'a' : overflow:hidden ( it works).
2)set at the end of 'b' div with 'clear':both
*
*) i would love to know more options ( besides fixed height to div 'a'...)
*) and of course , what is the better way.
A: @Royi Namir; there others mades like clearfix like this
css:
.clearfix:after {
display: block;
content: " ";
clear: both;
}
as per the better way clearfix & overflow:hidden both are better because you no need to write any extra markup in your html for every element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to audit log member.createuser My ASP.NET application is Membership enabled and users with Administration Role can create other user with different roles.
Is there an way that i can maintain an audit log of user creation, so i can keep a track that which Administrator created which user.
Thanks in advance.
A: Sure the framework uses a stored procedure (forget the exact name, but it's named appropriately). In that proc, add an insert to insert an audit record.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get form validator script to work with an array? I am trying to implement the JavaScript Form Validation script from Javascript-Coder.com that can be found here.
I have it working for elements on a form, but I am wondering how to get it to work with an array. Specifically I have a form on a webpage here, which the user can add rows to. Then I have the following form:
<form method="post" name="booking" id="booking" action="bookingengine.php">
<fieldset>
<h2>Waged/Organisation Rate</h2>
<p>
<input type="text" name="name[]" id="name">
<input type="text" name="email[]" id="email">
<input type="text" name="organisation[]" id="organisation">
<input type="text" name="position[]" id="position">
</p>
<p><span class="add">Add person</span></p>
</fieldset>
<fieldset>
<h2>Unwaged Rate</h2>
<p>
<input type="text" name="name2[]" id="name2">
<input type="text" name="email2[]" id="email2">
</p>
<p><span class="add">Add person</span></p>
</fieldset>
<p><input type="submit" name="submit" id="submit" value="Submit and proceed to payment page" class="submit-button" /></p>
</form>
Currently the form validator script looks like this:
<script language="JavaScript" type="text/javascript">
var frmvalidator = new Validator("booking");
frmvalidator.addValidation("email[]","req","Please enter a valid email address");
frmvalidator.addValidation("email[]","email","Please enter a valid email address");
</script>
But, if the user adds a second row to the top section of the form, the script only validates the email address in the first row, and I am wondering how I would get it to validate every row that is added to the form as well.
ADDITIONAL INFORMATION
Following the advice of Melsi the script for generating the form and handling validation has been completely rewritten. The answer by Melsi below includes the following features that I requested (most of which were in the original script too):
*
*The form is now empty on page load, and all rows (text boxes) are added dynamically by the user using buttons.
*The default values for each text box show when a new row is added with a unique colour.
*When the user clicks in each text box the colour for text and background changes.
*A 'Remove' button is added to the end of each row so that rows can be deleted.
VALIDATION NEEDED
The validations needed for each row are as follows:
*
*Name: is not 'Name' (Message: "Please enter your name"), max 100 characters (Message: "Your name should be less than 100 characters")
*Email: is a valid email address (Message: "Please enter a valid email address"), max 100 characters (Message: "Your email address should be less than 100 characters")
*Position: is not 'Position' (Message: "Please enter your position or N/A if not applicable"), max 100 characters (Message: "Your position should be less than 100 characters")
*Organisation: is not 'Organisation' (Message: "Please enter your organisation or
N/A if not applicable"), max 100 characters (Message: "Your organisation
should be less than 100 characters")
Then I would need a validation for submitting the form which checks that a row has been added to the form, with the message "Please add at least one person to your booking"
Example of validation:
//validate-name
box=document.getElementById(caller).name.charAt(0);
if(box=='n'){
if((document.getElementById(caller).value)=='Name')
{
alert('Please enter your name')
document.getElementById('message').innerHTML="<span>Please enter your name</span>";
//put focus back again if you like
document.getElementById(caller).focus();
return;
}
}
//if code comes here = validation success
document.getElementById(caller).style.backgroundColor = '#F5FEC1';
document.getElementById('message').innerHTML="<span style="+dbq+"background-color: #A3BB00"+ dbq+">Thanks!</span>";
}
A: You can add an onchange event on every field even in the dynamic ones, they will call the validator as sson as they are changed so the user knows in no time if it was a valid entrance.
==========edited part, there was some code here that is replaced with a better version=====
I wrote this code in a hurry, color example is applied, new line example is too, remove is added too, empty box on focus is applied too and all other things asked.
<html>
<head>
<script type="text/javascript">
/**
A dynamic name is assigned to a new field created.
*/
var id=0;
var dbq="\"";
/************************* addRow function end ******************************************/
function addRow(count)
{
/**
Decide what fieldset is going to host the row
*/
var myFieldset='fieldset2';
var section='2';
if(count==4){
myFieldset='fieldset1';
var organisationID = id++;
var positionID = id++;
var section=''
}
/**
Create ids
*/
divID = id++;
nameID = id++;
emailID = id++;
/**
The row will be hosted in a div
*/
var myDiv = document.createElement("div");
myDiv.setAttribute("id", divID);
/**
Create the text boxes
*/
myDivInnerHTML=
'<input type=text name=name'+section+'[]'+' value=Name id='+nameID+
' onFocus='+dbq+'emptyTheBox('+nameID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+nameID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+nameID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=email'+section+'[]'+' value=Email id='+emailID+
' onFocus='+dbq+'emptyTheBox('+emailID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+emailID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+emailID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+'>' ;
/**
Decide if we need 4 or 2 boxes
*/
if(count==4)
myDivInnerHTML=myDivInnerHTML+
'<input type=text name=organisation'+section+'[]'+' value=Organisation id='+organisationID+
' onFocus='+dbq+'emptyTheBox('+organisationID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+organisationID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+organisationID+');'+dbq+
' style='+dbq+'color:#66634F;'+dbq+' >'+
'<input type=text name=position'+section+'[]'+' value=Position id='+positionID+
' onFocus='+dbq+'emptyTheBox('+positionID+');'+dbq+
' onkeyup='+dbq+'changeInputColor('+positionID+');'+dbq+
' onBlur='+dbq+'fieldValidator('+positionID+');'+dbq+
' style='+dbq+'color:#66634F'+dbq+'>' ;
/**
Create a button to remove the row too.
*/
myDivInnerHTML=myDivInnerHTML+
'<input type=button class="remove" value="Remove" onClick='+dbq+'removeDiv('+divID+','+ myFieldset +');'+dbq+' >';
/**
Add the div-row to the fieldset
*/
myDiv.innerHTML = myDivInnerHTML;
document.getElementById(myFieldset).appendChild(myDiv);
}
/************************* addRow function end ******************************************/
/**
Change the color of the text being entered
*/
function changeInputColor(caller){
document.getElementById(caller).style.color = 'black';
}
/**
Remove a row on demand
*/
function removeDiv(divID, myFieldset){
myFieldset.removeChild(document.getElementById(divID));
}
/**
Empty the box on initial click
*/
function emptyTheBox(caller)
{
var val=document.getElementById(caller).value;
if(val=='Name' || val=='Email' || val=='Organisation' || val=='Position' )
document.getElementById(caller).value='';
}
/**
Display a message
*/
function echo(message)
{
document.getElementById('message').innerHTML="<h3>"+message+"</h3>";
}
/**********************Validates a single field, return false on fail************************/
function fieldValidator(caller)
{
var error='';
/**
Identify the field (if it is email, name etc) by getting the first character
which is always the same,also get its value and full name
*/
var currentFieldCategory = document.getElementById(caller).name.charAt(0);
var currentFieldValue = document.getElementById(caller).value;
var currentField = document.getElementById(caller);
/**
Check for empty value
*/
if(currentFieldValue == '')
{
echo('Please fill the data!');currentField.focus();
return 'Please fill the data!';
}
/**
Check if default value left behind
*/
if(currentFieldValue.toLowerCase()=="name" || currentFieldValue.toLowerCase()
=="email" || currentFieldValue.toLowerCase()=="organisation" ||
currentFieldValue.toLowerCase()=="position" )
{
echo('Please check you entry, default data left behind!');currentField.focus();
return 'Please check you entry, default data left behind!';
}
/**
Validate the NAME field
*/
if(currentFieldCategory=='n')
{
if(currentFieldValue.match(/^[ |'|-]/)||!(/^[a-zA-Z- ']*$/.test(currentFieldValue))
|| currentFieldValue.length<4 || currentFieldValue.length>70)
{
echo('Non valid name found!');currentField.focus();
return 'Non valid name found!';
}//inner if
}//outer if
/**
Validate a non empty EMAIL name field
*/
if(currentFieldCategory=='e')
{
var atpos=currentFieldValue.indexOf("@");
var dotpos=currentFieldValue.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=currentFieldValue.length)
{
echo('Non valid email found!');currentField.focus();
return 'Non valid email found!';
}//inner if
}//outer if
/**
Validate a non empty ORGANIZATION name field
*/
if(currentFieldCategory=='o')
{
if(currentFieldValue.length<2 || currentFieldValue.length>50)
{
echo('Use at least 2 letters and less than 50 for your organisation.');
currentField.focus();
return 'Use at least 2 letters and less than 50 for your organisation.';
}//inner if
}//outer if
/**
Validate a non empty POSITON name field
*/
if(currentFieldCategory=='p')
{
if(currentFieldValue.length<7 || currentFieldValue.length>40)
{
echo('Use at least 7 letters and less than 40 to describe your position.');
currentField.focus();
return 'Use at least 7 letters and less than 40 to describe your position.';
}//inner if
}//outer if
/**
Now on success do the rest
*/
document.getElementById(caller).style.backgroundColor = '#FF9900';
document.getElementById('message').innerHTML="";
return true;
}
/*****************fieldValidator ***function ends*****************************************/
/*******************************************************************************************/
function finalValidator()
{
/**
Get the form object
*/
var myForm=document.getElementById('booking').elements;
/**
Check if the form has no rows, for now 3 indicates no rows,
BE CAREFULL it might change if more buttons added,
just alert the length to see.
*/
if(myForm.length==3)
return false;
/**
Iterate through the form for all fields
*/
for(var i = 0; i < myForm.length; i++)
{
//If it is a text field validate it
if(myForm[i].type=='text')
{
var validation = fieldValidator(myForm[i].id);
if(validation!==true)
{
echo (validation);
return false;//prevent submit
}//validation if
}//field type if
}//for loop
}//function
/*******************************************************************************************/
</script>
</head>
<body bgcolor=gray>
<div id="add-buttons"><span class="add" onclick="addRow(4);"><input type="button" class="button" value="Add Waged Person"></span><span class="add" onclick="addRow(2);"><input type="button" class="button" value="Add Unwaged Person"></span></div>
<div id="message" ></div>
<div id="form-wrap">
<form method="post" name="booking" id="booking" action="bookingengine.php">
<fieldset id="fieldset1">
<div class="subtitle">Waged/Organisation Rate</div>
</fieldset>
<fieldset id="fieldset2">
<div class="subtitle">Unwaged Rate</div>
</fieldset>
<!-- return finalValidator will allow submit only if fields are validated-->
<p><input type="submit" name="submit" id="submit" onClick="return finalValidator();"
value="Submit booking" class="submit-button" /></p>
</form>
</body>
</html>
Validation added.
The array and the color things are a bit trivial and you should show what effort you have done here your self.It is interesting to be involved only when you see the will on someone.
A: I've decided to add an other answear cause there is some other-additional things I want to mention about debuging.
As for the error you mention it caused by this line:
<div id="booking" style="font-size:16px;margin-bottom:10px;padding:5px">Please add the number of people
Why did this happen?
If you look closer it has got an id assigned the value booking, but you also have the html form assigned the same id, this create a conflict as javascript does not know which one do you mean.
Advices
-You always devide things when debuging, this means that you had to run the script above on its own, if it run okay and then when embeded in you application did not then you know 100% there is a conflict.
-You mentioned a particular function creating the problem (and you were right), then you had to go inside the function and put one alert('Hello there whatever!'); on a line at a time starting from the very very top, as soon an alert is not poped then you know which line has the problem. Then you alert the variables on this line to see if they have the value they should have... most probably the value will not have the value must have and you problem has beome very small already.
That's for now, take care of the id's, they must be unique! If you see my example I assign an increasing index on them at the end
id="someElement"+(id++);
Sorry if this is too much to read... but debuging the wrong way can be more pain than that (there are some god tutorials on debuging!).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use less variables with $_GET I've noticed that instead of using:
http://yoursite.com/index.php?page=4
I could just use:
http://yoursite.com/index.php?4
How to do this in php and JavaScript?
A: In the example you have posted, now 4 is the key instead of value.
If you are passing ONLY one parameter via query string this is doable,otherwise you wont know in PHP what is what without a key for your parameter.
In the particular example you can get it like this in PHP
$id = null
if(!empty($_GET)){
$keys = array_keys($_GET);
// verify that the first key contains only digits, and use it as id
// ctype_digit does not work here because the key is now an int so use is_numeric
if(is_numeric($keys[0]))
$id = $keys[0];
}
I do not know what do you want to do in Javascript here.
Also if you are trying to generate SEO friendly URLs I would suggest that you look into URL Rewriting.
A: $page = $_SERVER['QUERY_STRING'];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: One of my queries now only returns one record after working fine for 10 years - I did not change any code I've had a mysql database on my website for about 10 years. I recently (5 or 6 months) ago had to upgrade to version 5.x and did so without any problems. My database uses four tables and has been working fine until about a week ago. One of my tables is now returning only one record even when there are many records matching the query. I have not made any changes to the code for many years. I have been researching this problem for several hours and have not come up with any answers and so I'm posting the code here for some help. This code is querying a flat file with 11,549 records, each record containing 15 fields.
<?php
mysql_connect ('localhost:/tmp/mysql5.sock', 'my_user_name', 'my_password') or
die("Could not connect: " . mysql_error());
mysql_select_db (virtualc_sac);
$result = mysql_query ("select * from doublestar
where con = '$con' and sep > '$sep1' and sep < '$sep2'
group by 'name' order by '$order'");
echo ("<tr><td colspan='14' align='center'><font face='arial, helvetica' size='2'>
<b>Search Results for<br>
Constellation=$con and Separation > $sep1 arc minutes
and Separation < $sep2 arc minutes, Sorted by $order</b><br><br></td></tr>");
if (mysql_num_rows($result) == 0) {
echo "<tr><td width='10'></td>
<td width='470' colspan='14' align='left'><font face='arial, helvetica' size='2'>Sorry, no records were found. Try altering your selection criteria. Hitting the BACK button on your browser will show you your previous selection criteria.</td>";
} else {
while ($row = mysql_fetch_array($result)) {
{
echo "<tr>
<td width='80' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Name
</td>
<td width='50' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Star
</td>
<td width='50' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>RA
</td>
<td width='50' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Dec
</td>
<td width='30' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Comp
</td>
<td width='50' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Mag1
</td>
<td width='50' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Mag2
</td>
<td width='30' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Sep
</td>
<td width='30' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>PA
</td>
<td width='60' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>U2000
</td>
<td width='30' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Spec
</td>
<td width='240' align='left' valign='bottom'>
<font face='arial, helvetica' size='1'>Notes
</td>";
echo "<tr>
<td width='80' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["name"];
echo "</td>";
echo "<td width='50' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["star"];
echo "</td>";
echo "<td width='50' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["ra"];
echo "</td>";
echo "<td width='50' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["decl"];
echo "</td>";
echo "</td>";
echo "<td width='30' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["comp"];
echo "</td>";
echo "<td width='50' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["mag1"];
echo "</td>";
echo "<td width='50' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["mag2"];
echo "</td>";
echo "<td width='30' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["sep"];
echo "</td>";
echo "<td width='30' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["pa"];
echo "</td>";
echo "<td width='60' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["u2000"];
echo "</td>";
echo "<td width='30' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["spec"];
echo "</td>";
echo "<td width='240' align='left' valign='top'>
<font face='arial, helvetica' size='1'>";
echo $row["notes"];
echo "</td></tr>";
}
}
}
?>
A: @DuaneFrybarger I would start by making sure your database is ok. Personally, my favorite tool is phpMyAdmin, and use the SQL tab to type in your query and run it. If all of the records come up as expected, then the database is ok. If not, then run a simple SELECT * ... query to make sure all of the records are there. If all of this goes ok, then you need to go through all of your HTML again. Some other thoughts:
*
*your code to create the row of headings is inside the while-loop - do you want a header row for each record?
*there's an extra </td> as mentioned previously right after echo $row["decl"];
*are the variables assigned earlier in your script from $_POST-variables?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to mock context while unit testing code using VirtualPathUtility.GetAbsolute method I am running unit tests on code which uses VirtualParthUtility.GetAbsolute, but am having problems mocking the context for this to work.
I've set up a mock context with Moq as follows
private Mock<HttpContextBase> MakeMockHttpContext(string url) // url = "~/"
{
var mockHttpContext = new Mock<HttpContextBase>();
// Mock the request
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(x => x.ApplicationPath).Returns("/");
mockRequest.Setup(x => x.Path).Returns("/");
mockRequest.Setup(x => x.PathInfo).Returns(string.Empty);
mockRequest.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(url);
mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);
// Mock the response
var mockResponse = new Mock<HttpResponseBase>();
mockResponse.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);
mockHttpContext.Setup(x => x.Response).Returns(mockResponse.Object);
return mockHttpContext;
}
And attached this to an MVC Controller
_myController.ControllerContext = new ControllerContext(MakeMockHttpContext("~/").Object, new RouteData(), _slideSelectorController);
The code that runs during the test hits the line:
venue.StyleSheetUrl = VirtualPathUtility.ToAbsolute(venue.StyleSheetUrl); // input like "~/styles/screen.css"
Every time this runs, it steps into System.Web.VirtualPathUtility, with the problem that the "VirtualParthString" to be returned always throws an exception:
public static string ToAbsolute(string virtualPath)
{
return VirtualPath.CreateNonRelative(virtualPath).VirtualPathString;
}
The reason for the exception is easy to see in System.Web.VirtualPathString:
public string VirtualPathString
{
get
{
if (this._virtualPath == null)
{
if (HttpRuntime.AppDomainAppVirtualPathObject == null)
{
throw new HttpException(System.Web.SR.GetString("VirtualPath_CantMakeAppAbsolute", new object[] { this._appRelativeVirtualPath }));
}
if (this._appRelativeVirtualPath.Length == 1)
{
this._virtualPath = HttpRuntime.AppDomainAppVirtualPath;
}
else
{
this._virtualPath = HttpRuntime.AppDomainAppVirtualPathString + this._appRelativeVirtualPath.Substring(2);
}
}
return this._virtualPath;
}
}
Through the Watch Window I can see that _virtualPath and HttpRuntime.AppDomainAppVirtualPathString are both null, hence it throws an exception.
If _virtualPath were set, the exception wouldn't happen. But after the VirtualPath.Create method has created a new VirtualPath object, it doesn't set the _virtualPath property before it is returned. An extract from the Create method up to this point is:
VirtualPath path = new VirtualPath();
if (UrlPath.IsAppRelativePath(virtualPath))
{
virtualPath = UrlPath.ReduceVirtualPath(virtualPath);
if (virtualPath[0] == '~')
{
if ((options & VirtualPathOptions.AllowAppRelativePath) == 0)
{
throw new ArgumentException(System.Web.SR.GetString("VirtualPath_AllowAppRelativePath", new object[] { virtualPath }));
}
path._appRelativeVirtualPath = virtualPath;
return path;
So if anyone can suggest how to get this unit test working, that will be very helpful!
Thanks,
Steve
A: I would just create a wrapper interface. Something like:
public interface IPathUtilities
{
string ToAbsolute(string virtualPath);
}
You can inject that into your controller. At test time, use a stub. At runtime, you'll have a class that implements IPathUtilities and calls VirtualPathUtility.ToAbsolute().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Pushing sidebar down in responsive CSS and HTML website Is there a way to make a sidebar collapse to the bottom of the page without any JavaScript when the browser reaches a certain size.
I'm creating a responsive theme that can be seen at http://flexibletheme.tumblr.com/. By resizing your browser window to below 600px, the theme goes into a linear version (just resize your browser smaller until it changes to this).
At the top the sidebar changes into a full menu, and this is the part which I want to go to the bottom instead of staying at the top.
The relevant parts of the CSS code are @media screen and (max-width: 600px) [this tells the browser to use the specified CSS when the browser is less than 600px], the sidebar using the HTML 5 element called , and each post is wrapped in .
A: Have you tried moving the entire aside block underneath the container? I'm still learning responsive web design myself, but my understanding is that if you structure your html for the smallest size you want to accommodate, you will have a cleaner layout with less hacks.
A: Place your sidebar inside your #container div and float your section left and your sidebar right.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: KeyguardManager FLAG_DISMISS_KEYGUARD for Service When the screen is turned on, I want to check is power button activated it, if yes, it will auto dismiss the keyguard and run the toast.
When the screen is turned off, the keyguard will be re-enabled. (the code works till here)
However, when the screen is OFF, and i pressed "Volume up" button, the screen turns ON. (but it goes into the loop where it detects "power" button is pressed).
The case should be it shall not activate "Dismiss keyguard" when other buttons(except "power" button) are pressed.
any help is much appreciated to solve this bug :)
another question - how do I use FLAG_DISMISS_KEYGUARD in Service?
public class myService extends Service{
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
boolean pressed = false;
Vibrator myVib;
//screen is turned on
if (!screenOn)
{
pressed = onKeyDown(26, null);
//if it turned on by power button. bug = always go into this loop
if(pressed)
{
Context context = getApplicationContext();
CharSequence text = "Service started. power button pressed";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
//dimiss keyguard
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
Context context2 = getApplicationContext();
CharSequence text2 = "SCREEN ON";
int duration2 = Toast.LENGTH_SHORT;
Toast toast2 = Toast.makeText(context2, text2, duration2);
toast2.show();
}
else
{
Context context = getApplicationContext();
CharSequence text = "Service started. NOT power button pressed";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
//screen is turned off
else {
myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
myVib.vibrate(500);
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.reenableKeyguard();
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_POWER)
return true;
else
return false;
}
}//end of myService class
A: Okay so this is not as simple as it would seem
Services cannot actually own the currently running activity but you need an activity to get a reference to the window
So you could do that bit a couple of different ways.
Turning off the screen from a service
In the answer given in this question a dummy activity is created
(one that is not inflated) and used to get the window (works but
not sure what if the uninflated activity causes a leak or other issues. Plus it seems kinda like a dirty hack)
Or.....
The CommonWares way
how can i get the current foreground activity from a service
You could handle the actual window manipulation in a callback fired when your service broadcasts an intent
to the activity that will be doing this. (Better design but a bit more archetectural reworking)
Example
Once you decide how you want to do (I would recommend #2)
The following should work but, note I have not tested it.
//Get the window from the context
WindowManager wm = Context.getSystemService(Context.WINDOW_SERVICE);
//Unlock
//http://developer.android.com/reference/android/app/Activity.html#getWindow()
Window window = getWindow();
window.addFlags(wm.LayoutParams.FLAG_DISMISS_KEYGUARD);
//Lock device
DevicePolicyManager mDPM;
mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: All Directions with google directions API Is there a way I can get all routes from my current location to "any other location"?
By any other location I mean that the map should show all valid directions to locations I haven't specified. The range (in terms of distance) of the directions may be, say, 1 mile from my current location.
The only parameter I want to provide is my current location and check which all directions I can travel over.
A: No Google Maps can't do this nativity.
Might commonly be known as "Time Travel" Maps
Can see a crude demo
http://maps.forum.nu/gm_driving_radius.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: LinearLayout at the top and at the bottom of the screen I have two different LinearLayouts inside one LinearLayout and I would like the first layout to be at the top and the second layout to be at the bottom. I tried with android:gravity="top" but it didn't work. Here is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="top">
<ImageView android:layout_height="wrap_content" android:id="@+id/imageView1"
android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow android:weightSum="2">
<Button android:text="Button" android:id="@+id/button2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
<Button android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
</TableRow>
<TableRow android:weightSum="2">
<Button android:text="Button" android:id="@+id/button3"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
<Button android:text="Button" android:id="@+id/button4"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
</TableRow>
</TableLayout>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="bottom">
<ImageView android:layout_height="wrap_content" android:id="@+id/imageView1"
android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<TableRow android:weightSum="2">
<Button android:text="Button" android:id="@+id/button2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
<Button android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
</TableRow>
<TableRow android:weightSum="2">
<Button android:text="Button" android:id="@+id/button3"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
<Button android:text="Button" android:id="@+id/button4"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"></Button>
</TableRow>
</TableLayout>
</LinearLayout>
A: You could simply add :
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1" />
between your top and bottom LinearLayout(and remove the gravity from the parent container).
A: change you parent layout as RelativeLayout instead of LinearLayout, and
for top of the parent layout set following in child layout
android:layout_alignParentTop="true"
and for bottom of the parent layout set following in child layout
android:layout_alignParentBottom="true"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Printer output from java applet is no longer in vector format? I have an online sheet music generator that for draws sheet music graphics to an area about 600pixels square. This looks OK on the screen but if printed each note would look blocky.
I always used to be able to print this applet in Internet explorer and get a full vector output of the sheet music so the notes were perfectly rounded, even though they are only a dozen pixels in radius.
Sometime over the summer there must have been an update to java, or (internet explorer?) so my printouts now look horribly blocky. Can anyone think of a reason for this?
I have two versions of my applet, one is double buffered for animation purposes,(which would obviously produce a rasterised image unsuitable for printing) the other draws straight to the screen which is the one which I have been using for printing and has worked fine up until now!
Any help would be much appreciated as I use this program professionally and I have to print several thousand pages from it next week!
A:
Can anyone think of a reason for this?
The obvious answer to that might be 'a change to Java', which can be tested by disabling the later Java version in the Java Control Panel (1), and using the earlier version only.
(1) Java Control Panel
*
*(Close the Java Cache Viewer.)
*Navigate to the Java tab of the JCP.
*Select the View button
*In the Java Runtime Environment Settings dialog, check the earlier versions, uncheck the later ones.
Java Runtime Environment Settings dialog
If that works
Use the earlier version for the 'several thousand pages'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Big comments with Sublime Text 2 I would like to make comments like this in Sublime Text 2:
/********************
* This is a comment *
********************/
Is there an easy way to make those automatically?
Also, where can I find good documentation about such stuff. I love Sublime, but I feel it's poorly documented!
A: You could create a snippet for doing this.
Go to Tools -> New Snippet and a new file is opened. Paste this in it:
<snippet>
<content>
<![CDATA[
/********************
* $0 *
********************/
]]>
</content>
<tabTrigger>bigcom</tabTrigger>
</snippet>
Save this in your Packages\User-Folder (which should be set automatically when saving).
Now you can just type bigcom (as defined in the <tabTrigger> - element) and hit tab. The comment will appear and the cursor is set at the position, where $0 is set in the snippet.
Additionaly, you could add a scope - element inside the <snippet>-block, so this snippet will only work in a specific syntax scope, for example:
<scope>source.python</scope>
Unfurtonately, I don't know how you could add the *-character on both sides of the line you are writing in automatically, when you jump into a new line, so I don't know if this fits your needs. You would have to add those manually. Still I hope this helps in some way.
Edit:
Found something for this in another question on stackoverflow. Have a look at this answer. When doing this, at least the * character on the beginning of the new line is added. I'll have a look if I can get it to add the character at the end of the line too.
When it comes to the documentation, I agree, there's not really a lot out there. Of course there is the official documentation: Sublime Doc and of course the forum: Sublime Forum (which is a good resource to some point, not like the poorly filled Doc). On the other hand I always recommend reading the post on net.tutsplus, which is a nice starting point.
I pretty much stumbled over the most interesting parts that come with the standard installation while browsing trough the Global Settings and Key Bindings-Files, which you can open over the Preferences - Menu
A: You could also try using the DocBlockr plugin
A: Warning, self plug.
The DocBlockr plugin can automatically 'decorate' a comment for you. Right now it only works on inline comments, but it gets the job done. The shortcut key is Ctrl+Enter
// foo bar baz
Becomes
/////////////////
// foo bar baz //
/////////////////
And it works on consecutive comments too:
// foo
// bar baz quux
Becomes
//////////////////
// foo //
// bar baz quux //
//////////////////
A: Use this handy sublime plugin https://packagecontrol.io/packages/Comment-Snippets
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Finding Column Labels corresponding to specific columns in sql server 2005 I am facing problem, finding out specific column names. I am using SQL Server 2005 and am coding in struts 2 framework.
Here is what needs to be done:
I want to find out the column names which have a particular value in a particular row.
For example:
In a row in employee table, if the value of a particular column is "true", I want to know the column name.
I know in SQL server we can access all the column names of a table using this query:
select column_name from information_schema.columns where table_name = 'table's name'
but I am not able to fulfill my purpose.
I guess I have defined my issue clearly, if there is anything that I missed out please tell.
Thanks!!
A: I'll assume you're not using an ORM, and that you're using JDBC, although unfortunately you don't say how you're getting data from the database.
You need to use ResultSetMetaData if you're using JDBC. from which you can get the name of a column by its index.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Job queuing library/software for Java The premise is this: For asynchronous job processing I have a homemade framework that:
*
*Stores jobs in database
*Has a simple java api to create more jobs and processors for them
*Processing can be embedded in a web application or can run by itself in on different machines for scaling out
*Web UI for monitoring the queue and canceling queue items
I would like to replace this with some ready made library because I would expect more robustness from those and I don't want to maintain this. I've been researching the issue and figured you could use JMS for something similar. But I would still have to build a simple java API, figure out a runtime where I would put the processing when I want to scale out and build a monitoring UI. I feel like the only thing I would benefit from JMS is that I would not have to do is the database stuff.
Is there something similar to this that is ready made?
UPDATE
Basically this is the setup I would want to do:
*
*Web application runs in a Servlet container or Application Server
*Web application uses a client api to create jobs
*X amount of machines process those jobs
*Monitor and manage jobs from an UI
A: You can use Quartz:
http://www.quartz-scheduler.org/
A: Check out Spring Batch.
Link to sprint batch website: http://projects.spring.io/spring-batch/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: What is the performance difference between a JVM method call and a remote call? I'm gathering some data about the difference in performance between a JVM method call and a remote method call using a binary protocol (in other words, not SOAP). I am developing a framework in which a method call may be local or remote at the discretion of the framework, and I'm wondering at what point it's "worth it" to evaluate the method remotely, either on a much faster server or on a compute grid of some kind. I know that a remote call is going to be much, much slower, so I'm mostly interested in understanding the order-of-magnitude differnce. Is it 10 times slower, or 100, or 1,000? Does anyone have any data on this? I'll write my own benchmarks if necessary, but I'm hoping to re-use some existing knowledge. Thanks!
A: It's impossible to answer your question precisely. The ratio of execution time will depends on factors like:
*
*The size / complexity of the parameters and return values that need to be serialized for the remote call.
*The execution time of the method itself
*The bandwidth / latency of the network connection
But in general, direct JVM method calls are very fast, any kind of of serialization coupled with network delay caused by RMI is going to add a significant overhead. Have a look at these numbers to give you a rough estimate of the overhead:
http://surana.wordpress.com/2009/01/01/numbers-everyone-should-know/
Apart from that, you'll need to benchmark.
One piece of advice - make sure you use a really good binary serialization library (avro, protocol buffers, kryo etc.) couple with a decent communications framework (e.g. Netty). These tools are far better than the standard Java serialisation/io facilities, and probably better than anything you can code yourself in a reasonable amount of time.
A: No one can tell you the answer, because the decision of whether or not to distribute is not about speed. If it was, you would never make a distributed call, because it will always be slower than the same call made in-memory.
You distribute components so multiple clients can share them. If the sharing is what's important, it outweighs the speed hit.
Your break even point has to do with how valuable it is to share functionality, not method call speed.
A: Having developed a low latency RMI (~20 micro-seconds min) it is still 1000x slower than a direct call. If you use plain Java RMI, (~500 micro-seconds min) it can be 25,000x slower.
NOTE: This is only a very rough estimate to give you a general idea of the difference you might see. There are many complex factors which could change these numbers dramatically. Depending on what the method does, the difference could be much lower, esp if you perform RMI to the same process, if the network is relatively slow the difference could be much larger.
Additionally, even when there is a very large relative difference, it may be that it won't make much difference across your whole application.
To elaborate on my last comment...
Lets say you have a GUI which has to poll some data every second and it uses a background thread to do this. Lets say that using RMI takes 50 ms and the alternative is making a direct method call to a local copy of a distributed cache takes 0.0005 ms. That would appear to be an enormous difference, 100,000x. However, the RMI call could start 50 ms earlier, still poll every second, the difference to the user is next to nothing.
What could be much more important is when RMI compared with using another approach is much simpler (if its the right tool for the job)
An alternative to use RMI is using JMS. Which is best depends on your situation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Implementing push/pop in a linked list (C++) I'm trying to incorporate push/pop into a linked list and I can't seem to get it to work. When I run my test function, I set my linked list to zero and I try to push on values but the list keeps getting returned with no values in it. Could anyone possibly tell me what I'm doing wrong?
A: if (top == NULL){
current = top;
current->next = NULL; //NULL->next : will cause segfault
}
if top is NULL, you set current = top [which is NULL], and then you access current->next, which will cause a segfault, you are trying to access NULL..
EDIT: follow up to comments:
your if statement seems redundant, you should probably only need to set: current->next = head; and head = current; [in addition to the current allocation]
A: Instead of
if (top == NULL){
current = top;
current->next = NULL;
}
you want
if (top == NULL){
top = current;
current->next = NULL;
}
And of course, after this, you have to make sure that you actually set head to top again.
Now that you've made this change, it should be clear that both cases do the same thing -- so no case distinction is actually necessary. So the function can be simplified to
void push(Data * newPushData){
LinkNode * current = new LinkNode(newPushData);
current->next = head;
head = current;
}
A: The top variable is local variable for push(...) function. You can use head instead, and I'd rather modify the if statement.
I think that function should look like this:
void push(Data * newPushData){
LinkNode * current = new LinkNode(newPushData);
if (head != NULL){
current->next = head;
head = current;
}
else{
head = current;
current->next = NULL; // if you haven't done it in LinkNode constructor
}
}
A: void push(Data * newPushData)
{
if( head != NULL )
{
LinkNode current = new LinkNode(newPushData);
current->next = head;
head = current;
}
else
{
head = new LinkNode(newPushData);
}
}
A: can you please specify the attributes of the linked list class ? [ is there slightly chance you are doing something wrong]
Instead of you , I'd do :
void push(Data * newPushData){
if (head == NULL)
head->data = newPushData
tail = head ;
else // regular situation
{
Node * node = new Node() ;
tail->next = node;
node->data = newPushData;
node->next = NULL ;
tail = node ;
}
}
In a linked list you have got to maintain the head pointer point on the head of the list , maintain that the tail pointer is point on the tail of the list ,
You must take care of the 2 cases of enlarging the list.
the best way for learning is to illustrate an insertion on a blank linked list.
Take care
S
A: Try this code...
void push(data * newpushdata){
if(head !=null){
linkednode current = new linkednode(newpushdata);
current->next = head;
head = current;
}
else {
head = new linkednode(newpushdata);
}
}
A: that is my working solution for a Stack containing int elements, but maybe it's better to create a void pushStack using Stack **S instead of Stack *S.
in pop(Stack **S) i created a sentinel, so if the stack is empty -1 is returned.:
typedef struct StackT {
int val;
struct StackT *next;
} Stack;
int isStackEmpty (Stack *S) {
if (S == NULL)
return 1;
else
return 0;
}
int *pop(Stack **S) {
Stack *tmp = *S;
int i = -1;
if (isStackEmpty(tmp) == 0) {
i = tmp->val;
*S = tmp->next;
}
return i;
}
Stack *pushStack (Stack *S, int x) {
Stack *node = (Stack *) malloc (sizeof (Stack));
node->val = x;
node->next = S;
return node;
}
you can call pop and stack easly:
Stack *S = NULL;
int x = somevalue;
int y;
S = pushStack(S, x);
y = pop(&S);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to exclude password protected posts in WordPress loop I have a custom post type that supports password protected entries. In a custom loop using a new WP_Query object, I want to exclude those password protected posts from the results. What arguments do I need set in order to do this? I am using the latest trunk version of WordPress 3.2.1.
A: I really like Kevin's approach, but I adjusted it slightly:
// Create a new filtering function that will add our where clause to the query
function my_password_post_filter( $where = '' ) {
// Make sure this only applies to loops / feeds on the frontend
if (!is_single() && !is_admin()) {
// exclude password protected
$where .= " AND post_password = ''";
}
return $where;
}
add_filter( 'posts_where', 'my_password_post_filter' );
A: I come up to this question where I was looking for the same. However, I read WP_Query document line by line then found very simple solution and that is just to add 'has_password' => false argument to the query $args
So the code will be as below...
$args = [
'post_type' => [ 'post', 'page' ],
'posts_per_page' => 3,
'post__not_in' => get_option( 'sticky_posts' ),
'has_password' => FALSE
];
Here you can see I have excluded Sticky and Password Protected posts.
A: Did you take a look at the post_status argument of WP_Query?
"Protected" seems like a good candidate to exclude.
Edit: Okay, it seems like you'll have to modify the where clause to achieve what you want:
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// exclude password protected
$where .= " AND post_password = ''";
return $where;
}
if (!is_single()) { add_filter( 'posts_where', 'filter_where' ); }
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
A: After a bit of playing about, I found the posts_where filter a bit too intrusive for what I wanted to do, so I came up with an alternative. As part of the 'save_post' action that I attached for my custom post type, I added the following logic;
$visibility = isset($_POST['visibility']) ? $_POST['visibility'] : '';
$protected = get_option('__protected_posts', array());
if ($visibility === 'password' && !in_array($post->ID, $protected)) {
array_push($protected, $post->ID);
}
if ($visibility === 'public' && in_array($post->ID, $protected)) {
$i = array_search($post->ID, $protected);
unset($protected[$i]);
}
update_option('__protected_posts', $protected);
What this does is hold an array of post id's in the options table where the post is protected by a password. Then in a custom query I simply passed this array as part of the post__not_in option e.g.
$query = new WP_Query(array(
'post_type' => 'my_custom_post_type',
'post__not_in' => get_option('__protected_posts'),
));
This way I could exclude the protected posts from an archive page but still allow a user to land on the password protected page to enter the password.
A: In addition to @Peter Chester's answer:
You may also want to exclude password-protected posts from the Previous Post and Next Post links, if you have those at the bottom of your post page.
To do so you can add the exclusion to the get_previous_post_where and get_next_post_where hooks.
add_filter( 'get_previous_post_where', 'my_theme_mod_adjacent' );
add_filter( 'get_next_post_where', 'my_theme_mod_adjacent' );
function my_theme_mod_adjacent( $where ) {
return $where . " AND p.post_password = ''";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: i written a winforms application in VB .NET in visual studio 2010 I have to run a thread create in the code.
In the form1 i have a button that run the new separate thread for elaborate some data, so i need it for not freeze the form.
I have inizialized thread:
dim th as thread = new thread (addressof elaborate)
And at the button.click event:
th.isbackground= true
th.start()
Now, at the form load i have iconized my program, but when i start new thread the tray icon is duplicated from it.
I want to resolve that when start new thread it's not show new notifyicon.
Any ideas?
(i don't have found anything online, only Multiple notification icons appear when using multithreading)
A: Create a class called Elab
inside that class, put a sub called work
Add a timer to your form that is disabled
with a tickcount of say 1000
Declare this in your form class:
Dim El as Elab
inside Form_Load() put:
El = New Elab()
Under your button, put this:
Dim gThread as new System.Threading.Thread(Address of El.Work)
Timer1.Enabled = True
Inside Elab declare a variable called Result:
Public Result as boolean
When elab has finished whatever it is doing, set result as true, and store the results in public variables you can access later.
Inside the timer:
If El.Result = True then
'Get results, deal with data
end if
This isn't written particularly well, and isn't a working example, but is to mearly point you in the right direction, by giving a thread an address of a sub inside a class, you can then access the same class from other threads, which means your form doesn't freeze, and you're not creating a new instance of your form, you are just accessing an existing classes sub routine; just make sure to give yourself a way to get the results (in this example i suggested a timer, but a "get result" button would do the same job) once the thread has completed.
Remeber:
If you need Elab to finish before a particular part of code can continue (for example, elab might add two numbers, and you need the result to continue) you can start the thread and do this:
Do until El.Result = True
Application.DoEvents()
System.Threading.Thread.Sleep(1)
Loop
gThread.Join()
Hope this helps a little.
So the answer to your question is; don't put your sub inside a form, instead put it in a class that you can create an instance of.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Compiling eAccelerator to decode PHP Coded Files By any chances is it possible to compile eAccelerator using OP Codes, to decompile the code loaded by eaccelerator_load(); and how?
I Use eAccelerator 0.9.5, PHP 4.4.4.
A: I think you're looking for thing similar to HipHop for php?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Problem adding contacts informations I'm trying to add some contacts from an xml file which have been serialize with Simple xml framework and there is a weird error :
ERROR/ContentProviderOperation(10727): mType: 1, mUri: content://com.android.contacts/data, mSelection: null, mExpectedCount: null, mYieldAllowed: false, mValues: data1=Karl Koffi Marx Antoine Carter mimetype=vnd.android.cursor.item/name, mValuesBackReferences: raw_contact_id=1, mSelectionArgsBackReferences: null
This is the code
ContactList contactList = serializer.read(ContactList.class, xmlFile);
int nbreContacts = contactList.contact.length;
for(int i=0;i<nbreContacts;i++)
{
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
id = contactList.contact[i].getId();
name = contactList.contact[i].getName();
addName(Integer.parseInt(id), name);
flush(c);
}
private void addName(int contactId, String displayName)
{
if(displayName != null)
{
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, contactId)
.withValueData.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
.build());
}
}
private void flush(Context c)
{
ContentResolver cr = c.getContentResolver();
try
{
cr.applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (RemoteException e)
{
Log.e("Writing", "Remote Error writting data ", e);
}
catch (OperationApplicationException e)
{
Log.e("Writing", "OAE Error writting data", e);
}
}
Any help would be appreciate.
A: Thanks to @Reno on the chat room.
withValueBackReference(Data.RAW_CONTACT_ID, contactId) changed to .withValueBackReference(Data.RAW_CONTACT_ID, 0)
I first thought RAW_CONTACT_ID was refering to the contact id that's why I was wrong. Problem solved and hope that will help someone else :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Check IF condition in Case statement of Stored procedure I am using CASE Statement in Stored procedure. I am using like
create proc USP_new
(
@searchtype varchar(30),
@stateName char(2),
@keywords varchar(300),
@locations varchar(100),
@searchBy varchar(20),
@keywordOption varchar(5),
@jobType char(4),
@startDate varchar(20),
@endDate varchar(20),
@companyID int
)
as begin
declare @mainQuery varchar(8000)
SELECT @mainQuery = 'SELECT JobID, JobTitle, CompanyInfo, JobSummaryLong, ModifiedDate
FROM Jobs
WHERE IsActive = 1 '
IF @startDate = '' BEGIN
SELECT @mainQuery = @mainQuery + 'And ModifiedDate >= ''' + @startDate + ' 00:00:00'' '
END
SELECT @mainQuery = @mainQuery + 'And ModifiedDate <= ''' + @endDate + ' 23:59:59'''
SELECT
CASE @mainQuery
WHEN 'state' THEN 'ONE'
WHEN 'keyword' THEN 'Second'
WHEN 'company' THEN 'Third'
ELSE 'Other'
END
I want check more condition on this 'Keyword' like When Keyword and keyword is not null then
goto THEN condition..
I used like WHEN 'keyword' AND (@keyword IS NULL) THEN '' but its is giving syntax error.
IT is possible to check condition like this or any other way to check this
Thanks....
A: It's really hard to tell what you are trying to accomplish with this stored proc, but I think you are definitely making thing harder than they need to be. You could probably re-write this as a single query like so:
SELECT
KeywordResult = CASE
WHEN @keywords = 'state' THEN 'ONE'
WHEN @keywords = 'keyword' THEN 'Second'
WHEN @keywords = 'company' THEN 'Third'
ELSE 'Other' END,
JobID,
JobTitle,
CompanyInfo,
JobSummaryLong,
ModifiedDate
FROM
Jobs
WHERE
IsActive = 1
AND (@StartDate <> '' AND ModifiedDate >= @StartDate)
AND ModifiedDate <= @endDate + ' 23:59:59'''
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: zeromq: how to prevent infinite wait? I just got started with ZMQ. I am designing an app whose workflow is:
*
*one of many clients (who have random PULL addresses) PUSH a request to a server at 5555
*the server is forever waiting for client PUSHes. When one comes, a worker process is spawned for that particular request. Yes, worker processes can exist concurrently.
*When that process completes it's task, it PUSHes the result to the client.
I assume that the PUSH/PULL architecture is suited for this. Please correct me on this.
But how do I handle these scenarios?
*
*the client_receiver.recv() will wait for an infinite time when server fails to respond.
*the client may send request, but it will fail immediately after, hence a worker process will remain stuck at server_sender.send() forever.
So how do I setup something like a timeout in the PUSH/PULL model?
EDIT: Thanks user938949's suggestions, I got a working answer and I am sharing it for posterity.
A: If you are using zeromq >= 3.0, then you can set the RCVTIMEO socket option:
client_receiver.RCVTIMEO = 1000 # in milliseconds
But in general, you can use pollers:
poller = zmq.Poller()
poller.register(client_receiver, zmq.POLLIN) # POLLIN for recv, POLLOUT for send
And poller.poll() takes a timeout:
evts = poller.poll(1000) # wait *up to* one second for a message to arrive.
evts will be an empty list if there is nothing to receive.
You can poll with zmq.POLLOUT, to check if a send will succeed.
Or, to handle the case of a peer that might have failed, a:
worker.send(msg, zmq.NOBLOCK)
might suffice, which will always return immediately - raising a ZMQError(zmq.EAGAIN) if the send could not complete.
A: This was a quick hack I made after I referred user938949's answer and http://taotetek.wordpress.com/2011/02/02/python-multiprocessing-with-zeromq/ . If you do better, please post your answer, I will recommend your answer.
For those wanting lasting solutions on reliability, refer http://zguide.zeromq.org/page:all#toc64
Version 3.0 of zeromq (beta ATM) supports timeout in ZMQ_RCVTIMEO and ZMQ_SNDTIMEO. http://api.zeromq.org/3-0:zmq-setsockopt
Server
The zmq.NOBLOCK ensures that when a client does not exist, the send() does not block.
import time
import zmq
context = zmq.Context()
ventilator_send = context.socket(zmq.PUSH)
ventilator_send.bind("tcp://127.0.0.1:5557")
i=0
while True:
i=i+1
time.sleep(0.5)
print ">>sending message ",i
try:
ventilator_send.send(repr(i),zmq.NOBLOCK)
print " succeed"
except:
print " failed"
Client
The poller object can listen in on many recieving sockets (see the "Python Multiprocessing with ZeroMQ" linked above. I linked it only on work_receiver. In the infinite loop, the client polls with an interval of 1000ms. The socks object returns empty if no message has been recieved in that time.
import time
import zmq
context = zmq.Context()
work_receiver = context.socket(zmq.PULL)
work_receiver.connect("tcp://127.0.0.1:5557")
poller = zmq.Poller()
poller.register(work_receiver, zmq.POLLIN)
# Loop and accept messages from both channels, acting accordingly
while True:
socks = dict(poller.poll(1000))
if socks:
if socks.get(work_receiver) == zmq.POLLIN:
print "got message ",work_receiver.recv(zmq.NOBLOCK)
else:
print "error: message timeout"
A: The send wont block if you use ZMQ_NOBLOCK, but if you try closing the socket and context, this step would block the program from exiting..
The reason is that the socket waits for any peer so that the outgoing messages are ensured to get queued.. To close the socket immediately and flush the outgoing messages from the buffer, use ZMQ_LINGER and set it to 0..
A: If you're only waiting for one socket, rather than create a Poller, you can do this:
if work_receiver.poll(1000, zmq.POLLIN):
print "got message ",work_receiver.recv(zmq.NOBLOCK)
else:
print "error: message timeout"
You can use this if your timeout changes depending on the situation, instead of setting work_receiver.RCVTIMEO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
} |
Q: Does libpcap watch sent packets? Does pcap_next display packets that were sent?
For example:
If I ping google.com while libpcap is listening for packets, then run pcap_next twice, will both of the returned values be a packet, or will one of them be null?
Edit:
Yes it does.
A: Yes, it does.
And here is some extra text to satisfy the rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem finding exact regular expression pattern in C# I am finding little tough figuring out the exact Regex for myself.
I have a text where I have to search for a particular html like tag. The tag is like
<snippet lang="java">some java code</snippet>
My text is something like
This is a sample text where <snippet lang="java">some java code</snippet> and other sample text where this that <snippet lang="java">some java code 2</snippet>
can anyone suggest how can I write regex for this?
A: The most trivial one you can come up with would be:
<snippet lang="java">.*?</snippet>
You probably might want to capture whatever is contained between those tags in a group:
<snippet lang="java">(.*?)</snippet>
And maybe even make the java part variable:
<snippet lang="([^"]+)">(.*?)</snippet>
Quick PowerShell test:
PS> $text = 'This is a sample text where <snippet lang="java">some java code</snippet> and other sample text where this that <snippet lang="java">some java code 2</snippet>'
PS> [Regex]::Matches($text, '<snippet lang="([^"]+)">(.*?)</snippet>')
Groups : {<snippet lang="java">some java code</snippet>, java, some java code}
Success : True
Captures : {<snippet lang="java">some java code</snippet>}
Index : 28
Length : 45
Value : <snippet lang="java">some java code</snippet>
Groups : {<snippet lang="java">some java code 2</snippet>, java, some java code 2}
Success : True
Captures : {<snippet lang="java">some java code 2</snippet>}
Index : 112
Length : 47
Value : <snippet lang="java">some java code 2</snippet>
Mind you, this is all very basic Regex knowledge (or Regex 101 in US university (college?) parlance). If you need to ask such questions, maybe you should rethink whether you actually need regular expressions. As Jamie Zawinski once noted:
Some people, when confronted with a problem, think
“I know, I'll use regular expressions.”
Now they have two problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to answer on GET request in asp.net I have a problem and I would really appreciate your help.
An external application is sending via GET some parameters on address of my asp.net page. (something like http://mypage.com/default.aspx?id=123). I read this parameter on page load and do some other things.
If I receive the parameter correctly I must answer immediately the external application (the same which send me the parameter) with plain text 'OK'.
How to do this reply with c# asp.net ? Any sample code ? Thanks in advance for help.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Page.Request.QueryString["id"];
if (!String.IsNullOrEmpty(id))
{
SendAnswer();
}
}
private void SendAnswer()
{
// ??????? send simple reply 'OK' as plain text
}
}
A: You can send anything you want with Response.Write. You might have to do Response.Clear first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Country name with space not accepted in BlackBerry ObjectChoiceField I am developing a registration page in BlackBerry app. I am sending all the fields entered to the local server.Country is one of the form fields and is in a ObjectChoiceField. Whenever user selects a country having more than one word for ex: United States of America, it says sign up failed. When user selects country with single name, registration is always successful.Can anybody guide me how can I make the ObjectChoiceField accept the spaces or remove the spaces in the country?
A: There is no problem in ObjectChoiceField. For example if you want to send the Value like "Black Berry" you must send it to the web service like "Black%20Berry". Because %20 takes the space character. So after you are taking the value form ObjectChoiceField means......
ar[obchfield.getSelectedIndex()];// this is your value say for example:"Black Berry".
Take this below code in seperate Classname Utility.java:
public class Utility {
public static String escapeHTML(String s){
StringBuffer sb = new StringBuffer();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
switch (c) {
case ' ': sb.append("%20"); break;
default: sb.append(c); break;
}
}
return sb.toString();
}}
Then do like this:
Utility.escapeHTML(ar[obchfield.getSelectedIndex()]);//converts the "Black Berry" to "Black%20Berry".
then it returns a String like: "Black%20Berry" and send it to server. Enough.
Your problem is solved.
If you have any doubt come on StackOverFlow chat room name "Life for Blackberry" to clarify Your and our doubts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7538998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: what's the best technique for selecting records with long comparison in where clause Say, I need to select records from a table and exclude records with id 1,2,5,9,15.
I do this:
"SELECT * FROM TABLE_NAME WHERE id <> 1 OR id <> 2 OR id <> 5 OR id <> 9 OR id <> 15"
But what if I have like 1000 records and I need to exclude 200 records?
Would I have to type 200 " OR id <> id_number"? Or is there a better way to do the query?
A: Try:
SELECT * FROM TABLE_NAME WHERE id NOT IN (1, 2, 5, 9, 15)
A: You can maybe exclude a range. Instead of id<>1 OR id<>2 .. id<>5 you can do : id<1 AND id>5.
and you can check the "where id not in (1, 2, 3 ...)" option
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7539000",
"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.