text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: delete shared preference data when i install same application means overriding application i use shared preference for saving data but when i install same application then my shared preference data not delete it remains as it is so how to delete shared preference data when i install same application without uninstall the application means just over write on the same application.
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Editor editor = settings.edit();
editor.putString("MY_NAME", UserId);
editor.putString("PASSWORD", password);
editor.commit();
setResult(RESULT_OK);
A: I tried below code to make this work change it to suit your needs
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(this);
boolean isFirstRun = wmbPreference.getBoolean("FIRSTRUN", true);
if (!isFirstRun)
{
// Code on first run
SharedPreferences.Editor editor = wmbPreference.edit();
editor.clear();
editor.commit();
}
else
{
// DO something
SharedPreferences.Editor editor = wmbPreference.edit();
editor.putBoolean("FIRSTRUN", false);
editor.commit();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Scaling rounded images using CSS3 and animate() I'm trying to create a scale functionality for certain images when they are hovered, while maintaining a rounded image effect using CSS3. See code below:
$(".nodes a").hover(function() {
if (!$(this).hasClass('inactive')) {
$(this).css({'z-index' : '99'});
$(this).find('span').addClass('active');
$(this).find('span').addClass("hover").stop().animate({ marginTop: '-24px', marginLeft: '-24px', top: '50%', left: '50%', width: '80px', height: '80px', WebkitBorderTopLeftRadius: 40, WebkitBorderTopRightRadius: 40, WebkitBorderBottomLeftRadius: 40, WebkitBorderBottomRightRadius: 40, MozBorderRadius: 40, BorderRadius: 40 }, 250); }
}, function() {
if (!$(this).hasClass('inactive')) {
$(this).css({'z-index' : '0'});
$(this).find('span').removeClass('active');
$(this).find('span').removeClass("hover").stop().animate({ marginTop: '0', marginLeft: '0', top: '0', left: '0', width: '32px', height: '32px', WebkitBorderTopLeftRadius: 32, WebkitBorderTopRightRadius: 32, WebkitBorderBottomLeftRadius: 32, WebkitBorderBottomRightRadius: 32, MozBorderRadius: 32, BorderRadius: 32 }, 250); }
});
The HTML looks like this -
<ul class="nodes">
<li>
<a href="/">
<span style="background: url(image.jpg) no-repeat center center; width: 32px; height: 32px;">
<img src="image.jpg" style="opacity: 0;" />
</span>
</a>
</li>
</ul>
What I can't get to work is the MozBorderRadius when animating (it doesn't keep a consistant circle, WebkitRadius and BorderRadius seems to work though), as well as keeping the image centered as it animates. I figured giving the image a MarginTop and marginLeft of half the amount of width and size added to it when animating would do, but it just aligns itself to the bottom.
A: You don't have to set all corners of webkit radius, just "WebkitBorderRadius" is enough.
And for animating MozBorderRadius, you can use ( "border-radius" : "40px" ). Here is your code working on webkit and moz :
$(".nodes a").hover(function() {
if (!$(this).hasClass('inactive')) {
$(this).css({'z-index' : '99'});
$(this).find('span').addClass('active');
$(this).find('span').addClass("hover").stop().animate({
marginTop: '-24px',
marginLeft: '-24px',
top: '50%',
left: '50%',
width: '80px',
height: '80px',
'border-radius' : '40px',
WebkitBorderRadius: 40,
BorderRadius: 40,
}, 250);
}
}, function() {
if (!$(this).hasClass('inactive')) {
$(this).css({'z-index' : '0'});
$(this).find('span').removeClass('active');
$(this).find('span').removeClass("hover").stop().animate({
marginTop: '0',
marginLeft: '0',
top: '0',
left: '0',
width: '32px',
height: '32px',
'border-radius' : '32px',
WebkitBorderRadius: 32,
MozBorderRadius: 32,
BorderRadius: 32
}, 250);
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to block php errors to be logged in codeigniter How to block the php errors like Severity: Notice —> Undefined variable
to be get logged in codeigniter , even by keeping the log threshold level at 3 at config settings.
this scenario occurs due to that all variables are not getting used each and every time.
thanks in advance
A: error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
This will suppress all warnings, notice and deprecated(if using php 5.3) messages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Threads/Sockets limits in Linux First of all: sorry for my english.
Guys, I have a trouble with POSIX sockets and/or pthreads. I'm developing on embedded device(ARM9 CPU). On the device will work multithread tcp server. And it will be able to process a lot of incoming connections. Server gets connection from client and increase counter variable(unsigned int counter). Clients routines will run in separate threads. All clients will use 1 singleton class instance(in this class will be opened and closed same files). Clients works with files, then client thread closes connection socket, and calls pthread_exit().
So, my tcp server can't handle more than 250 threads(counter = 249 +1(server thread). And I got "Resource temporary unavailable". What's the problem?
A: Whenever you hit the thread limit - or as mentioned run out of virtual process address space due to the number of threads - you're.... doing it wrong. More threads don't scale. Especially not when doing embedded programming. You can handle requests on a thread pool instead. Use poll(2) to handle many connections on fewer threads. This is prettty well-trod territory and libraries (like ACE, asio) have been leveraging this model for good reason
The 'thread-per-request' model is mainly popular because of it's (perceived) simple design.
As long as you keep connections on a single logical thread (sometimes known as a strand) there is no real difference, though.
Also, if the handling of a request involves no blocking operations, you can never do better than polling and handling on a single thread after all: you can use the 'backlog' feature of bind/accept to let the kernel worry about pending connections for you! (Note: this assumed a single core CPU, on a dual core CPU this kind of processing would be optimal with one thread per CPU)
Edit Addition Re:
ulimit shows how much threads can OS handle, right? If yes, ulimit does not solve my problem because my app uses ~10-15 threads in same time.
If that's the case, you should really double check that you are joining or detaching all threads properly. Also think of the synchronization objects; if you consistently forget to call the relevant pthread *_destroy functions, you'll run into the limits even without needing it. That would of course be a resource leak. Some tools may be able to help you spot them (vlagrind/helgrind come to mind)
A: Use ulimit -n to check the number of file system handles. You can increase it for your current session if the number is too low.
Also you can edit /etc/security/limits.conf and to set a permanent limit
A: Usually, the first limit you are hitting on 32-bit systems is that you are running out of virtual address space when using default stack sizes.
Try explicitly specifying the stack size when creating threads (to less than 1 MB) or setting the default stack size with "ulimit -s".
Also note that you need to either pthread_detach or pthread_join your threads so that all resources will be freed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Each element height if higher then function Good day, I'm trying to figure out how to do small thing.
I have several elements on page that needs to checked on height and if height is higher, for example > 100, then I need to call function for them.
So far I came up to this:
var filterHeight = $('div.class').height();
if (filterHeight > 100) {
$('div.class').css('height', '100px');
$('div.class').css('overflow-y', 'scroll');
}
Problem with that as you know is that it will add those params to all element because I strictly point to that.
I guess it I will need to do something with .each(), but...
Thank you for your suggestions and help.
Because I can't answer my own question I'm updating here.
I used your solution and change it a little bit, instead adding inline css I added class that fetch css.
So what I did is:
1) When page loads
$('div.class').each(function() {
if ($(this).height() > 200) {
$(this).addClass('scroller');
}
});
.scroller {
height: 200px;
overflow-y: scroll !important;
}
So it checked all blocks with height more than 200px and adds class.
2) After I'm calling for Ajax/JOSN and it gives me new data for those blocks I was in need to check for those elements heigh changes. So on .ajax complete I removed class and check again.
complete: function () {
$('.box.refine .middle ul').removeClass('scroller')
$('.box.refine .middle ul').each(function() {
if ($(this).height() > 200) {
$(this).addClass('scroller');
}
});
}
Thats all.
A: You need to look at jQuery .each()
Something like:
$('.check-these').each( function(){
if ($(this).height() > 100) {
$(this).css('height', '100px');
$(this).css('overflow-y', 'scroll');
}
});
This isn't tested but should put you on the right track.
A: $('div.class').each(function(){
if($(this).height() > 100)
{
$(this).css({height: "100px", overflow-y: "scroll"});
}
});
A: Loop through the elements and check each individually:
$('div.class').each(function() {
if ($(this).height() > 100) {
$(this).css('height', '100px').css('overflow-y', 'scroll');
}
});
But why not just put that in the css to begin with?
div.class {
height: 100px;
overflow-y: scroll;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get subscribers UID of a user through Graph API A few weeks ago Facebook allowed to subscribe a user. Can we access the UID of these subscribers for one user through the Graph API or FQL?
A: Obviously the graph API path should be:
https://graph.facebook.com/_UID_/subscribers
the path is valid, not documented though.
hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What 'possible data inconsistency' is entity framework worried about in a 'foreign key participating in multiple relationships' situation? Suppose the following database schema:
Table A: AId (PK)
Table B: BId (PK)
Table C: CId (PK)
Table AB: AId, BId (composite PK, FKs to A and B), Data
Table BC: BId, CId (composite PK, FKs to B and C), Data
Table ABC: AId, BId, CId, Data
In the database, ABC has two FKs: one to AB on AId and BId, and one to BC on BId and CId.
Use the EF Designer and attempt to create a Model from this database.
If you have Include foreign key columns in the model checked, it works; but having FK Columns in the model isn't very nice.
If you have Include foreign key columns in the model unchecked, only one of the FKs from ABC will be successfully mapped. To see what went wrong, you have to view the .edmx xml (thanks Craig!) and you see this error:
warning 6037: Foreign key constraint 'FK_ABC_BC' has been omitted from the storage model. Column 'BId' of table 'Model.Store.ABC' is a foreign key participating in multiple relationships. A one-to-one Entity Model will not validate since data inconsistency is possible.
I've read the only other mention of this problem I can find on SO, and I don't think this is the same problem. I can't see anything wrong at a database design level. I'm going to work round this for the time being by imposing surrogate keys on AB and BC, but what I'd really like to know is:
What possible data inconsistency is EF worried about happening here, if it created a model to match the database?
And is there anything I can do to persuade it that everything's going to be OK?
A: My opinion is that EF is too clever in this scenario and it prevents you from using entity where you can assign only one relation and make the entity non-savable because relation to second entity will not exists.
There is also possibility that EF has some internal problem with tracking state of independent associations if more than one association is based on the same foreign key column but that is just another guess. Generally database features used to map EF features cannot be shared among multiple constructions. The only exceptions I can think about now are primary keys and in their own way discriminator columns.
I would like to mention that I don't like this type of relations in database at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Microdata itemprop causes W3C validator error After adding Microdata to my pages, I got many errors from W3C validator complaining the itemprop:
there is no attribute "itemprop"
From code like this:
<p itemprop="description">...</p>
This is my DOCTYPE and html tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://www.facebook.com/2008/fbml">
How to fix the validator errors?
p.s. Previously I have the validator error for itemscope as well. But after I changed it to itemscope="itemscope" then the error is fixed.
A: OK, here is what I did to make this work with the Validator:
Referring to this page: http://www.w3.org/TR/2011/WD-microdata-20110525/
I enclosed the main in my page (the "wrapper" if you will) with the following:
<div id="layout" itemscope>
If you have itemscope in the div tag for your page or for the div containing microdata, then the W3C Validtor will like it just fine.
A: Documents with HTML 5 plus Microdata used to validate successfully but because of Bug #14020 the validator has become more strict on declaring documents as "valid". Your document is valid HTML 5 + Microdata, but is not strictly an HTML 5-only document.
You can use http://Validator.nu/ to validate HTML 5 + Microdata.
The site linked to in Fabian's answer is not the W3C site he mentions, so I wouldn't trust that as much for HTML 5 as I might have for earlier (pre-2000) versions of HTML.
The reason you had to change itemscope to itemscope="itemscope" is that previous browsers and specifications have defined incompatible interpretations (sometimes true, sometimes false) of code such as itemscope (no value), itemscope="" (an empty string is interpreted as false by XPath) and itemscope="false" (any non-empty string sometimes interpreted as true). Thus the statement in the spec that "The values 'true' and 'false' are not allowed on boolean attributes." However, "true" and "false" can appear in certain attribute values because they are allowed on enumerated attributes such as draggable. See bullet #4 regarding coding boolean values.
The workarounds (elsewhere) to insert invalid code with scripting may hide that code from the validator, but it won't create a document that is any more valid than using static HTML code because the HTML 5 specification is defined in terms of the internal document model, not the external representation. See HTML 5 Specifications focus on the DOM.
A: The DOCTYPE needs to be HTML5 for microdata to validate.
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
.....
It will work with paragraph tag:
http://www.w3.org/TR/2011/WD-microdata-20110525/
A: if you just want to remove this tag you can do so by removing tag from file which is located in main root folder
"wp-includes/general-template.php" at 891 line
you can just remove extra tag.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: MAC address randomly changes when bringing interface up Every time I start my network interface, I get a different MAC address! If I try to force the MAC address value using
ifconfig usb0 hw ether AA:BB:DD..:FF
it will be again different after issuing
ifconfig usb0 up
What make this MAC address change? How can I stop this to happen and stick to HW burned MAC address?
I am using a panda board (omap4/armv7) on a angtrom distribution. The inteface is a smsc95xx USB 2.0 Ethernet.
Thanks,
Fabrice.
A: There is an issue with the smsc95xx driver.
[PATCH] smsc95xx: generate random MAC address once, not every ifup
There is also something in the work to get a 'repeatable' MAC generation going, but it didn't get much uptake:
Beagleboard xM smsc95xx MAC address from die id
Edit just searching for smsc95xx mac address gives a ton of competing patches, with some more explanations (the smc hub+NIC frequently doesn't have an EEPROM, so also no MAC)
A: MAC addresses are typically coded in the chipset, but mutable.
It might be that your distro is randomising it for security reasons.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using maxcpucount to parallelise unit testing in msbuild? In a particular SOA-styled application I'm working on we have a large number of unit tests in each service. The tests for each service run serially, and I want to test running the tests for each service in parallel.
In our msbuild file is the following:
<Target Name="RunUnitTests">
<ItemGroup Condition="'@(UnitTestsOutput)' == ''">
<UnitTestsOutput Include="$(UnitTestsOutputFolder)\**\*Tests.dll" />
</ItemGroup>
<Exec Command="$(NUnitRunner) /nologo /labels /timeout=30000 @(UnitTestsOutput, ' ')" />
</Target>
So all tests project assemblies end with the name "Tests", thus they get found/picked up with that search.
Would it be possible/feasible to do something like this?
<Target Name="RunUnitTests">
<ItemGroup Condition="'@(UnitTestsOutput)' == ''">
<UnitTestsOutputService1 Include="$(UnitTestsOutputFolder)\*Service1*\*Tests.dll" />
<UnitTestsOutputService2 Include="$(UnitTestsOutputFolder)\*Service2*\*Tests.dll" />
<UnitTestsOutputService3 Include="$(UnitTestsOutputFolder)\*Service3*\*Tests.dll" />
<UnitTestsOutputService4 Include="$(UnitTestsOutputFolder)\*Service4*\*Tests.dll" />
<UnitTestsOutputService5 Include="$(UnitTestsOutputFolder)\*Service5*\*Tests.dll" />
</ItemGroup>
<Exec Command="$(NUnitRunner) /nologo /labels /timeout=30000 @(UnitTestsOutputService1, ' ')" />
<Exec Command="$(NUnitRunner) /nologo /labels /timeout=30000 @(UnitTestsOutputService2, ' ')" />
<Exec Command="$(NUnitRunner) /nologo /labels /timeout=30000 @(UnitTestsOutputService3, ' ')" />
<Exec Command="$(NUnitRunner) /nologo /labels /timeout=30000 @(UnitTestsOutputService4, ' ')" />
<Exec Command="$(NUnitRunner) /nologo /labels /timeout=30000 @(UnitTestsOutputService5, ' ')" />
</Target>
And then if the build is run using /maxcpucount it could possibly parallelise those sets of tests?
A: You can use BuildInParallel = true and a custom target:
<Project .... DefaultTargets="RunAll" />
...
<Target Name="RunSingle">
<ItemGroup>
<UnitTestsOutputService Include="$(UnitTestsOutputFolder)\*Service$(ServiceNum)*\*Tests.dll" />
</ItemGroup>
<Exec Command="$(NUnitRunner) /nologo /labels /timeout=30000 @(UnitTestsOutputService , ' ')" />
</Target>
<ItemGroup>
<Parallel Include="1;2;3;4;5" />
<ItemGroup>
<Target Name="RunAll">
<ItemGroup>
<Projects Include="$(MSBuildProjectFile)" > <-- for recursive call to same build file -->
<Properties>ServiceNum=%(parallel.identity)</Properties> <-- Service1, Service2 .. -->
</Projects>
</ItemGroup>
<MSBuild Projects="@(Projects)" BuildInParallel="true" Targets="RunSingle" />
</Target>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java :Can I observe value change on object by watching hashcode? I have a Model class DOModel :
package amarsoft.dbmp.credit.web.model;
import ejp.annotations.ConcreteTableInheritance;
import amarsoft.rcp.base.databinding.BindableModel;
@ConcreteTableInheritance
public class DOModel extends BindableModel {
/**
* 编号
*/
private String id;
/**
* 名称
*/
private String name;
/**
* 模板类型,没有太大意义
*/
private String type;
/**
* 模板参数
*/
private String args;
private String updateTable;
private String updateWhere;
private String fromClause;
private String whereClause;
private String groupClause;
private String orderClause;
public String getId() {
return id;
}
public void setId(String id) {
this.firePropertyChange("id", this.id, this.id = id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.firePropertyChange("name", this.name, this.name = name);
}
public String getType() {
return type;
}
public void setType(String type) {
this.firePropertyChange("type", this.type, this.type = type);
}
public String getArgs() {
return args;
}
public void setArgs(String args) {
this.firePropertyChange("args", this.args, this.args = args);
}
public String getUpdateTable() {
return updateTable;
}
public void setUpdateTable(String updateTable) {
this.firePropertyChange("updateTable", this.updateTable, this.updateTable = updateTable);
}
public String getDoUpdateWhere() {
return updateWhere;
}
public void setDoUpdateWhere(String doUpdateWhere) {
this.firePropertyChange("updateWhere", this.updateWhere, this.updateWhere = doUpdateWhere);
}
public String getFromClause() {
return fromClause;
}
public void setFromClause(String fromClause) {
this.firePropertyChange("fromClause", this.fromClause, this.fromClause = fromClause);
}
public String getWhereClause() {
return whereClause;
}
public void setWhereClause(String whereClause) {
this.firePropertyChange("whereClause", this.whereClause, this.whereClause = whereClause);
}
public String getGroupClause() {
return groupClause;
}
public void setGroupClause(String groupClause) {
this.firePropertyChange("groupClause", this.groupClause, this.groupClause = groupClause);
}
public String getOrderClause() {
return orderClause;
}
public void setOrderClause(String orderClause) {
this.firePropertyChange("orderClause", this.orderClause, this.orderClause = orderClause);
}
@Override
public String toString() {
return "DOModel [id=" + id + ", name=" + name + "]";
}
@Override
public int dataValueHashCode() {
int code = 0;
if (id != null) {
code += id.hashCode();
}
if(name != null){
code += name.hashCode();
}
if(type != null){
code += type.hashCode();
}
if(args != null){
code += args.hashCode();
}
if(updateTable != null){
code += updateTable.hashCode();
}
if(updateWhere != null){
code += updateWhere.hashCode();
}
if(fromClause != null){
code += fromClause.hashCode();
}
if(whereClause != null){
code += whereClause.hashCode();
}
if(groupClause != null){
code += groupClause.hashCode();
}
if(orderClause != null){
code += orderClause.hashCode();
}
return code;
}
}
this class is used in ORM, when one or more property of DOModel's instance is changed, I need to persist the DOModel's instance back to database.
so there is a problem for me: how can I know a DOModel instance object is modified compared to a specific time ?
please notice the method dataValueHashCode, I use a combination of the hash code of all the properties to measure if a model is changed.the basic flow is:
1.load the a DOModel object from database
2.call dataValueHashCode method and cache it
3.(optional)modify property values
4.when need to save the object back to database, call dataValueHashCode method again
and compare it to the cached one
5.if match, no change. if not match, save it back to database.
It seems that works right now, but as a java newbie, I am worrying there is potential problems. so before I go further, I want to prove my way will not lead me to a wrong place.
As a Chinese, my English is not good enough. if you have problem to understand what I am talking about, please post comment, I will try my best to edit this question.
thanks a lot!
A: That sounds like you're relying on "equal hash codes imply equal objects" which is not safe to rely on.
Assuming a proper implementation of hashCode, you should be able to rely on "different hash codes mean unequal objects" - but the reverse is not true.
In particular, an implementation of:
@Override public int hashCode() {
return 0;
}
is always valid. Sucky, but valid.
A: If you want to be sure that there is no change you have to compare the contents of the attributes rather than the hash code. For that you should implement the equals method. The problem with the hash code is that though unlikely it can be the same value for different property values.
A: There is something potentially wrong with that approach: two different objects may have the same hashCode value (the contract for hashcode is only that if a.equals(b) is true, then a.hashCode == b.hashCode, theoretically, all hashCodes could return 1 they would still be valid albeit inefficient)
So you need to come up with a cryptographic hash of yours that doesn't use hashcode, if you want to be absolutely certain it reflects your object change. I suggest using MD5 encryption, which (almost) uniquely identifies a string. It's not completely collision-resistant (means theoretically, there are multiple strings with the same output), but in practice, it's good enough.
http://en.wikipedia.org/wiki/MD5
It's quite easy to do in Java:
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
final byte[] data = stringToConvert.getBytes();
messageDigest.update(data,0,data.length);
final BigInteger hash = new BigInteger(1,messageDigest.digest());
return String.format("%1$032X", hash);
A: This is not the way to override hashCode(). Joshua Bloch tells you the correct way to do it in chapter 3 of his "Effective Java".
A:
It seems that works right now, but as a Java newbie, I am worrying there is potential problems.
It's not a safe approach: A change in an object, does not guarantee that the objects hash code changes.
Keep in mind that a hash code is simply an int. If your object have more than 232 states (as in your case) you are bound to have hash collisions.
A few more pointers regarding your code:
*
*When overriding hashCode, you need to also override equals.
*Your hashCode implementation is not very good (it doesn't provide a very good distribution)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Working directory issue when importing msbuild file in another msbuild file I am trying to specify some additional targets/tasks to an msbuild file by extending an existing msbuild file (a web applicartion .csproj file). The idea is to put configuration specific tasks in this "extended ms build file" and use this file in our build server (TeamCity). The way I tried to solve it at first was to add a folder "msbuildscripts" to my web project and put the extended ms build file there:
<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<Import Project="../My.Web.csproj" />
...more stuff...
</Project>
and then build this file using something like:
c:\myweb\msbuild.exe msbuildscripts/extended.msbuild.file.xml
Now, this wont work because when importing the original ms build file, that csproj file will be "executed" in the "wrong" folder (msbuildscripts), and the csproj-build-file wont find any of its referenced folders/items.
Is there any way to tell msbuild.exe to use a specific working directory? I know it is possible to solve this problem using an execute task, but that doesnt seem like a good solution.
A: Use MSBuild task like this:
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="MyBuild">
<ItemGroup>
<ProjectToBuild Include="../My.Web.csproj" />
</ItemGroup>
<Target Name="MyBuild">
<MSBuild Targets="Build" Projects="@(ProjectToBuild)"></MSBuild>
</Target>
</Project>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Read Text and Image Locations (x.y coordinates) using PDFBox I am doing a java program to read encrypted PDF files and extract the contents of the file page by page including the text, images and their positions(x,y coordinates) in the file. Now I'm using PDFBox for this purpose and I'm getting the text and images. But I couldn't get the text position and image position. Also there are some problems reading some encrypted PDF files.
A: Take a look at org.apache.pdfbox.examples.util.PrintTextLocations. I've used it quite a bit and it's very helpful to make analyses on the layout of elements and bounding boxes in PDF documents. It also revealed items printed in white ink, or outside the printable area (presumably document watermarks, or "forgotten" items pushed out of sight by the author).
Usage example:
java -cp app/target/pdfbox-app-1.5.0.jar org.apache.pdfbox.examples.util.PrintTextLocations ~/tmp/mydoc.pdf >~/tmp/out-text-locations.txt
You'll get something like that:
Processing page: 0
String[53.9,59.856995 fs=-6.0 xscale=6.0 height=-3.666 space=1.3320001 width=4.6679993]A
String[58.568,59.856995 fs=-6.0 xscale=6.0 height=-3.666 space=1.3320001 width=2.6640015]f
String[61.232002,59.856995 fs=-6.0 xscale=6.0 height=-3.666 space=1.3320001 width=1.6679993]e
...
Which you can easily parse and use to plot element's position, bounding-box, and the "flow" (trajectory through all the elements), etc. for each page. As I'm sure you are already aware of, you'll find that PDF can be almost impossible to convert to text. It is really just a graphic description format (i.e. for the printer or the screen), not a markup language. You could easily make a PDF that prints "Hello world", but that jumps randomly through the character positions (and that uses different glyphs than any ISO char encoding, if you so choose), making the PDF very hard to convert to text. There is no notion of "word" or "paragraph". A two-column document, for example, can be a nightmare to parse into text.
For the second part of your question, I had good results using xpdf version 3.02, after fixing Xref.cc (make XRef::okToPrint(),XRef::okToChange(),XRef::okToCopy() and XRef::okToAddNotes() all return gTrue). That's to handle locked documents, not encrypted ones (there are other utils out there for that).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Replication master-slave in MySQL having more tables on the slave Question to database specialists:
is it possible to make replication master-slave in MySQL having more tables on the slave? I know only about different table definitions
http://dev.mysql.com/doc/refman/5.1/en/replication-features-differing-tables.html
A: You can have tables on the slave that do not exist on the master and replication will proceed normally for those tables that exist on both master and slave (assuming you have not excluded them from replication of course!).
If you want tables on the slave that do not exist on the master you will have to create them directly on the slave database.
For example:
Master has tables a, b, c
Slave has tables a, b, c.
Replication is set up to replicate changes from a, b and c on the master to the slave.
Create table d on the slave (so slave now has tables a, b, c and d).
Replication should continue for tables a, b and c with table d on the slave unaffected.
In this situation table d would exist only on the slave.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GTK: how to get width and height of GTK_ICON_SIZE_BUTTON etc? I need to add my own images into GTK Icon Theme, so i need to somehow figure the size in pixels GTK uses to display icons of different predefined sizes: GTK_ICON_SIZE_BUTTON, GTK_ICON_SIZE_MENU, GTK_ICON_SIZE_DIALOG etc. GTK manual states that sizes are available as value of gtk-icon-sizes property of GtkSettings object. I have executed following code on latest ubuntu:
#!/usr/bin/env python
import gtk; print(gtk.settings_get_default().get_property('gtk-icon-sizes'))
But the output is very short:
'panel-menu=22,22;gtk-button=16,16'
Where can i find rest of the sizes, for example for GTK_ICON_SIZE_DIALOG or GTK_ICON_SIZE_LARGE_TOOLBAR?
A: GTK resizes the icons to whatever size they need to be. According to the Icon Theme Specification, you should make at least one 48x48 icon, and optionally a scalable SVG icon. That is enough to be able to display any of those sizes.
The Tango Icon Theme Guidelines recommend some supplementary sizes that you can make, in order to minimize how often the icon has to be resized internally by GTK.
A: Just add your images to the icon list with gtk_icon_theme_add_builtin_icon, and then use them as named icons.
An example in Vala:
Gdk.Pixbuf pixbuf;
pixbuf = new Gdk.Pixbuf.from_file_at_size(Path.build_filename(AutovalaPluginConstants.DATADIR,"valaplugin","application.svg"),-1,-1);
Gtk.IconTheme.add_builtin_icon("autovala-plugin-executable",-1,pixbuf);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drag and drop in preferences (reordering of items) I have few items like this
<ListPreference android:key="key1"
android:title="@string/title"
android:entries="@array/asd"
android:entryValues="@array/asd1"
android:defaultValue="109" android:dialogTitle="title"
android:negativeButtonText="@string/cancel" />
<ListPreference android:key="key2"
android:title="@string/title2"
android:entries="@array/asd2"
android:entryValues="@array/asd22"
android:defaultValue="109" android:dialogTitle="title"
android:negativeButtonText="@string/cancel" />
and they are all placed in one category . . ., the thing I want to do is to be able to reorder the items ( to put key2 before key1 with drag and drop)
is this possible at all in android and how can I do this ?, what methods should I override ?
After dragging the second item and doping above the first the items should be swapped.
A: Go through this example
It helps me a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Deploy EJB2 on Weblogic 10.3 I try to deploy ejb2 on weblogic 10.3 but I face a problem the deployed ear can't see new methods added to any ejb session bean. I added the method to remote interface and I added the implementation to bean class. I hope anyone can help. Thanks
A: I believe WebLogic 10.3 supports EJB3, so you'll have to do some modification. You already have the evidence to prove it.
A: As you say the old EJBs are working, but it's not reflecting updated methods - I think this is cached.
Drill down on your server to the following path or a similar one
DefaultDomain\servers\DefaultServer\cache\EJBCompilerCache
There will be many folders in there with random names like ff7i19ot3cg6 and l443b5vws35h
Clear out all these folders and redeploy the app
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: add multiple languages to tinymce in asp.net? In our project we used tinymce from creating moxiecode tinymce dll.
I added fr.xml and fr.js files to related langs folder in tinymce folder.
And modified code like below in Language.aspx page which is in langs folder of imagemanager plugin in tinymce folder.
string langfr = "fr';
LanguagePack langPack = man.LangPack;
langPack.Load(this.MapPath(@"im/" + langfr + ".xml"));
Moxiecode.Manager.Utils.GroupCollection groups = langPack.Languages[langfr].Groups;
and modified "en" language selection to "fr".
Is this the right way to add another language to tinymce
I followed the above implementation like in the site
A: You can only have one langugage per editor instance. Each instance can get its own language-setting using a different tinymce configuration for each editor instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to delete reference of image file? I have used test images for my developing process and now I want to change my test images to another images. so I deleted the whole test image folder and change to new folder. But it still shows old images. How do I remove these reference from old images and use new images?
A: Clean your project (in the Xcode menu) images are cached when building and never go away when you want them to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP load all extension dlls Would there be a performance hit if I loaded a large number of extensions compared with one or two extensions?
I'm using PHP 5.3.8 on IIS 6/FastCGI and if it makes a difference WinCache for PHP.
A: You'll find that there won't be any noticeable performance hit. On our shared hosting platform we enable pretty much all of the available extensions that ship with PHP. These are virtual servers hosting 800 to 1200 sites with 4GB of RAM and two virtual CPU's.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Checking if the array has, for example, three values How would I check if an array(with three values) that was passed to a function from another file has all three values?
For example I want to get an error if someone puts in $ids=Api_Books_Book::getTest(array(1,2,)); (There is no value on the the third key/index).
this is my code so far
public static function getTest($ids){
$input_result = array(
);
foreach ($ids as $id) {
$input_result['result']['Id '.$id] = $id;
}
if((array_key_exists('0',$ids))){
echo "You have inputted some data in the Api_Books_Book::getTest<br/>";
$input_success = "Successful!";
}
else
{
echo "There is no data<br/>";
$input_success = "Not Successful";
}
$result=array('status'=>$input_success,
'message'=>"some errors will be displayed here",
'result'=> $input_result
);
rdie($result);
return $result;
}
A: If you have simple numerically indexed arrays, the only thing that makes sense is count:
if (count($array) != 3) // not valid
or:
if (count($array) < 3) // not valid
You can use $array = array_values($array) to reset the numeric keys to make sure the values are at index [0], [1] and [2] and not any other indexes.
If you have key => value pairs and you expect certain keys to be set, use array_diff_key:
$expectedKeys = array('foo', 'bar', 'baz');
if (array_diff_key(array_flip($expectedKeys), $array)) // not valid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Re: java.lang.OutOfMemoryError: requested 32756 bytes for ChunkP I have been working on java project functionality enhancements. After complete the project I can deploy this into production server. But I am getting this error in the log file while accessing the application in production. Am using tomcat 7, jdk 6update 16.
A fatal error has been detected by the Java Runtime Environment:
java.lang.OutOfMemoryError: requested 32756 bytes for ChunkPool::allocate. Out of swap space?
Internal Error (allocation.cpp:117), pid=17388, tid=38580
Error: ChunkPool::allocate
JRE version: 6.0_22-b04
Java VM: Java HotSpot(TM) Client VM (17.1-b03 mixed mode windows-x86 )
If you would like to submit a bug report, please visit:
http://java.sun.com/webapps/bugreport/crash.jsp
Current thread (0x022eb000): JavaThread "CompilerThread0" daemon [_thread_in_native, id=38580, stack(0x4a950000,0x4a9a0000)]
Stack: [0x4a950000,0x4a9a0000], sp=0x4a99f760, free space=13d4a99f770k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
V [jvm.dll+0x1fd0f0]
V [jvm.dll+0xa471c]
V [jvm.dll+0x27b6]
V [jvm.dll+0x29b2]
V [jvm.dll+0x2bb3]
V [jvm.dll+0x53881]
V [jvm.dll+0x53b38]
V [jvm.dll+0x5577c]
V [jvm.dll+0x56626]
V [jvm.dll+0x5686a]
V [jvm.dll+0x28317]
V [jvm.dll+0x283b8]
V [jvm.dll+0x28524]
V [jvm.dll+0x28634]
V [jvm.dll+0x88399]
V [jvm.dll+0x88edf]
V [jvm.dll+0x1e7004]
V [jvm.dll+0x185f3c]
C [msvcr71.dll+0x9565]
C [kernel32.dll+0x1339a]
C [ntdll.dll+0x39ed2]
Can anyone find where is the problem and help me how to avoid this.
A: java.lang.OutOfMemoryError: requested 32756 bytes
That 32756 chunk was just the last straw; it's the OOM error that's your problem.
What are your JVM memory settings when you start up?
Attach VisualVM 1.3.2 to the Tomcat process when it starts up. You'll be able to see the entire generational memory layout, threads, etc.
A: What are your current memory settings defined for tomcat server ?
Try setting CATALINA_OPTS in catalina.sh
export CATALINA_OPTS="-Xms512m -Xmx1024m"
A: A brief bit of searching on google leads me to believe this is related to the JIT compiler. How many services are running on your server? Is it a 32 bit operating system?
Have a read through this link : http://www.codingthearchitecture.com/2008/01/14/jvm_lies_the_outofmemory_myth.html
What are your Java VM startup arguments?
A: If I recall correctly, usually with Tomcat (6), you don't get this hotspot error when you hit your Xmx memory ceiling. In my experience this happens when the JVM isn't able to allocate any more memory from the O/S even though it should be "allowed" to. Could it be possible that you just don't have enough free memory available to allocate to the JVM?
If that's not the case you'll want to inspect the memory at the time of the error. If you aren't able to attach a profiler in real time you can add the flags: -XX:+HeapDumpOnOutOfMemoryError and -XX:HeapDumpPath=/path/to/dumps to your CATALINA_OPTS then when the system next throws an OOM, it will dump it's heap to the folder specified. You can then analyse that with http://visualvm.java.net/ or similar Java profiler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android / XMPP: presence listener ignores/drops UNAVAILABLE presences I'm trying to establish a simple xmpp group chat on Android using the smack/asmack xmpp library. And basically everything is working, except: UNAVAILABLE presences, i.e., when a user leaves a chat room, seem to be ignored. Presences from users entering the group chat are fine.
Both my local Openfire server as well as a xmpp client (Instantbird) tell me that there is a UNAVAILABLE presence when user leaves. Only my stuff has troubles.
Here's the main snippet of my code. In short, when a user (re-)enters the room I see the console output ("presenceListener.processPacket"), when a user leaves nothing happens.
public boolean join(String room, user) {
this.chat = new MultiUserChat(this.xmppConn, room);
this.presenceListener = new PacketListener() {
@Override
public void processPacket(Packet packet) {
System.out.println("presenceListener.processPacket");
if (packet instanceof Presence)
// Handle presence
}
};
this.chat.addParticipantListener(this.presenceListener);
this.messageListener = ...
this.chat.addMessageListener(this.messageListener);
...
try {
this.chat.join(user);
...
} catch (...) {
...
}
}
I would understand when the listener would pick up nothing. But this is too weird for me at the moment. I'm happy about any hint...thanks!
Christian
A: I found a working solution here.
It uses a PacketFilter with a filter for presence packets, attaching it to the xmpp connection; inspite my solution via attaching a ParticipantListener to the MultiUserChat.
I still don't know why my original attempt fails, but...well...it works now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP Heredoc string rules Can someone here explore the intricacies of using heredoc in PHP using example PHP code snippets, based on what the manual says below?
The php.net manual says:
It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.
If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.
Heredocs can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.
Here is the link to PHP manual: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
A: This is a simple use:
$bar = "stackoverflowpro";
$foo = <<<HTML
<p>Hello $bar</p>
HTML;
A: echo <<< _HTML
... some HTML code here ...
_HTML;
Important is that the closing tag is precisely the same as defined after the "<<<" and that the closing tag is placed without indent (no tabs, completely sticky to the left) and is closed by a ";".
Note: the "_" is not required, but I use it to indicate better that it is a heredoc which is closing.
A: Note: a minor incompatible change was made to heredoc in PHP 7.3. See the second section for the changes since PHP 7.3.
Pre PHP 7.3
The closing heredoc identifier MUST NOT have any characters at all between the start of line and the identifier, it MAY have a single ; IMMEDIATELY afterwards and MUST NOT have any other characters after it. If the identifier gets indented it must be treated as part of the heredoc string. The only character that may appear before the newline is ;. You can't even include any whitespace between the identifier and the ; or between the ; and the newline. This means that if you use a heredoc inside a function call, you must insert a line break just after the closing identifier (i.e. before any , or ), etc.).
In other words, the only thing that can appear on the line with the closing identifier is the identifier itself and optionally one semicolon (;) immediately after the identifier. The next character (if not at End-Of-File) MUST be a valid newline character for the operating system that PHP is running on.
This is a valid heredoc string:
$text = <<<EOT
Hello!
EOT;
This heredoc string hasn't been closed and EOT; is considered part of the string:
$text = <<<EOT
Hello!
EOT;
The previous example fixed:
$text = <<<EOT
Hello!
EOT;
A heredoc inside a function call (note that ); must appear on a new line to work):
print(<<<EOT
Hello!
EOT
);
The same as above with very weird indentation (note that the only thing on the closing identifier line is the identifier and a newline). Hello! will have five spaces before it in the string:
print(<<<EOT
Hello!
EOT
);
Extra rules post PHP 7.3
In PHP 7.3 and later, the identifier is allowed to have whitespace before it, as long as it matches the whitespace indentation in the rest of the string. Spaces and tabs can't be mixed and the indentation of every line in the string must be identical. Extra horizontal whitespace of any type can appear immediately after the indentation whitespace except immediately before the closing identifier.
This previous example is now valid in PHP 7.3 and above:
$text = <<<EOT
Hello!
EOT;
The identifier can no longer appear anywhere else within the string, except within a longer identifier or after printing (non-whitespace) characters. Identifiers consist of letters and underscores, but not numbers or symbols.
Invalid (+ is not a letter or underscore):
$text = <<<FOO
Hello!
FOO+
FOO;
Valid (Hello!\n FOOD):
$text = <<<FOO
Hello!
FOOD
FOO;
Valid (Hello!\n A FOO):
$text = <<<FOO
Hello!
A FOO
FOO;
The closing identifier no longer needs to be the only thing on its line (except for the previously mentioned optional semicolon and indentation).
Valid (Hello!1588648007):
$text = <<<FOO
Hello!
FOO . time();
A: Just to refresh the discussion. Since PHP ver. 7.3 and upper there are some new rules in HEREDOC syntax:
The closing marker for doc strings is no longer required to be
followed by a semicolon or newline. Additionally the closing marker
may be indented, in which case the indentation will be stripped from
all lines in the doc string.
See the docs: https://www.php.net/manual/en/migration73.new-features.php
Try it here: Online PHP tester with my example
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Page Jumping - Can't stop it I'm making mock ups for a flash app using HTML pages - I'm using HTML pages to demonstrate it inside a browser, plus it looks better pixel for pixel, and I'm using jQuery for rich animations on some pages.
I'm using normal <a> tags for my buttons which navigate through the HTML pages.
But if I have scrolled halfway down the page and click on a button at the bottom of the page - when it goes to the next HTML page it jumps back to the top of the page - this is obviously going to happen.
Is there any javascript or tricks that can prevent all <a> tags from jumping to the top of the page when navigating though my HTML pages. Or even better, if I could give my <a> tags a class so it doesn't interfere with my jQuery animations - because some use <a> tags.
My html pages are like so:
page-1.html
page-2.html
page-3.html
page-4.html
page-5.html
I'm not actually using jQuery or JavaScript to navigate through my pages, so when it jumps to page-2.html from page-1.html - it always jumps to top.
My <a> tags are using full href's <a href="page-2.html" class="stop-jumping" title="Page 2"><img ... /></a>
I'm looking for something to include in the head of every HTML page to stop my page from moving when navigating using <a> tags.
A: I assume your a tag doesn't have a proper href attribute and you just put "#" in it (which is bad from a semantic and usability point of view).
Your browser is thinking you're clicking on an anchor, try to find it in the DOM, fail and then brings you back to the top of the page.
A way to avoid that is to bind a function on the click event of your a tags and call preventDefault()
$("a").click(function(event) {
event.preventDefault();
}
See the jQuery doc.
Edit due to huge edit on question
You need to use HTML anchor. On each of your html pages, give an id on the element you want your users screen to be aligned on.
<h1 id="the_place">The user screen will be aligned to this element</h1>
And on every link that leads to another page, add #the_place on the end of the href attribute
<a href="/page-2.html#the_place">Go to page 2</a>
That should do it =).
A: $("a").click(function(e) {
e.preventDefault();
}
A: You could use
return false
at end of the function that handle your navigation or calling
e.preventDefault and e.stopPropagation
that stop the normal behaviour of the event (in your case a click event on an anchor).
A: Yes when you have a click event return false
$('a').click(function(){
return false;
}
This will break the standard a tag event
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't read tables from firefox using Java sqlite jdbc I'm using the following code to connect and read moz_bookmarks from Java
String connection = "jdbc:sqlite:/" + Tracking.FILES_LOCATION + "places.sqlite";
Connection conn1 = DriverManager.getConnection("jdbc:sqlite:path_to_places.sqlite/");
Statement stat = conn1.createStatement();
ResultSet rs1 = stat.executeQuery("select * from moz_bookmarks;");
But I keep getting : "java.sql.SQLException: file is encrypted or is not a database"
Even after upgrading my jdbc sqlite driver for sqlite3
Any help is greatly appreciated
Thanks!
A: You create a connection name in first line, but in the second line you have a connection string which is probably copied from some tutorial.
Try to use connection variable when calling getConnection method.
A: Try this:
String connection = "jdbc:sqlite:/" + Tracking.FILES_LOCATION + "places.sqlite";
Connection conn1 = DriverManager.getConnection(connection);
Statement stat = conn1.createStatement();
String Query = "select * from moz_bookmarks";
ResultSet rs1 = stat.executeQuery(Query);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make FastCodePatch work in Delphi XE2 Win64 platform? Unit FastCodePatch.pas works in Win32 platform. Delphi XE2 supports Win64 platform, any ideas how to make FastCodePatch works in Win64 platform?
unit FastcodePatch;
interface
function FastcodeGetAddress(AStub: Pointer): Pointer;
procedure FastcodeAddressPatch(const ASource, ADestination: Pointer);
implementation
uses
Windows;
type
PJump = ^TJump;
TJump = packed record
OpCode: Byte;
Distance: Pointer;
end;
function FastcodeGetAddress(AStub: Pointer): Pointer;
begin
if PBYTE(AStub)^ = $E8 then
begin
Inc(Integer(AStub));
Result := Pointer(Integer(AStub) + SizeOf(Pointer) + PInteger(AStub)^);
end
else
Result := nil;
end;
procedure FastcodeAddressPatch(const ASource, ADestination: Pointer);
const
Size = SizeOf(TJump);
var
NewJump: PJump;
OldProtect: Cardinal;
begin
if VirtualProtect(ASource, Size, PAGE_EXECUTE_READWRITE, OldProtect) then
begin
NewJump := PJump(ASource);
NewJump.OpCode := $E9;
NewJump.Distance := Pointer(Integer(ADestination) - Integer(ASource) - 5);
FlushInstructionCache(GetCurrentProcess, ASource, SizeOf(TJump));
VirtualProtect(ASource, Size, OldProtect, @OldProtect);
end;
end;
end.
The solution provided by Ville Krumlinde doesn't work on 64 bits package. It works on Standalone .exe application only.
A: The following code works for both Win32 - Standalone and Package, Win64 - Standalone and Package:
type
TNativeUInt = {$if CompilerVersion < 23}Cardinal{$else}NativeUInt{$ifend};
PJump = ^TJump;
TJump = packed record
OpCode: Byte;
Distance: integer;
end;
function GetActualAddr(Proc: Pointer): Pointer;
type
PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp;
TAbsoluteIndirectJmp = packed record
OpCode: Word; //$FF25(Jmp, FF /4)
Addr: Cardinal;
end;
var J: PAbsoluteIndirectJmp;
begin
J := PAbsoluteIndirectJmp(Proc);
if (J.OpCode = $25FF) then
{$ifdef Win32}Result := PPointer(J.Addr)^{$endif}
{$ifdef Win64}Result := PPointer(TNativeUInt(Proc) + J.Addr + 6{Instruction Size})^{$endif}
else
Result := Proc;
end;
procedure FastcodeAddressPatch(const ASource, ADestination: Pointer);
const
Size = SizeOf(TJump);
var
NewJump: PJump;
OldProtect: Cardinal;
P: Pointer;
begin
P := GetActualAddr(ASource);
if VirtualProtect(P, Size, PAGE_EXECUTE_READWRITE, OldProtect) then
begin
NewJump := PJump(P);
NewJump.OpCode := $E9;
NewJump.Distance := TNativeUInt(ADestination) - TNativeUInt(P) - Size;
FlushInstructionCache(GetCurrentProcess, P, SizeOf(TJump));
VirtualProtect(P, Size, OldProtect, @OldProtect);
end;
end;
A: For the FastcodeAddressPatch-function, this version works both in 32-bit and 64-bit when I try. The key is changing "pointer" to "integer" because the Intel relative jump-instruction ($E9) still use an 32-bit offset in 64-bit mode.
type
PJump = ^TJump;
TJump = packed record
OpCode: Byte;
Distance: integer;
end;
procedure FastcodeAddressPatch(const ASource, ADestination: Pointer);
const
Size = SizeOf(TJump);
var
NewJump: PJump;
OldProtect: Cardinal;
begin
if VirtualProtect(ASource, Size, PAGE_EXECUTE_READWRITE, OldProtect) then
begin
NewJump := PJump(ASource);
NewJump.OpCode := $E9;
NewJump.Distance := NativeInt(ADestination) - NativeInt(ASource) - Size;
FlushInstructionCache(GetCurrentProcess, ASource, SizeOf(TJump));
VirtualProtect(ASource, Size, OldProtect, @OldProtect);
end;
end;
procedure Test;
begin
MessageBox(0,'Original','',0);
end;
procedure NewTest;
begin
MessageBox(0,'Patched','',0);
end;
procedure TForm5.FormCreate(Sender: TObject);
begin
FastcodeAddressPatch(@Test,@NewTest);
Test;
end;
I'm not sure what the other function does but I'm guessing it should be like this:
function FastcodeGetAddress(AStub: Pointer): Pointer;
begin
if PBYTE(AStub)^ = $E8 then
begin
Inc(NativeInt(AStub));
Result := Pointer(NativeInt(AStub) + SizeOf(integer) + PInteger(AStub)^);
end
else
Result := nil;
end;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Can't add a HOME email has been specified yet to an existing ANDROID contacs I have a proplem when I make a app "contacts manager" for android.
I have processed creating and deleting a contact with name, and phone
but when I want to add more a home email info to an existing contacts but can't do that.
here my code:
ArrayList ops = new ArrayList();
String selectName = ContactsContract.Data.CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "= ? ";
String[] NameArgs = new String[]{strId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String selectPhone = ContactsContract.Data.CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "= ? ";
String[] phoneArgs = new String[]{strId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
String selectEmail = ContactsContract.Data.CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "= ? ";
String[] emailArgs = new String[]{strId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String selectPostAdd = ContactsContract.Data.CONTACT_ID + "= ? AND " + ContactsContract.Data.MIMETYPE + "= ? AND " + ContactsContract.CommonDataKinds.StructuredPostal.TYPE + "= ? ";
String[] postAddArgs = new String[]{strId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE, String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)};
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectName, NameArgs)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, updContact_name.getText().toString())
.build());
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, updContact_phone.getText().toString())
.build());
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectEmail, emailArgs)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, updContact_textMail.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPostAdd, postAddArgs)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.DATA, updContact_textPostAdd.getText().toString())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME)
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
this code is available for update a contacts but an Item Info(here is email, StructruedPostal) has been created once. but when I create it with contacts app of android with only name, number (don't touch email, structuedPostal) and save, I don't update it in my android app.
somebody have experience about this pls help me! tks
sorry about my grammar english! It have more mistake and wrong grammar. :(. Tks all
A: Updating will not insert field which doesn't exist, so follow these steps.
*
*First query for the raw Contact Id of your Contact.
*use new Insert method to insert data that has not been inserted to the contact previously when created (in the oppt case newUpdate() will work fine).
A piece of code goes like this
String[] params = new String[] {"Give your Contact"};// you need query and get this too.
String[] proj = {ContactsContract.RawContacts._ID};
Cursor c = context.getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,proj,
ContactsContract.Data._ID +"= ?", params, null);
long rawContactId = -1;
while(c.moveToNext()){
rawContactId = c.getLong(0);
}
c.close();
After getting those values,
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, data.getEmail2Address())
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME)
.build());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Programmatically find and change html on pages in my Plone site I want to search for all documents inside a fairly large Plone site that contain a specific snippet of html in the body (list items with headings inside them, urgh ...) and then change that html (drop the headings).
Pointers on how to do that are much appreciated!
A: You should create a browserview (or run the instance in debug mode) and run this code:
from Products.CMFCore.utils import getToolByName
import re
ctool = getToolByName(context, 'portal_catalog')
results = ctool.searchResults(portal_type='Document')
for i in results:
obj = i.getObject()
text = obj.getField('text').get(obj)
<find and remove your html using the regular expression module>
obj.reindexObject()
If you need to do this many times, you could evaluate to add your custom index that simplify the job.
A: I have not tried it in a while, but check out GoReplace
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: automatic method running on load with singleton javascript class I have a javascript class defined like this:
myClass = {
var1:0,
var2:0,
initVars: function() {},
method1: function() {},
method2: function() {}
}
Now this class is instantly instantiated upon load. ( I believe ) and there is only ever one instance of this class.
Now lets say i want one of the functions, myClass.initVars() to run as soon as the class is ready, is this possible? because at the moment i have this line under where the class is defined
myClass.initVars();
so as soon as this class has finished being defined, it moves onto the next command.
But is it possible for me to remove this line underneath the class definition and have it run automatically?
A: This should do what you want. Create your object inside an auto-executed function and call the initVars method inside there and then return the newly created and initialised object.
myClass = (function(){
var that = {
var1:0,
var2:0,
initVars: function() {},
method1: function() {},
method2: function() {}
};
that.initVars();
return that;
})();
http://jsfiddle.net/CQ29F/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to catch Ctrl+C on Windows and Linux with Qt I have Qt console server application. I wish when somebody presses Ctrl+C to quit my server correctly (calling destructors, etc.). I've read this, however I want this to work on both Linux and Windows. How to do it?
A: I use this class to catch signals in C++ console applications. It is not specific to Qt, however. It uses SetConsoleCtrlHandler() on Windows platforms, and functions provided by <signal.h> on other platforms. The tricky bit is that "signal" is not a cross platform term - Windows and POSIX have different definitions for them. Anyway this class attempts to map them to a common vocabulary. Ctrl^C is one that maps well on both platforms.
I hope this can be adapted to your specific situation. Please mind that error checking is minimal and should probably be improved.
Usage (main.cpp)
#include "SignalHandler.h"
class Application : public SignalHandler
{
public:
Application() : SignalHandler(SignalHandler::SIG_INT), myThread(NULL) {}
int Application::main(int argc, char *argv[])
{
// Main program instructions here (e.g. start a thread)
myThread = new Thread(...);
myThread->start();
myThread->join();
delete myThread;
return 0;
}
bool handleSignal(int signal)
{
std::cout << "Handling signal " << signal << std::endl;
if (_myThread && _myThread->isRunning())
{
_myThread->stop();
// The thread is going to stop soon, so don't propagate this signal further
return true;
}
// Let the signal propagate as though we had not been there
return false;
}
private:
Thread* myThread;
};
int main(int argc, char* argv[])
{
Application app;
return app.main(argc, argv);
}
SignalHandler.h
class SignalHandler
{
public:
SignalHandler(int mask = DEFAULT_SIGNALS);
virtual ~SignalHandler();
enum SIGNALS
{
SIG_UNHANDLED = 0, // Physical signal not supported by this class
SIG_NOOP = 1, // The application is requested to do a no-op (only a target that platform-specific signals map to when they can't be raised anyway)
SIG_INT = 2, // Control+C (should terminate but consider that it's a normal way to do so; can delay a bit)
SIG_TERM = 4, // Control+Break (should terminate now without regarding the consquences)
SIG_CLOSE = 8, // Container window closed (should perform normal termination, like Ctrl^C) [Windows only; on Linux it maps to SIG_TERM]
SIG_RELOAD = 16, // Reload the configuration [Linux only, physical signal is SIGHUP; on Windows it maps to SIG_NOOP]
DEFAULT_SIGNALS = SIG_INT | SIG_TERM | SIG_CLOSE,
};
static const int numSignals = 6;
virtual bool handleSignal(int signal) = 0;
private:
int _mask;
};
SignalHandler.cpp
#include "SignalHandler.h"
#include <assert.h>
#ifndef _WIN32
#include <signal.h>
#else
#include <windows.h>
#endif //!_WIN32
// There can be only ONE SignalHandler per process
SignalHandler* g_handler(NULL);
#ifdef _WIN32
BOOL WINAPI WIN32_handleFunc(DWORD);
int WIN32_physicalToLogical(DWORD);
DWORD WIN32_logicalToPhysical(int);
std::set<int> g_registry;
#else //_WIN32
void POSIX_handleFunc(int);
int POSIX_physicalToLogical(int);
int POSIX_logicalToPhysical(int);
#endif //_WIN32
SignalHandler::SignalHandler(int mask) : _mask(mask)
{
assert(g_handler == NULL);
g_handler = this;
#ifdef _WIN32
SetConsoleCtrlHandler(WIN32_handleFunc, TRUE);
#endif //_WIN32
for (int i=0;i<numSignals;i++)
{
int logical = 0x1 << i;
if (_mask & logical)
{
#ifdef _WIN32
g_registry.insert(logical);
#else
int sig = POSIX_logicalToPhysical(logical);
bool failed = signal(sig, POSIX_handleFunc) == SIG_ERR;
assert(!failed);
(void)failed; // Silence the warning in non _DEBUG; TODO: something better
#endif //_WIN32
}
}
}
SignalHandler::~SignalHandler()
{
#ifdef _WIN32
SetConsoleCtrlHandler(WIN32_handleFunc, FALSE);
#else
for (int i=0;i<numSignals;i++)
{
int logical = 0x1 << i;
if (_mask & logical)
{
signal(POSIX_logicalToPhysical(logical), SIG_DFL);
}
}
#endif //_WIN32
}
#ifdef _WIN32
DWORD WIN32_logicalToPhysical(int signal)
{
switch (signal)
{
case SignalHandler::SIG_INT: return CTRL_C_EVENT;
case SignalHandler::SIG_TERM: return CTRL_BREAK_EVENT;
case SignalHandler::SIG_CLOSE: return CTRL_CLOSE_EVENT;
default:
return ~(unsigned int)0; // SIG_ERR = -1
}
}
#else
int POSIX_logicalToPhysical(int signal)
{
switch (signal)
{
case SignalHandler::SIG_INT: return SIGINT;
case SignalHandler::SIG_TERM: return SIGTERM;
// In case the client asks for a SIG_CLOSE handler, accept and
// bind it to a SIGTERM. Anyway the signal will never be raised
case SignalHandler::SIG_CLOSE: return SIGTERM;
case SignalHandler::SIG_RELOAD: return SIGHUP;
default:
return -1; // SIG_ERR = -1
}
}
#endif //_WIN32
#ifdef _WIN32
int WIN32_physicalToLogical(DWORD signal)
{
switch (signal)
{
case CTRL_C_EVENT: return SignalHandler::SIG_INT;
case CTRL_BREAK_EVENT: return SignalHandler::SIG_TERM;
case CTRL_CLOSE_EVENT: return SignalHandler::SIG_CLOSE;
default:
return SignalHandler::SIG_UNHANDLED;
}
}
#else
int POSIX_physicalToLogical(int signal)
{
switch (signal)
{
case SIGINT: return SignalHandler::SIG_INT;
case SIGTERM: return SignalHandler::SIG_TERM;
case SIGHUP: return SignalHandler::SIG_RELOAD;
default:
return SignalHandler::SIG_UNHANDLED;
}
}
#endif //_WIN32
#ifdef _WIN32
BOOL WINAPI WIN32_handleFunc(DWORD signal)
{
if (g_handler)
{
int signo = WIN32_physicalToLogical(signal);
// The std::set is thread-safe in const reading access and we never
// write to it after the program has started so we don't need to
// protect this search by a mutex
std::set<int>::const_iterator found = g_registry.find(signo);
if (signo != -1 && found != g_registry.end())
{
return g_handler->handleSignal(signo) ? TRUE : FALSE;
}
else
{
return FALSE;
}
}
else
{
return FALSE;
}
}
#else
void POSIX_handleFunc(int signal)
{
if (g_handler)
{
int signo = POSIX_physicalToLogical(signal);
g_handler->handleSignal(signo);
}
}
#endif //_WIN32
A: Hope this works for you.
In your class header:
#include <signal.h>
class sth:{
...
...
static void sigHandl(int sig){
if(sig==2){
QCoreApplication::quit();
//exit(EXIT_FAILURE);
}
}
};
in your constructor add this line:
signal(SIGINT,sigHndl);
A: That code work on Windows and i think he might work on Linux.
ui->setupUi(this);
QAction *ctrlp =new QAction("plus",this), *ctrlm = new QAction("minus",this);
ctrlp->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Plus));
ctrlm->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Minus));
connect(ctrlp, SIGNAL(triggered()), this, SLOT(on_pushButton_4_clicked()));
connect(ctrlm, SIGNAL(triggered()), this, SLOT(on_pushButton_5_clicked()));
connect(ui->pushButton_2,SIGNAL(clicked()),SLOT(close()));
ui->textEdit->addAction(ctrlp);
ui->textEdit->addAction(ctrlm);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: gotoxy function with C ( linux/unix ) I am making a terminal software like GNU MC and I need gotoxy foo, but it has to be in C. It can be in macro or in C, but not in ASM code because I don`t know ASM. Any bit operators can be used too, but I had no idea how to pseudocode it or how to start doing this. Any advice will be most appreciated :)
A: Is this function sufficient?
void gotoxy(int x, int y)
{
printf("You are now at position (%d, %d). You"\
" look around and you see a vast emptiness...", x, y);
}
You do, however, mention that you are using software like GNU MC (Midnight Commander?), so perhaps you actually mean something more like:
void goto_url(char* url) { ... code here... }
A: Hope this snippet works with you.
I found these snippet on google long ago. I just saved it on my disk, now after seeing your post I just opened it.
Code
#include <stdio.h>
#include <stdlib.h>
void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}
int main(void)
{
gotoxy(10,10);
printf("hello world");
return 0;
}
A: see the ncurses library for such a function
you need some function from the listed here
http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/printw.html#PRINTWCLASS
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Select the fields are duplicated in mysql Assuming that I have the below customer_offer table.
My question is:
How to select all the rows where the key(s) are duplicated in that table?
+---------+-------------+------------+----------+--------+---------------------+
| link_id | customer_id | partner_id | offer_id | key | date_updated |
+---------+-------------+------------+----------+--------+---------------------+
| 1 | 99 | 11 | 14 | mmmmmq | 2011-09-21 12:40:46 |
| 2 | 100 | 11 | 14 | qmmmmq | 2011-09-21 12:40:46 |
| 3 | 101 | 11 | 14 | 8mmmmq | 2011-09-21 12:40:46 |
| 4 | 99 | 11 | 14 | Dmmmmq | 2011-09-21 12:59:28 |
| 5 | 100 | 11 | 14 | Nmmmmq | 2011-09-21 12:59:28 |
+---------+-------------+------------+----------+--------+---------------------+
UPDATE:
Thanks so much for all your answer. There are many answers are good. Now I got the solution to do.
A: select *
from customer_offer
where key in
(select key from customer_offer group by key having count(*) > 1)
Update:
As mentioned from @Scorpi0, if with a big table, it is better to use join. And from mysql6.0 the new optimizer will convert this kind of subqueries into joins.
A: Self join
SELECT * FROM customer_offer c1 inner join customer_offer c2
on c1.key = c2.key
or group by the field then take when count > 1
SELECT COUNT(key),link_id FROM customer_offer c1
group by key, link_id
having COUNT(Key) > 1
A: SELECT DISTINCT c1.*
FROM customer_offer c1
INNER JOIN customer_offer c2
ON c1.key = c2.key
AND c1.link_id != c2.link_id
Assuming link_id is a primary key.
A: There are many threads on the mysql website which explains how to do this. This link will explain how to do this using mysql: http://forums.mysql.com/read.php?10,180556,180567#msg-180567
As a brief example the code below is from the link with a slight modification which better suits your example.
SELECT *
FROM tbl
GROUP BY key
HAVING COUNT(key)>1;
You can also use a joing which is my prefered method, as this removes the slower count method:
SELECT *
FROM this_table t
inner join this_table t1 on t.key = t1.key
A: Use a sub-query to do the count check, and the main query to select the rows. The count check query is simply:
SELECT `link_id` FROM `customer_offer` GROUP BY `key` HAVING COUNT(`key`) > 1
Then the outer query will use this by joining into it:
SELECT customer_offer.* FROM customer_offer
INNER JOIN (SELECT `link_id` FROM `customer_offer` GROUP BY `key` HAVING COUNT(`key`) > 1) AS count_check
ON customer_offer.link_id = count_check.link_id
A: SELECT link_id, key, count(key) as Occurrences
FROM table
GROUP BY key
HAVING COUNT(key)>1;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem with memory deallocation for non-dynamically created std::vectors storing normal (i.e. non-dynamically allocated) data Consider the following code, compiled with g++ problem.cpp -o problem:
#include <vector>
using namespace std;
int main()
{
while(1){}
return 0;
}
When this code is executed, the command top reports that ~80K of memory is being consumed.
Now consider this code:
#include <vector>
using namespace std;
int main()
{
vector<int> testVec;
for(int i = 0;i<100000000;i++)testVec.push_back(i);
while(1){}
return 0;
}
As expected, top report that around ~300MB of memory is consumed.
Now finally, consider this code:
#include <vector>
using namespace std;
int main()
{
vector<int> testVec;
for(int i = 0;i<100000000;i++)testVec.push_back(i);
testVec.clear();
vector<int>().swap(testVec);
while(1){}
return 0;
}
Now top reports that ~4196K is being consumed(!) -- why isn't it only ~80K is as in the first example? How can I finally free up that last bit of memory that is presumably being consumed by the vector? I've read that in addition to .clear(), the 'swap trick' is meant to free up everything but apparently it's not working as I expected it would do. What am I missing?
A: You should probably just ignore it. The swap trick frees the memory from the vector, but that does not mean that the allocator (or even the malloc or equivalent implementation underneath) will yield the memory back to the system. That is, the vector is most probably not the one holding the memory up.
A: From what I know, there are two ways to deallocate memory on this case:
*
*Put the code that use vector in bracket (simple and efficient)
{
// ..........
}
*Use shared pointer, but make sure that there is exactly only one shared pointer. You can call "reset" in order to free up the memory.
shared_ptr<vector<int> > testVec(new vector<int>);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: EF 4.1 - DBContext SqlQuery and Include I want to execute a raw sql using DBContext SqlQuery and then include related entites. I've tried the following but it doesn't load the related entities:
string sql = "Select * from client where id in (select id from activeclient)";
var list = DbContext.Database.SqlQuery<Client>(sql).AsQueryable().Include(c => c.Address).Include(c => c.Contactinfo).ToList();
Any help?
A: It is not possible. Include works only with ESQL or linq-to-entities because it must be processed during query building to construct correct SQL query. You cannot pass SQL query to this construction mechanism. Moreover your code will result in executing SQL query as is and trying to call Include on resulted enumeration.
You can also use simple linq query to get your result:
var query = from c in context.Clients.Include(c => c.Address).Include(c => c.Contactinfo)
join ac in context.ActiveClients on c.Id equals ac.Id
select c;
This should produce inner join in SQL and thus filter are non-active clients.
A: Not direct answer, but instead of writing raw sql query you could use something like this
_conext.Clients.Where(c => _conext.ActiveClients.Any(a => a.ClientId == c.Id));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Adding live functionality to dynamically added element in jQuery I make an element in jQuery plugin:
this.addButton = $("<a>", {
text: "ADD",
"class": "addButton"
}).appendTo(this.element);
Then i add live functionality:
this.addButton.live("click", function() {
that.somefunction("addSomething");
});
And it isn't working.
IF i change "live" to "bind" it works OR when i do:
$('.addButton').live("click", function() {
that.somefunction("addSomething");
});
it works too. But why adding live to an dynamically added element doesn't work?
Any ideas?
A: live() needs to examine the event on a parent element to work. The way you have set it up, the event can not propagate to any parent element.
A: Because of the way live() works:
The .live() method is able to affect elements that have not yet been
added to the DOM through the use of event delegation: a handler bound
to an ancestor element is responsible for events that are triggered on
its descendants. The handler passed to .live() is never bound to an
element; instead, .live() binds a special handler to the root of the
DOM tree. In the example above, when the new element is clicked, the
following steps occur: A click event is generated and passed to the
for handling. No handler is directly bound to the , so the
event bubbles up the DOM tree. The event bubbles up until it reaches
the root of the tree, which is where .live() binds its special
handlers by default.
* As of jQuery 1.4, event bubbling can optionally stop at a DOM
element "context". The special click handler bound by .live()
executes. This handler tests the target of the event object to see
whether it should continue. This test is performed by checking if
$(event.target).closest(".clickme") is able to locate a matching
element. If a matching element is found, the original handler is
called on it. Because the test in step 5 is not performed until the
event occurs, elements can be added at any time and still respond to
events.
lives doesn't bind an event to an object, it attach a listener to the window and then when the events bubble ups it checks for the original target. So you don't add it to the new object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Low quality image after resizing Hello i'm using this function in order to resize/upload an image . There's any quick adjustment i could make in order to improve the resized image quality without changing the full function?
FileUpload FileUpload1 =(FileUpload)ListView1.InsertItem.FindControl("FileUpload1");
string virtualFolder = "~/albume/";
string physicalFolder = Server.MapPath(virtualFolder);
string fileName = Guid.NewGuid().ToString();
string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
FileUpload1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension));
//test resize
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/albume/") + fileName + extension);
int srcWidth = img.Width;
int srcHeight = img.Height;
int thumbHeight = (int)((800.0 / srcWidth) * srcHeight);
System.Drawing.Image thumb = img.GetThumbnailImage(800, thumbHeight, null, IntPtr.Zero);
img.Dispose();
FileUpload1.Dispose();
thumb.Save(Server.MapPath("~/albume/") + fileName + extension, System.Drawing.Imaging.ImageFormat.Jpeg);
//end resize
myAlbum.poza = fileName + extension;
A: instead of this code:
thumb.Save(Server.MapPath("~/albume/") + fileName + extension, System.Drawing.Imaging.ImageFormat.Jpeg);
use this one :
System.Drawing.Imaging.ImageCodecInfo[] info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
System.Drawing.Imaging.EncoderParameters param = new System.Drawing.Imaging.EncoderParameters(1);
param.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
thumb.Save(Server.MapPath("~/albume/") + fileName + extension, info[1], param);
A: use this snippet:
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
stolen from this question/answer: Resizing an Image without losing any quality see Kris's ultra voted answer and vote it up :)
A: On my site, I use the following code to resize user images before they are sent to the page.
You may be able to make use of something similar - try investigating the various Interpolation modes.
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
graphics.Clear(ColorTranslator.FromHtml("#F4F6F5"));
graphics.DrawImage(bmp, 0, 0, 145, 145);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
target.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
memoryStream.WriteTo(context.Response.OutputStream);
}
}
A: The best is not to use "GetThumbnailImage" this makes low quality. According to http://msdn.microsoft.com/de-de/library/system.drawing.image.getthumbnailimage%28VS.80%29.aspx
Resize the image by redrawing it like:
private static Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
found on
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Invoking WCF no parameter method from Biztalk orchestration I'm new at Biztalk, I've been making some tutorials, now I have an issue I don`t' find the solution but think is kind of easy
I have a WCF Service method with no parameters that returns an XML file.
I want to call this method from biztalk orchestration, I have used the "Add ->Generated Item –> Consume WCF Service" wizard to generate the schemas and to be able to create a request, response port.
Now I just have to send a request to this service, an XML specifying the method I want to call. But I dont want to drop an XML file whits this message in a folder, read from there, and then call service.
It doesnt have parameters, so I want to generate the message in the orchestration and automatically call the service with it. How can I contruct the message from "nothing" just the schema?
thanks!
A: you could create a request message in your Orchestration in a Message Assignment shape.
Create a message type matching the request message - e.g msgRequest. In the Construct Shape, set the outgoing message to msgRequest. Go to the schema for the request and Generate an instance of that schema. Use the load xml method to assign the xDoc variable to the msgRequest message.
the expression would be something like:
xDoc = new System.XmlDocument();
xDoc.LoadXml("<GeneratedRequest/>");
Message_1.body = xDoc;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java - get element position in array I'm familiar with the ways I can get an element position in array, especially the ones showed here: Element position in array
But my problem is I can't figure out how to convert this code to fit my needs.
What I want to check is if a String has a match in an ArrayList and if so, what's the index of the String in the ArrayList.
The annoying part is I managed to verify the String is in the ArrayList (see first line of my code)
listPackages is the ArrayList
current_package is the String I want to find its position in listPackages.
Here's my code:
if (listPackages.contains(current_package)) {
int position = -1;
for(int j = 0; j < listPackages.size(); j++) {
if(listPackages[j] == current_package) {
position = j;
break;
}
}
}
Would appreciate any help!
Thanks!
A: Use indexOf:
int index = listPackages.indexOf(current_package);
Note that you shouldn't generally use == to compare strings - that will compare references, i.e. whether the two values are references to the same object, rather than to equal strings. Instead, you should call equals(). That's probably what was going wrong with your existing code, but obviously using indexOf is a lot simpler.
A: just use the call listPackages.indexOf(current_package);
ArrayList.contains(Object o) calls indexOf(Object o) internally in ArrayList:
/**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
A: Hope this will help you.change your code like this:
if (listPackages.contains(current_package)){
int position=listPackages.indexOf(current_package);
}
Also if you will make position variable as global you can access its value outside this block of code. :)
A: use the indexof method to get the position -
listPackages.indexOf(current_package)
http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Is there a simpler way to write the following cucumber test? I'm usisng cucmber to test a php app and it's working quite well actually.
I have a cucmber feature that uses the following step to check for the presence of a link in a page:
Then /^I should see a link that contains "(.+)"$/ do |link|
assert !!(response_body =~
/<a ([\w\.]*="[\w\.]*" )*href="(http:\/\/)?([\w\.\/]*)?(#{link})/m), response_body
end
Now, this works but it's butt ugly and complicated.
Originally I tried using the xpath thing:
response_body.should have_xpath("//a[@href=\"#{link}\"]")
But then if I check for a link to 'blah.com' then it won't match 'http://blah.com" - which kind of defeats the whole purpose of the test. Hence the reason I switched to regex.
So is there a simpler way to write the test which doesn't rely on complicated regular expressions?
Cheers.
EDIT:
After lots of hair-pulling... I did find a less messy way to find images on my page:
response_body.should include(image)
Where the image string is set to something like 'myimage.png' - of course, this will break if the actual text 'myimage.png' is on the page and not the image.
There must be a better way. I was considering Hpricot to see if I can parse the html and pull out the attribute I want to test, then test that with a regex but that all seems so... bloated.
A: Something like this should work:
response_body.should have_css("a[href*='#{link}']")
See this for details:
http://www.w3.org/TR/css3-selectors/#attribute-substrings
EDIT:
Looks like the equivalent method for webrat is have_selector, so:
response_body.should have_selector("a[href*='#{link}']")
A: Then /^I should see the image "(.+)"$/ do |image|
response_body.should have_selector("img[src*='#{image}']")
end
Then /^I should see a link that contains "(.+)"$/ do |link|
response_body.should have_selector("a[href*='#{link}']")
end
Thanks AlistairH - your advice worked! :)
I still don't undestand why it's searching html with a css selector syntax but maybe that was just a design choice they guy who wrote it took because it looked easier than regex...? I don't know.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Text scrolls outside of UITextView object I have some text in a UITextView object. The issue I'm having is that the text scrolls outside of the UITextField box. How would I go about fixing this?
thanks for any help
textBG.contentInset = UIEdgeInsetsZero;
where 'textBG' is the name of my UITextView
A: USE this in textViewShouldBeginEditing method it will help you
YourTextViewObject.contentInset = UIEdgeInsetsZero;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC 3 refresh changes made to page doesnt work I am starting to learn MVC 3 (Razor engine) and I am having difficulty understanding why my changes don't get applied to page. Basically I have done this: I have imported my DAL and model projects, I have created one controller and one view (in their respective folders) and in the controller Index method I am passing list of products to View
Data.ProductRepository repository = new Data.ProductRepository();
var list = repository.GetProducts(1, true);
return View(list);
And the data is displayed correctly on the page. Now, I want to reformat the columns that are auto generated in the view (I used scaffold list tamplate). The problem is that no matter what I change into this view, the changes are not reflected on the page. I stop the web server, start again, always the same layout is displayed. Even removing columns from table doesn't work. It seems like it is using some cashed version of this page.
Thanks,
Goran
A: After reinstalling both OS (XP) and IDE, it started working without any proeblems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement fingure print as password for the screen in iphone Is there any way to implement fingerprint as password for the screen in iPhone?
IS it possible?
A: No, the iPhone screen can't read fingerprints. Try a retinal scanner using the camera and flash instead :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add Jquery Mobile effects to dynamically added elements? While working with Jquery Mobile I am facing a strange issue. Jquery Mobile adds some default classes and css to every element based upon data-role etc. when i create new elements normal css get applied to all the new generated elements , but not Jquery Mobile ?
html
<ul data-role="listview" >
<li><a href="#">sada</a></li>
<li><a href="#">sada</a></li>
<li><a href="#">sada</a></li>
</ul>
<a href="#" data-role="button" class="hello" >Add</a>
SCRIPT
$('.hello').click(function(){
$('ul').append('<li><a href="#">sada</a></li> ');
})
check JsFiddle here http://jsfiddle.net/sahil20grover1988/zZMXQ/2/ . Clicking on button will create new Li element in LIST How to apply JQuery Mobile features to elements
A: you need to reload the jquery mobile list style
after appending the element
try this:
$("ul").listview("refresh");
A: You need to use jQuery live function for bind new action for newly added element
$('a').live('click',function(){
//do something
})
and you can refresh the list like this to get the list view correct,
http://jsfiddle.net/zZMXQ/13/
$("ul").listview("refresh");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: URI-specific ExceptionMapper in JAX-RS I'm using Jersey, and Guice as my IOC-container. I'd like to know if it is possible to associate an ExceptionMapper with a specific URI. The reason for this is that I want to map the same exception differently based on what URI was visited. For example, suppose I've got the following two exception mappers for my custom exception:
public class MyExceptionMapperForFirstURI implements
ExceptionMapper<MyException> {..return response based on first URI..}
public class MyExceptionMapperForSecondURI implements
ExceptionMapper<MyException> {..return response based on second URI..}
As far as I understand you bind an ExceptionMapper in your ServletModule as follows:
public class MyModule extends ServletModule {
@Override
public void configureServlets() {
super.configureServlets();
bind(MyCustomExceptionMapper.class);
}
}
How would I go about binding MyExceptionMapperForFirstURI and MyExceptionMapperForSecondURI so that they get associated with the correct URIs. Is this possible, and if possible: is this the correct way to do this?
A: This is quite late answer ;-) but you can always inject the UriInfo and branch on that. So,
@Context
UriInfo uriInfo;
.....
if (matchesA(uriInfo.getAbsolutePath())) {
// do something
}
A: Not sure how the URI's of your app look like, but if it is possible to split your app into two servlets or filters, then you can do it like that - i.e. have one servlet/filter serve one set of resources and include the first mapper and have the other servlet/filter serve the other set of resources and include the other mapper.
If these are custom exceptions, you can also pass Request as an argument to the exception and have just a single mapper - decide on the response based in the request uri in the mapper.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Dynamically generate unevaluated expressions to create lagged data.frame? I have data.frame Z and I would like to select only a couple of variables stored in the character vector vars. This of course can easily be done by:
Z[,vars]
The problem is that I need als the lags 1 and 4 of these variables. I use lag(variable,-1) to get them. I tried the following that was suggested here earlier:
require(plyr)
l <- c(0,1,4)
expand.grid(x=vars,l=l)
# which results in
x l
var1 0
var2 0
var3 0
var1 1
var2 1
var3 1
var1 4
var2 4
var3 4
buildFaDf <- function(x,l) paste("lag(Z$",x,",-",l,")",sep="")
test <- mlply(vars,buildFaDf)
gives back a list of like this:
....
$`4`
[1] "lag(Z$var1,-1)"
If I call that list element I just get the characters back, but of course I´d like to have the data itself. In the end I want to unlist and end up with a data.frame containing all vars and their respective lags.
I also played around with substitute , eval and expression and could not get it done.
Note I am not focused to the mlply solution here it just was suggested to me lately and I am a little biased at the moment maybe.
A: Perhaps you are over-complicating the problem. The way I see it, there are two steps to solving this:
*
*Step 1: Create a subset of a data.frame - this is trivial, and you show it in your question.
*Step 2: Create lagged variables for all columns in a data.frame
Here is one way of doing step 2. I'll demonstrate with the built-in dataset faithful:
data(faithful)
dat <- head(faithful, 10)
lag1 <- function(x) c(NA, head(x, -1))
lag4 <- function(x) c(rep(NA, 4), head(x, -4))
data.frame(
dat,
llply(dat, lag1),
llply(dat, lag4)
)
eruptions waiting eruptions.1 waiting.1 eruptions.2 waiting.2
1 3.600 79 NA NA NA NA
2 1.800 54 3.600 79 NA NA
3 3.333 74 1.800 54 NA NA
4 2.283 62 3.333 74 NA NA
5 4.533 85 2.283 62 3.600 79
6 2.883 55 4.533 85 1.800 54
7 4.700 88 2.883 55 3.333 74
8 3.600 85 4.700 88 2.283 62
9 1.950 51 3.600 85 4.533 85
10 4.350 85 1.950 51 2.883 55
To turn the solution into a function that does the subsetting as well as lagging, do the following:
dat <- data.frame(head(faithful, 10), newcol=LETTERS[1:10])
laggedDF <- function(x, vars){
lag1 <- function(x) c(NA, head(x, -1))
lag4 <- function(x) c(rep(NA, 4), head(x, -4))
dat <- x[, vars, drop=FALSE]
print(dat)
data.frame(
dat,
llply(dat, lag1),
llply(dat, lag4)
)
}
laggedDF(dat, vars=c("eruptions", "newcol"))
eruptions newcol eruptions.1 newcol.1 eruptions.2 newcol.2
1 3.600 A NA NA NA NA
2 1.800 B 3.600 1 NA NA
3 3.333 C 1.800 2 NA NA
4 2.283 D 3.333 3 NA NA
5 4.533 E 2.283 4 3.600 1
6 2.883 F 4.533 5 1.800 2
7 4.700 G 2.883 6 3.333 3
8 3.600 H 4.700 7 2.283 4
9 1.950 I 3.600 8 4.533 5
10 4.350 J 1.950 9 2.883 6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java iterate map from a certain index I have a map created from a json string that is sorted in the order I need to parse in.
If there is a key at index 6 (7th key), I want to be able to iterate from this key to the end of the map and do what processing I need with these key/value pairs.
Is there anyway to do this?
A: A Map doesn't in general maintain an order of the keys. You'll need to use
*
*A NavigableMap, such as TreeMap. Preferable if your keys have a natural order.
*A LinkedHashMap which is a map implementation which preserves the insertion order.
Example snippet (LinkedHashMap):
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "six");
map.put(7, "seven");
map.put(8, "eight");
map.put(9, "nine");
int index = 0;
for (Integer key : map.keySet()) {
if (index++ < 6)
continue;
System.out.println(map.get(key));
}
// Prints:
// seven
// eight
// nine
Example snippet (TreeMap):
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(5, "five");
map.put(6, "six");
map.put(7, "seven");
map.put(8, "eight");
map.put(9, "nine");
for (Integer key : map.tailMap(6).keySet())
System.out.println(map.get(key));
// Prints
// six
// seven
// eight
// nine
A: The Map interface doesn't allow direct access by index. The best you can do is something like:
Map m;
....
int count 0;
for(object el : m){
if(count++ < 6) continue;
//do your stuff here
}
This assumes that your Map implementation is sorted - otherwise there is no guaranteed order when enumerating.
A: Depending on the underlying map implementation, the order has already been lost when it was parsed.
LinkedHashMap is the beast you are after - the Linked part gives you your predictable iteration order.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Vaadin Compile widgets(addons) I need some help compiling the widgets of my vaadin project. I have downloaded an addon (FormSender) , because it an client-side component i have to Compile my wingets, when i click the Vaadin widgets compile button in eclipse, i get the following message :
Compiling widgetset com.example.vaadinproject.widgetset.VaadinprojectWidgetset
Updating GWT module description file...
Sep 28, 2011 10:32:50 AM com.vaadin.terminal.gwt.widgetsetutils.ClassPathExplorer getAvailableWidgetSets
INFO: Widgetsets found from classpath:
org.vaadin.hene.popupbutton.widgetset.PopupbuttonWidgetset in jar:file:/home/s2padmin/workspace/VaadinProject/WebContent/WEB-INF/lib/popupbutton-1.2.1.jar!/
com.vaadin.terminal.gwt.DefaultWidgetSet in jar:file:/home/s2padmin/workspace/VaadinProject/WebContent/WEB-INF/lib/vaadin-6.6.0.jar!/
com.example.vaadinproject.widgetset.VaadinprojectWidgetset in file:/home/s2padmin/workspace/VaadinProject/src
org.vaadin.risto.formsender.widgetset.FormsenderWidgetset in jar:file:/home/s2padmin/workspace/VaadinProject/WebContent/WEB-INF/lib/formsender-0.1.jar!/
Sep 28, 2011 10:32:50 AM com.vaadin.terminal.gwt.widgetsetutils.ClassPathExplorer getAvailableWidgetSets
INFO: Search took 28ms
Done.
Starting GWT compiler
Sep 28, 2011 10:33:16 AM com.vaadin.terminal.gwt.widgetsetutils.ClassPathExplorer getPaintablesHavingWidgetAnnotation
INFO: Searching for paintables..
Sep 28, 2011 10:33:17 AM com.vaadin.terminal.gwt.widgetsetutils.ClassPathExplorer getPaintablesHavingWidgetAnnotation
INFO: Search took 1075ms
Widgetset compilation completed
it looks good so far, a new file is being made in my project "widgetset.gwt.xml" it contains :
inherits name="org.vaadin.risto.formsender.widgetset.FormsenderWidgetset"
but its not working ... i get the following message in my portlet :
Widgetset does not contain implementation for
org.vaadin.risto.formsender.FormSender. Check its @ClientWidget
mapping, widgetsets GWT module description file and re-compile your
widgetset. In case you have downloaded a vaadin add-on package, you
might want to refer to add-on instructions. Unrendered UIDL:
org.vaadin.risto.formsender.FormSender(NO CLIENT IMPLEMENTATION FOUND)
id=PID7
Im working with eclipse, have liferay portal installed +vaadin addon.
have anyone seen something like this? is it because of liferay or something else , i have tryed lots of addons , but none of them is working.
A: I have downloaded an liferay plugin wich compiles the Vaadin addons.I was running my application as a portlet on Liferay , so i needed to compile the shared widgetset on Liferay , the compile button of Vaadins eclipse plugin compiled the widgets to the project not to the Portal itself.
Addon :
Vaadin Control Panel for Liferay
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Including a header file from another directory I have a main directory A with two sub directories B and C.
Directory B contains a header file structures.c:
#ifndef __STRUCTURES_H
#define __STRUCTURES_H
typedef struct __stud_ent__
{
char name[20];
int roll_num;
}stud;
#endif
Directory C contains main.c code:
#include<stdio.h>
#include<stdlib.h>
#include <structures.h>
int main()
{
stud *value;
value = malloc(sizeof(stud));
free (value);
printf("working \n");
return 0;
}
But I get an error:
main.c:3:24: error: structures.h: No such file or directory
main.c: In function ‘main’:
main.c:6: error: ‘stud’ undeclared (first use in this function)
main.c:6: error: (Each undeclared identifier is reported only once
main.c:6: error: for each function it appears in.)
main.c:6: error: ‘value’ undeclared (first use in this function)
What is the correct way to include the structures.h file into main.c?
A: When referencing to header files relative to your c file you should use #include "path/to/header.h"
The form #include <someheader.h> is only used for internal headers or for explicitly added directories (in gcc with the -I option).
A: write
#include "../b/structure.h"
in place of
#include <structures.h>
then go in directory in c & compile your main.c with
gcc main.c
A: If you work on a Makefile project or simply run your code from command line, use
gcc -IC main.c
where -I option adds your C directory to the list of directories to be searched for header files, so you'll be able to use #include "structures.h"anywhere in your project.
A: If you want to use the command line argument then you can give gcc -idirafter ../b/ main.c
then you don't have to do any thing inside your program.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
}
|
Q: Have eclipse "quick diff" reference source on a per project basis? I'm using Eclipse Indigo and was wondering if I can configure Quick diff, especially the Reference source, on a per project basis?
Not all of my projects use SVN or GIT, etc. and so I've to switch several times.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Intellij / Grails development what to set to avoid PermGen errors? i am using IntelliJ to develop Grails application but as our application grows i am hitting the Permgen errors when using the Tomcat plugin. I have tried several combination in settings permgen size but they seem not to have any effect.
Any solution in dealing with these Permgen errors?
A: In the Run menu, select Edit Configurations, choose the configuration that executes run-app for your Grails app, then enter a value for permgen as shown in red below.
A: Do you mean that you get perm gen errors after redeploying several times?
If yes, this is a flaw with Tomcat itself. The only way to fix it is to shut down Tomcat, restart it to empty out perm gen, and try again.
Grails itself contributes to the problem by using reflection to help enforce "convention over coding." Reflection uses perm gen to do its work. Hibernate can contribute as well; see
http://www.jroller.com/agileanswers/entry/preventing_java_s_java_lang
If you attach VisualVM 1.3.2 to the Tomcat process you'll be able to see all of memory, threads, etc. Maybe that'll help you understand better if something else is happening.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: mysql .net update stored procedure cannot be found i am using mysql with .net framework 4.0 . i have stored procedures in my database. my stored procedure calling is:
public DataTable addProductMenu(int myid, string itemname)
{
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlDataAdapter adapt = new MySqlDataAdapter("updateProductMenu", connection);
adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
adapt.SelectCommand.Parameters.AddWithValue("myid", myid);
adapt.SelectCommand.Parameters.AddWithValue("itemname", itemname);
DataTable dt = new DataTable();
adapt.Fill(dt);
adapt = null;
if (dt != null && dt.Rows.Count != 0)
{
return dt;
}
else
{
return null;
}
}
code is working when i use insert, select commands in database but not update. i tested my procedure in mysql query browser and its working fine.
Also tried this code for just update query
public DataTable updateProductMenu(int myid, string itemname)
{ //Veritabanından ürün menüsündeki başlığı güncelle
MySqlConnection cnx = new MySqlConnection(connectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
string cmdText = "updateProductMenu";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);
cmd.CommandType = CommandType.StoredProcedure;
MySqlParameter param;
param = new MySqlParameter("?myid", MySqlDbType.Int32);
param.Value = myid;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);
param = new MySqlParameter("?itemname", MySqlDbType.VarChar);
param.Value = itemname;
param.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param);
adapter.SelectCommand = cmd;
DataTable dt = new DataTable();
adapter.Fill(dt);
adapter = null;
if (dt != null && dt.Rows.Count != 0)
{
return dt;
}
else
{
return null;
}
}
both have the error
Procedure or function '`updateProductMenu`' cannot be found in database '`mydatabase`'.
ADDED-----------------------------------------
the user has all privileges. i checked again.
here is my connectionstring in web.config file...:
<add name="maktesConn" connectionString="Server = myserver; Port =3306; Database =mydatabase; Uid =mysqlsanatkar; Pwd =*123qsanatq*/;" />
.......and here is part of my class.....:
public class Mimages
{
private string connectionString;
public Mimages()
{
connectionString = ConfigurationManager.ConnectionStrings["maktesConn"].ToString();
}
and here is part of my stored procedure
DROP PROCEDURE IF EXISTS mydatabase.updateProductMenu $$
CREATE PROCEDURE mydatabase.updateProductMenu (myid INT, itemname VARCHAR(60))
BEGIN
....
A: Are you saying that you are able to call other stored procedures with the same code or just select and insert commands ?
Have you checked caps on both database name and stored procedure name? Depending on settings MySql will convert names to lower case and become case sensitive.
Checked security for db current ?
A: Solved the problem.... mysql connector for .net was 6.3.7. i updated it to 6.4.4. Now all my stored procedures are working. Thanks for your reply "bang" btw.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why this local variable can keep its value in the function
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I recently met a problem in Python.
Code:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
the output would be
[1]
[1, 2]
[1, 2, 3]
but why the value in the local list: L in the function f remains unchanged?
Because L is a local variable, I think the output should be:
[1]
[2]
[3]
I tried another way to implement this function:
Code:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
This time, the output is:
[1]
[2]
[3]
I just don't understand why...
Does anyone have some ideas? many thanks.
A: The default parameters are in fact initialized when the function is defined, so
def f(L = []): pass
is quite similar to
global default_L = []
def f(L = default_L): pass
You can see this way that it is the same list object that is used in every invocation of the function.
A: The list in def f(a, L=[]) is defined as the function is defined. It is the same list every time you call the function without a keyword argument.
Setting the keyword to None and checking / creating as you have done is the usual work around for this sort of behaviour.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MPMoviePlayerController : orientation problem finally I have to post my problem here. Yes it could be duplicate question here as I have referred many answers regarding to this question.But I could not find any fix. (Also didn't find any question regarding to tab-bar app specific so...) And I don't want to use MPMoviePlayerViewController
I have tab-bar application. In last tab's VC there is a button. On click event I want to start movie player. For that I am using MPMoviePlayerController. Its all fine when orientation is Portrait . But regarding to changes, now I have to play it in landscape mode only.
here is my code :
-(void)playMovie
{
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
[self.scrollView addSubview:moviePlayer.view];
[moviePlayer play];
[moviePlayer setFullscreen:TRUE];
}
-(void)btnPlayHandler:(id)sender
{
NSLog(@"btnPlayHandler");
NSURL * videoUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[dictResponse valueForKey:@"VideoPath"]]];
moviePlayer = [[MPMoviePlayerController alloc]initWithContentURL:videoUrl];
//[moviePlayer.view setFrame:CGRectMake(20, 40, 280, 222)];
moviePlayer.fullscreen = YES ;
moviePlayer.shouldAutoplay = NO ;
[self performSelector:@selector(playMovie) withObject:nil afterDelay:1];
}
- (void) movieWillExit:(NSNotification *)notification
{
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
}
- (void) movieExit:(NSNotification *)notification
{
[moviePlayer stop];
[moviePlayer.view removeFromSuperview];
moviePlayer = nil ;
[btnPlay setHidden:FALSE];
}
- (void)moviePreLoad:(NSNotification *)notification
{
NSLog(@"moviePreLoad");
}
- (void)moviePlaybackComplete:(NSNotification *)notification
{
NSLog(@"moviePlaybackComplete");
[btnPlay setHidden:FALSE];
}
Only device's orientation is changed not player's view ! How to accomplish this ??? Is it because the tab-bar application ?
A: You are making the window landscape, but as you have set the MPMoviePlayer view in scrollview, it is not rotating. try to rotate the scrollview according to your orientation.
See this link http://blog.sallarp.com/shouldautorotatetointerfaceorientation/. Hopefully it will solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is setting multiple variables in 1 line valid in javascript? (var x=y='value';) This is valid in php:
$x=$y='value';
This will in esscence set both $x and $y to 'value'.
Is this valid in javascript?
var x=y='value';
I have tested it in chrome console and it worked as expected, but just wanted to double check before starting to use it.
A: It only works if the var y as been previously defined, otherwise ywill be global.
In such case, you better do:
var x, y;
x = y = 'value';
Assignments Chaining
Another antipattern that creates implied globals is to chain assignments as part of a
var declaration. In the following snippet, a is local but b becomes global, which is
probably not what you meant to do:
// antipattern, do not use
function foo() {
var a = b = 0;
// ...
}
If you’re wondering why that happens, it’s because of the right-to-left evaluation. First,
the expression b = 0 is evaluated and in this case b is not declared. The return value of
this expression is 0, and it’s assigned to the new local variable declared with var a. In
other words, it’s as if you’ve typed:
var a = (b = 0);
If you’ve already declared the variables, chaining assignments is fine and doesn’t create
unexpected globals. Example:
function foo() {
var a, b;
// ...
a = b = 0; // both local
}
“JavaScript Patterns, by Stoyan Stefanov
(O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”
A: To prevent the y from becoming a global variable, use the following:
var x, y = x = 'value';
Apparently the declarations are simply evaluated from left to right.
A: I'm pretty sure that the most readable form is the one that has not been brought up yet:
let x = 0, y = 0
A: Yes, that is valid in Javascript.
However, after googling the problem, this Stack Overflow question explains some caveats, so use with caution.
A: When vars have different values you can easily write:
var x = 0,
y = 1,
...
z = 2;
A: In some cases involving objects and arrays, Assignments Chaining is not safe.
This is an example:
const a = {}
// Use Assignments Chaining to save some typing.
a['foo'] = a['bar'] = []
// I just want to set a['foo'] when some condition meets.
for (let i = 0; i < 5; i++) {
a['foo'].push({ title: 'hello', number: i / 2 })
}
// But you maybe get this unexpected assignment.
console.log(a['bar'])
/*
[
{
"title": "hello",
"number": 0
},
{
"title": "hello",
"number": 0.5
},
{
"title": "hello",
"number": 1
},
{
"title": "hello",
"number": 1.5
},
{
"title": "hello",
"number": 2
}
]
*/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: cs0030:Unable to generate a temporary class I have a Web Service, when I try to generate the object of it I am getting below error.
"Unable to generate a temporary class (result=1).error CS0030: Cannot convert type 'ShortSell.ShortSellRQOriginDestinationInformationFlightSegment[]' to 'ShortSell.ShortSellRQOriginDestinationInformationFlightSegment'error CS0030: Cannot convert type 'ShortSell.ShortSellRSOriginDestinationOptionFlightSegment[]' to 'ShortSell.ShortSellRSOriginDestinationOptionFlightSegment'error CS0030: Cannot convert type 'ShortSell.ShortSellRQOriginDestinationInformationFlightSegment[]' to 'ShortSell.ShortSellRQOriginDestinationInformationFlightSegment'error CS0029: Cannot implicitly convert type 'ShortSell.ShortSellRQOriginDestinationInformationFlightSegment' to 'ShortSell.ShortSellRQOriginDestinationInformationFlightSegment[]'error CS0029: Cannot implicitly convert type 'ShortSell.ShortSellRSOriginDestinationOptionFlightSegment' to 'ShortSell.ShortSellRSOriginDestinationOptionFlightSegment[]'error CS0029: Cannot implicitly convert type 'ShortSell.ShortSellRSOriginDestinationOptionFlightSegment' to 'ShortSell.ShortSellRSOriginDestinationOptionFlightSegment[]'"}
I tried changing the temp folder properties to writable but I am still getting this error. Why am I getting this error and how can I fix it?
A: It's a known bug that won't be fixed:
*
*Microsoft Connect: XmlSerializer Code Generation component cannot handle nested unbounded elements when there is only one element
The error occurs when a complex type in the wsdl contains exactly one element with unbounded occurrence. The workaround, taken from this forum discussion (credit to Elena Kharitidi), is to add dummy attributes to such types:
<xs:sequence maxOccurs="unbounded">
<xs:element ../>
<xs:sequence>
<xs:attribute name="tmp" type="xs:string" /> <-- add this
and
<xs:sequence>
<xs:element maxOccurs="unbounded"/>
<xs:sequence>
<xs:attribute name="tmp" type="xs:string" /> <-- add this
A: In my wdsl there was no "xs:sequence" element, so I couldn't apply wsdl file change directly. However, I fixed the issue by referencing below post.
https://stackoverflow.com/a/27507816/503446
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Visual studio 2010: limiting the number of editor tabs Visual studio doesn't appear to limit the number of opened editor tabs.
I'm using ReSharper and at a certain number of opened editor tabs things get really slow. So I have to keep track of opened tabs and periodically close old ones.
It would be cool if I could set a limit so that it would close old tabs when the limit is reached.
Is there a setting in VS / ReSharper or any VS addons that can help to achieve this?
A: I'm trying to solve this with a primitive addin at the moment. Seems to be working fine. Still testing it.
public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
_applicationObject = (DTE2)application;
_applicationObject.Events.WindowEvents.WindowCreated +=
window =>
{
if (window.Document != null)
{
documentWindows.AddFirst(window);
if(documentWindows.Count > 7)
{
Window lastWindow = documentWindows.Last.Value;
documentWindows.Remove(lastWindow);
lastWindow.Close(vsSaveChanges.vsSaveChangesYes);
}
}
};
_applicationObject.Events.WindowEvents.WindowClosing +=
window =>
{
if(window.Document != null)
{
documentWindows.Remove(window);
}
};
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android MediaPlayer custom control panel hide I have created a custom control panel for a video player. Now I want to give a effect like default MediaController where the panel becomes visible when the screen is touched and it becomes invisible again after the last touch time. I can use this type of code for that.
Thread thread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// make the panel invisible
}
});
}
};
I can start the thread when the screen is touched and make it invisible after 60 seconds. But in my case, if the user touches the screen again in between this 60 seconds, the panel should vanish after 60 seconds from the last touch. How to consider this case also?
A: I would recommend using a combination of Runnables and a Handler. You can do Handler calls using postDelayed() to do something after, say, 60 seconds.
Here's an example:
private Handler mHandler = new Handler();
mHandler.post(showControls); // Call this to show the controls
private Runnable showControls = new Runnable() {
public void run() {
// Code to show controls
mHandler.removeCallbacks(showControls);
mHandler.postDelayed(hideControls, 60000);
}
};
private Runnable hideControls = new Runnable() {
public void run() {
// Code to hide the controls
}
};
A: Simply delete/cancel current timer.
Btw, you should not do it by Thread, but by posting message to a Handler. Such future timer task doesn't need another thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Process reuse - async BeginOutputReadLine problem I've encountered an interesting problem.
C# allows reusing process resource (according to MSDN) - so I call instance Start() method after process is finished:
Process p = new Process();
// init
p.Start();
And some time later:
p.Kill();
// not important
p.Start();
When I have a thread performing sync read everything seems to be ok - output is being read after first and second Start() call.
Now the funny thing. When I use async read (everything initialized properly):
p.BeginOutputReadLine();
output is being read only after first Start() call. After second call process is started without any output being redirected.
I've also tried calling Cancel and Begin once more:
p.CancelOutputRead();
p.Kill();
// not important
p.Start();
p.BeginOutputReadLine();
with same result.
Some machine details: Win 7 Ultimate x86 SP1 (CPU also x86), tested on .NET 2.0 / 3.0, VS 2008
The question is - is it some framework bug or my misunderstanding of the Process.Start definition ("Starts (or reuses) the process resource that is specified by the StartInfo property of this Process component and associates it with the component.")? Any help much appreciated.
I suppose the solution is recreation of the process object, but it'll probably be slower.
A: Calling Kill makes it necessary to add your event handler for OutputDataReceived again before calling Start.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: cross domain xml read I want to get xml data from the foreign domain using ajax,But without using Proxi.
Is there any way to get xml data using ajax. Actually I want to do something like this:
enter code here
jQuery.getScript("http://m.jbv.no/mobile/stopmonitoring/xml/OSL",function(data, textStatus){
console.log(data); //data XML returned
console.log(textStatus); //success
console.log('Load was performed.');
});
$.ajax({url: "http://m.jbv.no/mobile/stopmonitoring/xml/OSL", dataType:'html', crossDomain:true, error:function(jqXHR, textStatus, errorThrown) { alert(jqXHR) }, success: function(data){ alert(data) }});
A: You can use easyxdm javascript library for communicating between crossdomains. I used this library for fixing the width, height of iframe or any other element that resides on other domain there was no other way for communicating to other domain because of security reasons.
May be this can help you. So here is a link:
http://easyxdm.net/wp/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: image uploading is not working in php I am working on image uploader in cakephp. I have used this link "http://www.jquery4u.com/tutorials/thumbnail-image-upload-ajaxphp/#comment-10823" to display thumb images when user clicks the browse button . Everything is working fine in fire fox but not working in other browsers(IE, chrome). This is because File properties ( i.e type, tmp_name, name) were not submitted when user clicks the submit button. Below is my code for image uploading
<?php
echo $form->create('imageupload');
echo $form->input('image_browse',array('label'=>false,'div'=>false, 'size'=>23, 'type'=>'file','class'=>'image_browse','id'=>'image_browse','onChange'=>'javascript:previewImage(this.value)));
echo $form->submit();?>
In my controller, i am using the var_dump($_FILES); to see the file parameters, but it is giving following output.
array
'image_browse' =>
array
'name' => string '' (length=0)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 4
'size' => int 0
Even though i gave the proper image path, it is giving file not uploaded error. If i remove the js file link used to display thumbs, it is working good. But i want to display thumb as well as upload the file.
How to solve this issue?
Thanks in advance
Pushpa
A:
Hey Buddy!
Start the form as:
<?php
echo $this->Form->create('imageupload', array('type' => 'file'));
?>
and after that create input elements
A: Had a similar problem
If your $_FILES and $_POST are empty, this can be due to
*
*the limit set by post_max_size in php.ini
*the limit set by upload_max_filesize in php.ini
Unfortunately the first limit is not reported back as an error code in $_FILES['error'].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NodeJS and Mongoose with Mongodb sharding issue I have been using NodeJS, MongooseJS with Mongodb. It is throwing the following error when i try to insert an record in mongodb using mongooseJS
"MongoError: right object doesn't have full shard key"
FYI: MongoDB Table having shard key
Please tell me how to resolve this issue! and what is that error mean?
A: When you are inserting any object into Mongo collection which has shard key, object should have all shard keys (i.e. full shard key).
As mongodb's doc says:
All (non-multi)updates, upserts, and inserts
must include the current shard key."
current shard key in the sense all the shard key which are currently applicable.
A: Mongoose 2.5.3 has support for sharding, just include the shardkey in the schema options and Mongoose does the rest.
var LoginSchema = new Schema({attribut: String},
{ shardkey: { at: 1, _user: 1 }}
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting Same Request.UrlReferrer I have one page Result.aspx.this is main page of my website.
There are many images of proudcts in this pages.
When i click on image of product, it is redirected to DetailResult.aspx
Image Code is here:
<td>
<a href="<%#Eval("DetailsURL")%>">
<asp:Image runat="server" ID="ImgThumb" Width="115" Height="81" />
</a>
</td>
Now, On load event of DetailResult.aspx, i am getting runtime error for NullReferenceException(or any).
To handle runtime error, i have configured web.config with CustomErrors tag
CustomErrors Tag Code here:
<customErrors mode="On" defaultRedirect="~/Result.aspx?RunTimeError=1">
</customErrors>
So the runtime error of DetailResult.aspx page redirects to Result.aspx.
In this case, on Result.aspx when i try to get previous page URL using Request.UrlReferrer, i am getting its value "Result.aspx" instead of "DetailResult.aspx"
A: UrlReferrer is an http header sent by your browser. If you click a link on Result.aspx, and you end up on Result.aspx?RunTimeError=1, your browser (not unreasonably) decides that the UrlReferrer should be set to the page that initiated the action. That there was a 302 redirect from DetailResult.aspx is not particularly important.
If you would like to know the page that caused the error, you could configure an errorpage that will append this information to the querystring before redirecting.
Menno
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rhodes or Titanium for Rails app in iphone? Hi i wanted to develop an iphone app with Ruby..
Is Rhodes or Titanium the best option?
i need to integrate GPS and google maps
A: Rhodes is the only way to actually write a mobile app in Ruby. It is not possible to do so with Titanium or any other framework. Rhodes (and PhoneGap for that matter) emphasize writing interfaces with HTML5 and styling libraries like jQuery Mobile and Sencha Touch (but still to build a native app NOT a web app). Titanium creates its own UI abstractions and does not allow use of such styling libraries. We believe that use of HTML5
A: If you want to write the iPhone app in Ruby then Rhodes is as far as I know your only choice. I've made several apps with Titanium and the only language(s) you can use is Javascript/Coffeescript (Coffeescript compiles to JS). Titanium's Ruby support is only for desktop as someone has already pointed out.
As far as capabilities for Rhodes check out http://docs.rhomobile.com/rhodes/device-caps. Looks like they have support for Geolocation and Native maps.
A: Rhodes seems to be a Ruby only solution, while Titanium offers support for Ruby/Python/PHP. Because of this, I would choose Rhodes. Other than that, you should have access to all of the features from all the frameworks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how can i get set integer, string value from my Enum in Java? How can i pre-define any types of values in the Enum?
public enum Hardware
{
USB2(0) = "external low speed",
PCI(1) = "embedded",
USB3(2) = "external high speed
}
System.out.println( Hardware.USB2 ) // show me external low speed
A: You can define members in enums. Then override the toString()
You can define a getDesc() method which is IMO better that override toString().
public enum Hardware
{
USB2(0, "external low speed"),
PCI(1,"embedded"),
USB3(2,"external high speed");
private String desc;
private int id;
private Hardware(int id, String desc) {
this.id = id;
this.desc = desc;
}
@Override
public String toString() {
return this.desc;
}
}
Just note that is solution is available starting at Java version 1.5
A: enum Hardware
{
USB2("external low speed"),
PCI("embedded"),
USB3("external high speed");
private String val;
private Hardware(String val){
this.val = val;
}
public String toString(){
return val;
}
}
A: public enum Hardware {
USB2(0, "external low speed"),
PCI(1,"embedded"),
USB3(2,"external high speed);
String desc;
int id;
public Hardware(int id, String desc) {
this.id = id;
this.desc = desc;
}
public String toString() {
return this.desc;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: FOP failing to use data when used with JAXB I'm generating a document using FOP (0.95) by passing a source XML file created using JAXB (2.2.13), when I run it I get a virtually empty PDF (it looks like I'd expect if no data was supplied in the source XML) and the only log output is:
DEBUG [FOP] target-resolution set to: 72.0dpi (px2mm=0.35277778)
INFO [org.apache.fop.layoutmgr.table.TableLayoutManager] table-layout="fixed" and width="auto", but auto-layout not supported => assuming width="100%"
WARN [org.apache.fop.layoutmgr.PageBreakingAlgorithm] Part/page 0 overflows the available area in block-progression dimension. (fo:static-content, no context info available)
but if I comment out the line
@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.blah.com/ctms/Comparison")
in the package-info.java file generated from my XSD by JAXB and recompile then the PDF generates fine.
Is there an obvious change I need to make so that I can use the generated JAXB code without editing anything, or alternatively some debugging I can enable to see what is happening?
My XSD is:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:pi="http://www.blah.com/ctms/Comparison" targetNamespace="http://www.blah.com/ctms/Comparison" elementFormDefault="unqualified">
<xs:element name="comparison">
<xs:annotation>
<xs:documentation>Document containing comparison data for report</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="sub-category" type="pi:sub-category" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="import-id" type="xs:string"/>
<xs:element name="row-no" type="xs:string"/>
<xs:element name="investigator-no" type="xs:string"/>
<xs:element name="clinical-personnel-name" type="xs:string"/>
<xs:element name="report-footer-message" type="xs:string"/>
<xs:element name="checklist" type="pi:checklist" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="properties" type="pi:properties" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="field-type">
<xs:sequence>
<xs:element name="importValue" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="existingValue" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="record-type">
<xs:sequence>
<xs:element name="field" type="pi:field-type" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="sub-category">
<xs:sequence>
<xs:element name="record" type="pi:record-type" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="message" type="xs:string" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>
<xs:complexType name="checklist">
<xs:sequence>
<xs:element name="checklist-no" type="xs:string"/>
<xs:element name="checklist-title" type="xs:string"/>
<xs:element name="checklist-description" type="xs:string"/>
<xs:element name="checklist-status" type="xs:string"/>
<xs:element name="completed-by" type="xs:string"/>
<xs:element name="completed-date" type="xs:string"/>
<xs:element name="question-item" type="pi:question-item" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="question-item">
<xs:sequence>
<xs:element name="item-desc" type="xs:string"/>
<xs:element name="response" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="item-no" type="xs:string"/>
</xs:sequence>
</xs:complexType>
and the following is an example of the generated XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:comparison xmlns:ns2="http://www.blah.com/ctms/Comparison">
<sub-category name="Specialist Fields">
<record>
<field name="Specialist Field">
<importValue>Adult Endocrinologist [AE]</importValue>
<existingValue>Adult Endocrinologist [AE]</existingValue>
</field>
<field name="Key Opinion Leader">
<importValue></importValue>
<existingValue>No</existingValue>
</field>
<field name="Board Certification">
<importValue></importValue>
<existingValue>Yes</existingValue>
</field>
</record>
<record>
<field name="Specialist Field">
<importValue>Cardiac Surgeon [CS]</importValue>
<existingValue>Cardiac Surgeon [CS]</existingValue>
</field>
<field name="Key Opinion Leader">
<importValue></importValue>
<existingValue>No</existingValue>
</field>
<field name="Board Certification">
<importValue>No</importValue>
<existingValue>Yes</existingValue>
</field>
</record>
</sub-category>
<sub-category name="Clinical Personnel Address">
<record>
<field>
<importValue>2-Line 1</importValue>
<importValue>Florida [US-FL]</importValue>
<importValue>United States of America [USA]</importValue>
</field>
</record>
<record>
<field>
<existingValue>Line 1</existingValue>
<existingValue>Florida [US-FL]</existingValue>
<existingValue>United States of America [USA]</existingValue>
</field>
</record>
</sub-category>
<sub-category name="Membership Information">
<record>
<field name="Association/Society">
<importValue>The Dennis the Menace Fan Club</importValue>
</field>
<field>
<existingValue>Tufty Club</existingValue>
</field>
</record>
</sub-category>
<sub-category name="Centre">
<record>
<field name="Centre">
<existingValue>Centre Name 313</existingValue>
<existingValue>Address Line 1 for Cneter 313</existingValue>
<existingValue>Address Line 2 for Cneter 313</existingValue>
<existingValue>Address Line 3 for Cneter 313</existingValue>
<existingValue>Address Line 4 for Cneter 313</existingValue>
<existingValue>Centre Town City 313</existingValue>
<existingValue>P_C 313</existingValue>
<existingValue>ZZ Country CA0................ [CA0]</existingValue>
</field>
<field>
<existingValue>Centre Name 312</existingValue>
<existingValue>Address Line 1 for Cneter 312</existingValue>
<existingValue>Address Line 2 for Cneter 312</existingValue>
<existingValue>Address Line 3 for Cneter 312</existingValue>
<existingValue>Address Line 4 for Cneter 312</existingValue>
<existingValue>Centre Town City 312</existingValue>
<existingValue>P_C 312</existingValue>
<existingValue>ZZ Country CA0................ [CA0]</existingValue>
</field>
</record>
<message>The system identified 2 Centres as being a potential match to the imported Centre details and therefore both the imported Centre and each Centre associated to the existing Clinical Personnel is listed below.</message>
</sub-category>
<sub-category name="Clinical Personnel">
<record>
<field name="Investigator Alias Code">
<importValue>5656</importValue>
<existingValue>545</existingValue>
</field>
<field name="Title">
<existingValue>Mrs</existingValue>
</field>
</record>
</sub-category>
<sub-category name="Therapeutic Interests">
<record>
<field name="Therapeutic Group/Interest">
<importValue>Therapeutic Interest Group Descripti Max [ABCDEFZ]/Therapeutic Interest Description 012 Max [ABCDEFZ]</importValue>
</field>
</record>
</sub-category>
<sub-category name="Fraud and Misconduct Events">
<record>
<field name="Event">
<importValue>Very Bad Things [VBAD]</importValue>
<existingValue>Very Bad Things [VBAD]</existingValue>
</field>
<field name="Event Date">
<importValue>10-Jan-2011</importValue>
<existingValue>01-Sep-2011</existingValue>
</field>
</record>
<record>
<field name="Event">
<importValue>Bad Things [BAD]</importValue>
<existingValue>Bad Things [BAD]</existingValue>
</field>
<field name="Event Date">
<importValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<existingValue>22-Sep-2011</existingValue>
</field>
</record>
<record>
<field name="Event">
<existingValue>Extremely Bad Things [EBAD]</existingValue>
</field>
<field name="Event Date">
<existingValue>14-Sep-2011</existingValue>
</field>
</record>
</sub-category>
<import-id>30</import-id>
<row-no>2</row-no>
<investigator-no>153</investigator-no>
<clinical-personnel-name>Mrs B B SPECIALIST</clinical-personnel-name>
<report-footer-message>Report Produced at 28-09-2011 09:42 by Mr Installation</report-footer-message>
<properties><property key="heading.clinicalPersonnelComparisonReport">Clinical Personnel Comparison Report</property><property key="heading.importId">Import Id</property><property key="heading.recordNo">Record No</property><property key="heading.existingDuplicateClinicalPersonnel">Existing Duplicate Clinical Personnel</property><property key="heading.clinicalPersonnelComparisonReportTitle">This report details the differences which exist between the imported Clinical Personnel and the existing master Clinical Personnel.</property><property key="heading.clinicalPersonnelComparisonReportTitleNoDifferences">No differences exist between the imported Clinical Personnel and the existing master Clinical Personnel.</property><property key="heading.followingClinicalPersonnelDetailsDiffer">The following Clinical Personnel details differ:-</property><property key="heading.clinicalPersonnelDetails">Clinical Personnel Details</property><property key="heading.itemName">Item Name</property><property key="heading.importValue">Import Value</property><property key="heading.existingClinicalPersonnelValue">Existing Clinical Personnel Value</property><property key="heading.addressDetails">Address Details</property><property key="heading.noDifferencesIdentified">No differences identified</property><property key="heading.addressType">Address Type</property><property key="heading.field">Field</property><property key="heading.importAddress">Import Address</property><property key="heading.existingClinicalPersonnelAddress">Existing Clinical Personnel Address</property><property key="heading.fraudMisconduct">Fraud and Misconduct</property><property key="heading.event">Event</property><property key="heading.eventDate">Event Date</property><property key="heading.associatedCentre">Associated Centre</property><property key="heading.importCentre">Import Centre</property><property key="heading.existingClinicalPersonnelCentre">Existing Clinical Personnel Centre</property><property key="heading.specialistsFields">Specialist Fields</property><property key="heading.therapeuticInterests">Therapeutic Interests</property><property key="heading.therapeuticGroupInterest">Therapeutic Group/Interest</property><property key="heading.membershipInformation">Membership Information</property><property key="heading.invMembershipsInformationMembership">Association/Society</property><property key="heading.investigatorNo">Investigator No</property><property key="heading.existingClinicalPersonnelChecklists">Existing Clinical Personnel Checklist(s)</property><property key="heading.checklistNo">Checklist No</property><property key="heading.title">Title</property><property key="heading.description">Description</property><property key="heading.status">Status</property><property key="heading.completedBy">Completed By</property><property key="heading.completedDate">Completed Date</property><property key="heading.question">Question</property><property key="heading.response">Response</property></properties>
</ns2:comparison>
(The only edit I've made to the above files is to replace my work's name with "blah")
Update I have also tried setting elementFormDefault="qualified" in the XSD, but that doesn't help (although the generated XML does lose the "ns2" namespace prefix)
A: How do you create your XSL-FO? Some XSLT transformation? Seems like this transformation expects the document in the default namespace.
If this is so then there's two ways to approch this:
*
*If you want to keep the XSLT as it is, you have to change the schema to be namespaceless.
*If you're OK to change the XSLT, make it process elements in your namespace instead of empty namespace. Use elementFormDefault="qualified" and attributeFormDefault="unqualified", it's a usual practice.
The decision is mainly based on the question - if you care about the namespace of your schema. If you don't, the first way will cost you less effort. Me personally, I'd opt for the second option, I think namespaces to be important.
Yet another way is to keep namespaces but use an XSLT to drop them before rendering with FOP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how can i connect my blackberry app to my website rest API? I am trying to build my first app for blackberry mobile's but i am new @ mobile development and i am cant find the correct way to connect my app with my webiste rest API can anyone guide me where to start from?
Thanx in advance :D
A: HttpConnection conn = null;
InputStream is = null;
ByteArrayOutputStream bos = null;
String response = null;
String connectionURL = null;
try {
connectionURL = "THIS CONTAIN YOUR API URL"
conn = (HttpConnection) Connector.open(connectionURL);
conn.setRequestProperty("Content-Type","application/json");
System.out.println("Response code : "+conn.getResponseCode());
if(conn.getResponseCode() == HttpConnection.HTTP_OK)
{
is = conn.openInputStream();
int ch=-1;
bos = new ByteArrayOutputStream();
while((ch = is.read())!=-1)
{
bos.write(ch);
}
response = new String(bos.toByteArray());
System.out.println("Response : "+response);
}
} catch (Exception e)
{
System.out.println("Exception .."+e);
}finally
{
if(conn != null)
conn.close();
if(is != null)
is.close();
if(bos != null)
bos.close();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: wordpress simple google map I am use SGM plugin for wordpress and there are grey stripes
This is example from http://clarknikdelpowell.com/wordpress/simple-google-map/
[SGM lat="28.022827" lng="-81.73127" zoom="14" type="TERRAIN" directionsto="62 4th St NW, Winter Haven, FL 33881" content="Clark/Nikdel/Powell, Inc.62 4th St NW, Winter Haven FL 33881For directions enter your address below"]
A: The internal sections of the google map are made of out square divs. Maybe you are setting all divs to have left/right margins or paddings in your style sheets? Try disabling styles for your webpage and see if this problem still occurs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Twitter4J: Get more than 1 tweet from a user I'm trying to get a list of recent statuses from each user on a persons list of followers. I've got the following to get the users...
IDs list = twitter.getFriendsIDs(0);
for(long ID : list.getIDs()){
twitter4j.User TW_user = twitter.showUser(ID);
}
All I can get from this is getStatus() which is their most recent status. getHomeTimeline() is also insufficient as I need a list of recent tweets from each user. Is there anyway I can achieve this using Twitter4J?
A: I was just trying to find this answer myself. I had decent success using the getUserTimeline method. Looks like you're trying to look up a list of friend IDs, so this method below should take the long[] and spit out all the user statuses. lookupUsers also accepts a String[] of screen names if you want to look users up that way instead.
public static void lookupUsers(long[] usersList) {
try {
Twitter twitter = new TwitterFactory().getInstance();
ResponseList<User> users = twitter.lookupUsers(usersList);
Paging paging = new Paging(1, 100);
List<Status> statuses;
for (User user : users) {
statuses = twitter.getUserTimeline(user.getScreenName(), paging);
System.out.println("\nUser: @" + user.getScreenName());
for (Status s : statuses) {
System.out.println(s.getText());
}
}
} catch (TwitterException e) {
e.printStackTrace();
}
}
A: Alex's answer is close, but will only get you 100 tweets per user. The following will get you all (or at least the API's max limit):
IDs list = twitter.getFriendsIDs(0);
for(long ID : list.getIDs()) {
Status[] tweets = getAllTweets(twitter, ID);
System.out.println(ID + ": " + tweets.length);
}
Status[] getAllTweets(Twitter twitter, long userId)
{
int pageno = 1;
List statuses = new ArrayList();
while (true)
{
try
{
int size = statuses.size();
Paging page = new Paging(pageno++, 100);
statuses.addAll(twitter.getUserTimeline(userId, page));
if (statuses.size() == size)
break;
}
catch (TwitterException e)
{
e.printStackTrace();
}
}
return (Status[]) statuses.toArray(new Status[0]);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can pickerview have date component to it? I need to add a date component to my PickerView. Any ideas on how to get the date component? One way is to manually maintain all the date related info, take current date add and subtract to get the reqd dates, but this is very tedious, any other methods?
EDIT:I have not yet got about to writing the code, i need some ideas on how to go about getting the values for the date component(not UI). One solution I have is to take the current date and then use the 'dateByAddingTimeInterval' to maintain the the last 50 and next 50 days, but his approach is very crude. Is there a better way to do this?
A: Going from comments here:
I suggest you to try this one approach.
*
*Creating one UIPickerView.
*Setting its parameters (step 1 in class that implements UIPickerViewDataSource):
*
*Implement - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView that will provide number of components. In your case it is 3 : return 3;
*Implement - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component that will return the number of row for each component.
*Setting its parameters (step 1 in class that implements UIPickerViewDelegate):
*
*Implement - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view which will return UILabel for component 0 and 1 and UIView with two UILabel's as subview (gray one and black one) for component 2
Also you can make more customization by implementing other methods in delegate class:
Setting the Dimensions of the Picker View
– pickerView:rowHeightForComponent:
– pickerView:widthForComponent:
Setting the Content of Component Rows
– pickerView:titleForRow:forComponent:
Complete list of methods you can find here: UIPickerViewDelegate Protocol Reference
A: I went ahead and used the same approach that i had mentioned in the question(given below). Even though its crude, it gets the work done. I have not tested this approach for large values of date in the third component. As of now i just have (30+30) values including the current date and its pretty stable and quick.
"One solution I have is to take the current date and then use the 'dateByAddingTimeInterval' to maintain the the last 50 and next 50 days, but his approach is very crude."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making HTTP POST request in Qt with Meego 1.2 Harmattan Here's the situation - I attach some file (JPEG image) to the HTTP POST request so it should be sent to the local server via Wi-Fi and server should return some result (simple text).
Here's the problem I faced doing this in my Qt-application for Nokia N9 (Meego 1.2 Harmattan).
After request is sent, proceed by the server and answer is sent back (I can see log on the server) there's a huge delay (about 1 min) before data from server reaches the handset.
If answer returns in several parts - the delay is before first part and others are getting very fast (as it should be with the first one too).
The same code I use in the same app for Symbian^3 (Symbian Anna) on Nokia C6-01 and it works just fine - all the data returns in a couple of seconds (tested in the same network with the same server and request). Also I have several GET requests sending from this app to the same server and all of them works fine too. So it might be the only Meego problem.
Snippets:
void PostDownloader::sendPostJpgImage(QString url, QImage image) {
if(mainReply)
return;
char boundary[] = "AyV04a234DsHeKHcvNds";
image = image.convertToFormat(QImage::Format_RGB888);
QByteArray body;
QBuffer buffer(&body);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "JPG");
buffer.close();
QByteArray b;
b.append("--").append(boundary).append("\r\n");
b.append("Content-Disposition: form-data; name=\"jpgfile\"; filename=\"camera\"\r\n");
b.append("Content-Type: image/jpeg\r\n");
b.append("\r\n");
b.append(body);
b.append("\r\n");
b.append("--").append(boundary).append("--");
QNetworkRequest req = QNetworkRequest(QUrl(url));
req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(QString("multipart/form-data; boundary=")+boundary));
req.setHeader(QNetworkRequest::ContentLengthHeader, QString::number(b.size()));
req.setRawHeader("Connection", "Close");
req.setRawHeader("Cache-Control", "no-cache");
req.setRawHeader("Keep-Alive", "1");
mainReply = manager->post(req, b); //POST
connect(mainReply, SIGNAL(readyRead()), this, SLOT(dataReceived()));
connect(mainReply, SIGNAL(finished()), this, SLOT(finished()));
}
So the delay is before calling the dataReceived() slot. How can this can be solved? What can you advice?
Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: atebits Twitter fast scrolling I'm looking to implement the same technique used by atebits in the Twitter app to achieve very fast UITableView scrolling,
http://blog.atebits.com/2008/12/fast-scrolling-in-tweetie-with-uitableview/
But, due to Tweetie being purchased by Twitter, atebits has ceased to exist and the sample code has gone, along with all of the css for the site.
Does anybody have a copy of the sample code or a different resource on implementing this method of drawing UITableViewCell's into one view?
A: Available here: https://github.com/enormego/ABTableViewCell
He is simply doing his own drawing in the drawRect: method inherited from UIView. See also Tricks for improving iPhone UITableView scrolling performance?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Resolving first time exception I am working on the nop ecommerce website, When i try to run the project, i am getting a continuous series of exceptions in the debug section of visual studio 2010 and the browser doesnt shows the website, on the bottom left of the browser , it displays waiting for localhost.
The exceptions are :
A first chance exception of type 'Autofac.Core.Registration.ComponentNotRegisteredException' occurred in Autofac.DLL
The thread '<No Name>' (0xb08) has exited with code 0 (0x0).
Does anyone knows the way around , I am struggling to cope with as the website was running fine previously but suddenly it has stopped working :(
A: I am currently having the same problem with Orchard. The problem seemed to occur when the beta of visual studio 2011 was installed, it has been suggested that it is being caused by a MVC or Razor assembly from the gac which is loaded and is taking over the ones which bin-ship.
http://orchard.codeplex.com/discussions/346791
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: A tooltip or something similar move with cursor in WPF Is it possible to move a Tooltip or something like that with cursor when mouse goes on a specific control?
I tried TextBlock, but Margin property not work.
private TextBlock tooltip = new TextBlock();
private void imgRoom_MouseEnter(object sender, MouseEventArgs e)
{
Point position = e.GetPosition((IInputElement)sender);
tooltip.Visibility = System.Windows.Visibility.Visible;
tooltip.Margin = new Thickness(position.X, position.Y, 0, 0);
tooltip.Width = 100;
tooltip.Height = 100;
tooltip.Background = new SolidColorBrush(Colors.Red);
}
private void imgRoom_MouseMove(object sender, MouseEventArgs e)
{
Point position = e.GetPosition((IInputElement)sender);
tooltip.Margin = new Thickness(position.X, position.Y, 0, 0);
}
A: I don't know if this is a best practice, or if it performs well, but you could use an Adorner.
I've created a proof of concept before, but haven't used it in a production scenario (yet). The adorner can be used to create something like this (tooltip), or a custom mouse cursor or drop target icons.
Make sure you set IsHitTestVisible = false if the adorner doesn't need to be hit tested and might appear directly under the mouse location.
UPDATE
Just fully read the description of adorners:
Common applications for adorners include:
*
*Adding functional handles to a UIElement that enable a user to manipulate the element in some way (resize, rotate, reposition, etc.).
*Provide visual feedback to indicate various states, or in response to various events.
*Overlay visual decorations on a UIElement.
*Visually mask or override part or all of a UIElement.
A: You can achieve the effect using a Popup and some simple properties upon it. From window code...
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Name="rect" Margin="50,50,0,0" Width="100" Height="100" Fill="LightBlue" MouseMove="Rectangle_MouseMove" MouseLeave="Rectangle_MouseLeave" />
<Popup Name="floatingTip" AllowsTransparency="True" Placement="Relative" PlacementTarget="{Binding ElementName=rect}">
<TextBlock>Look At Me</TextBlock>
</Popup>
</Grid>
</Window>
And this is what the codebehind would look like.
...
private void Rectangle_MouseMove(object sender, MouseEventArgs e)
{
if (!floatingTip.IsOpen) { floatingTip.IsOpen = true; }
Point currentPos = e.GetPosition(rect);
// The + 20 part is so your mouse pointer doesn't overlap.
floatingTip.HorizontalOffset = currentPos.X + 20;
floatingTip.VerticalOffset = currentPos.Y;
}
private void Rectangle_MouseLeave(object sender, MouseEventArgs e)
{
floatingTip.IsOpen = false;
}
...
So from the XAML you can see that the popup placement is relative to the rectangle. When you go mousing over the rectangle, it becomes visible, and its position is updated as the mouse moves. Naturally this is a very basic solution, but with some minor tweaks, handling events like 'MouseEnter' and property adjustment you can come up with some really neat effects.
A: This moves the tooltip around with the mouse cursor.
private void OnMouseMoveHandler(object sender, MouseEventArgs args)
{
if ((sender as FrameworkElement).ToolTip == null)
(sender as FrameworkElement).ToolTip = new ToolTip() { Placement = PlacementMode.Relative };
double x = args.GetPosition((sender as FrameworkElement)).X;
double y = args.GetPosition((sender as FrameworkElement)).Y;
var tip = ((sender as FrameworkElement).ToolTip as ToolTip);
tip.Content = tooltip_text;
tip.HorizontalOffset = x + 10;
tip.VerticalOffset = y + 10;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Using redis with node.js (express) I am learning node.js (and express framework) & here is a basic newbie question about redis & node.js. How to pass redis data to templates? What should I correct in my script, so I could display the value of teststring in a template?
app.get('/', function(req, res){
res.render('index', {
test: redisclient.get("teststring"),
});
});
Thanks in advance!
A: Since node.js modules (including the one for redis) tends to be non-blocking and asynchronous, they are returning results in callbacks. Try it this way (I also recommend to read this article regarding asynchronous code and callbacks):
app.get('/', function(req, res) {
redisclient.get("teststring", function(error, response) {
if(response) {
res.render('index', {
test: response,
});
} else {
res.render('index', {
test: error,
});
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why 3 rows deleted sql query puzzle? can anybody tell me the technical reason for this?
CREATE TABLE test (
id varchar(3) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO test VALUES ('0'), ('1'), ('2'), ('ab'), ('bb');
select * from test;
DELETE FROM test WHERE id=0;
Which Deletes 3 rows from table test.
A: Because this:
SELECT 0 = 'ab';
+----------+
| 0 = 'ab' |
+----------+
| 1 |
+----------+
To delete exact rows use BINARY operator, it will force byte by byte comparison -
DELETE FROM test WHERE id = BINARY 0;
A: When you compare numbers to strings, they are compared as float numbers. Any string that does NOT start with a digit is implicitly converted to number 0.
A: There is Difference Between a Character '0' and an integer 0.. When u Compare a Char with integer the Char string if not an integer returns a false value (i,e) A 0 hence making the condition true and delete the First, 4th and 5th row from ur Table... To Delete the particular row you need to check condition like this...
Delete from test where id = '0'; (A Char 0 not An Integer 0)
A: Try instead comparing values of the same type e.g.
DELETE FROM test WHERE id = CAST(0 AS VARCHAR(3));
A: Okay got first i confused when i see this but now i got it
when you're running
select * from test;
DELETE FROM test WHERE id=0;
This query Compares every row as a Integer not string,
So when MySQL comes to ab & bb so MySQL Take it as a 0 and delete it
if you start it with any digit like 1ab so MySQL Take 1ab as 1 and when you fire query for deleting 1 instead of 0 it will delete 1ab
Try
select * from test;
DELETE FROM test WHERE id='0';
This Code compare rows as a string so when he get exact '0' MySQL delete it else nothing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Trouble on testing a JavaScript redirection I am using Ruby on Rails 3.1.0 and the rspec-rails 2 gem. I would like to test a JavaScript redirection but I am some trouble on doing that.
In my controller file I have:
respond_to do |format|
format.js { render :js => "window.location.replace('#{users_url}');" }
end
In my spec file I have:
it "should redirect" do
xhr :post, :create
response.should redirect_to(users_url)
end
If I run the spec I get the following:
Failure/Error: response.should redirect_to(users_url)
Expected response to be a <:redirect>, but was <200>
How can I implement the spec code so to correctly test the JavaScript redirection?
ATTEMPTS AT SOLUTION
If I use
response.should render_template("window.location.replace('#{users_url}');")
I get
Failure/Error: response.should render_template("window.location.replace('#{users_url}');")
expecting <"window.location.replace('http://<my_application_url>/users');"> but rendering with <"">
If I use
response.should render_template(:js => "window.location.replace('#{users_url}');")
the spec successfully passes, but too much! That is, I can state also the following and the spec will (unexpectedly) pass:
response.should render_template(:js => "every_thing")
I have also seen this question\answer and the proposed solution works, but I think that is the best solution to accomplish what I aim.
A: RSpec controller specs use the rack_test driver, which does not execute Javascript. To test pages that use Javascript for redirection, you should really look at another driver.
Capybara with selenium-webdriver does this nicely. RSpec request specs replace your controller specs for those tests that rely on Javascript.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server - How to find if clustered index exists We got 500+ tables and want to identify which tables doesn't have primary keys. Because creating index on large table will help to improve performance.
Required Command - to identify table which are HEAPS (as they dont have clustered index)
Regards
A: SELECT OBJECT_NAME(object_id)
FROM sys.indexes
WHERE index_id=0
AND OBJECTPROPERTY(object_id, 'IsUserTable') = 1
Finds all heaps. This issue is orthogonal to whether or not a PK exists though. A heap can have a non clustered PK and a clustered index isn't necessarily the PK. To find tables without a PK you can use.
SELECT *
FROM sys.tables t
WHERE NOT EXISTS
(
SELECT *
FROM sys.indexes i
WHERE is_primary_key=1 AND i.object_id = t.object_id
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Social Networking Friends table - Explain Plan - Error Failed to enable constraints error I have a below table structure for friends table
TABLE STRUCTURE
CREATE TABLE `my_friends` (
`first_user_id` int(10) unsigned NOT NULL,
`second_user_id` int(10) unsigned NOT NULL,
`approved` tinyint(1) NOT NULL DEFAULT '0',
`request_sent` int(10) unsigned DEFAULT NULL,
`request_approved` int(10) unsigned DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
and
DATA
insert into `my_friends` values (4,1,1,null,null);
insert into `my_friends` values (7,8,1,null,null);
insert into `my_friends` values (1,7,1,null,null);
insert into `my_friends` values (2,7,1,null,null);
insert into `my_friends` values (4,2,1,null,null);
To get all the friends for user id "1" , I am running the below query
QUERY TO GET FRIENDS
SELECT first_user_id user_id, second_user_id friend_id from my_friends where first_user_id=1 and approved=1
union
SELECT second_user_id user_id ,first_user_id friend_id from my_friends where second_user_id=1 and approved=1
and when I check explain plan for this , this throws
EXPLAIN PLAN ERROR
Error
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
I am using this query in most of the queries as a subquery and this one causing the issue to check explain plan for all other queries
A: This is an issue with Mysql and raised with mysql
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Treeview vs nested Expanders Edit 2 :
This is what i want to do with only 1 treeview :
my treeview with outlook style http://img204.imageshack.us/img204/8218/sansreju.jpg
Edit :
I want to know how make a treeview with different expander styles in terms of the level. I currently use nested expanders.
Original question :
I am trying to get a WPF Treeview that has differents expanders styles in terms of the level.
What i actually have is that :
a listview wich contains differents templates in term of the ojbect type by using a selector
<ListView Name="MyTreeView" ItemTemplateSelector="{StaticResource Selector}">
<!-- Items Template -->
<HierarchicalDataTemplate x:Key="ItemsTemplate" ItemsSource="{Binding Childrens}">
<TextBlock Text="{Binding Name}" Margin="5,0" VerticalAlignment="Center"/>
</HierarchicalDataTemplate>
<!-- SubNode Template -->
<DataTemplate x:Key="SubNodeTemplate">
<Expander Style="{StaticResource SubExpander}">
<TreeView ItemsSource="{Binding Childrens}"
ItemTemplateSelector="{StaticResource Selector}"/>
</Expander>
</DataTemplate>
<!-- Node Template -->
<DataTemplate x:Key="NodeTemplate">
<Expander Style="{StaticResource MainViewExpander}">
<ListView ItemsSource="{Binding Childrens}"
ItemTemplateSelector="{StaticResource Selector}"/>
</Expander>
</DataTemplate>
And this is the code behind with object used for mapping :
I got a list (of IUpSlideItem ) and apply it to MyTreeview.ItemsSource
Public Interface IUpSlideItem
Property Childrens As List(Of IUpSlideItem)
Property Name As String
End Interface
Public Class Item
Implements IUpSlideItem
Public Property Childrens As System.Collections.Generic.List(Of IUpSlideItem) Implements IUpSlideItem.Childrens
Public Property Name As String Implements IUpSlideItem.Name
End Class
Public Class Node
Implements IUpSlideItem
Public Property Childrens As System.Collections.Generic.List(Of IUpSlideItem) Implements IUpSlideItem.Childrens
Public Property Name As String Implements IUpSlideItem.Name
End Class
Now the question is to know if only 1 treeview with different expander style in terms of the type's item is possible. I need this because i want single item select only.
A: by using an item container style selctor you can have 1 treeview with different expander style :
http://msdn.microsoft.com/fr-fr/library/system.windows.hierarchicaldatatemplate.itemcontainerstyleselector%28v=vs.90%29.aspx
edit : this solution is working, i have a perfect TreeView now
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Are git branches just tags? I noticed the ability of git to checkout to a specific commit. After that, I began to understand how git really works.
But I want to be sure that this is correct:
When I create a branch, it is nothing more than a tag that points to the current commit. When I checkout this branch, I checkout the commit this "tag" points to. Now, when I commit something, a new commit is created. The current checked out branch tag is now updated, so that it points to the new commit.
So... in fact, I could do all of this manually, right?
It´s just a feature to make things easier.
A: Yes, that's a good model for what a branch is. Beware, though, about the terminology - git also has a concept of tags, but tags don't move - they forever point to the same commit.
Update: adding a little more detail, which might be of interest...
Your current branch is stored in the file HEAD, which either points to a branch, in which case the contents look like:
ref: refs/heads/master
... or it points directly to a commit, in which case the contents will look like:
2b45553eec2019594724dcbb4c252a74cbb5f38e
In the former case, the branch master is advanced when you create a new commit, but in the latter situation (known as "detached HEAD" for hopefully obvious reasons), no branch will be changed when you create a new commit.
A: Branch is a reference pointer, it points to current commit as you say.
But you shouldn't use those words interchangeably because they mean something else.
A: Yes, for git, a branch is basically just a reference to a commit that is automatically updated when you commit. You could track it yourself, as you noted.
In fact, git expose all the low-level blocks upon which more higher-level abstraction are build. You can if you want use command like git hash-object, git mk-tree and git commit-tree to manually do what git add and git commit if you want (see the Raw Git chapter in the Git Book to know how to do it in details).
Please also note that git has two kind of tag. The lightweight tags are just reference to commit (via its hash) that don't move automatically. There is also the notion of tag objects that are real git objects, archived like commit, and that can contains a message and a signature.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: LINQ query records based on date array I have a table (I am using Entity Model) and filtered that table using LINQ query which is working fine.
Now I want to filter the records on the basis of array of dates. I am not able to implement IN clause on array of dates
filteredList = leadsNewAndScheduled.Where(lead =>
(LeadTypeIDs.Contains(lead.TYPE_ID.ToString()) ||
LeadTypeIDs == string.Empty) &&
(priorityIDs.Contains(lead.PRIORITY_ID.ToString()) ||
priorityIDs == string.Empty) &&
(((lead.EXPIRED_ON <= dateExpiry ||
Convert.ToDateTime(lead.EXPIRED_ON) == DateTime.Today.Date) &&
lead.STATUS_ID == (int)Enumerations.LeadStatus.New) ||
lead.STATUS_ID == (int)Enumerations.LeadStatus.Active) &&
(lead.START_TIME IN (arrAppointmentDates))
).ToList();
I want your help in following
(lead.START_TIME IN (arrAppointmentDates))
Thanks in advance.
A: Use Predicate Builder
Write your query without the date condition like
var query = leadsNewAndScheduled.Where(lead =>
(LeadTypeIDs.Contains(lead.TYPE_ID.ToString()) ||
LeadTypeIDs == string.Empty) && ....
Then write
var predicate = PredicateBuilder.False<Lead>();
foreach (DateTime date in dates)
{
DateTime temp = date;
predicate = predicate.Or (p => p.START_TIME == temp);
}
var result = query.Where(predicate).ToList(); // Don't call ToList() earlier
However please note that if you're using Entity Framework you need to call AsExpandable() on the entity set before applying predicates on it like so:
return objectContext.Products.AsExpandable().Where (predicate);
A: I solved this problem while declaring list of dates and then applying contains clause in LINQ query.
example:
//list of dates.
List<DateTime> arrAppointmentDates;
//change in query
arrAppointmentDates.Contains(Convert.ToDateTime(lead.START_TIME).Date)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to sort PHP multidimensional associative array with a selected key value How to sort following php array with its 'zindex' key value
$array = array('the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=>2),
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
)
Is there any php function for getting the output as follows,
$array = array(
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
'the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=>2),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
)
A: usort($array, function($a, $b) {
if ($a['name'] == $b['name']) {
return 0;
}
return ($a['name'] < $b['name']) ? -1 : 1;
});
This should do the trick for you... It did for me ;)
A: usort($array,function($el1,$el2){
return $el1-$el2;
});
Requires PHP5.3
if you need older versions' support replace anonymous function by usual one
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: -vf unrecognized with php exec() function I am using php to create a video with fade effects. But exec() function gives following output:
array(19) {
[0]=>
string(67) "FFmpeg version 0.6.1, Copyright (c) 2000-2010 the FFmpeg developers"
[1]=>
string(74) " built on Dec 4 2010 15:35:31 with gcc 4.1.2 20080704 (Red Hat 4.1.2-48)"
[2]=>
string(649) " configuration: --prefix=/usr --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --incdir=/usr/include --disable-avisynth --extra-cflags='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fPIC' --enable-avfilter --enable-avfilter-lavf --enable-libdirac --enable-libfaac --enable-libfaad --enable-libfaadbin --enable-libgsm --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libx264 --enable-gpl --enable-nonfree --enable-postproc --enable-pthreads --enable-shared --enable-swscale --enable-vdpau --enable-version3 --enable-x11grab"
[3]=>
string(35) " libavutil 50.15. 1 / 50.15. 1"
[4]=>
string(35) " libavcodec 52.72. 2 / 52.72. 2"
[5]=>
string(35) " libavformat 52.64. 2 / 52.64. 2"
[6]=>
string(35) " libavdevice 52. 2. 0 / 52. 2. 0"
[7]=>
string(35) " libavfilter 1.19. 0 / 1.19. 0"
[8]=>
string(35) " libswscale 0.11. 0 / 0.11. 0"
[9]=>
string(35) " libpostproc 51. 2. 0 / 51. 2. 0"
[10]=>
string(122) "Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/usr/slideshow/frame1.mp4':"
[11]=>
string(11) " Metadata:"
[12]=>
string(26) " major_brand : isom"
[13]=>
string(25) " minor_version : 512"
[14]=>
string(35) " compatible_brands: isomiso2mp41"
[15]=>
string(33) " encoder : Lavf52.64.2"
[16]=>
string(58) " Duration: 00:00:05.00, start: 0.000000, bitrate: 31 kb/s"
[17]=>
string(107) " Stream #0.0(und): Video: mpeg4, yuv420p, 320x240 [PAR 1:1 DAR 4:3], 29
kb/s, 1 fps, 1 tbr, 1 tbn, 1 tbc"
[18]=>
string(24) "Unrecognized option 'vf'"
}
Why it is giving unrecognized option 'vf' while it works fine when run directly on server.My command is : "ffmpeg -i /usr/slideshow/frame1.mp4 -vf 'fade=out:0:5' /usr/slideshow/fade1.mp4"
I am executing it with exec() function. Why the error is coming and what should i use to apply filter to my input video. I am working on CentOS server.
Please guide me...
A: I found the answer i just tried the full path of ffmpeg directory where ffmpeg was installed and it worked...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Applying an aggregate function on an in-memory result set based on each row in it I need to generate a result set in two steps. The first step is simple and generates a base in-memory result set (let's call it B). In the second step, I need to add an additional column to B (let's call it c). For each row in B, c can be calculated by using an aggregate function on B based on the values of that row (this does look inefficient though).
The final result set is B + c. Results must be sorted by a column from B as well as the c column, so the whole thing should be a single query.
Getting B is simple, but how do I process it further based on its contents?
EDIT. Here's a table analogy to illustrate what I mean by "applying an aggregate function on B based on each row in B":
Say, we have a table T with a column col. Let's say that for each row in T we want to calculate the number of rows that have a higher col value. You could do it like this:
select
t1.*,
(select sum(case when t2.col > t1.col then 1 else 0 end) from T t2) as count
from T t1
In my case the problem is that B is not a real table but an in-memory result set. How can I process it in a similar way?
A: OK - I'll give it another go.
Aliasing both the in memory results set and the columns that you need to use in that results set to derive c should work.
To continue your example from above:
select B.col,
(select sum(case when B2.col > B.col then 1 else 0 end) from (select whatever_col as col
from whatever_table) B2) as c
from
(select whatever_col as col from whatever_table) as B;
Let me know if I've got the wrong end of the stick again!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Unable to use jquery scrollto plugin - getting error "targ is undefined..." I am using jquery 1.3.2 in my project. I selected the 1.3.x option from the scrollto download page ->
http://plugins.jquery.com/node/635/release?api_version[]=1266 and tried with both the available options there -
ScrollTo 1.4.2 and ScrollTo 1.4.1.
but I am getting this error in both cases.
Here is the code part -
<script type="text/javascript">
$(document).ready(function()
{
if($('tr#manager-'+agencyId).length)>0)
$('tr#manager-'+agencyId).scrollTo();
});
</script>
<script type="text/javascript" src="/js/jquery.scrollTo.js"></script>
But I am getting this error in firefox ->
targ is undefined
attr[key] = targ[pos]; (jquery.scrollto line 157)
And in IE 8 ->
Message: 'targ' is null or not an object
Line: 157
Char: 6
Code: 0
URI: http://localhost:9001/js/jquery.scrollTo.js
The error appears only on calling .scrollTo().
Anybody faced this issue. What else do I need to check? Any pointers? Thanks.
A: if($('tr#manager-'+agencyId).length)>0)
there's an extra bracket after length.
A: You should provide a target that the plugin can scroll to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Escaping backslashes in php no matter how many \ in string I'm very new to PHP. Currently,I'm facing one issue to escape \ and store in mysql DB.
eg., If the string is like $str = \\aaaa\bbb\\\cccc$$ , I would like to save that string in DB . However, I don't know how to escape those backslashes. Please help me settle it.
A: Your best option is to use prepared statements (e.g. through PDO):
$dbh = new PDO(…);
$sth = $dbh->prepare('INSERT INTO `yourtable` ( `column` ) VALUES ( :string )');
$sth->execute(array(':string' => '\\aaaa\bbb\\\cccc$$'));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: IsNumeric check in linq The following linq
var subjectMarks = (from DataRow row in objDatatable.Rows
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
throws an exception since some row["EXM_MARKS"] has non numeric values like AB etc.
How can I get the sum of only numeric ones out of them?
A: Add where clause that filters out the records that cannot be parsed as decimals. Try:
decimal dummy;
var subjectMarks = (from DataRow row in objDatatable.Rows
where decimal.TryParse(row["EXM_MARKS"], out dummy)
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
A: You could create an extension method SafeConvertToDecimal and use this in your LINQ query:
var subjectMarks = (from DataRow row in objDatatable.Rows
select row["EXM_MARKS"].SafeConvertToDecimal()).Sum();
This extension method would look like this:
public static decimal SafeConvertToDecimal(this object obj)
{
decimal result;
if(!decimal.TryParse(obj.ToString(), out result))
result = 0;
return result;
}
This approach has the advantage that it looks clean and you aren't converting each object twice as do all other answers.
A: For linq to sql queries you can use built-in SqlFunctions.IsNumeric
Source: SqlFunctions.IsNumeric
A: use
Decimal Z;
var subjectMarks = (from DataRow row in objDatatable.Rows
where Decimal.TryParse (row["EXM_MARKS"], out Z)
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
A: You can make some extensions utility class like this for elegant solution:
public static class TypeExtensions
{
public static bool IsValidDecimal(this string s)
{
decimal result;
return Decimal.TryParse(s, out result);
}
}
and use it in this way:
var subjectMarks = (from DataRow row in objDatatable.Rows
where row["EXM_MARKS"].IsValidDecimal()
select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
Hope this helps.
A: var subjectMarks = objDatatable.Rows.Where(row => row["EXM_MARKS"].ToString().All(char.isDigit))
part of solution is getted in: here
A: For LINQ to SQL queries with Entity Framework Core, ISNUMERIC function is part of EF Core 6.0 under EF.Functions
Before version 6.0, you can create a user-defined function mapping !
User-defined function mapping : Apart from mappings provided by EF Core providers, users can also define custom mapping. A user-defined mapping extends the query translation according to the user needs. This functionality is useful when there are user-defined functions in the database, which the user wants to invoke from their LINQ query for example.
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();
_ = await ctx.Blogs.Where(b => ctx.IsNumeric(b.Name)).ToListAsync();
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
static ILoggerFactory ContextLoggerFactory
=> LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0")
.EnableSensitiveDataLogging()
.UseLoggerFactory(ContextLoggerFactory);
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDbFunction(IsNumericMethodInfo)
.HasName("ISNUMERIC")
.IsBuiltIn();
}
private static readonly MethodInfo IsNumericMethodInfo = typeof(BlogContext)
.GetRuntimeMethod(nameof(IsNumeric), new[] { typeof(string) });
public bool IsNumeric(string s) => throw new NotSupportedException();
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Superfish IE7 z-index bug with Nivo slider or Photospace in wordpress I have a website with a superfish menu and I have two different plugins for slideshows, nivo slider in the main page: http://hermandaddelcalvario.org/wordpress/ and photospace in the gallery page: http://hermandaddelcalvario.org/wordpress/imagenes-3/
The problem comes with IE7, the dropdown falls behind the images on both pages. I searched a lot and everyone suggests that I do this:
/*gallery container*/
#content{
position:relative;
z-index: 1;
}
/*superfish container*/
#navwrap{
position:relative;
z-index: 2;
}
I did so but to no avail, is there something else I missed?
A: The issue occurs in both IE 6 and 7 due to the way they create a stacking order. More details can be found here: http://brenelz.com/blog/squish-the-internet-explorer-z-index-bug/
In short - within your conditional IE stylesheets you will need to give your menus parent a z-index of higher value than your slideshow.
A: Ok this is a bit lame, 3 secs after I asked the question I found my answer here: Jquery Superfish problem in IE7
Using that script now it works but I still want to know what's wrong with the css here, I'd go for a css solution before this but I wanted to state that would solve the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery .remove not working as expected I have the following which is supposed to remove the element ".mycontainer" when I click on a close button. It's not removing the element though. When I use firebug. I can see that it is just moving it to outside of the html tags at the beginning on the code.
$('.closeButton').click( function() {
$(".mycontainer").slideUp( function() {
$(".closeButton").parent().appendTo(".ContentsHolder");
$(this).remove();
});
});
It works if I comment out the 3rd line //$(".closeButton").parent().appendTo(".ContentsHolder");
but this removes the content so I can't access it again.
EDIT:
My html looks something like this if it helps to understand what I'm doing...
<div class='ContentsHolder'>
</div>
<div class='mycontainer'>
<div class='myContent'>
<a class='closebutton'>close</a>
... other content ...
</div>
</div>
I have also managed to make it work by putting a delay on the removal of mycontainer $(this).delay(500).remove();
I would not think this is a great solution though.
A: You could just chain the remove function after the slideUp like so :
$('.closeButton').click( function() {
$(".mycontainer").slideUp( function() {
$(".closeButton").parent().appendTo(".ContentsHolder");
}).remove();
});
A: It looks like $(this) is a different context to what you think.
Try adding console.log($(this)); to see the actual context in the console.
$('.closeButton').click( function() {
$(".mycontainer").slideUp( function() {
$(".closeButton").parent().appendTo(".ContentsHolder");
console.log($(this));
$(this).remove();
});
});
A: I have solved same problem before like this:
$(".mycontainer").slideUp(500, function() {
$(this).remove();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Images in OOXML (Office Open XML) standard documents are damaged. Where I can find a good one? We are working on a project to deal with OOXML format, specifically DOCX format. We downloaded PDFs from ISO site (http://standards.iso.org/ittf/PubliclyAvailableStandards/index.html) but found all images in the PDF are black. Some images have colored lines but none of them has text.
Is there anyone read the standard?
Where I can get a good document with good images.
Thanks
A: You can take a look at the ECMA-376 version of the standard at the following link. I would download the third edition set of the pdf's as they are the most recent to date.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to upgrade my custom android application which will not be released to the Android market? I tried several links but no one has given any appropriate answer. Scenario is something like :
I have my custom .apk file with version 1.0(let's say) which is already installed in android device(we are not using Android market to install it) and later point of time we have to release the same .apk file with some fixes of application bugs. So is there any possible way to upgrade pre-installed android application without uninstalling it?
Please provide some possible suggestion.
Thanks, piks
A: Should be relatively simple:
In the new version of your code, make sure you increment the version numbers like so :
android:versionCode="2"
android:versionName="1.1"
Then build your APK and copy it over to your device.
Use something like Astro to open the file, android should detect that you already have it installed, yet this APK will have a later version number so it will give you the option to "upgrade".
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get an instance of a paused activity? Is there any way to get the instance of a paused Activity? I need to run a public method from another Activity when it is paused, and there is no way I can use a static method
A: That doesn't make sense from the Android perspective. If it's something that'll affect the Activity's UI, then centralize the information in an external class and read it inside paused Activity's onResume.
A: You can store the instance of an activity in a Hashtable with a unique key in the onPause() method(), and retrieve it whenever you want it and work on it. of check for mull pointer exception coz dvm/a-os may have killed the activity if it thinks thats the best thing to do.
I am not sure if this will work, but the official method i guess could be: you can try retrieving all the activities using ContextManager/ActivityManager apis and iterate through each n do the needful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send post form with java? I would like to send a post form with java on a website. I came up with this, but I dont what to do next or if this is even the right way.
URL url = new URL("http://127.0.0.1");
URLConnection conn=url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
the post form looks like this.
<form action="prikaz4.php" method="post">
<select name="igralec"/>
<option value="Kobe Bryant">Kobe Bryant</option>
<option value="Dwayne Wade">Dwayne Wade</option>
<input type="submit" />
</form>
A: Apache's HttpClient project will handle this better for you.
or you can try this code:
// Using java.net.URL and
//java.net.URLConnection
URL url = new URL("http://jobsearch.dice.com/jobsearch/jobsearch.cgi");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(uc.getOutputStream(), "8859_1");
out.write("username=bob&password="+password+"");
// remember to clean up
out.flush();
out.close();
A: You can write code similar to this :
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.impl.client.HttpClients;
public class PostReqEx {
public void sendReq(String url,String email,String fname){
HttpClient httpClient = HttpClients.createDefault();
PostMethod postMethod = new PostMethod(url);
postMethod.addParameter("Email", email);
postMethod.addParameter("fname", fname);
try {
httpClient.executeMethod(postMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
String resp = postMethod.getResponseBodyAsString();
} else {
//...postMethod.getStatusLine();
}
}
}
A: You may want to consider using HttpClient library from Apache. It's got HttpPost class, which is very easy to use.
A: It's easy to use unirest .
<dependency>
<groupId>com.konghq</groupId>
<artifactId>unirest-java</artifactId>
<version>3.1.02</version>
<classifier>standalone</classifier>
</dependency>
Unirest.config().verifySsl(false);
HttpResponse response = Unirest.post("http://127.0.0.1")
.field("timestamp", "1571971524")
.field("appId", "xxx")
.field("sign", "3e345613c687110ebf437da23ad5a13f")
.asString();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Limiting file download based on access level on asp.net I have a web app made in asp.net mvc3. There is a facility to upload and download files using the application. Uploaded files will be stored in some folder under web root. I want allow downloading files to those who have access to the files only. No one should be able to download the file by directly pasting in the file URL.
I use shared hosting with limited IIS access. So what would be the best way to achieve this?
A: How are you storing the data on the access rights currently? It sounds like you are not going to be able to make use of IIS to control access to your files and will have to handle it yourself.
As this is the case, rather than link to the file directly you should store the files outside of your web root and then handle requests coming in for files through ASP.NET MVC using a GET method. At that point you can check the user's credentials, and if they have access you can serve the file.
I'm not too familiar with it, but it looks like ASP.NET MVC makes serving up files very easy with the ability to return a FileContentResult, supported by the Controller.File method (documentation here).
This blog post looks like a great start, and you would just need to insert your credential-checking logic into the Get method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to go back to TRY block after error? I want to check in my stored procedure, if a table contains specific columns. I want to raise an error if such a column exist, because they are not allowed. First I came up with the following idea, which obviously has a defect that I can understand.
BEGIN TRY
SET @sql = N'SELECT TOP 0 forbidden_column_name1 INTO #t1 FROM ' + @input_table ;
EXEC @err = sp_executesql @sql ;
IF @err = 0 -- i.e. if succeeds
RAISERROR('Input table cannot contain ''forbidden_column_name1''. This name is reserved!', 16, 99) ;
SET @sql = N'SELECT TOP 0 forbidden_column_name2 INTO #t1 FROM ' + @input_table ;
EXEC @err = sp_executesql @sql ;
IF @err = 0 -- i.e. if succeeds
RAISERROR('Input table cannot contain ''forbidden_column_name2''. This name is reserved!', 16, 99) ;
SET @sql = N'SELECT TOP 0 forbidden_column_name3 INTO #t1 FROM ' + @input_table ;
EXEC @err = sp_executesql @sql ;
IF @err = 0 -- i.e. if succeeds
RAISERROR('Input table cannot contain ''forbidden_column_name3''. This name is reserved!', 16, 99) ;
END TRY
BEGIN CATCH
IF ERROR_STATE() = 99
BEGIN
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
RETURN ;
END
-- Do nothing and continue execution, if column doesn't exist
END CATCH
This code would check only the existence of forbidden_column_name1. The others are not checked, because an exception has to be raised during the check of forbidden_column_name1: either from the sp_executesql, if column doesn't exist, or from the RAISERROR, if the column does exist. Either way, the execution passes to catch block and never comes back.
My question is, is there a way to force the execution go back to the TRY block, if an error is not actually an error, but actually something that is desired. Otherwise I have to put all checks in separate TRY/CATCH blocks, which makes the code seem a little bit redundant.
A: Why not query sys.columns, to determine the existence or not of these columns, rather than trying to infer their existence by querying the table?
e.g.
IF EXISTS(select * from sys.columns where object_id = OBJECT_ID(@table_name) and name in (
'forbidden_column1','forbidden_column2','forbidden_column3'))
BEGIN
RAISERROR('One or more forbidden columns detected. Review the documentation',16,99)
RETURN
END
--Proceed, knowing that the table doesn't contain the forbidden columns
A: You would have to wrap each individual select statement in a try/catch block.
BEGIN TRY
SET @sql = N'SELECT TOP 0 forbidden_column_name1 INTO #t1 FROM ' + @input_table ;
EXEC @err = sp_executesql @sql ;
IF @err = 0 -- i.e. if succeeds
RAISERROR('Input table cannot contain ''forbidden_column_name1''. This name is reserved!', 16, 99) ;
END TRY
BEGIN CATCH
IF ERROR_STATE() = 99
EXEC usp_RethrowError
END CATCH
To avoid repeating yourself, you could create a procedure for this that has parameters for both the name of the table, and the name of the column.
Definition of usp_RethrowError
A: Not a direct answer to your question but you're better off using INFORMATION_SCHEMA to determine if the columns exist.
Something like:
IF EXISTS (SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE
TABLE_NAME = @input_table AND COLUMN_NAME IN ('forbidden_column_name1', 'forbidden_column_name2', 'etc'))
BEGIN
RAISERROR('idiot', 16, 99)
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bug with pagination when 2 variables in the url on CodeIgniter I am still learning with the CodeIgniter framework. Today, I find myself faced with the problem of pagination.
Indeed I would have access to data via an id which requires a variable in the url and another one for the pagination.
This is my foos_by_day function (this is not the real name, it's just an example) in my controller called foo that returns an array of foos on a specific day.
These foos come from my database and go to my controller get_foos_by_day ($day) via the model called model_foos.
function foos_by_day($day) {
$configpages['base_url'] = 'http://www.exemple.com/ci/index.php/foo/foos_by_days/'.$foo."/";
$configpages['total_rows'] = count($this->model_foos->get_foos_by_day($foo));
$configpages['per_page'] = 10;
$config['uri_segment'] = 4;
$this->pagination->initialize($configpages);
$data['foos'] = $this->model_foos->get_foos_by_day($jour, (int)$this->uri->segment(4), $configpages['per_page'] );
$this->load->view('foo_view.php', $data);
}
And this is my view:
<?php foreach ($foos as $element): ?>
<div>
Name of the foo : <?=$element->name?><br />
Date of the foo : <?=$element->date?><br />
</div>
<?php endforeach; ?>
<?php echo $this->pagination->create_links(); ?>
I get something strange in my view when I input : http://www.example.com/ci/index.php/foo/foos_by_day/2011-09-28/
The numbering of my 32 foos starts at 4 (the last page). It displays correctly 10 foos per pages but when I click on another page, the selected page stays the fourth.
Moreover, the links behind the page numbers gives me the following statement:
<a href="http://www.example.com/ci/index.php/foo/foos_by_day/2011-09-28/">First</a>
<a href="http://www.example.com/ci/index.php/foo/foos_by_day/2011-09-28/20"><</a>
<a href="http://www.example.com/ci/index.php/foo/foos_by_day/2011-09-28/10">2</a>
<a href="http://www.example.com/ci/index.php/foo/foos_by_day/2011-09-28/20">3</a>
<strong>4</strong>
So : nothing, then 20, 10 and 20 (again). In short there is a bug in the pagination.
Have you ever been faced to this kind of situation (with a pagination error)? If so, how did you solve it?
How do you think I should proceed to find a regular pagination?
Thanks in advance.
P.S. : I didn't delete the index.php file but I have learned to do it on an other CodeIgniter.
A: Change
$config['uri_segment'] = 4;
to
$configpages['uri_segment'] = 4;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Confusing Java Class concept New to java and a concept is confusing me a lot.
As a c++ programmer when we declare a class we can not have a property having an object of same class like lets say we have a class name Foo as belows
class Foo {
int age;
Foo someName;
}
the above code will give error. While in java i can do it. Is there a special reason behind it? And how does it happen. Any good read will be helpful.
A: When you write Foo someName in Java, you're creating a reference to an object of type Foo. This is similar to writing Foo& someName in C++, which is allowed.
What is not allowed in C++ is for class Foo to have a member of type Foo (i.e. not Foo& or Foo*). If you think about it, this construct can't possibly make sense as it would require sizeof(Foo) to be infinitely large. This -- disallowed -- C++ construct has no direct Java equivalent.
A: In Java when you declare Foo someName, the someName is really a reference to an object of class Foo.
So there is no problem to have a property referencing an object of the same type.
This is similar to how you can have Foo& someName in C++.
A: Java stores objects as references. C++ doesn't. Therein is the difference.
With Java it does not need to know how much space to reserve for the Foo object. However in C++ the compiler needs to. So the C++ has an impossible task.
A: Thats because of an important between C++ and Java : in C++ , Foo above would be an object ; in Java Foo above is just a reference - not an object. ( You will have to write Foo someref = new Foo() for creating the object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Import custom protocol into MS Excel / Access I have a standalone Java application capable of replaying a time series of data records. Communication with the server is performed using a bespoke binary wire protocol over TCP/IP.
We have a requirement to be able to easily import data records from this application into MS Excel / Access and I am interested in the recommended way to do this.
One idea we're exploring is to write a web "wrapper" service (also in Java) that will communicate with the underlying server and then translate the binary data into a more friendly text format for consumption by Excel / Access. However, the drawback here is that we lose any type information associated with each field in a given record.
I've briefly looked into writing custom ODBC / OleDB drivers but this seems complex and is probably overkill for what we're trying to achieve.
Can anyone recommend any other approaches?
A: How about xlloop? http://xlloop.sourceforge.net/
Uses an Excel plugin to connect to a function server, where you can create your own functions.
A: You may connect with an Access Database via the JDBC/ODBC Bridge driver.
A: From your previous comments I assume that you need to serve dynamic/changing data. If that is the case then take maybe the IRtdServer interface and this article referring to Excel. Its a COM Interface so you probably will need something like Com4j
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C# .NET and direct object collections Hey all is there a collection type like arrayList which i can add an object to using an ID?
effectively as the title of my post sugests a Direct object collection. so for example:
DirectCollection.addAt(23, someobject);
and
DirectCollection.getAt(23);
etc etc
i know arraylist is usable in that case but i have to generate the initial entry with a null reference object and if if the object has an ID like 23 i have to generate 22 other entries just to add it which is clearly impractical.
basically using the object position value as a unique ID.
Any thoughts?
Many thanks.
A: You could use Dictionary<int, YourType>
Like this:
var p = new Dictionary<int, YourType>();
p.Add(23, your_object);
YourType object_you_just_added = p[23];
A: You could use a Dictionary
The code for your example would be very simple:
Dictionary<int, AType> directCollection = new Dictionary<int, AType>();
directCollection.Add(23, someObjectOfAType);
AType anObject = directCollection[23];
A: Use a dictionary.
Dictionary<int, YourType>
It allows you to add/get/remove items with a given key and non continuous ranges.
A: I think KeyedCollection or Dictionary is what you need.
A: Use System.Collections.Hashtable. It allow to store the heterogeneous type of object (a Hashtable can hold the multiple type of object).
Example:
System.Collections.Hashtable keyObjectMap = new System.Collections.Hashtable();
//Add into Hashtable
keyObjectMap["Key_1"] = "First String";
keyObjectMap["Key_2"] = "Second String";
//Add the value type
keyObjectMap["Key_3"] = 1;
keyObjectMap["Key_4"] = new object();
//Get value/object from Hashtable
string value = (string)keyObjectMap["Key_2"];
int intValue = (int)keyObjectMap["Key_3"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7581571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.