text
stringlengths 8
267k
| meta
dict |
---|---|
Q: What is "SQLiteDatabase created and never closed" error? I have closed the database in my adapter class, so whay is this error showingup on logcat but my application is not forcr closing but only error is showing on log cat..where i shuold have to close the database for ignoring this error...?
my errors are...below..in which class i left for closing the database.....i took help from this link http://www.vogella.de/articles/AndroidSQLite/article.html
ERROR/Database(265): Leak found
ERROR/Database(265): java.lang.IllegalStateException: /data/data/expenceanywhere.mobile/databases/data SQLiteDatabase created and never closed
ERROR/Database(265): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1581)
ERROR/Database(265): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:638)
ERROR/Database(265): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:659)
ERROR/Database(265): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:652)
ERROR/Database(265): at android.app.ApplicationContext.openOrCreateDatabase(ApplicationContext.java:482)
ERROR/Database(265): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:193)
ERROR/Database(265): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)
ERROR/Database(265): at expenceanywhere.mobile.NotesDbAdapter.open(NotesDbAdapter.java:56)
ERROR/Database(265): at expenceanywhere.mobile.AddEditExpense.onCreate(AddEditExpense.java:199)
ERROR/Database(265): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
ERROR/Database(265): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
ERROR/Database(265): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
ERROR/Database(265): at android.app.ActivityThread.access$2100(ActivityThread.java:116)
ERROR/Database(265): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
ERROR/Database(265): at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR/Database(265): at android.os.Looper.loop(Looper.java:123)
ERROR/Database(265): at android.app.ActivityThread.main(ActivityThread.java:4203)
ERROR/Database(265): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/Database(265): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/Database(265): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
ERROR/Database(265): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
ERROR/Database(265): at dalvik.system.NativeStart.main(Native Method)
A: Remember to always close db in Helper class
//---closes the database---
public void close()
{
DBHelper.close();
}
The similar question: Sqlite Database LEAK FOUND exception in android?
A: You have to close the database before exiting the application or exiting the class.
db.close()
A: You need to close any open database object with calling the close() method.
A: I confirm the problem with the leakage in the code from Voggella. What worked in my case was overriding OnDestroy method with a close statement as others proposed. I guess you can add this code in your AddEditExpense.java.
@Override
protected void onDestroy() {
super.onDestroy();
dbHelper.close();
}
A: I had the same problem in one of my apps. I opened and closed the database every time I accessed it. But I still got the error. I suppose different threads which access the shared object messes up the database status in this approach.
To overcome this I placed the database instance in the main Activity and shared it to all other activities. in the OnCreate() method of the main activity the db instance is created. I had to override the onResume() and onPause() methods which I closed the database (within onPause()) and opened (within onResume()) of the main activity.
I'm not sure whether this is the correct way of getting rid of the problem, but it has worked for me so far.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Make Google Charts adapt the vertical axis to the data I want Google chart to make better use of the vertical space available for this graph:
https://chart.googleapis.com/chart?chs=300x150&cht=bvs&chxt=x%2Cy&chd=t:7,8,5,6
QUESTION: How to make the vertical axis adapt to the range of values automatically?
For instance, 0→max value would be great.
Note: I could write a server-side algorithm to find the max value and use it as a parameter, but there is probably a better way to do this with Google Charts, right?
A: I ended up writing a server-side loop to check what is the maximum value, and then use it:
&chxr=1%2C0%2C" + max + "&chds=0," + max
Any better solution is welcome!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to load another page inside a div? I have created a number of divs using a loop, and then inside it there's a hidden field where the value is the url I want the div to be loaded. I have tried the load() function but turns out to be slow. Like when I used iframe, it takes a very long time to load and the height and width isn't expanded because of its child. Is there any other way to do this?
UPDATE
my html code filename index.html.erb
<div id="surveyDiv" style="overflow-y:auto;" >
<% @sections.each do |sec| %>
<% #sec = @sections.first %>
<br/>
<% @div_id = "survey_section_" + (sec.id).to_s %>
<div id="<%=h @div_id %>">
<img src="/images/loading.gif" id="loadingPic"/>
<input type=hidden id="hid" name="hid" value="<%=h @srcString + "?section=" + (sec.id).to_s %>"/>
<!--<iframe id="the_frame" name="the_frame" src="<%#=h @srcString + "?section=" + (sec.id).to_s %>" scrolling="yes" frameborder="no" ></iframe>-->
</div>
<script type="text/javascript">
/*$('div:last').load($('input[type=hidden]:last').val())*/
$.get($('input[type=hidden]:last').val(), function(data) {
$('.surveyDiv div:last').html(data);
});
$('div:last').ready(function() {
$('#loadingPic').css('display','none')
});
</script>
<% end %>
</div>
Samich's answer is good, but then, when I used it, I can't see now the loaded html..hehe
A: I dont really understand ... ASP?
but try this
<div id="surveyDiv" style="overflow-y:auto;" >
<% @sections.each do |sec| %>
<% #sec = @sections.first %>
<br/>
<% @div_id = "survey_section_" + (sec.id).to_s %>
<div id="<%=h @div_id %>">
<img src="/images/loading.gif" id="loadingPic" />
<input type="hidden" class="helloimhidden" id="hid<%=h @div_id %>" name="hid" value="<%=h @srcString + "?section=" + (sec.id).to_s %>" />
</div>
<% end %>
</div>
<script type="text/javascript">
$('.helloimhidden').each(function() {
var myInput = $(this);
$.get(myInput.val(), function(data) {
myInput.parent().html(data);
});
});
</script>
please let me know how it goes, I'm afraid only the last div will show results due to myInput got overwritten... if so try this
<script type="text/javascript">
var myI = 0;
var myInput = [];
$('.helloimhidden').each(function() {
myInput[myI] = $(this);
$.get(myInput[myI].val(), function(data) {
myInput[myI].parent().html(data);
});
myI++;
});
</script>
A: Samich is right, get is ok for your task. And about resizing divs: i came across similar issue with a popup on one of my websites. Popup resized according to the loaded content, but something weird happened in safari and explorer. If text was too long, then popup took maximum width which is not good, i prefer to have word wraps instead. Ideal way is to define width of the content in the content. For example you have HTML to be loaded into the container:
<div class="d1">some text</div>
In order to provide cross-browser consistency you should either define .d1 width through css or define inline style for the div tag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling Inherited IUnknown::Release() in a destructor Why does calling the inherited IUnknown::Release() function on a IWICImagingFactory object in a destructor cause a "CXX0030: Error: expression cannot be evaluated" to be shown each entry in the object's virtual function table (__vfptr)?
This is in reference to an earlier question I posted but I've since realized that the problem only occurs in the destructor. The virtual function table appears valid anywhere else I have checked. However, once in the destructor all entries are shown with the CXX0030 error and attempting to call the inherited IUknown::Release() fails.
Edit: Here is some code to demonstrate:
HRESULT DemoApp::CreateDeviceIndependentResources()
{
HRESULT hr;
hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &mpDirect2DFactory);
if (SUCCEEDED(hr))
{
hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&mpWICFactory)
);
}
//CoCreateInstance returns S_OK.
//Other unrelated code here.
}
HRESULT DemoApp::CreateDeviceResources()
{
HRESULT hr;
//Other unrelated code here for creating device-dependant resources.
//mpBackgroundBitmap is a ID2D1Bitmap*.
if(SUCCEEDED(hr))
{
hr = LoadBitmapFromFile(
mpRenderTarget,
mpWICFactory,
L".\\background.png",
0,
0,
&mpBackgroundBitmap);
}
}
//The below LoadBitmapFromFile() code is taken directly from an MSDN sample.
//I didn't write it.
HRESULT DemoApp::LoadBitmapFromFile(
ID2D1RenderTarget *pRenderTarget,
IWICImagingFactory *pIWICFactory,
PCWSTR uri,
UINT destinationWidth,
UINT destinationHeight,
ID2D1Bitmap **ppBitmap
)
{
IWICBitmapDecoder *pDecoder = NULL;
IWICBitmapFrameDecode *pSource = NULL;
IWICStream *pStream = NULL;
IWICFormatConverter *pConverter = NULL;
IWICBitmapScaler *pScaler = NULL;
HRESULT hr = pIWICFactory->CreateDecoderFromFilename(
uri,
NULL,
GENERIC_READ,
WICDecodeMetadataCacheOnLoad,
&pDecoder
);
if (SUCCEEDED(hr))
{
// Create the initial frame.
hr = pDecoder->GetFrame(0, &pSource);
}
if (SUCCEEDED(hr))
{
// Convert the image format to 32bppPBGRA
// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
hr = pIWICFactory->CreateFormatConverter(&pConverter);
}
if (SUCCEEDED(hr))
{
// If a new width or height was specified, create an
// IWICBitmapScaler and use it to resize the image.
if (destinationWidth != 0 || destinationHeight != 0)
{
UINT originalWidth, originalHeight;
hr = pSource->GetSize(&originalWidth, &originalHeight);
if (SUCCEEDED(hr))
{
if (destinationWidth == 0)
{
FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
}
else if (destinationHeight == 0)
{
FLOAT scalar = static_cast<FLOAT>(destinationWidth) / static_cast<FLOAT>(originalWidth);
destinationHeight = static_cast<UINT>(scalar * static_cast<FLOAT>(originalHeight));
}
hr = pIWICFactory->CreateBitmapScaler(&pScaler);
if (SUCCEEDED(hr))
{
hr = pScaler->Initialize(
pSource,
destinationWidth,
destinationHeight,
WICBitmapInterpolationModeCubic
);
}
if (SUCCEEDED(hr))
{
hr = pConverter->Initialize(
pScaler,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
}
}
else // Don't scale the image.
{
hr = pConverter->Initialize(
pSource,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
}
if (SUCCEEDED(hr))
{
// Create a Direct2D bitmap from the WIC bitmap.
hr = pRenderTarget->CreateBitmapFromWicBitmap(
pConverter,
NULL,
ppBitmap
);
}
SafeRelease(&pDecoder);
SafeRelease(&pSource);
SafeRelease(&pStream);
SafeRelease(&pConverter);
SafeRelease(&pScaler);
return hr;
}
//Now I call SafeRelease() in my destructor and the virtual function table entires are showing the error.
DemoApp::~DemoApp()
{
SafeRelease(&mpDirect2DFactory);
SafeRelease(&mpWICFactory); //here is the problem apparently
SafeRelease(&mpDWriteFactory);
SafeRelease(&mpRenderTarget);
SafeRelease(&mpBackgroundBitmap);
}
//SafeRelease is defined as:
template<class Interface>
inline void SafeRelease(Interface** ppInterfaceToRelease)
{
if(*ppInterfaceToRelease != NULL)
{
(*ppInterfaceToRelease)->Release();
(*ppInterfaceToRelease) = NULL;
}
}
The problem is when I call SafeRelease() on the WICFactory object, I get:
First-chance exception at 0x0024e135 in DemoApp.exe: 0xC0000005: Access violation reading location 0x6d5c28f0.
Unhandled exception at 0x0024e135 in DemoApp.exe: 0xC0000005: Access violation reading location 0x6d5c28f0.
A: I struggled with this problem lately too. The problem is that the creation and release of IWICImagingFactory depends on CoInitialize/CoUninitialize being called before and after, respectively. In your application it is likely that CoUninitialize() is called before the IWICImagingFactory is released in the destructor, which causes a crash. Note that ID2D1RenderTarget and such do not seem to be affected and can still be released after CoUninitialize() is called.
Remove the call to CoUninitialize() from RunMessageLoop() or wherever it is and put it after the release call in the destructor and the crash should go away.
A: Calling virtual functions inside the constructor or destructor does not call the function you assume it will call. It always results in call to the functions of that same class.
You can assume virtual dispatch is disabled in constructor and destructors.
An more appropriate way of saying this is:
During the execution of a constructor or destructor, virtual calls on the object for which the constructor or destructor is run behave as if the dynamic type of the object expression used in the call is equal to the class of the constructor or destructor.
Courtesy: A lengthy discussion in C++ Lounge, Where finally, @JohannesSchaublitb came up with this apt definition, which most of us seemed to agree on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Color issue in MATLAB I'm writing a function file which is used to draw a line in an image. Now I'm facing the color issue. If I set color=[255 255 255] or color=[128 128 128] in the command window, the lines that appears in the image are both white.
For [128 128 128], it should be gray color, right? Which is not corresponding to the color table. I have tested some values for the color, the conclusion is that it takes any number greater than zero as 255. How do I fix this problem?
The following is my code.
function [ret]=drawline(p1,p2,color,img);
xmax=size(img,1);
ymax=size(img,2);
if (p1(1)>xmax) || (p2(1)>xmax) || (p1(2)>ymax) || (p2(2)>ymax)
error('value of point is ouside the image.');
elseif (p1(1)==xmax) || (p2(1)==xmax) || (p1(2)==ymax) || (p2(2)==ymax)
error('warning: value of point reach the max.');
elseif (color(1)>256) ||(color(2)>256)||(color(3)>256)
error('color value is out of range.');
else
m=(p2(2)-p1(2))/(p2(1)-p1(1));
m=round(m);
c=p1(2)-m*p1(1);
for x=linspace(p1(1),p2(1),1000)
y=m*x+c;
if p1(1)==p2(1)
x=p1(1);
y=p1(1):p2(2);
end
img(round(y),round(x),1)=color(1);
img(round(y),round(x),2)=color(2);
img(round(y),round(x),3)=color(3);
end
end
ret=img
A: You might be using floating point images, where the color range is [0, 1] instead of [0, 255]. Perhaps the system is truncating all values over 1 instead of raising an error. I'm not matlab-savvy enough to correct your code, unfortunately.
A: I presume you then do image(img) in order to display the image. In that case, [255 255 255] will correspond to white as a true color value, regardless of the color map. You need to create a monochrome image, which will then be treated as indexed data and displayed using the color map.
See the Tips section of the image help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Open office files in Blackberry app I want to open office documents, like Word, Excel and PowerPoint, from my BlackBerry app. I am able to download the files from the server, but I am not sure how to open them.
A: On BlackBerry devices there is a trial version of DataViz DocsToGo pre-installed. And you can use DocsToGo Word to open Word documents, DocsToGo Excel to open excel documents, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get an auth token on Android device I am developing an application which stores local data on cloud. I want to use a permanent authentication token as primary key. How can we generate authentication token from android device which should not expire after a session. Please help me. Thanks in advance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: generating hash table using perl script I am trying to create hash table using perl. please can help me because i am begginer to perl and i am reading but i am not able to implement. i need to create hash table from below code data number as a key and description as value.
A: For a common data format like XML, don't try to do this manually by reading the file line by line and parsing it yourself. Instead, use a perl module to do it for you.
The XML::Simple module may be sufficient for you to start with. I think the module is already installed on your system by default.
use strict; # tip: always use strict and warnings for safety
use warnings;
use Data::Dumper;
use XML::Simple;
my $data = XMLin(\*DATA); # loads up xml into a hash reference assigned to $data
print Dumper $data; # uses Data::Dumper to print entire data structure to console
# the below section emulates a file, accessed via the special DATA file handle
# but you can replace this with an actual file and pass a filename to XMLin()
__DATA__
<DATA>
<!-- removed -->
</DATA>
UPDATE
Now that the xml file is loaded into a hashref, you can access that hash and organise it into the structure that you want.
# loads up xml into a hash reference assigned to $data
my $data = XMLin(\*DATA);
# organise into [testnumber => description] mappings
# not sure if 'Detection' is what you meant by 'description'
my %table = ( $data->{Testnumber} => $data->{Detection} );
The problem with this scenario is that the xml data only contains a single testnumber, which is all this code handles. If you want to handle more than that, then you'll probably need to loop over an array somewhere. I don't know how the xml data will look like if there is more, so I don't know where the array will be.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Buggy image resizing with CSS on Chrome, any way to fix it? I'm displaying some favicons from external domains in my site. The problem is that when the favicon is anything different than 16px and I resize it the output is not always perfect. Randomly I get just the top or bottom half of the image, when I refresh suddenly the icon is displayed whole.
I have only experienced this problem in Chrome where it happens 90% of the time, I tested it on Firefox briefly and didn't seem to occur.
<style>
.icon {
width: 16px;
height: 16px;
</style>
<img class="icon" src="http://getfavicon.appspot.com/http://curiousphotos.blogspot.com/2010/07/creative-gizmos.html">
Is there a way to resize images without tearing?
A: May that can solve your problem:
<style>
.icon {
width: 16px !important;
height: 16px !important;
</style>
A: there are actually several methods,
1
<style>
.icon {
width: 16px;
height: 16px;
}
</style>
2
<style>
.icon {
max-width: 16px;
max-height: 16px;
}
</style>
3
<img width="16" height="16" class="icon" src="http://getfavicon.appspot.com/http://curiousphotos.blogspot.com/2010/07/creative-gizmos.html" />
I suppose #3 is more suitable for chrome
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WebDriver in C# (work with windows and synchronization) I work with webDriver in #IE9 and I find one problem. If I started tests in Run mode, then all test fail because webDriver not exists (two window ie), but if I put breakpoint in tests and start tests Debug mode I have passed all tests. Please tell me, what do, because I don't know.
This my code:
private void MyMethods(IWebdriver driver)
{
foreach (var item in driver.WindowHandles) // if I put breakpoint, I see 2 count Window Handles else this methods don't work.
{
if (driver.SwitchTo().Window(item).Title == "PortalSubMenuPopupForm")
{
driver.SwitchTo().Window(item);
break;
}
}
}
A: Selenium has an "issue" with IE where new windows might not appear on the WindowHandles list right away.
The solution is either
*
*wait a fixed amount of time before calling driver.WindowHandles
or
*
*use the WebDriverWait class to wait for the number of elements under WindowHandles to change
I think the second one is more robust. Here is a quick implementation:
public void LaunchNewWindow(IWebElement element)
{
int windowsBefore = driver.WindowHandles.Count;
element.Click();
TimeSpan timeout = new TimeSpan(0, 0, 10);
WebDriverWait wait = new WebDriverWait(driver, timeout);
wait.Until((_driver) =>
{
return _driver.WindowHandles.Count != windowsBefore;
//optionally use _driver.WindowHandles.Count > windowsBefore
});
}
Now you can use the function like so:
IWebElement clickMe = //some element that launches a new window
LaunchNewWindow(clickMe);
foreach (var item in driver.WindowHandles)
{
//etc.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL Server, TimeSpans I am having a trouble in querying my database.. I have a table :
**Room**
+----------------------------------+
|RoomNo---RoomStatusID---RoomTypeID|
| 1 --- 1 --- 1 |
| 2 --- 1 --- 1 |
+----------------------------------+
**ClientRoom**
+--------------------------------------------------------------------+
|ClientRoomNo---RoomNo--------ArrivalDate-------------DepartureDate |
| 1 --- 1 ---- 2011-10-03 1:00:00 ---- 2011-10-03 4:00:00|
| 2 --- 1 ---- 2011-10-03 5:00:00 ---- 2011-10-03 8:00:00|
+--------------------------------------------------------------------+
If I use this query =
SELECT Room.RoomNo, RoomType.RoomType
FROM Room INNER JOIN
RoomType ON Room.RoomTypeNo = RoomType.RoomTypeNo
FULL OUTER JOIN ClientRoom ON Room.RoomNo = ClientRoom.RoomNo
WHERE
(((ClientRoom.ArrivalDate <= '10-03-2011 1:00:00' AND
ClientRoom.ArrivalDate <= '10-03-2011 5:00:00') AND
(ClientRoom.DepartureDate <= '10-03-2011 1:00:00' AND
ClientRoom.DepartureDate <= '10-03-2011 5:00:00'))
OR Room.RoomStatusId = 1)
It would return
**ClientRoom**
+--------------------------------------------------------------------+
|ClientRoomNo---RoomNo--------ArrivalDate-------------DepartureDate |
| 2 --- 1 ---- 2011-10-03 5:00:00 ---- 2011-10-03 8:00:00|
+--------------------------------------------------------------------+
Because it reached up to 5:00am in the morning.
But when I change the Arrival and Departure to.. 5:00 - 8:00..
RoomNo 1 is still in the results.
I already tried NOT BETWEEN :(
A: You did not explain what result you want in what circumstances. But this condition
ClientRoom.ArrivalDate <= '10-03-2011 1:00:00' AND
ClientRoom.ArrivalDate <= '10-03-2011 5:00:00'
looks fishy, because the first part is redundant. You could simply say
ClientRoom.ArrivalDate <= '10-03-2011 5:00:00'
Same thing for the next part:
ClientRoom.DepartureDate <= '10-03-2011 1:00:00' AND
ClientRoom.DepartureDate <= '10-03-2011 5:00:00'
This is the same as just saying:
ClientRoom.DepartureDate <= '10-03-2011 5:00:00'
Edit: From the comments I read it, that you have a given timespan (a,d) and want to check for each row, if your timespan overlaps with the timespan of the row (A,D). You want to see only non-overlapping rows.
This means your WHERE clause must be like this quasicode:
WHERE d <= A -- my departure will be before the rows arrival
OR a >= D -- my arrival is behind the rows departure
In full terms:
WHERE ( '10-03-2011 5:00:00' <= ClientRoom.ArrivalDate
OR '10-03-2011 1:00:00' >= ClientRoom.DepartureDate
)
OR Room.RoomStatusId = 1
Edit 2:
What does the query with this fixes? "Show me all schedule rows, which do not conflict with my schedule." But the query should be "Show me the rooms which do not have any conflicts with my schedule." That is a completely different beast but easily translated into SQL:
SELECT
Room.RoomNo
FROM Room
WHERE NOT EXISTS (
SELECT 1
FROM ClientRoom
WHERE
Room.RoomNo = ClientRoom.RoomNo
AND ( '10-03-2011 5:00:00' <= ClientRoom.ArrivalDate
OR '10-03-2011 1:00:00' >= ClientRoom.DepartureDate
)
)
OR Room.RoomStatusId = 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Asp.net Mvc 2 How to reroute to www.example.com/my-profile i would like to reroute this address www.exmaple.com/my-profile to a profile controller i have in my mvc application. There is my global.aspx, as you can the the default routing is
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}/", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This is the Maproute i'm trying to use to reroute to www.exmaple.com/my-profile
routes.MapRoute(
"Profile", // Route name
"{profile_name}/", // URL with parameters
new { controller = "Portfolio", action = "Index", page = UrlParameter.Optional } // Parameter defaults
);
The problem is when i type www.exmaple.com/profile it trys to direct me to the default maproute, not the one i have specified.
But when i can do this www.example.com/profile/my-profile
routes.MapRouteLowercase(
"Profile", // Route name
"profile/{profile_name}/", // URL with parameters
new { controller = "Portfolio", action = "Index", page = UrlParameter.Optional } // Parameter defaults
);
it works fine, but i dont want to add profile before my-profile. I would like it to work like facebook.com/my-profile or youtube.com/my-profile.
Does anyone one know how i accomplish this, i have been looking for a solution for over 2 months (on and off)
Thanks
A: Your routing if I remember rightly will return the first matching pattern for the URL. I would expect in your case, your URL is matching your default pattern first.
Move your more specific route above your 'default' route and see if this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting error on calling SaveAs method I'm trying to create a csv file from an excel file using MS Excel Interop in my C#/Winforms app.
Am getting this error on SaveAs method in the code below.
'The file could not be accessed. Try one of the following:
• Make sure the specified folder exists. • Make sure the folder that
contains the file is not read-only. • Make sure the file name does
not contain any of the following characters: < > ? [ ] : | or
* • Make sure the file/path name doesn't contain more than 218
characters.'z
I tried setting readonly to false in Workbook's Open(...) method as per:
Problem saving excel file after inserting data , but still getting the same error.
In my code, the csv file path was:C:\
If I change the csv file path to C:\SomeFolder or some shared UNC path, then I dont get this error.
Please advise.COuld there be some permissions issues with C drive?
Heres the code:
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Visible = false;
wbkSrc = xlApp.Workbooks.Open(m_sSrcFil,
Type.Missing, false, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
wstSrc = (Worksheet)wbkSrc.Worksheets[sSrcSht];
//wstSrc.Activate();
rngWork = wstSrc.Cells.get_Range("H:H", System.Reflection.Missing.Value);
rngWork.NumberFormat = "General";
dteTmpDate = Convert.ToDateTime(m_sBusDate);
sTmpFileName = m_sSrcFil.Substring(0, m_sSrcFil.IndexOf(".")) + "_" +
m_sUserName + "_" + dteTmpDate.ToString("yyyy_MM_dd") + ".Csv";
wstSrc.SaveAs(sTmpFileName, XlFileFormat.xlCSV, Type.Missing,
Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
A: Clearly sTmpFileName is an invalid path. The error message tells you that. Perhaps m_sUserName contains characters that are not allowed. Perhaps it is a DOMAIN\USER format user name. Perhaps the file name really is too long. Or perhaps something else is up. Take a look at the actual value of sTmpFileName and you will have your explanation.
As an aside, your code is mistaken in using SubString and IndexOf(".") to get the filename without the extension. Filenames can have multiple periods in them. The extension is simply that text after the final period. Consider these file names and how your code will deal with them:
C:\My.Folder.Name\TheFile.xls
C:\MyFolder\TheFile.Name.xls
Instead you should use Path.GetFileNameWithoutExtension.
A: Excel SaveAs is quite picky. Things like c:\folder\\file.csv (note the double backslash) are accepted by File.Exists or when you open a workbook, but not when saving
A: Check your FilePath where you are saving if it is more than 218 characters then also you will get this error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: pop up detail view out of tableviewcell I am working on a app where I want to expand a tableviewcell to cover almost all the screen with animation when it is selected by user. I am looking to create a uiview on the tableviewcell and expend it to cover major portion of the screen when user selects the row.
The main problem I am having is to get the frame from where my pop up view will start expending. How will I get the frame of the row which is touched?
Thanks
Pankaj
A: Is it crucial that the cell should not reposition?
If not ( i am guessing not, as you are anyway planning to cover whole screen):
When the cell is selected, scroll the cell to top (using scrollToRowAtIndexPath) and either insert your custom view to cell's contentView or modify its parameters if its already there with different opacity/size etc
A: Use UITableView function to get the rect for the row by passing the its NSIndexPath.
- (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using fread to read into int buffer I would like to know if I can use fread to read data into an integer buffer.
I see fread() takes void * as the first parameter. So can't I just pass an integer
buffer (typecast to void *) and then use this to read howmuchevery bytes I want to from the file, as long as the buffer is big enough ?
ie. cant i do:
int buffer[10];
fread((void *)buffer, sizeof(int), 10, somefile);
// print contents of buffer
for(int i = 0; i < 10; i++)
cout << buffer[i] << endl;
What is wrong here ?
Thanks
A: This should work if you wrote the ints to the file using something like fwrite ("binary" write). If the file is human-readable (you can open it with a text editor and see numbers that make sense) you probably want fscanf / cin.
A: As others have mentioned fread should be able to do what you want
provided the input is in the binary format you expect. One caveat
I would add is that the code will have platform dependencies and
will not function correctly if the input file is moved between
platforms with differently sized integers or different
endian-nesses (sp).
Also, you should always check your return values; fread could fail.
A: Yes you can use fread to read into an array of integers
int buffer[10];
size_t readElements = fread((void *)buffer, sizeof(int), 10, somefile);
for(int i = 0; i < readElements; i++)
cout << buffer[i] << endl
You can check the number of elements fread returns to print out.
EDIT: provided you are reading from a file in binary mode and the values were written as cnicutar mentioned with fwrite.
A: I was trying the same and was getting the same result as yours, large int value when trying to read integer using fread() from a file and finally got the reason for it.
So suppose if your input file contains only:
*
*"5"
*"5 5 5"
The details I got from http://www.programmersheaven.com/mb/beginnercpp/396198/396198/fread-returns-invalid-integer/
fread() reads binary data (even if the file is opened in 'text'-mode). The number 540352565 in hex is 0x20352035, the 0x20 is the ASCII code of a space and 0x35 is the ASCII code of a '5' (they are in reversed order because using a little-endian machine).
So what fread does is read the ASCII codes from the file and builds an int from it, expecting binary data. This should explain the behavior when reading the '5 5 5' file. The same happens when reading the file with a single '5', but only one byte can be read (or two if it is followed by a newline) and fread should fail if it reads less than sizeof(int) bytes, which is 4 (in this case).
A: As the reaction to response is that it still does not work, I will provide here complete code, so you can try it out.
Please note that following code does NOT contain proper checks, and CAN crash if file does not exist, there is no memory left, no rights, etc.
In code should be added check for each open, close, read, write operations.
Moreover, I would allocate the buffer dynamically.
int* buffer = new int[10];
That is because I do not feel good when normal array is taken as pointer. But whatever. Please also note, that using correct type (uint32_t, 16, 8, int, short...) should be done to save space, according to number range.
Following code will create file and write there correct data that you can then read.
FILE* somefile;
somefile = fopen("/root/Desktop/CAH/scripts/cryptor C++/OUT/TOCRYPT/wee", "wb");
int buffer[10];
for(int i = 0; i < 10; i++)
buffer[i] = 15;
fwrite((void *)buffer, sizeof(int), 10, somefile);
// print contents of buffer
for(int i = 0; i < 10; i++)
cout << buffer[i] << endl;
fclose(somefile);
somefile = fopen("/root/Desktop/CAH/scripts/cryptor C++/OUT/TOCRYPT/wee", "rb");
fread((void *)buffer, sizeof(int), 10, somefile);
// print contents of buffer
for(int i = 0; i < 10; i++)
cout << buffer[i] << endl;
fclose(somefile);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Refreshing every minutes In a form, there is a label. It shows whether web service is connected or not at every minutes. How to code to repeat this process? Will I use the thread or timer? Please share me.
A: You will need a timer object in order to run the code every X minutes. Using a separate thread to check the web service only needs to be done if it will take a while to check and you want your form to remain responsive during this time.
Using a timer is very easy:
Private WithEvents timer As New System.Timers.Timer
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Set interval to 1 minute
timer.Interval = 60000
'Synchronize with current form, or else an error will occur when trying to
'update the UI from within the elapsed event
timer.SynchronizingObject = Me
End Sub
Private Sub timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles timer.Elapsed
'Add code here to check if the web service is updated and update label
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: linq expression error:cant display column? i am trying to join my linq query with another table. How can I display the name in the Customer table? I am getting an error: does not contain a definition for 'Name'?
from p in Purchases
join c in Customers on p.CustomerID equals c.ID
group p by p.Date.Year into SalesPerYear
select new {
customername= SalesPerYear.First().Name,
customerid= SalesPerYear.First().CustomerID,
totalsales= SalesPerYear.Sum(x=>x.Price)
}
A: You're grouping p (i.e. purchases) by date - so the customer details are no longer present.
Try this instead:
from p in Purchases
join c in Customers on p.CustomerID equals c.ID
group new { p, c } by p.Date.Year into SalesPerYear
select new {
CustomerName = SalesPerYear.First().c.Name,
CustomerId = SalesPerYear.First().p.CustomerID,
TotalSales = SalesPerYear.Sum(x => x.p.Price)
}
Or alternatively:
from p in Purchases
join c in Customers on p.CustomerID equals c.ID
group new { p.CustomerId, p.Price, c.CustomerName }
by p.Date.Year into SalesPerYear
select new {
SalesPerYear.First().CustomerName,
SalesPerYear.First().CustomerId
TotalSales = SalesPerYear.Sum(x => x.Price)
}
A: SalesPerYear is an IGrouping. You need to access Name, CustomerID etc off the Value property of the IGrouping.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tools to work with visual studio project on server? i want tools like Team foundation or SVN subversion to work with the team in same project by putting source project on the server. i want program that do it but i don't want svn and team foundation . are there another tools like them?
Thanks
A: There's GIT, it's nearly like SVN but its not :O http://en.wikipedia.org/wiki/Git_(software)
A good online website for this would be https://github.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Asp.net Postback issue I have Department Dropdown on change of this I made jquery-ajax request to get the Department Details.
I'll be binding this result to a Div.
that works well till here.
When I click an asp.net button or any server side control after post back the div element is emptied.
How can I get the previous result in the div element.
Success function for Ajax call goes like below:
function OnSuccess(response) {
var List = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
DeptDetails = "";
$.each(List, function () {
DeptDetails = "<table cellpadding='0' cellspacing='0' class='grid' border='0' width='94%'>";
DeptDetails = DeptDetails + "<tr><td align='right' style='padding-left: 10px; padding-top: 3px;'>Store Name:</td><td align='left' style='padding-left:3px;padding-top:3px;'>" + this["DeptName"] + "</td></tr>";
DeptDetails = DeptDetails + "<tr><td align='right' style='padding-left: 10px; padding-top: 3px;'>Address:</td><td align='left' style='padding-left:3px;padding-top:3px;'>" + this["Address"] + "</td></tr>";
DeptDetails = DeptDetails + "<tr><td align='right' style='padding-left: 10px; padding-top: 3px;'>Zone:</td><td align='left' style='padding-left:3px;padding-top:3px;'>" + this["ZoneName"] + "</td></tr>";
DeptDetails = DeptDetails + "<tr><td align='right' style='padding-left: 10px; padding-top: 3px;'>Zone Manager:</td><td align='left' style='padding-left:3px;padding-top:3px;'>" + this["ZoneManager"] + "</td></tr></table>";
$('div[id*="divDeptDetails"]').html(DeptDetails);
});
}
Thanks in advance.It is urgent guys.
A: jQuery(document).ready(function(){
// check here if the drop down has a selected item different than the default one
// make the same ajax call you are doing on the drop down
})
A: Anand, you need to persist the data by adding the data to the viewstate or by sending it along with a hidden input.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a sample source code for home automation on android? i wanted to know how the home automation is done in android. if anyone has a sample code of a single switch button for a light to switch on or off..??? it would be helpful for me..i wanted to know how the coding is being done of this.
Thanks in advance
A: If you go to the Android market and search for 'Phidgets' you'll see application of the technology you require.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hibernate Session.save issue Hi I have a domain object lets say Student and its Roll no as a primary key
here is the sample mapping for it.
@Id
@Column(name = "Roll_NO", unique = true, nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Roll_NO_SEQ")
@SequenceGenerator(name = "Roll_NO_SEQ", sequenceName = "Roll_NO_SEQ", allocationSize = 1)
public Long getRollNo() {
return this.rollNo;
}
issue : lets say if a particular student was deleted from the database, and then re-admitted at the time of re-admission i want to retain the old roll no . so when i call session.save hibernate assigns a new roll No based on the Sequence specified rather then what i am setting through setRollNo() method. is there any way to achieve this in hibernate?
A: don't delete the record, add a new boolean field called soemthign like active or valid, and instead of deleting just make active = false.
Or,
You could insert the record to be deleted into an archive table and then delete, and then look up from there.
A: Given that you can't change the deleting of the rows, another way would be to write your own id generator that will only get a new sequence value if a value isn't already assigned. See the end of section 5.1.2.2 in the reference guide for info about writing your own generator. I've never tried this before, so I can only point you in the general direction.
A: Given that you cannot change the legacy code, Ryan has the right idea. I had to do basically the same thing some time ago in a personal project. There were two parts: the easy part is to allow the effective setting of an otherwise-autonumber-ed column's ID...and the other is to make the ID generator stop overwriting that value when you go to Save().
Here's the code to the FlexibleIDGenerator I used:
public class FlexibleIDGenerator extends IdentityGenerator implements Configurable {
public static final String DEFAULT = "default";
private IdentifierGenerator assignedGenerator;
private IdentifierGenerator defaultGenerator;
@SuppressWarnings("unchecked")
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
//boolean useDefault = false;
if (object instanceof OverridableIdentity) {
if (((OverridableIdentity) object).isIDOverridden()) {
try {
Class cl = object.getClass().getSuperclass();
Method[] methods = cl.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equalsIgnoreCase("setId")) {
methods[i].invoke(object, Integer.valueOf((((OverridableIdentity) object).getOverriddenID())));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return assignedGenerator.generate(session, object);
} else {
return defaultGenerator.generate(session, object);
}
} else {
return defaultGenerator.generate(session, object);
}
}
public void configure(Type type, Properties params, Dialect d) throws MappingException {
assignedGenerator = IdentifierGeneratorFactory.create("assigned", type, params, d);
defaultGenerator = IdentifierGeneratorFactory.create("increment", type, params, d);
}
}
To use that for a class, you update your Hibernate mapping file like this:
<id
name="Id"
type="integer"
column="id"
>
<generator class="com.mypackage.FlexibleIDGenerator"/>
</id>
One other detail: I added a method to my base object called "GetOverriddenID()" to avoid confusion about whether I'm using the "normal" ID (in Update() calls) or the overridden ones.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: embedding an X11 widget in Cocoa I'm working on pythonocc, which exposes the OpenCasCade API in a pythonic manner.
OCC is coupled to either the windows or X11 gui environment.
This is somewhat problematic on OSX; I need to build [Py]Qt4 for X11, rather than Cocoa, which makes distribution much harder than it should be. Hence the following question; is it possible to embed a X11 widget in Cocoa? That would allow me to use PyQt4 / PySide for Cocoa and make things a lot easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scope vs life of variable in C Could someone exactly explain the concept of scope and life of variable in C. Is it different in C++? I'm confused between scope and life.
A: Scope is the region where the variable is accessible.
Life time is the time span during which an object remains valid.
An simple example:
#include <iostream.h>
void doSomething()
{
x = 5; //Error! Not Accessible
}
int main()
{
int x = 4;
std::cout<< x << endl;
{
int x = 2;
cout << x << endl;
}
doSomething();
std::cout<< x << endl;
return 0;
}
The above gives the output:
4
2
4
In above program,
lifetime of variable x = 4 is throughout the main, i.e: It remains alive throughout the execution of the main, Also it is accessible within the main, that is its scope. Note that it is not accessible in the function because it is beyond the scope of the variable x.
while scope and lifetime of variable x = 2 is within the enclsing braces{ } inside the main.
A: "Scope" of a variable is a region of source code, where you can refer to that variable.
"Lifetime" is how long it exists during the program execution.
By default the lifetime of a local variable is the same as its scope:
void foo()
{
int x = 123;
cout << x << endl;
x += 1;
}
int main(){ foo(); foo(); foo(); }
Here, each time foo is called a new x is created (space is reserved for it on the stack), and when the execution leaves the block where x was declared, x is destroyed (which for int just means that the space that was reserved, now is freed for reuse).
In contrast:
void foo()
{
static int x = 123;
cout << x << endl;
x += 1;
}
int main(){ foo(); foo(); foo(); }
Here, since x is declared static, space is reserved for x before the program execution even begins. x has a fixed location in memory, it's a static variable. And C++ has special rules about the initialization of such a variable: it happens the first time the execution passes through the declaration.
Thus, in the first call of foo this x is initialized, the output statement displays 123, and the increment increases the value by 1. In the next call the initialization is skipped (it has already been performed), the value 124 is output, and the value is incremented again. So on.
The lifetime of this x is from start of execution to end of execution.
A: The scope of a variable is determined at compilation time. It is the region in the program where the same object that is defined through the definition is accessible through that identifier.
The lifetime of an object is a feature that is defined at runtime, through the flow of execution. An object can be accessed through a pointer even if the variable through which it was defined is not in scope.
void f(char *a) {
*a = 'f';
}
void g(void) {
char aChar = ' ';
f(&aChar);
}
Here the scope of variable aChar (the identifier) is the body of g. During the execution of g the lifetime of the object expands to the execution of f. Using the identifier aChar inside f would be illegal, the compiler would tell you something like "unknown indetifier aChar in function f". Using a pointer to that object as done above is completely legal.
A: The scope of a variable refers to the extent to which different parts of a program have access to the variable.
Variables can be declared as:
*
*Inside a function which is called local variables or internal variables.
*Outside of all functions which is called global variables or external variables and lifetime or "extent" extends across the entire run of the program.
Here is detailed tutorial about variables with examples : What is variable in C
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Searching Apps in App Store I want to search Apps in App Store by a keyword. Lets say if i type in "poker" and press enter then,
it should open all the apps in App Store having the string "poker" in there name or in description. i looked for Search API of apple but i am not able to find the specific term to search apps in App Store instead of itunes there. Examples out here are also only for itunes not for the apps in App Store.
Any help on this will be highly appreciated.
A: the AppStore is a part of iTunes.
if you use &entity=software in the search API, you'll be searching the AppStore.
a search for the example you proposed: http://itunes.apple.com/search?term=poker&entity=software
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trigger a click event on an inner element A row in a table where each first cell contains a link needs to be clicked and open a url.
<table>
<tr>
<td><a class="fancybox" href="detail.aspx?CID=67525">LT5C260A436C41</a></td>
<td>more data</td>
</tr>
<tr>
<td><a class="fancybox" href="detail.aspx?CID=17522">LA5C260D436C41</a></td>
<td>more data</td>
</tr>
...
</table>
The complete row should be clickable instead of only the link top open the detail page in a fancybox, ie in the page itself.
So I tried to do something like this:
$("table tr").bind('click',function(e) {
e.stopPropagation();
$(this).find("a").trigger('click');
});
But it seems that the event is bubbling recursivly resulting in a:
Uncaught RangeError: Maximum call stack size exceeded
How can I trigger the click on the full row instead of only the link in a proper way avoiding the stackoverflow?
UPDATE: I really appreciate the answers below, but my question is about triggering the event, NOT executing the behaviour inside that event. Workarounds could be nice, but not in this case.
A: Try this:
$("table tr a").bind('click', function(e) {
e.preventDefault();
window.open($(this).attr('href'));
return false;
});
$("table tr").bind('click', function(e) {
$(this).find("a").trigger('click');
});
I found what went wrong.
In your code,
$("table tr").bind('click',function(e) {
e.stopPropagation();
$(this).find("a").trigger('click');//This line again triggers a click event binded on the tr ELEMENT which contains the 'a' ELEMENT. So it goes into a infinite loop.
});
Update:
This will do.
$("table tr").bind('click', function(e) {
window.location.href = $(this).find("a.fancybox").attr('href');
});
$(this).find("a").trigger('click'); is actually not triggering the default
anchor tag behavior. It just tries to trigger a click event if a click event
is already bound to that element explicitly.
A: It may be that I misunderstood your question, but doesn't this do what you need:
$("table tr").click(function(e) {
e.stopImmediatePropagation();
if (! $(e.target).is('a')) {
$(this).find("a").trigger('click');
}
});
A: For the funny purpose of this exercise, here is a pure js solution, i.e., w/o using jQ lib).
Available here for testing: http://jsfiddle.net/Sr5Vy/3/
<table>
<tr id="node_1">
<td><a class="fancybox" href="detail.aspx?CID=67525">LT5C260A436C41</a></td>
<td>more data</td>
</tr>
<tr id="node_2">
<td><a class="fancybox" href="detail.aspx?CID=17522">LA5C260D436C41</a></td>
<td>more data</td>
</tr>
</table>
function AddEvent(id, evt_type, ma_fonction, phase) {
var oElt = document.getElementById(id);
if( oElt.addEventListener ) {
oElt.addEventListener(evt_type, ma_fonction, phase);
} else if( oElt.attachEvent ) {
oElt.attachEvent('on'+evt_type, ma_fonction);
}
// Debug
// alert('a \'' + evt_type + '\' event has been attached on ' + id );
return false;
}
function getElementsByRegExpOnId(search_reg, search_element, search_tagName) {
search_element = (search_element === undefined) ? document : search_element;
search_tagName= (search_tagName === undefined) ? '*' : search_tagName;
var id_return = new Array;
for(var i = 0, i_length = search_element.getElementsByTagName(search_tagName).length; i < i_length; i++) {
if (search_element.getElementsByTagName(search_tagName).item(i).id &&
search_element.getElementsByTagName(search_tagName).item(i).id.match(search_reg)) {
id_return.push(search_element.getElementsByTagName(search_tagName).item(i).id) ;
}
}
return id_return; // array
}
function FollowSpecialLinks(event) {
// Debug
// alert('event was successfully attached');
// Prevent propagation
event.preventDefault();
// Identify targetted node (eg one of the children of <tr>)
var targetted_elt = ShowEventSource(event);
//alert('Event\'s target : ' + targetted_elt);
// Extract the targetted url
if (targetted_elt == "A") {
var current_link = GetEventSource(event).href;
} else {
var current_tr = GetEventSource(event).parentNode;
var child_links = current_tr.getElementsByTagName('a');
var current_link = child_links[0].href;
}
// Now open the link
if(current_link) {
// Debug
alert('will now open href : ' + current_link);
window.location = current_link;
}
}
function GetEventSource(event) {
var e = event || window.event;
var myelt = e.target || e.srcElement;
return myelt;
}
function ShowEventSource(event) {
var elmt;
var event = event || window.event; // W3C ou MS
var la_cible = event.target || event.srcElement;
if (la_cible.nodeType == 3) // Vs bug Safari
elmt = la_cible.parentNode;
else
elmt = la_cible.tagName;
return elmt;
}
// Get all document <tr> id's and attach the "click" events to them
my_rows = new Array();
my_rows = getElementsByRegExpOnId(/^node_.+/, document , 'tr') ;
if (my_rows) {
for (i=0; i< my_rows.length; i++ ) {
var every_row = document.getElementById( my_rows[i] ) ;
AddEvent(every_row.id, 'click', FollowSpecialLinks, false);
}
}
A: This worked well:
$("table tr").click(function(e) {
var $link = $(this).find("a");
if (e.target === $link[0]) return false;
$link.trigger('click');
return false;
});
EDIT:
Why most solutions don't work — they fail, because when the link was clicked, the immediate handler attached runs. The event then bubbles to see if a handler was attached to a table cell, row, etc.
When you suggest triggering a click you cause the recursion: the link was clicked → fancybox → bubbles → aha! table row → trigger the link click → the link was clicked…
When you suggest to stop propagation, please note that event stops bubbling to parent elements, so a click handler attached to body will not be executed.
Why the code above works — we check if the event bubbled from a link. If true, we simply return and stop further propagation.
See the updated fiddle: http://jsfiddle.net/F5aMb/28/
A: Try
$(".fancybox").parent('td').parent('tr').bind('click',function(e) {
e.stopPropagation();
$(this).find("a").trigger('click');
});
A: Have you tried stopping immediate propagation when you click the link?This way you should stop the recursion
$('a').click(function(e){
e.stopImmediatePropagation();
alert('hi');
});
fiddle here: http://jsfiddle.net/3VMGn/2/
A: In order to compensate for the bubbling, you need to detect the target of the event and not click on the link more than once.
Also, jQuery's "trigger" function won't work for plain links, so you need a specialized click function.
you can try it out at: http://jsfiddle.net/F5aMb/27/
$("table tr").each(function(i, tr){
$(tr).bind('click',function(e) {
var target = $(e.target);
if( !target.is("a") ) {
clickLink($(this).find("a")[0]);
}
})
});
function clickLink(element) {
if (document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
} else {
//IE
element.click()
}
}
A: try
$('table tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
A: I was able to do it by giving each link a unique ID and then using jQuery to set the click event of that unique ID to redirect the window to the appropriate page.
Here is my working example: http://jsfiddle.net/MarkKramer/F5aMb/2/
And here is the code:
$('#link1').click(function(){
// do whatever I want here, then redirect
window.location.href = "detail.aspx?CID=67525";
});
$('#link2').click(function(){
// do whatever I want here, then redirect
window.location.href = "detail.aspx?CID=17522";
});
$("table tr").click(function(e) {
e.stopImmediatePropagation();
$(this).find("a").trigger('click');
});
A: You can do what you want with following code. I tested it on you jsfilddle seems working.
$("table tr").click(function(e) {
// check if click event is on link or not.
// if it's link, don't stop further propagation
// so, link href will be followed.
if($(e.target).attr('class')=='fancybox'){
alert('you clicked link, so what next ?.');
// else if click is happened somewhere else than link,
// stop the propagation, so that it won't go in recursion.
}else{
alert('no link clicked, :( ');
alert('now clicking link prgrammatically');
$(this).find('a').click();
e.preventDefault();
}
});
Let me know, if you want to achieve something else than this.
A: I think .click() or .trigger("click") only fires the event handlers for onclick.
See a sample here http://jsfiddle.net/sethi/bEDPp/4/
. Manually clicking on the link shows 2 alerts while firing the event through jQuery shows only 1 alert.
You can also refer to this link : re-firing a click event on a link with jQuery
Solution
If you are just looking to open a fancybox try this:
$("table tr").bind('click',function(e) {
var elem = $(e.target);
if(elem.is('a')){
return;
}
e.stopImmediatePropagation();
var parent= elem.is('tr') ? elem:elem.parents("tr").eq(0);
parent.find("a").trigger('click.fb');
});
where click.fb is the event that fancybox binds with the anchor element.
A: $('a.fancybox').click(function(evt){evt.stopPropagation())});
$('table tr:has[.fancybox]').click(function(evt){
$(this).find('.fancybox').trigger('click')
})
A: I think I have what you're looking for. What you need to do is to call click() on the anchor tag in the handler, and make sure you ignore events from the anchor itself. Also, WebKit doesn't support click(), so you have to implement it yourself.
Notice from the fiddle below that it properly follows the link target, that is, opens a new window, or loads into the same window. http://jsfiddle.net/mendesjuan/5pv5A/3/
// Some browsers (WebKit) don't support the click method on links
if (!HTMLAnchorElement.prototype.click) {
HTMLAnchorElement.prototype.click = function() {
var target = this.getAttribute('target');
var href = this.getAttribute('href');
if (!target) {
window.location = href;
} else {
window.open(href, target);
}
}
}
$("table tr").bind('click',function(e) {
// This prevents the stack overflow
if (e.target.tagName == 'A') {
return;
}
// This triggers the default behavior of the anchor
// unlike calling jQuery trigger('click')
$(this).find("a").get(0).click();
});
A: My usecase was to trigger a click when a -element was clicked. Checking the type of the target element solves the recursive call problem.
$('#table tbody td').click(function(e){
if ($(e.target).is('td')) {
$(this).find('input').trigger('click');
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Maximum size of HashSet, Vector, LinkedList What is the maximum size of HashSet, Vector, LinkedList? I know that ArrayList can store more than 3277000 numbers.
However the size of list depends on the memory (heap) size. If it reaches maximum the JDK throws an OutOfMemoryError.
But I don't know the limit for the number of elements in HashSet, Vector and LinkedList.
A: In all cases, you're likely to be limited by the JVM heap size rather than anything else. Eventually you'll always get down to arrays so I very much doubt that any of them will manage more than 231 - 1 elements, but you're very, very likely to run out of heap before then anyway.
A: It very much depends on the implementation details.
A HashSet uses an array as an underlying store which by default it attempt to grow when the collection is 75% full. This means it will fail if you try to add more than about 750,000,000 entries. (It cannot grow the array from 2^30 to 2^31 entries)
Increasing the load factor increases the maximum size of the collection. e.g. a load factor of 10 allows 10 billion elements. (It is worth noting that HashSet is relatively inefficient past 100 million elements as the distribution of the 32-bit hashcode starts to look less random, and the number of collisions increases)
A Vector doubles its capacity and starts at 10. This means it will fail to grow above approx 1.34 billion. Changing the initial size to 2^n-1 gives you slightly more head room.
BTW: Use ArrayList rather than Vector if you can.
A LinkedList has no inherent limit and can grow beyond 2.1 billion. At this point size() could return Integer.MAX_VALUE, however some functions such as toArray will fail as it cannot put all objects into an array, in will instead give you the first Integer.MAX_VALUE rather than throw an exception.
As @Joachim Sauer notes, the current OpenJDK could return an incorrect result for sizes above Integer.MAX_VALUE. e.g. it could be a negative number.
A: There is no specified maximum size of these structures.
The actual practical size limit is probably somewhere in the region of Integer.MAX_VALUE (i.e. 2147483647, roughly 2 billion elements), as that's the maximum size of an array in Java.
*
*A HashSet uses a HashMap internally, so it has the same maximum size as that
*
*A HashMap uses an array which always has a size that is a power of two, so it can be at most 230 = 1073741824 elements big (since the next power of two is bigger than Integer.MAX_VALUE).
*Normally the number of elements is at most the number of buckets multiplied by the load factor (0.75 by default). However, when the HashMap stops resizing, then it will still allow you to add elements, exploiting the fact that each bucket is managed via a linked list. Therefore the only limit for elements in a HashMap/HashSet is memory.
*A Vector uses an array internally which has a maximum size of exactly Integer.MAX_VALUE, so it can't support more than that many elements
*A LinkedList doesn't use an array as the underlying storage, so that doesn't limit the size. It uses a classical doubly linked list structure with no inherent limit, so its size is only bounded by the available memory. Note that a LinkedList will report the size wrongly if it is bigger than Integer.MAX_VALUE, because it uses a int field to store the size and the return type of size() is int as well.
Note that while the Collection API does define how a Collection with more than Integer.MAX_VALUE elements should behave. Most importantly it states this the size() documentation:
If this collection contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.
Note that while HashMap, HashSet and LinkedList seem to support more than Integer.MAX_VALUE elements, none of those implement the size() method in this way (i.e. they simply let the internal size field overflow).
This leads me to believe that other operations also aren't well-defined in this condition.
So I'd say it's safe to use those general-purpose collections with up to Integer.MAX_VLAUE elements. If you know that you'll need to store more than that, then you should switch to dedicated collection implementations that actually support this.
A: The maximum size depends on the memory settings of the JVM and of course the available system memory. Specific size of memory consumption per list entry also differs between platforms, so the easiest way might be to run simple tests.
A: As stated in other answers, an array cannot reach 2^31 entries. Other data types are limited either by this or they will likely misreport their size() eventually. However, these theoretical limits cannot be reached on some systems:
On a 32 bit system, the number of bytes available never exceeds 2^32 exactly. And that is assuming that you have no operating system taking up memory. A 32 bit pointer is 4 bytes. Anything which does not rely on arrays must include at least one pointer per entry: this means that the maximum number of entries is 2^32/4 or 2^30 for things that do not utilize arrays.
A plain array can achieve it's theoretical limit, but only a byte array, a short array of length 2^31-1 would use up about 2^32+38 bytes.
Some java VMs have introduced a new memory model that uses compressed pointers. By adjusting pointer alignment, slightly more than 2^32 bytes may be referenced with 32 byte pointers. Around four times more. This is enough to cause a LinkedList size() to become negative, but not enough to allow it to wrap around to zero.
A sixty four bit system has sixty four bit pointers, making all pointers twice as big, making non array lists a bunch fatter. This also means that the maximum capacity supported jumps to 2^64 bytes exactly. This is enough for a 2D array to reach its theoretical maximum. byte[0x7fffffff][0x7fffffff] uses memory apporximately equal to 40+40*(2^31-1)+(2^31-1)(2^31-1)=40+40(2^31-1)+(2^62-2^32+1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: JBlend with LWUIT I have made some applications on J2ME using LWUIT, CLDC 1.1, MIDP 2.0 and they are working great on Nokia handsets.
But when I tried to install these applications on Huawei G7206 (JBlend) some of the applications gives error (NOT SUPPORTED) and some crashes without displaying anything.
I have tested an application without LWUIT and it worked.
My question is,
what is the issue?
Either JBlend does not support LWUIT? or I have to downgrade my applications (I mean to remove some features)?
Does anyone know the limitations to work with JBlend?
A: Have you tested your applications on other devices?
Confirm that your jad doesn't include any other hidden requirements, jblend generally works with LWUIT but some VM's don't handle the full LWUIT properly and require an obfuscated application or similar hacks.
A: Whenever we use LWUIT in application the size of the application increase because of the jar file which we add in it. By obfuscation we can reduce the size of .jar file. And can become able to run in device.
Please try of obfuscate the application. You might get the solution of your problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: what is Reads and Writes in Sys.dm_exec_requests DMV of SQL Server As per explaination given on MSDN at link http://msdn.microsoft.com/en-us/library/ms177648.aspx
I am not able to understand the meaning of Reads and Writes fully.whether it is physical or logical or database Reads and Writes. Please help me out in this regards
A: It's number of physical reads/writes of 8k blocks. So if you multiply it by 8 you will get number of kilobytes that was read/written.
A: Martin answered your question...the logical_reads column corresponds to logical reads (i.e. requests that can be fulfilled by data currently available in the buffer cache) while reads corresponds to physical reads (i.e. requests for data that isn't currently in the buffer cache and requires a read from the relevant data file on disk).
A write in SQL Server modifies the page in memory; modified pages are marked as dirty and written to disk by asynchronous processes (also what Martin said).
Just to add, all of these figures represent number of pages, not rows.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to make newly added main menu option in magento admin section "selected" I have developed a new custom extension for magento admin section. Main menu option of this extension in admin section is visible. When I click on that menu option, functionality of this extension is working as per development/expected. But on this menu option "active" class is not being applied ( so that user can differentiate other menu option with this selected menu ).
There is no submenu under this main menu option. How can I apply "active" class on that menu option when this is clicked.
Thanks in advance!
A: You should use Mage_Adminhtml_Controller_Action::_setActiveMenu($menuPath) method.
For more details you can check Mage_Adminhtml_Cms_PageController::_initAction().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create a hash of a file on iOS? I'm trying to create unique file names by renaming them using their hashed value in iOS. How can I do that?
A: you could achieve this by extending NSString,
Try this in your .h:
@interface NSString(MD5)
- (NSString *)generateMD5Hash
@end
and this in your .m
- (NSString*)generateMD5Hash
{
const char *string = [self UTF8String];
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(string, strlen(string), md5Buffer);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
you can implement this by making a new class called NSString+MD5, and inserting the code above in the corresponding files (.h and .m)
EDIT: Do not forget to import
< CommonCrypto/CommonDigest.h >
EDIT 2:
And for NSData;
@interface NSData(MD5)
- (NSString *)generateMD5Hash;
@end
your .m:
- (NSString *)generateMD5Hash
{
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
CC_MD5(self.bytes, (CC_LONG)self.length, md5Buffer);
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
Please note that the value returned is autorelease and might need to be retained by the receiver.
Hope this helps.
A: Why don't you simply generate unique identifiers and use it? like
CFUUIDRef uuidObj = CFUUIDCreate(nil);
NSString *uniqueId = (NSString*)CFUUIDCreateString(nil, uuidObj);
CFRelease(uuidObj);
NSLog(@"%@",uniqueId);
[uniqueId autorelease];
A: Using NSData is an expensive choice. Better use NSFileHandler extension if you are dealing with big files anytime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Text box display when click on the edit button I have to display the text boxes and list boxes when click on the edit button. Please give suggestion to how to do that things.
HTML:
<div class="textboxes">
<ul>
<li><input type="text" id="txt" /></li>
<li><input type="text" id="txt" /></li>
<li><input type="text" id="txt" /></li>
</ul>
</div>
<input type="button" value="Edit" id="editBut" />
Javascript:
$("input[type='text']").blur(function(){
$(this).hide().after('<span class="dfk">' + $(this).val() + '</span>');
});
Here js fiddle : http://jsfiddle.net/thilakar/yvNuC/11/
Thanks
A: Here is it: http://jsfiddle.net/yvNuC/14/
$("#editBut").click(function() {
if ($('.textboxes').is(':visible')) {
$('.textboxes').hide();
// do save info
$(this).val('Edit');
}
else {
$('.textboxes').show();
$(this).val('Save');
}
});
Or if you need to display values after saving: http://jsfiddle.net/yvNuC/16/
A: Try this
$("#editBut").click(function() {
$('.textboxes span').hide();
$('.textboxes input[type=text]').show();
});
Check this DEMO
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pixel color calculation 255 to 0 I have been using the algorithm from Microsoft here:
INT iWidth = bitmap.GetWidth();
INT iHeight = bitmap.GetHeight();
Color color, colorTemp;
for(INT iRow = 0; iRow < iHeight; iRow++)
{
for(INT iColumn = 0; iColumn < iWidth; iColumn++)
{
bitmap.GetPixel(iColumn, iRow, &color);
colorTemp.SetValue(color.MakeARGB(
(BYTE)(255 * iColumn / iWidth),
color.GetRed(),
color.GetGreen(),
color.GetBlue()));
bitmap.SetPixel(iColumn, iRow, colorTemp);
}
}
to create a gradient alpha blend. Theirs goes left to right, I need one going from bottom to top, so I changed their line
(BYTE)(255 * iColumn / iWidth)
to
(BYTE)(255 - ((iRow * 255) / iHeight))
This makes row 0 have alpha 255, through to the last row having alpha 8.
How can I alter the calculation to make the alpha go from 255 to 0 (instead of 255 to 8)?
A: f(x) = 255 * (x - 8) / (255 - 8)?
Where x is in [8, 255] and f(x) is in [0, 255]
The original problem is probably related with the fact that if you have width of 100 and you iterate over horizontal pixels, you'll only get values 0 to 99. So, dividing 99 by 100 is never 1. What you need is something like 255*(column+1)/width
A: (BYTE)( 255 - 255 * iRow / (iHeight-1) )
iRow is between 0 and (iHeight-1), so if we want a value between 0 and 1 we need to divide by (iHeight-1). We actually want a value between 0 and 255, so we just scale up by 255. Finally we want to start at the maximum and descend to the minimum, so we just subtract the value from 255.
At the endpoints:
iRow = 0
255 - 255 * 0 / (iHeight-1) = 255
iRow = (iHeight-1)
255 - 255 * (iHeight-1) / (iHeight-1) = 255 - 255 * 1 = 0
Note that iHeight must be greater than or equal to 2 for this to work (you'll get a divide by zero if it is 1).
Edit:
This will cause only the last row to have an alpha value of 0. You can get a more even distribution of alpha values with
(BYTE)( 255 - 256 * iRow / iHeight )
however, if iHeight is less than 256 the last row won't have an alpha value of 0.
A: Try using one of the the following calculations (they give the same result):
(BYTE)(255 - (iRow * 256 - 1) / (iHeight - 1))
(BYTE)((iHeight - 1 - iRow) * 256 - 1) / (iHeight - 1))
This will only work if using signed division (you use the type INT which seems to be the same as int, so it should work).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I get APK file on phone of the installed applications I am trying to develop a application for backing up the files. I need to extract the APK files of installed applications like the Astro manager does.
If anyone know how to extract please give me the solution.
A: They are stored in /data/app/ but unless your phone is rooted you won't see anything there.
System apk's are stored at /system/app
A better way of getting the exact apk path :
PackageManager pm = getPackageManager();
List<PackageInfo> pkginfolist = pm.getInstalledPackages(PackageManager.GET_ACTIVITIES);
List<ApplicationInfo> appinfoList = pm.getInstalledApplications(0);
for (int x = 0; x < pkginfolist .size(); x++) {
PackageInfo pkginfo = pkginfolist.get(x);
pkg_path[x] = appinfoList.get(x).publicSourceDir;
}
A: You need to root your phone first. Then install Android SDK.
run adb or ddms->file explorer, look for your interested-in APK in /system/app
A: The most simplest method would be take backup of application using ASTRO file manager,
Open Astro File Manager> Tool > Application Manager > Backup see hep docs here.
it will backup your selected apps's .apk backup !
drop comment if any problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery Optimize link "href" selection I'm changing the class of "a" tag according to "href" file type. It works fine. Here's the code:
$('#divComment a[href$=".pdf"]').removeClass().addClass("pdf");
$('#divComment a[href$=".doc"]').removeClass().addClass("word");
$('#divComment a[href$=".docx"]').removeClass().addClass("word");
$('#divComment a[href$=".zip"]').removeClass().addClass("zip");
$('#divComment a[href$=".jpg"]').removeClass().addClass("image");
$('#divComment a[href$=".xls"]').removeClass().addClass("excel");
$('#divComment a[href$=".xlsx"]').removeClass().addClass("excel");
How do I optimize this code?
A: If by optimization, you mean to make the code more concise and maintainable, then you could create a look-up table.
Example:
var extensions = {
'.pdf': 'pdf',
'.doc': 'word'
// ...
};
$('#divComment a').each(function() {
var match = this.href.match(/\..+$/);
if(match && extensions[match[0]]) {
$(this).removeClass().addClass(extensions[match[0]]);
}
});
A: try this
$(document).ready(function(){
var extensions = {
'pdf': 'pdf',
'doc': 'word'
};
$('#divComment a').each(function() {
var href = this.href;
var ext = href.split('.').pop().toLowerCase();
if(extensions[ext]) {
$(this).addClass(extensions[ext]);
}
});
});
idea from @Felix Kling post..
jsfiddle
A: Try a switch case on the $('#divComment a').attr('href').
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Xcode: Adding transition animation on UITabBar Can we add transition animation on UITabBar when clicking on tab bar item?
A: The similar kind of problem has been solved here:
http://haveacafe.wordpress.com/2009/04/06/animated-transition-between-tabbars-view-on-iphone/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery AJAX response find div returns Null I have a table that gets sorted by a certain column when the user selects an option from the drop-down. It is a self-referencing PHP script that contains an IF clause for a GET request.
Since it is a self-referencing file, it returns the entire HTML content of the page, so I need a single div returned. The entire response returns fine, but jQuery find always returns null for any div.
Also, the response data always returns "string" even though I have specified html. I'm not sure if this is relevant or not.
This is what I have so far:
function sortTable()
{
var by=encodeURIComponent(document.getElementById("sort").value)
$.ajax({
type: "GET",
url: '/tasks?sort=',
data: by,
dataType: "html",
success: function(data) {
var tmp = data;
var test = $(tmp).find("sort-table");
alert(test.html());
},
});
A: I think you are missing something
var test = $(tmp).find(".sort-table");
or
var test = $(tmp).find("#sort-table");
A: var test = $(tmp).find("div.sort-table");
it will find divs with class sort-table
A: That was work for me
$(data).filter('div.test');
here is link Use Jquery Selectors on $.AJAX loaded HTML?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: wired scala type design my env is :
Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
watch this example first:
scala> var a = 1
a: Int = 1
scala> var c = 'c
c: Symbol = 'c
scala> var d = 1.1
d: Double = 1.1
scala> var b = "123"
b: java.lang.String = 123
scala> val e:String = "234"
e: String = 234
so, you can see the other literal except string, the default type are Scala Types(Int Double Symbol.
but the string literal is Java type.(java.lang.String
and when you define a value with the scala type String, the String literal will be the type Scala String.
why the string literal's default type isn't Scala String?
Second:
when you must call scala method from java.
and your scala method with Parameter like this:
def hello(i:Int) = {
println(i)
}
on java side . if you call like this.
object.hello(null)
it will fail by type mismatch.
the java.lang.Integer can be null. but the scala Int can't be null.
null in scala is the subtype of AnyRef. not AnyVal..
i found that AnyRef and AnyVal take me to the java1.4 world, which dose not have autobox.. .
A: Answer to your first question:
scala.String is simply a type synonym defined in Prelude Predef for good old java.lang.String. (Unlike scala.Int, scala.Float etc. which are distinct types from java.lang.Integer, java.lang.Float etc.)
This might help: (Observe the types.)
scala> def f(s: String) = s * 2
f: (s: String)String
scala> f("hello")
res7: String = hellohello
scala> def f(s: String): java.lang.String = s * 2
f: (s: String)java.lang.String
scala> f("hello")
res8: java.lang.String = hellohello
scala> type Str = String
defined type alias Str
scala> def f(s: String): Str = s * 2
f: (s: String)Str
scala> f("hello")
res9: Str = hellohello
A: missingfaktor has answered the first question you have.
For the second part of your question: Scala.Int is different to java.lang.Integer, it is really an alias for a java int, and has pretty much the same behaviour:
scala> def print(i: Int) = println(i + " class=" + i.getClass.getName)
print: (i: Int)Unit
scala> print(43)
43 class=int
So scala treats scala.Int as int where possible. Note that autoboxing/unboxing occurs as normal.
scala> print(new java.lang.Integer(666))
666 class=int
So actually, it does not make sense to pass a null to a method which is expecting an int. This is a compilation error in Java as well.
private void setInt(int i) {}
setInt(null); // compilation error
If you force a null java.lang.Integer to be passed where an int is expected, then you get a NullPointerException. This is exactly the same behaviour as Java.
scala> val f: java.lang.Integer = null
f: java.lang.Integer = null
scala> print(f)
java.lang.NullPointerException
....
If you want to create a scala method which takes a nullable object, declare it to take java.lang.Integer. The autoboxing/unboxing behaviour will be exactly the same as for Java.
scala> def print(i: java.lang.Integer) = println(i + " class=" + i.getClass.getName)
print: (i: java.lang.Integer)Unit
scala> print(43)
43 class=java.lang.Integer
scala> print(new java.lang.Integer(666))
666 class=java.lang.Integer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Intent.FLAG_ACTIVITY_CLEAR_TOP causes activity to pop-up even when application is on background? I'm using Android 2.2. I have an application which logouts (causing the application to return to the login page) after a certain period of inactivity. I am using Intent.FLAG_ACTIVITY_CLEAR_TOP for my Intent. However, I notice that when my application is on background and is inactive for a certain period of time, the login page suddenly pops-up and my application goes to foreground. I am expecting that the login page will remain to background. This does not happen when I am not using any flag for my intent. If I'm not using any flag for my Intent, the login page is quietly started on the background. But without using Intent.FLAG_ACTIVITY_CLEAR_TOP, I won't be able to clear my history stack.
Why is this happening? How can I launch an activity on background quietly?
Below is a snippet of my code:
@Override //Inside a class extending AsyncTask
protected void onPostExecute(String result)
{
((GlobalApplication)getApplicationContext()).setIsLogin(false); //user is not logged in anymore
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Below is a snippet the code I made from Lars' suggestion:
@Override //Inside a class extending AsyncTask
protected void onPostExecute(String result)
{
((GlobalApplication)getApplicationContext()).setIsLogin(false); //user is not logged in anymore
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(((GlobalApplication)getApplicationContext()).isOnBackground())
((GlobalApplication)getApplicationContext()).setPendingIntent(intent);
else
startActivity(intent);
}
@Override //overrides android.app.Activity. inside the current Activity
protected void onResume()
{
super.onResume();
Intent pendingIntent = ((GlobalApplication)getApplicationContext()).getPendingIntent();
if(pendingIntent != null)
startActivity(pendingIntent);
}
A: Have you tried checking if you are still logged in in the onResume part of your activities instead of calling your LoginActivity when a timer goes off (which is what I'm assuming you are doing)?
Edit: For clarification, you are logging the user out after a predefined period of time (or when an event occurs). At this point you start an AsyncTask which creates an intent for your loginActivity, adds a flag to it and starts it. And your problem is that you don't want the loginActivity to come to the foreground unless the user has the application open. Is that accurate?
Because if so I would recommend using the onResume methods like I mentioned above. These are called whenever an activity comes (back) to the foreground. For showing the login screen even when the user doesn't change activities you could try sending a broadcast and listening for it in your activities.
EDIT: Code snippet from my comment (Now correctly formatted):
@Override
protected void onResume() {
super.onResume();
if (!getLoggedIn())
{
startActivity(new Intent(this, LoginActivity.class));
finish();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Interactive visualization of a graph in python I have a program written in python using the module networkx to create a dynamic graph. It is a planer graph where the vertices remain constant but the edges change. Now I'm looking for a library that allows me to do two things, in a fast and quick manner preferably:
*
*Drawing the vertices as the lattice points inside a rectangle, i.e.
*Being able to select edges and vertices to change their color, position, weights, etc. as shown in the picture.
Thanks
A: For modest graph sizes, any good python graphics library should provide sufficient primitives to address this issue. For example, either Pyglet or PyGame would be suitable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: From a list of li, how do I tell which one is active using jquery? From a list of li, how do I tell which one is active with a highlight class using jquery?
For example, I have the ul list
<ul>
<li> 11111111 </li>
<li> 22222222 </li>
<li> 33333333 </li>
<li> 44444444 </li> <---- highlighed white/black by (.highlight) class
<li> 55555555 </li>
</ul>
A: $('li:contains(44444444)').addClass('highlight')
A: $("li.highlight")
will select the active element
A: the selector would be:
$('li.highlight')
or if you loop through the LIs and want to check if it's active you can use .is()
$('li').each(function(){
if($(this).is('.highlight')){
}
});
A: you could do
$('li').each(function(){
if($(this).hasClass('highlight')){
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 404 error handling with mako template Trying to display template rendered by mako on 404 errors, but it still displays standart error page with cherrypy footer and additional message: |In addition, the custom error page failed: TypeError: render_body() takes exactly 1 argument (3 given)"
The code:
def error_page_404(status, message, traceback, version):
tmpl = tpl.get_template("404.mako")
return tmpl.render(status, message)
cherrypy.config.update({'error_page.404': error_page_404})
Need help! How to display completely custom error pages with my layout(mako template)?
Full code:
import sys
sys.stdout = sys.stderr
import os, atexit
import threading
import cherrypy
from mako.template import Template
from mako.lookup import TemplateLookup
cherrypy.config.update({'environment': 'embedded'})
if cherrypy.engine.state == 0:
cherrypy.engine.start(blocking=False)
atexit.register(cherrypy.engine.stop)
localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)
path = os.path.join(absDir,'files')
templ_path = os.path.join(absDir,'html')
tpl = TemplateLookup(directories=[templ_path], input_encoding='utf-8', output_encoding='utf-8',encoding_errors='replace')
def error_page_404(status, message, traceback, version):
tmpl = tpl.get_template("404.mako")
return tmpl.render(status, message)
cherrypy.config.update({'error_page.404': error_page_404})
class Root:
def index(self):
tmpl = tpl.get_template("index.mako")
return tmpl.render(text = 'Some text',url = cherrypy.url())
index.exposed = True
_application = cherrypy.Application(Root(), None)
import posixpath
def application(environ, start_response):
environ['SCRIPT_NAME'] = posixpath.dirname(environ['SCRIPT_NAME'])
if environ['SCRIPT_NAME'] == '/':
environ['SCRIPT_NAME'] = ''
return _application(environ, start_response)
A: You are most likely raising an error with in your 404 handler and I guess you not setting the request.error_response of the cherrypy config like this, and about the error of response_body check this, you are probably using wrong the body of the template.
Edit from the comments:
def error_page_404(status, message, traceback, version):
tmpl = tpl.get_template("404.mako")
return tmpl.render(stat=status, msg=message)
cherrypy.config.update({'error_page.404': error_page_404})
The render method, only specify the function behavior with the keyword arguments, you could also be a little more flexible and specify the same function like this:
def error_page_404(status, message, traceback, version):
tmpl = tpl.get_template("404.mako")
args = {'stat': status,
'msg': message}
return tmpl.render(**args)
It will make it easier to expand your arguments for the template, I usually use **args
for my render calls.
But the basically the problem was (as you pointed out), that you where calling render with non-keyword arguments, and the expected input is just keyword arguments, for the template.
A: So, I figured out :) Thanks to cyraxjoe! Here is the code:
import sys
sys.stdout = sys.stderr
import os, atexit
import threading
import cherrypy
from mako.template import Template
from mako.lookup import TemplateLookup
cherrypy.config.update({'environment': 'embedded'})
if cherrypy.engine.state == 0:
cherrypy.engine.start(blocking=False)
atexit.register(cherrypy.engine.stop)
localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)
path = os.path.join(absDir,'files')
templ_path = os.path.join(absDir,'html')
tpl = TemplateLookup(directories=[templ_path], input_encoding='utf-8', output_encoding='utf-8',encoding_errors='replace')
def error_page_404(status, message, traceback, version):
tmpl = tpl.get_template("404.mako")
return tmpl.render(status, message)
cherrypy.config.update({'error_page.404': error_page_404})
class Root:
_cp_config = {'error_page.404': error_page_404}
def index(self):
tmpl = tpl.get_template("index.mako")
return tmpl.render(text = 'Some text',url = cherrypy.url())
index.exposed = True
_application = cherrypy.Application(Root(), None)
import posixpath
def application(environ, start_response):
environ['SCRIPT_NAME'] = posixpath.dirname(environ['SCRIPT_NAME'])
if environ['SCRIPT_NAME'] == '/':
environ['SCRIPT_NAME'] = ''
return _application(environ, start_response)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Multiple DAO's vs One DAO with configuration file I'm currently in the process of creating a data access layer for an application. This application will initially connect to an Oracle database but will later also connect to a DB2 database.
For connecting to the database I will use JDBC. At this time I'm considering my options. As I see it I have two (primary) options.
1) Create a design with support for multiple DAO factories, each instantiating the DAO's specific to their database. Initially, this design will only have one factory. Later it will be extended with a second factory and DAO classes.
2) Create one DAO factory which instantiates multiple DAO's for the different models. This DAO factory builds the DAO's based on a configuration file, which contains the JDBC driver path and connection url.
I'm tempted to choose the second option, which seems to remove quite some code duplication in the DAO's. Could anyone give the pros and cons of both approaches?
Why would you choose for multiple DAO factories (abstract factory pattern) when you don't really need it when using JDBC?
A: I believe Spring or Guice would be the best and cleanest option for you, where you'd want to pick the appropriate DAO implementation and inject it in the DAO consumer layer. Spring will also enable you to use Spring-JDBC which takes care of most of the boilerplate code making your DAO Impls easy to manage and code. You can also use ORMs with Spring.
A: Taking into account that you can't use Spring (even though it would save you from a lot of coding), I would say that 2nd variant is more appropriate to you, because you are going to implement dependecy management yourself and 1 dependency (single DAO factory) is always easier than 2.
Though, if you expect that amount of places were DAOs for both databases are used together is not big, then separating them into 2 factories will have a better structural meaning and is more clean. But if you expect, that pretty much every class that uses DAOs will need both worlds (Oracle + DB2), then again stick to the 2nd variant.
In any case, try to consider again about dependecy injection framework usage, because that what you are going to implement yourself anyway with all your factories.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to authenticate iOS/iPhone users with remote web application and re-use authentication ticket in future requests to the same web application? I am building an iOS application and I need to be able to make authenticated requests to a Rails 3 application for various bits of data. The Rails 3 application is using omniauth and URLs like https://myapp.com/auth/facebook to, for example, authenticate users via facebook ... and once authenticated, stores the authentication in a secured cookie named "auth.""
What I want to know is how to authenticate my users from the iOS/iPhone application, persist the authentication token and send it along with future requests to the Rails application?
Using ASIHTTPRequest I'm thinking of doing something like this:
*
*Open a UIWebview, loading with a URL from my web application specific for the provider they want to authenticate with (e.g. myapp.com/auth/facebook for facebook or myapp.com/auth/yahoo for yahoo, etc....).
*On success, somehow parse out and store the authentication cookie in the iOS application without displaying the webpage folks usually see when authenticating via the website ... and instead closing the UIWebView and navigating back to another UIVewController in the iOS application.
*Somehow include the persisted authentication token with future web requests to the Rails application.
*I also want to allow users to allow the iOS application to store this information locally so they don't have to re-login to the remote application if they choose too.
Is this approach appropriate? Is there a better way? And of course, how to actually implement the above?
Thanks - wg
A: Using OAuth is pretty easy (well, easy is not the word...), but I made an iOS application and a java server that use OAUth as identity schema and, following the full cycle, finally I adquired a token that identifies this user and (as only can be accessed using signed requests) can be safely stored in the phone (I use just the standardUserDefaults to store it). Only your application (using the secret) can sign the requests.
I don't know if this serves to you...
Ah! After the identification via web, the browser redirect a special url (registered for my application) and the url opens my application including the token in its parameters, so it is easy to retrieve the token after the identification phase in handleOpenURL.
A: *
*Once the UIWebview has authenticated with said service, get it to load another URL (for example: through a javascript on the page which said service returns to after authentication).
*Capture this request using a UIWebViewDelegate object which implements the following protocol method:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
*From here you have the NSURLRequest object. You can extract the headers of the request to NSDictionary which will contain the authentication cookie details, token, etc. using the following method of NSURLRequest
- (NSDictionary *)allHTTPHeaderFields
A: For my app this is what I'm doing.
My app is using devise with omniauth for login and user stuff.
Devise by itself can generate a unique token, with the flag token_authenticatable.
So on my login request, if the login is successful I reply with a JSON representation of my user and my user token. I save all that on the phone memory.
Then on every request I add the param auth_token=MY_USER_TOKEN.
And that's about it.
I had just a problem with the Facebook auth, because I'm using the Ios facebook SDK, so I forward the FB token to my app, verify it, and then just return the same devise auth_token for all following requests.
A: Ok here we go, I dont know the exact setup of your web service and all that, but what you can do is store the authentication token on the device using SQLite or Core Data, I am currently working on a app that requires authentication, and what I do is store the username and password locally on the device in the SQLite db using Core Data to interact with the db, then whenever I make an API calls I use the stored username and password for the authentication on the server side using gets, but I believe it is saver using post, as long as the web server has great security I don't believe there is any security risks. In what I understand about what you are building I would authenticate the user say on first launch and have the user be able to change log in credentials at a later stage, but after authentication I would send back an authentication token to the device and store that in the db and then whenever I need to authenticate with the web service I would send the auth token with a post request to the server. Does this make sense?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Why won't Oracle use my index unless I tell it to? I have an index:
CREATE INDEX BLAH ON EMPLOYEE(SUBSTR(TO_CHAR(EMPSHIRTNO), 1, 4));
and an SQL STATEMENT:
SELECT COUNT(*)
FROM (SELECT COUNT(*)
FROM EMPLOYEE
GROUP BY SUBSTR(TO_CHAR(EMPSHIRTNO), 1, 4)
HAVING COUNT(*) > 100);
but it keeps doing a full table scan instead of using the index unless I add a hint.
EMPSHIRTNO is not the primary key, EMPNO is (which isn't used here).
Complex query
EXPLAIN PLAN FOR SELECT COUNT(*) FROM (SELECT COUNT(*) FROM EMPLOYEE
GROUP BY SUBSTR(TO_CHAR(EMPSHIRTNO), 1, 4)
HAVING COUNT(*) > 100);
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
Plan hash value: 1712471557
----------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
----------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | | 24 (9)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | | | |
| 2 | VIEW | | 497 | | 24 (9)| 00:00:01 |
|* 3 | FILTER | | | | | |
----------------------------------------------------------------------------------
| 4 | HASH GROUP BY | | 497 | 2485 | 24 (9)| 00:00:01 |
| 5 | TABLE ACCESS FULL| EMPLOYEE | 9998 | 49990 | 22 (0)| 00:00:01||
----------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
3 - filter(COUNT(*)>100)
17 rows selected.
ANALYZE INDEX BLAH VALIDATE STRUCTURE;
SELECT BTREE_SPACE, USED_SPACE FROM INDEX_STATS;
BTREE_SPACE USED_SPACE
----------- ----------
176032 150274
Simple query:
EXPLAIN PLAN FOR SELECT * FROM EMPLOYEE;
PLAN_TABLE_OUTPUT
--------------------------------------------------------------------------------
Plan hash value: 2913724801
------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 9998 | 439K| 23 (5)| 00:00:01 |
| 1 | TABLE ACCESS FULL| EMPLOYEE | 9998 | 439K| 23 (5)| 00:00:01 |
------------------------------------------------------------------------------
8 rows selected.
Maybe it is because the NOT NULL constraint is enforced via a CHECK constraint rather than being defined originally in the table creation statement? It will use the index when I do:
SELECT * FROM EMPLOYEE WHERE SUBSTR(TO_CHAR(EMPSHIRTNO), 1, 4) = '1234';
For those suggesting that it needs to read all of the rows anyway (which I don't think it does as it is counting), the index is not used on this either:
SELECT SUBSTR(TO_CHAR(EMPSHIRTNO), 1, 4) FROM EMPLOYEE;
In fact, putting an index on EMPSHIRTNO and performing SELECT EMPSHIRTNO FROM EMPLOYEE; does not use the index either. I should point out that EMPSHIRTNO is not unique, there are duplicates in the table.
A: Because of the nature of your query it needs to scan every row of the table anyway. So oracle is probably deciding that a full table scan is the most efficient way to do this. Because its using a HASH GROUP BY there is no nasty sort at the end like in oracle 7 days.
First get the count per SUBSTR(...) of shirt no. Its thus first part of the query which has to scan the entire table
SELECT COUNT(*)
FROM EMPLOYEE
GROUP BY SUBSTR(TO_CHAR(EMPSHIRTNO), 1, 4)
Next you want to discard the SUBSTR(...) where the count is <= 100. Oracle needs to scan all rows to verify this. Technically you could argue that once it has 101 it doesn't need any more, but I don't think Oracle can work this out, especially as you are asking it what the total numer is in the SELECT COUNT(*) of the subquery.
HAVING COUNT(*) > 100);
So basically to give you the answer you want Oracle needs to scan every row in the table, so an index is no help on filtering. Because its using a hash group by, the index is no help on the grouping either. So to use the index would just slow your query down, which is why Oracle is not using it.
A: I think you may need to build a function-based index on SUBSTR(TO_CHAR(EMPSHIRTNO), 1,4); Functions in your SQL have a tendency to invalidate regular indexes on a column.
A: I believe @Codo is correct. Oracle cannot determine that the expression will always be non-null, and then must assume that some nulls may not
be stored in the index.
(It seems like Oracle should be able to figure out that the expression is not nullable. In general, the chance of any random SUBSTR expression always being
not null is probably very low, maybe Oracle just lumps all SUBSTR expressions together?)
You can make the index usable for your query with one of these work-arounds:
--bitmap index:
create bitmap index blah on employee(substr(to_char(empshirtno), 1, 4));
--multi-column index:
alter table employee add constraint blah primary key (id, empshirtno);
--indexed virtual column:
create table employee(empshirtno varchar2(10) not null
,empshirtno_for_index as (substr(empshirtno,1,4)) not null );
create index blah on employee(empshirtno_for_index);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL for selecting a cluster of records from a huge table with optimum SQL I'm trying to paginate using MS SQL Server 2005 in one of my ASP net applications. To fetch 10 records from the employee table I'm running the following SQL.
;WITH CTE AS (
SELECT EmployeeID,
[Name],
ROW_NUMBER() OVER(ORDER BY EmployeeID ASC) AS RowNo
FROM Employee
) SELECT *
FROM CTE WHERE RowNo BETWEEN 11 AND 20
The problem with this is my employee table is having 100 thousands of records and since I'm running the above query it is taking lot time. I have seen in MySQL that there is a phrase called LIMIT to limit the select record count.
Kindly help me to fetch a particular number of records records without using Common Table Expression and without running a query like the above one. I would like to know if there is a better way than this.
Thanks in advance for your time and help.
A: I tried your query on a table with 150.000 rows, I tried with on a column with an index and one without an index. Both was less than 1 second execution time. I imagine you have a different problem.
Since I imagine your problem lies elsewhere, I surgest you try this:
;WITH CTE AS (
SELECT EmployeeID,
[Name],
ROW_NUMBER() OVER(ORDER BY EmployeeID ASC) AS RowNo
FROM Employee WITH (NOLOCK)
) SELECT *
FROM CTE WHERE RowNo BETWEEN 11 AND 20
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unit Test Friendly way of using membership details inside the controller Here is a piece of code from one of the controller inside my ASP.NET MVC 3 App :
_destinationdetailRepository.Add(new DestinationDetail {
DestinationID = destination.DestinationID,
CreatedOn = DateTime.Now,
CreatedBy = User.Identity.Name
});
What is important here is the CreatedBy property value which is User.Identity.Name. It works great and I use this on another parts of my app as well. But, I guess this is not a unit test firendly way of doing things.
So, what is the way of using Membership data inside the controller so that I will be happy when I am unit testing my app.
A:
But, I guess this is not a unit test firendly way of doing things.
No, it's unit test friendly and it is correct code. The User property is an IPrincipal interface that can be mocked in an unit test.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you access the ui.item children in jQuery? I'm trying to access the following rectangularized item using the jQuery sortable plugin:
Currently my jQuery code looks like this (Note the question is about the even in the receive section):
$( "#listA, #listB" ).sortable({
connectWith: ".connected_sortable",
delay: 100,
receive: function(event, ui) {
alert(ui.item.text());
}
}).disableSelection();
HTML:
<ul id="listA" class="connected_sortable ui-sortable">
<li>
<div id="4">
Test Text
</div>
</li>
</ul>
How would I access that id using the alert? I tried alert(ui.item.context.childNodes.id) and the alert returns an 'undefined'.
edits: added HTML and clarified the question abit.
Thank you!
A: Try this way:
alert(ui.item.context.childNodes[0].id)
A: You can access id of an element with .attr
var id = $("yourSelector").attr("id");
A: try alert('ui.item >li').attr('id')
A: Here the solution: http://jsfiddle.net/a8bNn/1/
*
*Using "update" instead of "receive"
*use "ui.item.context.childNodes[1].id" to grab the id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can i interact directaly with data using UIB-Unified Interbase (http://www.progdigy.com/?page_id=5)? in my current application i can set dataset of datasource to table component (IBdac component from Devart.com)which enable me editing the data in the dbgrid directly .
uibdataset is read only which that is means it is not possible to edit any things except through update sql.
how can i achieve this properties with UIB components?
i'm using delphi xe, firebird2.5.
A: I am not familier with UIB, but did you try to use the TUIBQuery component? In my application I always use IBQuery to modify data.
Actually I use:
TIBQuery -> TDataSetProvider -> TClientDataSet -> TDataSource
If you are using a TDataSetProvider you have to invoke TClientDataSet.ApplyUpdates to post the changes to underlying database.
A: you have to put a TUIBDatabase, TUIBTransaction then a TUIBDataSet and it should be connected to your TUIBDatabase and TUIBTransaction at the end put a TDataSource connected to the TUIBDatabase:
TUIBDatabase -> TUIBDatabase -> TDataSource
e.g
object UIBTransaction1: TUIBTransaction
DataBase = UIBDataBase1
end
object UIBDataBase1: TUIBDataBase
Params.Strings = (
'sql_dialect=3'
'lc_ctype=NONE'
'user_name=SYSDBA'
'password=masterkey'
'sql_role_name=')
DatabaseName =
'D:\FIREBIRDTEST.FDB'
UserName = 'SYSDBA'
PassWord = 'masterkey'
LibraryName = 'fbclient.dll'
end
object UIBDataSet1: TUIBDataSet
Transaction = UIBTransaction1
Database = UIBDataBase1
SQL.Strings = ('select * from CUSTOMER;')
end
object DataSource1: TDataSource
DataSet = UIBDataSet1
end
you can also use the option mentioned by markus_ja however don't use TUIBQuery but use TUIBDatabase instead
TUIBDatabase -> TUIBDatabase -> TDataSetProvider -> TClientDataSet -> TDataSource
simply paste this code on your form:
object UIBTransaction1: TUIBTransaction
DataBase = UIBDataBase1
Left = 120
Top = 112
end
object UIBDataBase1: TUIBDataBase
Params.Strings = (
'sql_dialect=3'
'lc_ctype=NONE'
'user_name=SYSDBA'
'password=masterkey'
'sql_role_name=')
DatabaseName =
'D:\FIREBIRDTEST.FDB'
UserName = 'SYSDBA'
PassWord = 'masterkey'
LibraryName = 'fbclient.dll'
end
object UIBDataSet1: TUIBDataSet
Transaction = UIBTransaction1
Database = UIBDataBase1
SQL.Strings = ('select * from CUSTOMER;')
end
object DataSetProvider1: TDataSetProvider
DataSet = UIBDataSet1
end
object ClientDataSet1: TClientDataSet
ProviderName = 'DataSetProvider1'
end
object DataSource1: TDataSource
DataSet = ClientDataSet1
end
i hope that helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to construct Dynamic Dependent Combo series in jqGrid? I have two combos in my jqGrid. One has the listing of Countries and the other has the listing of states of that country. I want a system where when I change the Countries combo the corresponding value of that Country's State will construct the second combo.
Is a detailed example available?
A: With thanks for Oleg and to help others who are searching the same solution, the solution is as follows.
Look at the demo from this answer, or at the another demo from another answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Custom Object/Class in XCode 4 Interface builder Im using Xcode 4. In interface builder of my project, I pulled a custom Object (gold cube) from library. I named its class as MyController and did the same for its label. I saved these settings then.
But I'm not able to write this class to the project's class files. I mean I cannot generate class file from this custom object I pulled from the objects library. I wanted it to inherit from NSObject alone and I want to tie up some outlets.
How do I do this in Xcode 4? Please help. The help documentation regarding this topic is not good.
A: The cubes you see in Interface builder for objects are not there to generate code, they are there to represent objects.
You need to create the class normally and then configure the block to be an object of this class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue in serializing a vector of deques using Boost How do I serialize a vector of deques using Boost Serialization library.
Currently, I have the following code for this purpose:
#include <boost/serialization/deque.hpp> //in includes
Item1(6128, std::deque<float> ()), //constructor initializations
Item2(6128, std::deque<float> ()),
Item3(6128,std::deque<int> ()),
Item4(6128,std::deque<int> ()),
private:
friend class boost::serialization::access;
template <typename Archive>
void
serialize(Archive &ar,
const unsigned int /*file_version*/)
{
for (unsigned i = 0; i < Item1.size(); ++i)
{ar & Item1[i];}
for (unsigned i = 0; i < Item2.size(); ++i)
{ar & Item2[i];}
for (unsigned i = 0; i < Item3.size(); ++i)
{ar & Item3[i];}
for (unsigned i = 0; i < Item4.size(); ++i)
{ar & Item4[i];}
}
std::vector< std::deque<float> > Item1, Item2;
std::vector< std::deque<int> > Item3, Item4;
This code compiles and runs fine. However, the values I store are different from the ones I loaded while serializing. Am I doing something wrong? Is this the right method to serialize a vector of deques?
Your feedback is appreciated. Thanks!
A: You are not serializing the size of Item1...Item4
I suggest you use STL container serialization directly:
*
*http://www.boost.org/doc/libs/1_47_0/libs/serialization/doc/tutorial.html#stl
*http://www.boost.org/doc/libs/1_47_0/libs/serialization/doc/serialization.html#models
e.g.
ar & Item1;
ar & Item2;
ar & Item3;
ar & Item4;
Alternatively you could split into Load/Save methods and save / load the container size explicitely.
template<class Archive>
void save(Archive & ar, const unsigned int version) const
{
ar & Item1.size();
for (unsigned i = 0; i < Item1.size(); ++i)
{ar & Item1[i];}
ar & Item2.size();
for (unsigned i = 0; i < Item2.size(); ++i)
{ar & Item2[i];}
// etc...
}
template<class Archive>
void load(Archive & ar, const unsigned int version)
{
size_t size;
ar & size;
Item1.resize(size);
for (unsigned i = 0; i < Item1.size(); ++i)
{ar & Item1[i];}
ar & size;
Item2.resize(size);
for (unsigned i = 0; i < Item2.size(); ++i)
{ar & Item2[i];}
// etc...
}
BOOST_SERIALIZATION_SPLIT_MEMBER()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Free & private version control hosting website Any good Git or Subversion for non-public/non-open project. I have narrowed it down to these three. Now which of the 3 would you recommend. I am looking for secure, with a good up-time, private, support for 3-4 users and 1 repository and a space of about >200-300 MB
*
*assembla - http://offers.assembla.com/free-subversion-hosting/
*unfuddle - http://unfuddle.com/about/tour/plans
*xp-dev - http://xp-dev.com/pricing
I know GitHub is awesome for but it's free for public/open projects only and Google Code is only for open project. Am i right over here and what about SoundForge is it also for public projects.
A: I use assembla.
It's free and it's working great :) never had any problems with it.
A: Perhaps you will approach Mercurial and bitbucket.org? This solution very simple and has a private repo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How place background-image to the top of the div with padding In Html I've this code
<div class="page">
<div id="header">
...
</div>
</div>
And here is my css
.page {
width: 1028px;
background-color:#103250;
margin-left: auto;
margin-right: auto;
}
#header
{
background:url('/Img/SubpageBox1.png') no-repeat top;
height:150px;
padding-top:50px;
}
But now my background-image is placed out of div... On the top of the page... How can I place it on the top of the header?
A: You can specify the position of the background image:
background:url('/Img/SubpageBox1.png') no-repeat center 50px;
or using background-position css property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to put text in border I'm trying to insert some text in border but don't know how to do.
How can i put some text in middle of border.
Below is the screen-shot it should look like
A: use legend inside fieldset
The HTML Legend Field Element (<legend>) represents a caption for the
content of its parent <fieldset>.
A: Try HTML legend tag.
HTML legend
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: What about object instances reuse? I am wondering if there is any convention in Java (through Javadoc or implicit convention) to indicate that a given same class instance can be reuse in several contexts ?
I am asking that because in the SWT layout context I don't know if I am allowed to reuse the same GridLayout object for several Composite objects. I guess the answer is Yes after checking the source code (I can't see any state fields) but the Javadoc doesn't explicitly state it. Maybe the implicit convention is that "sharing" is allowed if not explicitly forbidden ?
A:
Maybe the implicit convention is that "sharing" is allowed if not explicitly forbidden ?
There is no such convention.
Instead, you should take the prudent approach; i.e. you should only reuse instances if the Javadocs explicitly states that you can do this safely.
Reading the code and observing that it is safe to share with the current implementation is no guarantee that it will be safe to share in future releases, or in earlier releases. It is a good idea to only rely on behavior that is documented.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP DATE strtotime date "0001-01-01" Hello guys is there a way to convert the date 0001-01-1 to a time format? I am trying to to use the php function strtotime("0001-01-01"), but it returns false.
My goal is to count the days from the date: 0001-01-01 to: 2011-01-01.
A: Use DateTime class. strtotime returns a timestamp which in your case will be out of int bounds.
A: As Ignacio Vazquez-Abrams has commented, dates before the adoption of the Gregorian calendar are going to be problematic:
*
*The Gregorian calendar was adopted at different times in different countries (anywhere from 1582 to 1929). According to Wikipedia, a few locales still use the Julian calendar.
*Days needed to be "removed" to switch to the Gregorian calendar, and the exact "missing" dates differ between countries (e.g. the missing days in September 1752). Some countries tried to do a gradual change (by removing February 29 for a few years); Sweden switched back to the Julian calendar to "avoid confusion", resulting in a year with February 30.
*Years were not always counted from January 1 (which has left its legacy in things like the UK tax year).
Michael Portwood's post The Amazing Disappearing Days gives a reasonable summary.
In short, you have to know precisely what you mean by "1 Jan 1 AD" for your question to make any sense. Astronomers use the Julian Day Number (not entirely related to the Julian calendar) to avoid this problem.
EDIT: You even have to be careful when things claim to use the "proleptic Gregorian calendar". This is supposed to be the Gregorian calendar extended backwards, but on Symbian, years before 1600 observe the old leap year rule (i.e. Symbian's "year 1200" is not a leap year, where in the proleptic Gregorian calendar it is).
A: I am afraid it wont work since strtotime changes string to timestamp, which have lowest value of 0, and its at 1970-01-01.. cant go lower than that..
date('Y-m-d', 0);
A: From the manual:
If the number of the year is specified in a two digit format, the values between 00-69 are mapped to 2000-2069 and 70-99 to 1970-1999. See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07).
You may want to give 'DateTime::createFromFormat' a shot instead this.
Also note that you cannot go below 1901 on a 32-bit version of PHP.
A: You cannot do that this way. Here is one option how to do this.
$date1= "2011-01-01";
$date2 = "2011-10-03";
//calculate days between dates
$time_difference = strtotime($date2) - strtotime($date1);
now you got time difference in seconds from wich you can get days, hours, minutes, seconds.
A: You can't use the function strtotime because this function return a timestamp and the time stamp start from 1970 so i advise you to searsh for a different way
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Postfix decrement I have a very simple question.
in this piece of code when will the value of n be decremented?
#include<stdio.h>
void func(int n)
{
//text//
}
int main()
{
int n=10;
func(n--);
return 0;
}
now when func() is called is the value of n decremented when control comes back to main() or is it decremented at that time only but n=10 is passed to func().
Please explain, also if there is a way to check the value then that will be really helpful.
A: When a function is called, all it's arguments are evaluated (in an implementation-defined order) before the function can start - it's a sequence point. So, after all the arguments are evaluated the function can finally begin.
What this means is that n-- is evaluated and yields the value 10 for the function. At the moment the function has begun n is already 9 but the n parameter of the function hold the value 10.
A simple way to check this:
void func(int n, int *np)
{
printf("Outside: %d\n", *np);
}
int main(void)
{
/* ... */
func(n--, &n);
}
A: The decrement will happen before the call to func, however func will be passed a copy of the old value still.
Consider the following modification to your program which illustrates this:
#include <stdio.h>
static int n;
void func(int m)
{
printf("%d,%d\n", n, m);
}
int main()
{
n = 10;
func(n--);
return 0;
}
Prints:
9,10
A: I think your question is better expressed by this code:
#include <stdio.h>
static int global_n;
void func(int n)
{
printf("n = %d, global_n = %d\n",
n, global_n);
}
int main()
{
global_n = 10;
func(global_n--);
return 0;
}
This demonstrates that the function is passed the old value, but the decrement happens before the call.
n = 10, global_n = 9
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In dealloc method set any delegate to nil is needed or not needed I have created tableview in my view by programmatic like below
table = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, 320, 370) style:UITableViewCellStyleDefault];
table.delegate = self;
table.dataSource = self;
table.separatorStyle = UITableViewCellSeparatorStyleNone;
[self.view addSubview:table];
in dealloc method i write like below
table.delegate = nil;
table.dataSource = nil;
[table release];
table=nil;
this the better way or below one is better
[table release];
table=nil;
I want to know if i dont reset delegate and dataSource what will happen
Thanq
A: If you are deallocating an object that acts as the delegate to other objects, you need to make sure that you have set their delegates to nil, before you call [super dealloc] (assuming the normal pattern that objects do not retain their delegates). This is because when [super dealloc] has returned, this object is no longer a valid object and the objects it is a delegate to effectively have dangling references, if they have not been set to nil.
In this particular case, you would probably get away without doing it because your object's dealloc probably won't get called except when the UI is being dismantled and the table view no longer needs to use its delegate or data source, but don't bet on it.
A: From Setting delegate to nil in dealloc:
It's a defensive programming move. It's clearing out the reference to the delegate object incase something else in your object tries to access the delegate after you've told it that you're done with it. As part of your dealloc you might have a method or do something that triggers a KVO notification that makes a call to the delegate. So setting the delegate's reference to nil prevents that from happening. If it did happen you could end up with some oddball crashes that are fun to reproduce and fix.
A: To add to the answers above, you do not need
table = nil;
in your dealloc. It won't hurt, but it is not necessary to nil out your ivars. Your view is being dealloc'ed and therefore your ivars will no longer be accessible. You are probably confusing that with:
self.table = nil;
which can function as an alternative way to release if you are accessing the ivar via a property.
Of course if you have ARC turned on, then you don't need the release at all.
And to answer your actual question, if you don't nil out the table's delegate and datasource on the dealloc of the view....nothing will happen. They are set to the view, which is in the process of being released. In this case, you will have no issues not doing it. In theory it's good form.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why this jquery code is not working on blackberry? I am developing phonegap app using jquerymobile.
but in blackberry 9780 it does not show me alert, my code is
document.addEventListener('deviceready', run, false);
function run(){
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json){
alert(json.followers_count); // not displaying in blackberry
});
}
My head part is :
<script src="phonegap.js">
</script>
<script src="jquery1.6.2.js">
</script>
<script src="jquery.mobile1.0b3.js">
It works fine in other mobiles like Android,iphone,ipad and also working on my Mozzila browser 8.0 but not working on blackberry OS 6.
Please help me.
Thanks
A: 1st make sure that run() is getting executed, if not, then try attachEvent
element.attachEvent('ondeviceready',run)
Edit
refer
JQuery JSONP cross domain call not doing anything
and
jQuery, JSON and Apache problem
A: A few things:
*
*there is a new version of jqm, the v1.0 RC1, try to work with this one.
*Use the Ripple Emulator from RIM to test more quiccly the app, is a Chrome broser plugin.
And the most important:
deviceready needs:
*
*in your body make this: <body onLoad='initSO()'>
then in the header, after loading: json2.js, phongap, jquery, jquerymobile... put this
function initSO() {
console.log('initSO()');
document.addEventListener("deviceready", onDeviceReadySO, true);
}
function onDeviceReadySO() {
console.log('hello word :D ');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jquery UI: adjust width of div by slider change I use jquery UI slider and want onchange to adjust a width of a div:
$('#slider').slider({
value: [17],
change: handleSliderChange
});
function handleSliderChange(){
...
}
here the html
<div id="slider"></div>
<div id="vardiv" style="width:300px;height:20px;border:3px solid black"> Testing </div>
i want that by adjusting the slider the width of the div #vardiv should be adjusted proportionally.
I guess we have to calculate a bit and use some functions.
THX 4 your support.
A: the change function would only be called after releasing the mouse,
if you want to have realtime effect you can use the slide function
like this:
$('#slider').slider({
value: 17,
slide: handleSliderChange
});
function handleSliderChange(event, slider){
$('#vardiv').css('width', slider.value + '%');
$("#vardiv").text(slider.value + '%');
}
working example:
http://jsfiddle.net/saelfaer/WXfkK/1/
A: To get this behavior I would write something like this, to get it short.
$("#slider").slider({
change: function (event, ui) {
$("#vardiv").css("width", ui.value + "%");
}
});
This event will executes everytime the slider changes. Inside that event the vardiv element will get a new proportionally width to it´s parent.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Non Blocking Client I´ve a question concerning non blocking Sockets: I understand how to register for example, two socketchannels for write/read events.
But how does such an event look like? If I want to write some data on SocketChannel1 (for example when I press a button) to a server how can I do this?
All examples I´ve found only deal with the registration of the sockets, like this:
http://rox-xmlrpc.sourceforge.net/niotut/#About%20the%20author
Greetings,
Flo
A: I would look at the examples which come with the JDK under the sample directory.
If you use non blocking IO, you should wait until after you have a write op from the socket to perform the write. While you are waiting, you can buffer the data. However, this rarely needed as this is only required when the write buffer of the socket is full (which shouldn't happen very often) and if this is the case for a long period fo time you may deside you have a slow consumer and close the connection instead.
Personally, I wouldn't suggest you use non-blocking NIO directly unless you have a very good understanding of what is going on. Instead I suggest you use a library like Netty which will handle all the edge cases for you. Or you could use blocking NIO which is much simpler (and can be faster for a small number of connections)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: json parsing from an url in phonegap app for an android mobiles Hi friends so far i have been worked only in android native app. First time i am trying to create an app in Phone gap for android devices.
I want to hit an url and there i get a return data in json format. I dont know to write a code in javascript to hit an URL and get back a return data. Please help me by giving a piece of code or any tutorial to hit an url and get the return data. From that returned data i need to do json parsing, pls guide me in json parsing in javascript too.
Please help me friends......
A: It depends if you are trying to do a request using GET or POST. You just need to use JSONRequest
If you are trying to just use a simple GET request then your syntax would look something like this:
requestNumber = JSONRequest.get(
"http://yourdomainname.com/request",
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
} else {
processError(exception);
}
}
);
If you are wanting to use POST and you need to send some information here is an example for that:
requestNumber = JSONRequest.post(
"http://yourdomainname.com/request",
{
username: "user",
action: "actionname"
},
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
} else {
processError(exception);
}
}
);
A: There is a tutorial of this on the phonegap wiki:
http://wiki.phonegap.com/w/page/36868306/UI%20Development%20using%20jQueryMobile
It just what you are looking for :)
Good Luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to show all content of an array in Java this is my first post on this web site, so please be patience :)
I'm studying java and I'm trying to create a small program that storage in two arrays the name of player and the attendance of them. I'm using JOptionPane for the 'user interface'. I would like, when the user ask for, to show the names and the respective attendance of them.
Here it's my code(it's not completed):
import javax.swing.*;
import java.text.*;
public class Pelada{
public static void main(String []args){
String[] players = new String[10];
int[] attendance = new int[10];
int x = 0, z = 0, control = 0, posPlayer = 0;
String test;
while(control != 4){
control = Integer.parseInt(JOptionPane.showInputDialog(null,"1- Add new players \n 2- List \n 3- Increment attendance \n 4- Delete player \n 4- Exit", "Choose an option below", JOptionPane.INFORMATION_MESSAGE));
if(control == 1){
players[x] = JOptionPane.showInputDialog(null, "New player: ", "Add New Player", JOptionPane.INFORMATION_MESSAGE);
attendance[x] = Integer.parseInt(JOptionPane.showInputDialog(null, "How many matchs have he played so far? ", "Attendance", JOptionPane.INFORMATION_MESSAGE));
x++;
}
else if(control == 2)
for (int i=0; i < players.length; i++){
JOptionPane.showMessageDialog(null, "Attendance = " + attendance[i], "N: " + i + "- " + players[i], JOptionPane.WARNING_MESSAGE);
}
else if(control == 3){
posPlayer = Integer.parseInt(JOptionPane.showInputDialog(null, "Choose the player id: ", "Player Id", JOptionPane.INFORMATION_MESSAGE));
attendance[posPlayer] = Integer.parseInt(JOptionPane.showInputDialog(null, "Increment ", "Attendance", JOptionPane.INFORMATION_MESSAGE));
}
}
}
}
A: Instead of having two arrays; one for players and one for attendance, make your code more object-oriented by creating a Player class encapsulating the name and attendance of a player:
public class Player {
private final String name;
private final int attendance;
public Player(String name, int attendance) {
this.name = name;
this.attendance = attendance;
}
public String getName() {
return name;
}
public int getAttendance() {
return attendance;
}
}
Then create Player objects and store them in an ArrayList. Don't use an array unless you know how many players are going to be added.
List<Player> players = new ArrayList<Player>();
if (control == 1) {
String name = JOptionPane.showInputDialog(null, "New player: ", "Add New Player",
JOptionPane.INFORMATION_MESSAGE);
int attendance = Integer.parseInt(JOptionPane.showInputDialog(null,
"How many matchs have he played so far? ", "Attendance", JOptionPane.INFORMATION_MESSAGE));
Player player = new Player(name, attendance);
players.add(player);
} else if (control == 2) {
for (int i = 0; i < players.size(); i++) {
Player player = players.get(i);
JOptionPane.showMessageDialog(null, "Attendance = " + player.getAttendance(), "N: " + i + "- " + player.getName(),
JOptionPane.WARNING_MESSAGE);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot implicitly convert type 'int' to 'int[]' I have declared my int[] as follows
int[] iroleID = new int[] { };
My code for getting the values from database and assigning to iroleid is as follows
if (oAuthenticate.getTaskID(out m_oDataSet1, "uspgetTaskID"))
{
for (int iTaskid = 0; iTaskid < m_oDataSet1.Tables[0].Rows.Count; iTaskid++)
{
iroleID = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
strTaskID = m_oDataSet1.Tables[0].Rows[iTaskid]["TaskID"].ToString();
arrTaskID.Add(strTaskID);
}
}
But i am getting an error as mentioned Cannot implicitly convert type 'int' to 'int[]' can any one help me
A: And no surprise here. Look at
iroleID = Convert.ToInt32(...);
Convert.ToIn32 results in an int just like the compiler claims.
Either do something like:
if (oAuthenticate.getTaskID(out m_oDataSet1, "uspgetTaskID"))
{
var iroleID = new int[m_oDataSet1.Tables[0].Rows.Count];
for (int iTaskid = 0; iTaskid < m_oDataSet1.Tables[0].Rows.Count; iTaskid++)
{
iroleID[iTaskid] = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
/* ... */
}
}
or rethink your algorithm.
PS: I can hardly tell you what exactly to do as you don't show what the purpose of iRoleID is.
A: off course!
iroleID = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
iroleID is an int array; Convert.ToInt32() returns an int .
so:
-you must declare an int variable tu store Convert.ToInt32() value
or
-just add Convert.ToInt32() result to iroleID ( iroleID.Add(Convert.ToInt32(...)) )
A: Sure, you can't just assign the int value to the int[] variable. Probably you need to add items to the collection. Change your int[] iroleID = new int[] { }; to List<int> iroleID = new List<int>(); and then change code to:
if (oAuthenticate.getTaskID(out m_oDataSet1, "uspgetTaskID"))
{
for (int iTaskid = 0; iTaskid < m_oDataSet1.Tables[0].Rows.Count; iTaskid++)
{
iroleID.Add(Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString()));
strTaskID = m_oDataSet1.Tables[0].Rows[iTaskid]["TaskID"].ToString();
arrTaskID.Add(strTaskID);
}
}
A: Use indexing for the int array to assign a value, you can't assign an integer directly to an integer array.
iroleID[0] = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
A: iroleID = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
This would convert the RoleID columns value to an integer. You are taking this integer and trying to assign it to an integer array which of course is not possible. What exactly is your idea? If it is to populate a single array with all the IDs you can do the same as you did but assign it to a normal integer and then add that integer to a list or something.
You can also just use plain ADO.NET to retrieve all the values from that column and cast it to an List. That would be better.
A: One problem has already been answered, you must add it to an array giving the position you want
iroleID[iTaskid] = Convert.ToInt32(m_oDataSet1.Tables[0].Rows[iTaskid]["RoleID"].ToString());
the other problem is, that you create an array. You must give the length of the array.
int[] iroleID = new int[m_oDataSet1.Tables[0].Rows.Count];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Migrating from "Linq to SQL" to Entity Framework 4 Problem
In the past, our development team decided to create a new enterprise application and decided to use "Linq to SQL" since the Entity Framework "sucked". (Not my opinion!) They used Visual Studio 2008 and the EF wasn't part of the default setup but required an additional add-in. So the decision was made to use Linq to SQL to access the database. As a result, we now have multiple projects around a datamodule class library containing a DBML and L2SQL entities...
Needed
It is now clear that those developers were wrong. Some moved on to other companies and a few new ones are included in this project. (Including me.) And we would like to use the Entity Framework instead. Preferably version 4 with .NET 4.0... This will allow us more flexibility with our data and we're hoping to include some inheritance in several of the entities, making the code easier to read and nicer to use.
Question: How to...
So, how to migrate from "Linq to SQL" to the Entity Framework 4 without the need to rewrite much of our code?
A: Manually. There is no other way and if you don't have integration test suite for all projects using the data module you should not start with any migration until you write those tests because many linq queries which worked in Linq-to-Sql doesn't work in Linq-to-entities (and not only Linq queries).
Generally that migration is wrong idea. It looks like you want to make a migration just because you want to use another technology. What real business value will be added by this effort? EF and Linq-to-entities offers some additions but it is in many ways worse than Linq-to-sql. There is no need to touch code which works unless you have some real business requirement which will make this necessary. Especially migrating to EFv1 would be really stupid move. You can use .NET 4 with your current code without any problems because Linq-to-Sql is part of .NET 4 as well.
If you ask me the former developers made a good choice when they made selection between EFv1 and Linq-to-Sql.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How does DirectShow manage default filters? When I render a media file with DirectShow (allowing DirectShow to build the graph automatically) I see that DirectShow has a set of default filters it uses. I also observed that installing 3rd party filters may change some default filters (usually 3rd parties set their own filters as default).
I was wondering how the default filters are managed (registry?) and how can I change them? How to cause a certain filter to be used by default?
Thanks,
Aliza
A: There is no such exactly thing as "default" filters in DirectShow. There is a merit system instead: each filter registration is provided with a merit for a filter. When fitler graph renders pins and streams, it starts with trying filters with higher merits.
See more at MSDN:
*
*Intelligent Connect
*Guidelines for Registering Filters
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C#, Finding 2 columns sum together in linq I am bit new to linq .
How do I get the total sum of two columns in my data table.
Let say 2 columns are A& B . I want numeric sum of entire column A and entire column B
(i.e totalSum= sum(A)+sum(B))
IMP :
If I have any field in either of 2 columns a non numeric field (eg AB,WH,DBNULL) . That field should be considered as zero while summing up the values so that it wont throw any exception.
A: For each row or the sum of entire column A and entire column B?
In the first case you could do a select:
var resultWithSum = from row in table
select new{
A = row.A, //optional
B = row.B, //optional
sum = row.A + row.B
}
Otherwise you can do:
result = table.Sum(row => row.A + row.B)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CacheDependency from 2 or more other cache items. (ASP.NET MVC3) I'm a little puzzled over the possible cachedependencies in asp.net, and I'm not sure how to use them.
I would like to add items to the HttpRuntime.Cache in a way, that the elements should invalidate if I change other elements in the cache. The dependencies should be defined by the key.
I want a function like this:
public MyObject LoadFromCache(string itemDescriptor, IEnumerable<string> dependencies)
{
var ret = HttpRuntime.Cache[itemDescriptor] as MyObject;
if (ret == null)
{
ret = LoadFromDataBase(itemDescriptor);
//this is the part I'm not able to figure out. Adding more than one dependency items.
var dep = new CacheDependency();
dependencies.ForEach(o => dep.SomeHowAdd(o));
HttpRuntime.Cache.Add(
itemDescriptor,
ret,
dependencies,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
Caching.CacheItemPriority.Normal,
null
);
}
return ret;
}
Help me out on this one.
A: I didn't know you could do this, but if you look at the CacheDependency constructor here, you can see that the second parameter is an array of cache keys, so that if any of those cached items change, the whole dependency will be changed and your dependent item will be invalidated as well.
So your code would be something like:
String[] cacheKeys = new string[]{"cacheKey1","cacheKey2"};
var dep = New CacheDependency("", cacheKeys);
HttpRuntime.Cache.Add(itemDescriptor, ret, dep ...);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Application Net 1.1 about w3wp.exe memory leak in server I have application web based net 1.1 Every three or four hour I have the restart my iis server because the performance becomes so slow , nothing will function with message memory leak. I traced the problem to the w3wp.exe in windows server 2003, Using the task manager, I can watch as memory is being added to this exe each time I open or refresh my web pages, but I never see memory released. Eventually there will be so much memory consumed, the web server will slow right down to nothing with display error memory leak and other message.
I don't know about solve that, I needed for monitoring memory used w3wp.exe so I can to release memory normal.
This Message
Server Error in '/myserver' Application.
Exception of type System.OutOfMemoryException was thrown.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.OutOfMemoryException: Exception of type System.OutOfMemoryException was thrown.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[OutOfMemoryException: Exception of type System.OutOfMemoryException was thrown.]
Version Information: Microsoft .NET Framework Version:1.1.4322.2443; ASP.NET Version:1.1.4322.2470
A: Unfortunately, it isn't likely to be the w3wp.exe process itself, but the assemblies that it loads to run your application. I would check through your source code and make sure that you are releasing unmanaged resources, closing connections and disposing of IDisposable types.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: django test client gets 404 for all urls I am doing my first experiments with django testing and I am having the problem that I always get the 404 template regardless which url (even /) I am using.
If I throw the very same code into the django shell it's working as expected and always presents me the contents of the requested url.
class SimpleTest(TestCase):
def setUp(self):
self.user = User.objects.create_user('test', 'test', 'test')
self.user.is_staff = True
self.user.save()
self.client = Client()
def test_something(self):
self.assertTrue(self.client.login(username='test', password= 'test'))
self.client.get("/")
The login returns True, but the get() fails. Any hints what I am doing wrong here?
A: Keep in mind that most views use something like get_object_or_404, get_list_or_404, or simply raise Http404 when there's a problem accessing some object or another. You'll need to make sure that your test database is populated with sufficient objects to fulfill all these requirements to make the view not return a 404.
Remember, when running tests, the database is rolled back after each test (using transactions), so each test method must stand on its own or the setUp method must populate the database with any required dependencies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Use MultiThreading to read a file faster I want to read a file of 500 Mb with the help of 2 threads, so that reading the file will be much faster. Someone please give me some code for the task using core java concepts.
A: Instead of trying to multi-thread the reading, you may benefit from multi-threading the processing of the data. This can make it look like using multiple threads to read can help, but in reality, using one thread to read and multiple threads to process is often better.
This often takes longer and is CPU bound. Using multiple threads to read files usually helps when you have multiple files on different physical disks (a rare occasion)
A: Multi-threading is not likely to make the code faster at all. This because reading a file is an I/O-bound process. You will be limited by the speed of the disk rather than your processor.
A: While you might not be able to speed up the read from disc by using multiple threads to read the file you can speed up the process by not doing processing in the same thread as the read.
This will be dependant on the contents of the file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to read a file from WEB-INF/resources folder? I am using Icefaces for webapplication development. I wish to read a file from the resources folder and use it in the sessionbean.
Actually I wish to setup Jasper Reports. I have already setup the libraries in the classpath. The problem I get is while fetching the file from /WEB-INF/resources/ folder. Everytime I run the code from SessionBean, I get the exception:
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: /resources/reports/myreport.jrxml (No such file or directory)
The Code I use is:
public void generateReport() {
try {
JasperCompileManager.compileReportToFile(
"/resources/reports/myreport.jrxml",
"/resources/reports/myreport.jasper");
} catch (Exception e) {
e.printStackTrace();
}
}
The above code is in the SessionBean.
Plz help
A: You are passing relative
URLs to method JasperCompileManager.compileReportToFile.
This method expects filenames as parameters, not URLs.
The solution suggested in other internet forums is:
JasperCompileManager.compileReportToFile(
getServletContext().getRealPath(xmlFile),
getServletContext().getRealPath(compiledFile));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook Share button and comment plugin conflict In my blog I need to implement both a Facebook share button (with a counter) and comment plugin. I just used the code below.
FACEBOOK SHARE
<a
name="fb_share"
type="button_count"
href="http://www.facebook.com/sharer.php">
Share
</a>
<script
src="http://static.ak.fbcdn.net/connect.php/js/FB.Share"
type="text/javascript">
</script>
FACEBOOK COMMENT PLUGIN
<div id="fb-root"></div>
<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/it_IT/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<div class="fb-comments" data-href="<?php the_permalink(); ?>" data-num-posts="2" data-width="524"></div>
In the end, it returns the error
Uncaught TypeError: Object # has no method 'provide'
on line 4, and this error don't show the comment plugin. It shows instead the share button.
Is there any solution to this problem?
A: I had the exact same problem. I ultimately had to switch which FB plugin I was using.
Here's the link to my site where I have the comments and the like button together:
http://www.jhousemedia.com/blog-articles/145/Building-A-Good-Website-For-Your-Business.html
I had to switch out the share button with the Like/Send plugin. Fortunately, they have an option to make it fit a similar form as the share button.
Here's the plugin used
http://developers.facebook.com/docs/reference/plugins/like/
A: I'm not sure, but you can try to comment or delete this line:
js.src = "//connect.facebook.net/it_IT/all.js#xfbml=1";
Maybe share and comment scripts are duplicating code.
A: Solved this by replacing the comments script with just this line in the header
<script src="http://connect.facebook.net/ro_RO/all.js#appId=202676036413585&xfbml=1"></script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Strange #_=_ appear at the end of url after response.redirect ASP.NET Anyone here using Response.Redirect() method, do have you encountered some strange characters attached to the end of the uri on the browser address bar?
The strange characters are hash, underscore, equal sign and underscore (without spaces) such as below... I have no idea what are these all about and when these strange characters appear, the redirection didn't happen properly.
#_=_
Any insights on this please share. Thanks
A: Anything in the location-part of a URL that follows a # refers to an anchor in the page, usually an <a name=""> or <whatever id="">. Some web sites use them (probably with client-side Javascript) to perform magic, but since you are asking this, I get the feeling that's not the case for you. So, there's no real rhyme or reason to that the existence or absence of those characters in and of themselves would cause the redirection to work or not. In fact, they aren't even sent to the server in the HTTP request (at least, Firefox doesn't).
Have you had a look at the HTTP request exchanges when this is happening? Something like Live HTTP Headers, HttpFox or Firebug (look at the Net panel) will help you with this, and might point you to where the errant #_=_ is coming from.
A: Here's my solution based on a couple others out there:
$(function () {
if (window.location.href.indexOf("#_=_") > -1) {
//remove facebook oAuth response bogus hash
if (window.history && window.history.pushState) {
history.pushState('', document.title, window.location.pathname);
} else {
window.location.href = window.location.href.replace(location.hash, "");
}
}
});
https://stackoverflow.com/a/7845639/1467810
https://stackoverflow.com/a/15323220/1467810
https://stackoverflow.com/a/2295951/1467810
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: BBCODE, preg_replace and double quotes preg_replace('/\[quote\=(.*?);(.*?)\](.*?)\[\/quote\]/ms', '<blockquote>Posted by: \1 at \2.<br/>\3</blockquote>', $text);
This is what I use to replace the [quote=user;id]content[/quote] bbcode. Anyway, it works fine only, if there is one quote in post.
If I got:
[quote=user1;1] [quote=user0;0]some content here[/quote]
this is my reply to user0 post[/quote]
It'll replace only first quote, other will be just not replaced by the <blockquote>.
How can I fix that?
A: tested, repaired version
<?php
$out = '[quote=user1;1] [quote=user0;0]some content here[/quote]this is my reply to user0 post[/quote]';
$cnt = 1;
while($cnt != 0){
$out = preg_replace('/\[quote\=(.*?);(.*?)\](.*?)\[\/quote\]/ms', '<blockquote>Posted by: \1 at \2.<br/>\3</blockquote>', $out, -1, $cnt);
}
echo $out;
http://codepad.org/3PoxBeQ5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problems with git after cvsimport I'm currently trying to migrate our cvs repository to git so all old data is needed but I am running into some problems.
Importing works.
First make a local cvs using cvs init in CVSREPOLOCAL
Copy the projectname there from the old drive then
git cvsimport -d /home/git/CVS_REPOLOCAL projectname -C projectname.git
gitosis is also configured to allow writing to projectname
[group projectname]
members joe jim tom bart
writable = projectname
on the local machine:
git clone ssh://git@server/projectnane.git
change a file and do:
git commit -a
[master 8a3d0f7] test
1 files changed, 1 insertions(+), 1 deletions(-)
gitk shows my change as the new master
... but when trying to make the change available for everybody else on the project:
git push
Counting objects: 7, done.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 432 bytes, done.
Total 4 (delta 2), reused 0 (delta 0)
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To ssh://[email protected]
! [remote rejected] master -> master (branch is currently checked out)
Is there a way to keep the old imported data and still get a ssh gitosis for multiple users?
I had one running but without the cvs import so not a solution :(
A: You have three options:
*
*Use one repository for the import and another, bare (without working copy) one for the central place. Push the code from the one where you imported cvs to the bare one. I'd consider this the cleanest option. I'd even argue to do the import on your workstation and not the server and to discard it once the switch is all over.
*Detach head on the repository (git checkout HEAD@{0}) or check out another branch (git checkout -b cvsimport).
*Actually implement the hook mentioned in the error message, but it's somewhat tricky and I don't think you'll actually need the work tree again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android root directory in centos 6 I've installed eclipse, ADT plugin for it and I get an error "Location of the Android SDK has not been setup in the preferences". I go to preferences but I can't find the root directory of android SDK. Where is it?
edit:
I've set the location to the preferences. Now I get the error 'Android SDK Content Loader' has encountered a problem parseSdkContent failed
A: Have you downloaded the SDK starter package from here? If not download to a directory of your choice and then point Eclipse to that directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS box-shadow did not work at IE or Safari #keyboard {
position: fixed;
background: #eee;
display: none;
border: 1px solid #ccc;
border-radius:7px;
width: 950px;
height: 300px;
padding: 5px;
cursor: move;
background-image:url('BackgroundImage.jpg');
box-shadow: -5px -5px 5px 5px #888;
-moz-border-radius: -5px -5px 5px 5px #888;
-webkit-border-radius: -5px -5px 5px 5px #888;
}
At upper css code, it is okey at Firfox browser.
But I cannot display shadow at IE8 or IE6 and safari as well.
box-shadow: -5px -5px 5px 5px #888;
Please let me know the solution.
A: To offer IE users an effect similar to box-shadow, I usually make use of proprietary MS filters, the following is an extract from my css:
-moz-box-shadow: 2px 4px 19px #333333;
-webkit-box-shadow: 2px 4px 19px #333333;
box-shadow: 2px 4px 19px #333333;
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=115, Color='#333333')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=6, Direction=115, Color='#333333');
Obviously the effect on IE is different, but playing with the various parameters you can get very closer (or at least acceptable) to your expectation on every browser
A: Box shadow which is css3, not supported in ie8 and older browser, But still we can get this using css3pie script
A: Also try prefixr.com, it helps me a lot for making css3 browser compatible
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to display the values into Android Client from MySQL using PHP Web Service I have question regarding on how to display the values into the Android Client from online database in MySQL using the PHP Web Service. The idea is such that initially when the activity is displayed, the first record must be displayed in the textview. There would be a button called Next which would display the next record and move the cursor to the next record in the database. My question is that the move to next record logic should be written in which place? That means should I write the move-to-next-record code in the Android client or should I write in the PHP code?
For the basic understanding of how to connect to an online db in Android Client I had referred to the question in this forum itself:
Connect to Remote DB which gave me a good understanding on how to connect to remote db. But here my idea is kind of different which is event based and has to move to the next record and display in the textview. Any hints and suggesstions? Very grateful if you help me! Thank you.
A: It is really bad idea to connect directly to database. AFAIK, you can create a PHP/MySQL Service to return data in such a format that clients can parse, like popular JSON.
Have a look at this: http://blog.sptechnolab.com/2011/02/10/android/android-connecting-to-mysql-using-php/
Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Send custom complex objects to Silverlight RIA services I've created a complex object which itself include a list of another object.
Example:
public class MyClass1
{
private List<MyClass2> myClass2List
[Key]
public long Id { get; set; }
public string Name { get; set; }
[Include]
[Association("FK_MyClass1_MyClass2", "Id", "MyClass1Id")]
public List<MyClass2> MyClass2List
{
get
{
if (this.myClass2List == null)
{
this.myClass2List = new List<MyClass2>();
}
return this.myClass2List;
}
set { this.myClass2List = value; }
}
}
public class MyClass2
{
[Key]
public long Id { get; set; }
public string Value { get; set; }
public long MyClass1Id { get; set; }
}
Now I want to send an instance of MyClass1 (which its MyClass2List is full) to the RIA services.
My first try was creating a get method with MyClass1 return type (to expose MyClass1) and also creating an Insert method for MyClass1 and MyClass2. It works but the MyClass2 Insert method is useless! I insert all the information in MyClass1 method. Also the get method is useless!
This is the domain service that works:
[EnableClientAccess]
public class MyDomainService : DomainService
{
public MyClass1 GetMyClass1()
{
return null;
}
[Insert]
public void Insert(MyClass1 myClass1)
{
... (Main code)
}
[Insert]
public void Insert(MyClass2 myClass2)
{
// I leave this method empty because I do the job in MyClass1 Insert method.
// If I don't add this method the Add operation on MyClass2List will not work!
}
}
As you see it doesn't have a clear implementation. Although I could use the traditional WCF Silverlight-Enabled services and simply use a single method to insert the MyClass1 instance.
Note that I tried the [Invoke] method (A simple invoke method which gives the MyClass1 as an input parameter) but then "MyClass1.MyClass2List" is empty!!!
How can I send a complex object to RIA services without having such useless methods and dirty implementation? I need to do all my works just in a single method. I don't need tracking and etc here. Is it better to use the traditional WCF Services besides the RIA or is there another way about RIA?
Thanks in advance
A: *
*You need to add [Composition] attribute to your one-to-many relationships as well. more info:[ +, +, + ]
*Also Try to switch to "RIA Services EF Code First Support"
A: On the client you just call SubmitChanges on the domain context. RIA then calls the appropriate insert methods for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Call ffmpeg via PHP but dont wait on it I have my upload script that handles the file upload and then calls exec(ffmpeg -i......
I call ffmpeg 3 times. One to convert to mp4, one to convert to wemb and one to get thumbnail.
Problem is that if an investigator uploads ALL his footage, he doesnt want to have to sit there and wait for it to convert before he can do anything else. So how can i send the 3 commands and then exit the script?
I also want to run exec(rm -r /path/to/original) so the original video is deleted but obviously I have to wait for conversions to be complete before it can be run
A: You can use the ampersand character after the command to run it in the background and get your prompt (control) back right away.
I suggest creating a bash script like:
#!/bin/sh
ffmpeg -i $1 -ab 64k -vb 420k $1.mp4
ffmpeg -i $1 -ab 64k -vb 420k $1.webm
Then run it from php like:
system ('myscript.sh tempfile &');
The following example uses if structure to decide whether to use sound or no. The first parameter is the filename, if the second one equals 0 then no sound on the mp4, if the third one is zero then no sound on the webm.
#!/bin/sh
if [ $2 -eq 0 ]
then
ffmpeg -i $1 -an -vb 420k $1.mp4
else
ffmpeg -i $1 -ab 64k -vb 420k $1.mp4
fi
if [ $3 -eq 0 ]
then
ffmpeg -i $1 -an -vb 420k $1.webm
else
ffmpeg -i $1 -ab 64k -vb 420k $1.webm
fi
You can use it from PHP like:
system ('myscript.sh ' . $tempfile . ' ' . (0 + $mp4sound) . ' ' . (0 + $webmsound) . ' &');
... but remember you can even start a PHP file instead of a shellscript like:
system ("php converter.php \"$tempfile\" \"$mp4sound\" \"$webmsound\" &');
A: *
*Handle the file upload and conversion separately
*After file has been uploaded,
*Put it into a job queue
*Run a cron job that check for latest queue every minute + if currently processing job has finished, if so then do the conversion.
*After conversion do a unlink(/path/to/original ) to delete original video
*Update the job status
Not sure if it make sense, something i am thinking of better than u do everything at once.
Add little abit more of the work behind to ease the pain infront
A: Try handling all ffmpeg conversions separately in one page. ex: convert.php
Once upload was done. sent hidden request to convert.php?id=someid
in top of the convert.php use ignore_user_abort(TRUE);
The process will run even the user closed the browser.
if the user is not closed that page still in that page with ajax response update status.
i hope it may help to get an idea..
A: Perhaps you can move the code that does the conversion into a script that is being called by a cron job.
For example, the user can upload a video to a directory and perhaps insert a record into a database table that contains all unconverted videos.
The cron job then runs every x minutes, checks the database for any unconverted videos, and then converts them. After that is done, the script can then delete the original videos and delete the row from the database.
A: If you are running on Linux, a trailing ampersand to your command in the exec()-call will start the process in the background.
You probably also want to redirect the output from ffmpeg to /dev/null
ffmpeg -i (...) > /dev/null 2>&1 &
The same approach could be used to call a shell script if you wanted to clean up after converting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why do I need a javascript compiler if I always precompile my assets? I am runnning rails 3.1 on my heroku server (but with the bamboo stack).
Since 3.1, I had to add a javascript compiler for uglifier. So I'm using therubyracer-heroku for now.
The reason I'm wondering is that I'm always precompiling my assets, and even pushing them to Amazon S3. So why should I still need a compiler on the host ?
I'm asking because therubyracer is a heavy gem, and so a lot of requests are failing because of memory issues.
A: A bit late on the answer, but you actually do not need a javascript runtime on the production server, and you should not.
You should turn of compiling on the server with : config.assets.compile = false
And precompile all the assets before deploying.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ITelephony.aidl not compiling in eclipse I am using the code of this answer, where as I have to add ITelephony.aidl to my project source, I did that.
But this aidl file not compiling. Is there any other step which are required?
A: First create a package in the src folder in your project named com.android.internal.telephony and within that package create a file and copy paste the interface ITelephony and save the file as ITelephony.aidl. When you compile you will get the .java file for the ITelephony in the gen folder.This is what I did and my issue got solved.
Hope this helps
A: If your aidl file is showing any error in eclipse then you should consider it and post the error here but if it is not showing any error you must clean your project and build it again. After this process you must go in "gen" folder and check either this file is compiled there and any class is exist with the same name of aidl file. If it is found, its mean aidl file is compiling properly.
Thanks and Regards,
Ali
A: Certin versions of Eclipse move the reference library folders for prjects.Either update eclipse, reinstall eclipse and the adt plug in or move the library within your eclipse folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to redirect requests to www.example.com/admin to different module in Zend I have a problem with redirecting requests in my application.
My rules:
*
*employer.domain.com - should point to a page of the employer - uses default module
*employer.domain.com/panel/ - should point to a administration page of specific employer - uses dashboard module
*www.domain.com - should point to page aggregating all employers - uses default module
I've tested a lot of different routes, but when one route is working, other get broken. Also often it works only for root paths, but when I add call to some controller and action - it crashes. Maybe I should write custom controller plugin? What do You think?
Here is my current configuration. It's a mess, but maybe it will help catching some silly mistake.
// employer.domain.com/panel
$pathRoute_panel = new Zend_Controller_Router_Route(
':panel/:controller/:action/:id/',
array(
'panel' => '',
'module' => 'dashboard',
'controller' => 'index',
'action' => 'index',
'id' => '',
),
array(
'panel' => 'panel'
)
);
$subdomainRoute = new Zend_Controller_Router_Route_Hostname(
':employer.'.$config['host'],
null,
array(
'employer' => '([a-z0-9]+)',
)
);
$router->addRoute('employer_panel', $subdomainRoute->chain($pathRoute_panel));
// employer.domain.com - main employer page
$pathRoute_panel = new Zend_Controller_Router_Route(
'',
array(
'module' => 'default',
'controller' => 'vcard',
'action' => 'index',
'id' => '',
)
);
$subdomainRoute = new Zend_Controller_Router_Route_Hostname(
':employer.'.$config['host'],
null,
array(
'employer' => '([a-z0-9]+)',
)
);
$router->addRoute('employer_vcard', $subdomainRoute->chain($pathRoute_panel));
// domain.com/
$pathRoute = new Zend_Controller_Router_Route_Module(
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
),
$dispatcher,
$request
);
$route = new Zend_Controller_Router_Route_Hostname($config['host']);
$router->addRoute('default', $route->chain($pathRoute));
// www.domain.com/
$pathRoute = new Zend_Controller_Router_Route_Module(
array(
'module' => 'default',
'controller' => 'index',
'action' => 'index',
),
$dispatcher,
$request
);
$route = new Zend_Controller_Router_Route_Hostname('www.'.$config['host']);
$router->addRoute('default_www', $route->chain($pathRoute));
EDIT: This is my solution:
// employer.domain.com
$pathRoute_panel = new Zend_Controller_Router_Route_Module(
array(
'module' => 'default',
'controller' => 'vcard',
'action' => 'index',
'id' => '',
)
);
$subdomainRoute = new Zend_Controller_Router_Route_Hostname(
':employer.'.$config['host'],
null,
array(
'employer' => '([a-z0-9]+)',
)
);
$router->addRoute('employer_vcard', $subdomainRoute->chain($pathRoute_panel));
// employer.domain.com/panel/
$pathRoute_panel = new Zend_Controller_Router_Route(
'panel/:controller/:action/:id/',
array(
'panel' => 'panel',
'module' => 'dashboard',
'controller' => 'index',
'action' => 'index',
'id' => '',
)
);
$subdomainRoute = new Zend_Controller_Router_Route_Hostname(
':employer.'.$config['host'],
null,
array(
'employer' => '([a-z0-9]+)',
)
);
$router->addRoute('employer_panel', $subdomainRoute->chain($pathRoute_panel));
A: // Enforce Subdomain usage
// Will match employer.domain.com/*
$subdomainRoute = new Zend_Controller_Router_Route_Hostname(
'employer.'.$config['host'] . '/*'
);
// Will match /panel/{id, required}/{controller, optional}/{action, optional}/{further parameters, optional}
$pathRoute_panel = new Zend_Controller_Router_Route(
'panel/:id/:controller/:action/*',
array(
'module' => 'dashboard',
'controller' => 'index',
'action' => 'index'
),
array(
'id' => '\d+'
)
);
// employer.domain.com - main employer page
// will match everything not matched before!
$pathRoute_page = new Zend_Controller_Router_Route(
'*',
array(
'module' => 'default',
'controller' => 'vcard',
'action' => 'index'
)
);
// You can add several routes to one chain ;) The order does matter.
$subDomainRoute->chain($pathRoute_page);
$subDomainRoute->chain($pathRoute_panel);
$router->addRoute($subDomainRoute);
Annotations are in the code. You can use the wildcard (*) to match anything further! There's no need of the default_www route - this's just the default behaviour (the default route now will match every subdomain but employer as it is matched by the subDomainRoute).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send email reminders on different conditions? I have a table called reservations which has columns start_date and end_date.
If date_diff(start_date and end_date) is 30 then I need to send an email on 8,2 and 1 days before end_date. same with the below..
60 – 15,4 & 1
120 and above – 30, 8, 2 & 1...
any idea how to do this ??
A: set up cronjob to do this kind of stuff.
A: write 3 separate sql statements for your query get these to work.
then put these into a mysql_query in php setting a variable if row count >0
using isset on the variable into email smtp script
set up a cron job to check every morning.
A: SELECT *,DATEDIFF(CURDATE(), end_date) as DIFF FROM TABLE WHERE DATEDIFF(CURDATE(), end_date) in (1,2,8)
A: What you can do is you create 2 tables, 1 for the main reservation information and the 2nd one will be for the storing of the send dates (or send reminder dates).
When the saving the record you will then retrieve the difference between the current date and the end_date; if difference will be 30 then you'll have to store send_dates 8,2 and 1 days before the end_date; same with the other conditions you have.
Then create a cron job (that will run daily) to check the 2nd table of the send_dates = current date. Then email if conditions is met.
Hope this is the one you needed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Model View Control in C# Designing a presentation type application which consists of 2 forms, the first form will be used to control the presentation so it can be manipulated on the fly, it will be based off the first monitor of the pc, the second form will be on the second monitor (or projector). I need to update the second form with numbers and pictures during the presentation. In terms of accessing information between forms, would MVC be the best way to do this?
http://www.c-sharpcorner.com/UploadFile/rmcochran/MVC_intro12122005162329PM/MVC_intro.aspx
Cheers!
A: You don't make it 100% clear if you're are using Forms or WPF (you've put both tags) if you are using WPF the most popular and comfortable design pattern for is generally the Model-View-ViewModel (MVVM) pattern. Is this is quite close to MVC but slightly different. You can read about it here
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
In your application it would mean having data classes that described and manipulated the presentation itself (the model).
Then you would have a view model class (or group of classes) that describe what's visible in each window and the current state of the controls and the currently displayed slide etc. both sets of view models bind to and update the same underlying presentation model.
Finally the XAML and controls render two a 'views' one for each window, the views then become nice and clean binding only to the current state of the ViewModel.
Hope this general outline provides helpful inspiration, if you want and more specific info or advice please ask.
Mark
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recover deleted rows from SQL Server 2000 A script accidentally deleted few rows from the database with the following query:
DELETE FROM that_table WHERE id IN (100, 101, 102)
More rows have been added in the mean time. Is there a way for me to recover the three rows into the same table (or perhaps another database/table)? I do not want to restore the database as if this means I lose all data added/updated after that query. Hand entering the missing rows is an option.
A: You can use ApexSQL Log, a SQL Server auditing and recovery tool which reads information from database transaction logs and provides undo T-SQL scripts both for DML and DDL operations.
Disclaimer: I work as a Product Support Engineer at ApexSQL
A: As you are on SQL Server 2000 you may be in luck as the free Redgate SQL Log Rescue Tool works against this version.
A: Luckily I had a backup so I used the procedure described here to restore the backup on the same server but under a new database:
Restoring a Complete Backup to a New Database on the Same Server
After the database backup was restored in a new database, I located the rows and inserted them:
INSERT INTO that_database..that_table
SELECT * FROM copy_database..that_table WHERE id IN (100, 101, 102)
The above query did not run out of the box, I had to enable identity insert and disable a couple of constraints temporarily.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: init, alloc and retain and "the initial value is never read" Ive have used the static analyser to look through my code and have arrived at the following question.
NSString *string = [[NSString alloc] init];
string = [object name];
This give me a memory error saying that the initial value is never read.
I replaced it with the following
NSString *string = [[object name]retain];
Is this better/correct coding?
Cheers
A: This code:
1: NSString *string = [[NSString alloc] init];
2: string = [object name];
is incorrect because in line 1: you allocate new memory and store reference to it in variable string. In line 2: you store in variable string reference to another memory location.
As a result, you didn't read memory value that was allocated at line 1: and even didn't release it. So moreover you have memory leak there.
If you want to save reference to some place in memory you don't need alloc+init. You should use alloc+init when you want to allocate some space in memory where you will write data or read from.
A: Your variable string is actually a pointer to an NSString object. The first line of your code created a new empty string and assigned a pointer to it to string. The second line of code then immediately overwrites that pointer with a pointer to a completely different string. You have never read the original value, and there is no way to access the allocated NSString, thus it has leaked.
The second option is correct., provided you release/autorelease it somewhere later.
A: I have seen someone else do this exact thing. NSString *string = [[NSString alloc] init]; creates a new object and assigns it to string. string = [object name]; Assigns the name of object to string. It is similar to saying int a = 0; a = 4, 0 has no effect on the 4. The problem with your code is that [[NSString alloc] init] creates a new object with a retain count of 1, because you do not release it it leaks. [object name] returns an autoreleased object which will disappear at the end of the runloop.
In short, use NSString *string = [[object name] retain];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I show nested data into a tree? Further progress. Please see at http://www.sencha.com/forum/showthread.php?153986-Empty-column-something-I-can-t-get-with-Ext.data.TreeStore-and-or-Ext.tree.Panel
I always appreciate any further advise.
I am trying to develop a simple extJS Ext 4.0.2a script to display some nested data as a Drag&Drop tree.
To try, I use a simple example from http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.reader.Reader
Data are given as a users.json file:
{
"users": [
{
"id": 123,
"name": "Ed",
"orders": [
{
"id": 50,
"total": 100,
"order_items": [
{
"id" : 20,
"price" : 40,
"quantity": 2,
"product" : {
"id": 1000,
"name": "MacBook Pro"
}
},
{
"id" : 21,
"price" : 20,
"quantity": 3,
"product" : {
"id": 1001,
"name": "iPhone"
}
}
]
}
]
}
]
}
I wish to display data as a tree, whose first level nodes are users, second level nodes are orders, and so on.
From the same doc, I learn how to define my models (I believe):
Ext.define("User", {
extend: 'Ext.data.Model',
fields: [
'id', 'name'
],
hasMany: {model: 'Order', name: 'orders'},
proxy: {
type: 'ajax', // rest
url : 'users.json',
reader: {
type: 'json',
root: 'users'
}
}
})
;
Ext.define("Order", {
extend: 'Ext.data.Model',
fields: [
'id', 'total'
],
hasMany : {model: 'OrderItem', name: 'orderItems', associationKey: 'order_items'},
belongsTo: 'User'
});
Ext.define("OrderItem", {
extend: 'Ext.data.Model',
fields: [
'id', 'price', 'quantity', 'order_id', 'product_id'
],
belongsTo: ['Order', {model: 'Product', associationKey: 'product'}]
});
Ext.define("Product", {
extend: 'Ext.data.Model',
fields: [
'id', 'name'
],
hasMany: 'OrderItem'
});
next, I define a tree store and a tree panel (for some selected fields):
var store = Ext.create('Ext.data.TreeStore', {
model: 'User',
autoLoad: true,
autoSync: true,
root: {
name: "Root node",
id: '0',
expanded: true
},
sorters: [{
property: 'id',
direction: 'ASC' // DESC
}]
});
var tree = Ext.create('Ext.tree.Panel', {
store: store,
displayField: 'name', // what nodes display (default->text)
columns: [{
xtype: 'treecolumn',
text: 'name',
dataIndex: 'name',
width: 150,
sortable: true
}, {
text: 'total',
dataIndex: 'total',
width: 150,
flex: 1,
sortable: true
}, {
text: 'price',
dataIndex: 'price',
width: 50,
flex: 1,
sortable: true
},{
text: 'quantity',
dataIndex: 'quantity',
width: 150,
flex: 1
}, {
text: 'id',
dataIndex: 'id',
flex: 1,
width: 15,
sortable: true
}],
collapsible: true,
viewConfig: {
plugins: {
ptype: 'treeviewdragdrop', // see Ext.tree.plugin.TreeViewDragDrop
nodeHighlightColor : '7B68EE',
nodeHighlightOnDrop : true,
nodeHighlightOnRepair: true,
enableDrag: true,
enableDrop: true
}
},
renderTo: 'tree-div',
height: 300,
width: 900,
title: 'Items',
useArrows: true,
dockedItems: [{
xtype: 'toolbar',
items: [{
text: 'Expand All',
handler: function(){
tree.expandAll();
}
}, {
text: 'Collapse All',
handler: function(){
tree.collapseAll();
}
}]
}]
});
});
I see the panel, the root and the first level users (as subnodes of the root). I do not see any subnodes (orders, order_items and so on).
I looked carefully at a number of posts, improved things quite a lot, but still miss to get a working solution.
A: I am facing the same task, and first was glad to run into your post!
After 5 hours of exploring the official docs regarding to it:
*
*http://docs.sencha.com/ext-js/4-0/#!/guide/data
*http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.reader.Reader
I was able to populate my nested treestore with nothing better than this:
(in my case the main model is Camgroup which hasMany Camera as 'cams': which allows to use .cams() for every group)
Ext.define('AV.store.sCamgroups', {
extend: 'Ext.data.TreeStore',
model: 'AV.model.Camgroup',
autoLoad: true,
root: {
expanded: true,
text: "Grouped Cameras"
},
proxy: {
type: 'ajax',
url: 'data/camgroups.json',
reader: {
type: 'json',
root: 'camgroups',
successProperty: 'success'
}
},
listeners: {
load: function(thisStore, rootnode, records, successful, eOpts){
records.forEach(function(group){
group.cams().each(function(cam) {
group.appendChild({
text: cam.get('name'),
leaf: true
});
});
});
}
}
});
camgroups.json returns smth like this:
{
success: true,
camgroups: [{
"id" : "group1",
"name" : "Exterior cams",
"cams" : [{
"id" : "cam3",
"name" : "Camera three",
"url" : "...",
"img" : "images/cams/3.png",
"ratio" : 1.33
},{
"id" : "cam4",
"name" : "Camera four",
"url" : "...",
"img" : "images/cams/4.png",
"ratio" : 1.33
}]
}]
}
Hope this will help you though keep looking for a better solution (prob defining a proper reader).
Again, in "Ext.data.reader.Reader" I can see that Reader has config property 'implicitIncludes' which is supposed 'to automatically parse models nested within other models in a response object', but I cannot make it working =(
Cheers,
Ilya
A: Further progress.
Please see at
http://www.sencha.com/forum/showthread.php?153986-Empty-column-something-I-can-t-get-with-Ext.data.TreeStore-and-or-Ext.tree.Panel
I appreciate any further advise.
I made some progress. It seems I need to modify my json:
{
"children": [ <<<<---- use the same string to insert nested data, see below too
{
"id": 12,
"name": "Ed2",
"children": [] <<<<---- need this line, otherwise, JS tries to load subnodes for ever
},
{
"id": 123,
"name": "Ed",
"children": [ <<<<---- as above
{
"id": 50,
"total": 100,
"info" : "hello",
"name" : "ciao",
"children": [ <<<<---- as above
{
"id" : 20,
"price" : 40,
"quantity": 2,
"children" : { <<<<---- as above
"id": 1000,
"name": "MacBook Pro",
"children": [] <<<<---- as above bis
}
},
{
"id" : 21,
"price" : 20,
"quantity": 3,
"children" : { <<<<---- as above
"id": 1001,
"name": "iPhone",
"children": [] <<<<---- as above bis
}
}
]
}
]
}
]
}
Then the following definition of a model works:
Ext.define("User", {
extend: 'Ext.data.Model',
fields: [
'id', 'name', 'info', 'price', 'quantity', 'order_id', 'product_id'
],
proxy: {
type: 'ajax', //rest
url : 'ex1.json',
reader: {
type: 'json',
root: 'children'
}
}
});
So, it seems that associations among models for the different levels of my nested data are not needed at all.
It works, although I am not sure whether there are drawbacks or not.
I am still looking for your advise, I go by try&mistake, I do not see the underlying logic yet.
Thks.
I have second thoughts. The trick to use a unique string 'children' does not seem so good.
Let me consider a very simple json:
{
"users": [
{
"id": 12,
"name": "Ed2",
"orders": []
},
{
"id": 123,
"name": "Ed",
"orders": [
{
"id": 50,
"info" : "hello",
"name" : "MM",
"leaf" : 'true',
"some_else": []
}]
}
]
}
The extJS tree I wish to get is:
Root
|--ED
|--ED2
|--MM
The model is just
Ext.define("User", {
extend: 'Ext.data.Model',
fields: [
'id', 'name'
],
hasMany: {model: 'Order', name: 'orders'},
proxy: {
type: 'ajax', //rest
url : 'my_file.json',
reader: {
type: 'json',
root: 'users'
}
}
});
Ext.define("Order", {
extend: 'Ext.data.Model',
fields: [
'id', 'name', 'info'
],
belongsTo: 'User'
});
The final output I get is just:
Root
|--ED
|--ED2
is it a mistake of mine, or a missing feature? is there a way out without to change my json?
Thanks a lot
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to change Aptana3 html template?? learning js by using aptana,
aptana2 can initial html file content in "Windows - Preferences - Aptana - HTML"
But in aptana3 i couldn't find this setting.
so i add new html file in project explorer by rightclick menu "new from template - html - xhtml 1.0 transitional template"
now the problem is...how to change template initial content?
A: Please see instructions for Creating a New Template and Modifying an Existing Template.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I return an image in an M-file? (MATLAB) My function file starts with function drawline(point1,point2,color,img). At the end, I'm supposed to return an image. How do I code the return line?
I posted codes in another Stack Overflow question, Color issue in MATLAB.
A: In your code, you should be returning the img variable, since that's the one you're modifying, not the image one, which doesn't exist.
Also, since all the basic types in MATLAB is (effectively) passed by value rather than reference, you need to assign the output argument in order to get anything back. Use the following function call:
[img] = drawline(p1,p2,color,img);
EDIT: Your function should look like this:
function img = drawline(p1,p2,color,img)
...
% code that updates IMG.
...
Then in the command window you must write
[img] = drawline(p1,p2,color,img);
An introduction to MATLAB functions can be found here: http://www.mathworks.co.uk/help/techdoc/learn_matlab/f4-2525.html.
A: You do not need to code the return line, just define the function so that it returns an image:
function [ Image ] = drawline( point1,point2,color,img )
...
function_instructions
...
end
the important thing is that you store an image in the Image variable.
In the script that calls the function drawline you should use this kind of statement:
[ Image ] = drawline( point1,point2,color,img );
If you need some help on matlab image processing check these out:
*
*http://amath.colorado.edu/courses/5720/2000Spr/Labs/Worksheets/Matlab_tutorial/matlabimpr.html
*http://www.mathworks.it/help/techdoc/ref/image.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server: Endless WHILE EXISTS loop I have problem with the following WHILE EXISTS loop. Could you consider what can be reason why it is endless loop and why it doesn't update values?
declare @part varchar(20)
while exists ((select top 1 * from part1 p where isnull(brojRacuna,'')=''))
begin
set @part=''
set @part=(select top 1 partija from part1 p where isnull(brojRacuna,'')='')
begin tran
update part1
set BrojRacuna= (select dbo.dev_brojracuna (@part))
where partija like @part
print @part
commit
end
EDIT 1: Because I didn't find solution in first moment, I created cursor and updated data in that way. After that I found that left couple rows that are not updated, because function had an issue with data and couldn't update values for that rows. In that case, fields have been empty always and loop became endless.
A: I don't understand why you select the partija value, since you have it in the where clause, you can simplify a lot this way:
declare @part varchar(20)
while exists ((select 1 from part1 p where isnull(brojRacuna,'')='' and partija='1111'))
begin
begin tran
update part1
set BrojRacuna= (select dbo.dev_brojracuna ('1111'))
where partija like '1111'
commit
end
By the way, if you have an endless loop, maybe the function dev_brojracuna doesn't return the correct value, and brojRacuna remains unaltered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: what is the need for the explicit "return" keyword when using onsubmit in a form using Javascript? I have a C/C++ programming background, and while casually learning Javascript through the @3C webpages on JS, I found this piece of code -
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
Well, I do not know if I have missed out any of their previous lessons; am confused over the "return" used in the line -
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
My question - Since the "onsubmit" in the above line on calling the function "validateForm()" will anyways be looking for a return value of true/false, what is the significance of this explicit return keyword? I see that on deleting the return keyword, and running the above code (as - onsubmit = "validateForm();" ) works, but even if an error in input is there the form ultimately gets submitted after displaying the warning message.
Could you please throw some light on the use of this "return" keyword in this scenario?
Also, I find that there is a lot of deviation in the way Javascript is written, considering my background in c/c++.. am i alone here..? :)
thanks!
A: well if the function returns false, then the event is canceled.
onsubmit="return validateForm();"
is somewhat equivalent to
onsubmit="if(!validateForm()) stop the event"
Of course, that there are other(cleaner) methods of stopping the event dom-propagation :
function stopEvent(event){
if(event.preventDefault)
event.preventDefault();
if(event.stopPropagation)
event.stopPropagation();
event.cancelBubble = true;
}
and then use it into an event-handler :
onsubmit = function(e){
if(!validateForm())
stopEvent(e);
}
A: OK, it seems there appear some misleading answers, so I'll try to provide an explanation. The notation <element onsubmit="handler_body"> is translated to something like:
element.onsubmit = function (event) {
with (document) {
with (this) {
handler_body
}
}
};
(We'll ignore the with-related stuff, it's not important here.) Now, consider the validateForm() function returns false. If you use onsubmit="return validateForm()", what subsequently turns obviously into onsubmit="return false", your handler will become
element.onsubmit = function () {
return false;
};
When the submit event is triggered (it's like the browser internally calls element.onsubmit()), element.onsubmit() returns false and thus the default value is suppressed.
However, if you'd just use onsubmit="validateForm();", the event handler would look like
element.onsubmit = function () {
false;
};
In this case, false is just a statement. element.onsubmit() doesn't return anything, and returning undefined from the event handler isn't enough to prevent the default behaviour.
@Simeon told that "The return in HTML is not needed.", but he actually also uses return false in his code.
A: The return in HTML is not needed. For the record, to attach the event programmatically is both more beautiful and powerful:
<html>
<head>
<script type="text/javascript">
var myForm = document.getElementById("myForm");
myForm.onsubmit = function() {
var x = myForm["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
};
</script>
</head>
<body>
<form id="myForm" action="demo_form.asp" method="post">
<label>
Email:
<input type="text" name="email">
</label>
<input type="submit" value="Submit">
</form>
</body>
</html>
A: I believe everyone has nearly answered the question, but then in different ways. Thanks guys.
I happened to read an excellent article online, which beautifully explains what is actually happening, mostly behind the scenes, using an example that closely resembles the question that I had posted.
Felt this would turn useful for anyone who might face this issue in the future.
Link to the article- http://www.quirksmode.org/js/events_early.html
Read the "Prevent Default" section of the page.
--arun nair
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JTextArea only with numbers, but allowing negative values I have a JTextArea which only has to accept numbers. This is my code:
DocumentFilter onlyNumberFilter = new AxisJTextFilter();
final JTextArea areaTextoXMin = new JTextArea(String.valueOf(xMin));
((AbstractDocument)areaTextoXMin.getDocument()).setDocumentFilter(onlyNumberFilter);
Works OK for positive numbers, but not for negative numbers. How can I fix that?
EDIT: Sorry, the AxisJTextFilter was found over the Internet and I forgot about that. Its code is:
import javax.swing.text.*;
import java.util.regex.*;
public class AxisJTextFilter extends DocumentFilter
{
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException
{
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.insert(offset, text);
if(!containsOnlyNumbers(sb.toString())) return;
fb.insertString(offset, text, attr);
}
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attr) throws BadLocationException
{
StringBuilder sb = new StringBuilder();
sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
sb.replace(offset, offset + length, text);
if(!containsOnlyNumbers(sb.toString())) return;
fb.replace(offset, length, text, attr);
}
public boolean containsOnlyNumbers(String text)
{
Pattern pattern = Pattern.compile("\\d*(\\.\\d{0,3})?");
Matcher matcher = pattern.matcher(text);
boolean isMatch = matcher.matches();
return isMatch;
}
}
A: Try modifying the regular expression (int the validation method containsOnlyNumbers).
Pattern pattern = Pattern.compile("^[\\-\\+]?\\d+(\\.\\d+)?$");
This will accept the following numbers:
*
*1234
*-1234
*+1234
*1234.1234
I hope it helps
Udi
A: This is intended as a comment on Udi's excellent post, but I can't figure out how to do that.
I think his pattern (d+) requires at least 1 digit, and it should be d? to allow 0-N digits. Because, as the user is typing, "-" is legal input. And a decimal point followed by no digits is always legal, especially while typing. It's only at the end (when you lose focus, etc., YMMV) that you can either require at least one digit, or, be accommodating and pragmatic and just treat the string "-" as 0.
And when developing these kinds of regular expressions don't forget that the user might be copying and pasting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using Git and Subversion in parallel (Tortoise) At work we use Subversion, I often use it with Tortoise. I want to start to use Git for non-official changes.
One problem is we seem to use both SVN Git and Tortoise Git on the same directories.
What would be the appropriate Git software to install? How to work? What should I do about the conflict between the Tortoises? I know you can quickly enable/disable features with registry-scripts, but that would be machine-wide.
I plan to move to git svn, and I somestimes use Visual Studio (I could use VS for Git only)
A: There are no "conflicts" betweeen TortoiseSVN and TortoiseGit. They can both share the icon overlay.
http://kerneltrap.org/mailarchive/git/2010/4/1/27119
Related question: Tortoise Git side-by-side with Tortoise SVN?
TortoiseGit is excellent for initial move to Git, and it supports git-svn related commands as well. And Git is at its best in the command line anyway, so if TortoiseGit is not what you want, I would say, just use the cli.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can't get my datagridview to write back to MS Access database I am using MS Access 2003 and vb.net to develop a windows application of inventory management.
I have used datagridview in the form and using FillBytoolstrip option, can filter data using type.
But i have no idea as to how can i update the database to reflect the latest changes in the gridview.
Tried searching but could not find proper and organised answer.
Could you please help me out with this ??
following is the code I have used. I am new to this. Please help !!
Private Sub BOM_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.PartnoTableAdapter.Fill(Me.HemDatabase1DataSet3.partno)
End Sub
Private Sub FillByToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FillByToolStripButton.Click
Try
Me.PartnoTableAdapter.FillBy(Me.HemDatabase1DataSet3.partno, TypeToolStripTextBox.Text)
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
A: You have set up a TableAdapter PartnoTableAdapter to do the database reads (using Fill & FillBy methods).
Use the same TableAdapter to write back to the database using its Update method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to keep html new line in textarea I am reading a column content using
$("#myText").text($.trim($(this).closest('tr').next('tr').find('.mytext).text()));
However, though there is multiple new lines, the text being copied doesn`t show the lines as new line but rather shows it as a line in the textrea.
if my text is
Line 1
Line 2
Line 3
it's appearing as
Line1Line2Line3
A: Probably you text in the table cell you have content like:
Line 1<br/>
Line 2<br/>
Line 3<br/>
Or in separate divs, or ny other method to splitting it on separate lines.
But textarea doesn't handle all html tags, it displays just plain text. And for separating line it uses \n\r whitch means new lane and carriage return.
Try to replace <br /> to \n\r. But it will helps only if your lines in the column splitted by <br />.
A: Use
$("#myText").html($.trim($(this).closest('tr').next('tr').find('.mytext').text()));
You used .text which only records what it says: "text". You need to use .html to keep the formatting.
A: It looks like the problem might be coming from your trim function. You are trimming all the newlines. To be able to trim it and have a newline at the end, you could manually put that newline in there:
$("#myText").text($.trim($(this).closest('tr').next('tr').find('.mytext').text()) + "\r\n");
And after reviewing this for several minutes, I have to agree this would be easier to troubleshoot with a jsfiddle. It's not totally clear exactly what's going on. We have to make a lot of assumptions about how you are using this code. E.g., we are assuming that
Line 1
Line 2
is actually
Line 1<br>
Line 2<br>
which should actually work the way you expect.
A: Does your code look like this Line 1<br/>Line 2<br/>Line 3<br/>? If you can format the html then try to format it like this:
Line 1<br/>
Line 2<br/>
Line 3<br/>
If you can't format html than you have to use html method and if #myText is textarea then you should use val method to set its value.
If you can't format html then your code should look like this to work:
$("#myText").val(
$.trim(
$(this).closest('tr').next('tr')
.find('.mytext').html().replace('<br/>', '/r/n')
)
);
with the replace part a little richer to address more general case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i create a User control of my asp.net web solution? I have asp.net Web Solution with WCF services. How do I convert the solution to a User control so that I can use it in my other applications uniformly.
Actually I want to convert my application to a user control.what is the easiest way of doing it. its an ASP.Net application.
Thanks in advance
IRP
A: IMHO this is not possible nor should it be desired.
If you pack your WCF service into a control what if there is more than one control on a page? What with the different user-sessions?
And of course this is strongly against the Seperation of Concerns-Principle.
What I would do is write a small framework, where one part is the Service and one part is the user-control. Basically you copy and past all you need into a new library-project and maybe do the ABC-stuff in code if you don't like the web.config aproach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get address out of a paragraph with regex Alright, this one's a bit of a pain. I'm doing some scraping with Python, trying to get an address out of a few lines of poorly tagged HTML. Here's a sample of the format:
256-555-5555<br/>
1234 Fake Ave S<br/>
Gotham (Lower Ward)<br/>
I'd like to retrieve only 1234 Fake Ave S, Gotham. Any ideas? I've been doing regex's all night and now my brain is mush...
Edit:
More detail about what the possible scenarios of how the data will arrive. Sometimes the first line will be there, sometimes not. All of the addresses I have seen have Ave, Way, St in it although I would prefer not to use that as a factor in the selection as I am not certain they will always be that way. The second and third line are alPhone (or possible email or website):
What I had in mind was something that
*
*Selects everything on 2nd to last line (so, second line if there are three lines, first line if just two when there isn't a phone number).
*Selects everything on last line that isn't in parentheses.
*Combine the 2nd to last line and last line, adding a ", " in between the two.
I'm using Scrapy to acquire the HTML code. The address is all in the same div, I want to use regex to further break the data up into appropriate sections. Now how to do that is what I'm unable to figure out.
Edit2:
As per Ofir's comment, I should mention that I have already made expressions to isolate the phone number and parentheses section.
Phone (or possible email or website):
((1[-. ])?[0-9]{3}[-. ])?\(?([0-9]{3}[-. ][A?([0-9]{4})|([\w\.-]+@[\w\.-]+)|(www.+)|([\w\.-]*(?:com|net|org|us))
parentheses:
\((.*?)\)
I'm not sure how to use those to construct a everything-but-these statement.
A: It is possible that in your case it is easier to focus on what you don't want:
*
*html tags (<br>)
*phone numbers
*everything in parenthesis
Each of which can be matched easily with simple regular expressions, making it easy to construct one to match the rest (presumably - the address)
A: This attempts to isolate the last two lines out of the string:
>>> s="""256-555-5555<br/>
... 1234 Fake Ave S<br/>
... Gotham (Lower Ward)<br/>
... """
>>> m = re.search(r'((?!</br>).*)<br/>\n((?!</br>).*)<br/>$)', s)
>>> print m.group(1)
1234 Fake Ave S
Trimming the parentheses is probably best left to a separate line of code, rather than complicating the regular expression further.
A: As far as I understood you problem, I think you are taking the wrong way to solve it.
Regexes are not a magical tool that could extract pertinent data from a pulp and jumble of undifferentiated elements of text. It is a tool that can only extract data from a text having variable parts but also a minimum of stable structure acting as anchors relatively to which the variable parts can be localized.
In your treatment, it seems to me that you first isolated this part containing possible phone number followed by address on 1/2 lines. But doing so, you lost information: what is before and what is after is anchoring information, you shouldn't try to find something in the remaining section obtained after having eliminated this information.
Moreover, I presume that you don't want only to catch a phone number and an address: you may want to extract other pieces of information lying before and after this section. With a good shaped regex, you could capture all the pieces in one shot.
So, please, give more of the text, with enough characters before and enough characters after the limited section allowing to write a correct and easier regex strategy to catch all the data you want. triplee has already asked you that, and you didn't, why ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Best way for Interpreter Executing I am writing a scripting language, i've done the lexer and parser and i want to dynamically execute in the memory.
Lets say i have something like
function Hello(World)
{
Print(world);
}
var world = "World";
var boolean = true;
if(boolean == true)
{
Print("True is True");
}
else
{
Print("False is True");
}
Hello(world);
what would be the best way to execute this snippet i'ved tried
1) OpCode Il Generation (i couldn't get if statement to work or anything other than Print function)
2) RunSharp, i cannot do the functions cause the way i can do it i have no idea how.
If anyone could point me to the right direction!
Alittle Code will help
Link to resource (not something like IronPython) would be also good
A: your script language like JavaScript,if it dynamic compile in memory.
example:
//csc sample.cs -r:Microsoft.JScript.dll
using System;
using System.CodeDom.Compiler;
using Microsoft.JScript;
class Sample {
static public void Main(){
string[] source = new string[] {
@"import System;
class JsProgram {
function Print(mes){
Console.WriteLine(mes);
}
function Hello(world){
Print(world);
}
function proc(){
var world = ""World"";
var bool = true;
if(bool == true){
Print(""True is True"");
}
else{
Print(""False is True"");
}
Hello(world);
}
}"
};
var compiler = new JScriptCodeProvider();
var opt = new CompilerParameters();
opt.ReferencedAssemblies.Add("System.dll");
opt.GenerateExecutable = false;
opt.GenerateInMemory = true;
var result = compiler.CompileAssemblyFromSource(opt, source);
if(result.Errors.Count > 0){
Console.WriteLine("Compile Error");
return;
}
var js = result.CompiledAssembly;
dynamic jsProg = js.CreateInstance("JsProgram");
jsProg.proc();
/*
True is True
World
*/
}
}
A: generate c# source and compile it :-)
http://support.microsoft.com/kb/304655
A: If I understand you right, you want to compile and run the code on runtime? then you could try http://www.csscript.net/index.html , its an example on the same page linked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits