text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: umbraco authorization problems I inherited an umbraco website from another developer and am having problems with authorization. The website seems to deny authorization to anonymous users even though I have set authorization to allow users="*". Is there something else I should be doing in umbraco?
A: It was file permissions error. The ACL on the actual directory was restricted but it ended up doing a forms authentication request instead. I gave everyone permissions to the files and that seemed to have cleared it up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android : What use is MediaController's AnchorView? I would like my MediaController to hide only when the user touches only the bottom half part of the screen, because i have some buttons on the top part that need to be accessible with one click.
That is, without the first click being intercepted by the MediaController.
From what i read on the developers doc :
...Specifically, the controls
will float above the view specified with setAnchorView(). The window
will disappear if left idle for three seconds and reappear when the
user touches the anchor view.
My anchor_view layout :
<View android:id="@+id/player_control"
android:layout_width="wrap_content"
android:layout_height="100dip"
android:layout_alignParentBottom="true">
</View >
Yet, when the Controller is on, whenever i touch the screen outside the anchor_view, it still only hides it, and doesn't fire the buttons events.
Is there a way to prevent that ?
A: The anchor view is used by the MediaController only as a reference to get the position where it should start to draw the controllers. Controllers themselves are drawn in a new window floating over the window which all your views are attached to. When an instance of MediaController is created, this new floating window is built (using an internal API) and a touch listener is associated to its decor view, i.e. to its whole surface. This is why touching any part of the screen results in hiding the media controllers, and this is why I believe there is no easy way to customize this behavior: it may require you to extend or reimplement MediaController.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Images mess up my table layout Here is the test file: http://www.nicoeinsidler.bplaced.net/test/mail_test.html
If there are no pictures everything works fine as expected, but as soon as I add picture to it they break my layout.
<img src="https://img.skitch.com/20110930-e89yb812kuhisgsuhf896aepnx.png" alt="http://www.nicoeinsidler.bplaced.net/test/mail_test.html" />
(I never layout my homepages with tables, so I'm not good at it. I have to do it because this will become a HTML-Email…)
Here is how it should look like:
A: The td inside the following tr needs to have a colspan of 3 (instead of 2)
(You should see the broken border in that row)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: COUNT(DISTINCT X) MySQL Query doesn't give results I need In MySQL I have a query to count all of the browsers from a page_views table that I want to aggregate. Here's my query:
SELECT
Browser,
COUNT(*)
FROM page_views
WHERE PageID = 58
GROUP BY Browser;
which gives, for example:
Chrome 14
Firefox 17
Internet Explorer 9
Opera 5
Safari 3
--------------------
Total 48
This is exactly what I want. It works fine and it's fast. Now I wanted to to a distinct on the IP address to remove users that have viewed the page more than once. I added DISTINCT in the COUNT so it looks like this:
SELECT
Browser,
COUNT(DISTINCT IPAddress)
FROM page_views
WHERE PageID = 58
GROUP BY Browser;
This looks like it works but in reality, I don't think it does. In my real-world environment, I do aggregates on multiple columns, one for Browser, on for day of the week, one for the month etc... so it's one query each but with different GROUP BY. How I noticed that it may not be the result I want is that every one of my queries has a different number for totals. Aggregating the views by browsers gives 48 total views, by day of week gives 45 total views, by month gives 50 total views. Something's not right.
Also, if I do a simple SELECT COUNT(DISTINCT IPAddress) FROM page_views WHERE PageID = 58 I get much less page views that the other aggregate queries have as a total.
Again, what I want is the first query I put above but only aggregate once for each IPAddress so it basically calculates the unique viewers of a page and not the total of views a page has.
What am I doing, or not doing correctly to get the results I want?
Thank you.
A: If you do:
SELECT
Browser,
day_of_the_week,
month_of_the_year,
COUNT(DISTINCT IPAddress)
FROM page_views
WHERE PageID = 58
GROUP BY Browser, day_of_the_week,month_of_the_year
The total of count(distinct) will no be the same as in your simple query.
If you want to eliminate duplicate IP-adresses in the same day, you'll need something like this:
SELECT
p1.Browser
, p1.pageID
, p1.WEEKDAY(`date`) as day_of_week
, p1.MONTH(`date`) as The_month
, COUNT(p2.Unique_visitors_this_day) as uniqueviews
FROM page_views p1
LEFT JOIN (SELECT id, 1 as Unique_visitors_this_day FROM page_views pv1
LEFT JOIN page_views pv2 ON (pv1.id > pv2.id
AND pv1.ipaddress = pv2.ipaddress
AND pv1.`date` = pv2.`date`)
WHERE pv2.id IS NULL) as p2
ON (p1.id = p2.id)
WHERE p1.PageID = 58
GROUP BY p1.Browser, p1.day_of_week, p1.The_month;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Windows Explorer Shell Extension: recursive delete via ITransferSource::RemoveItem? I'm implementing a Windows Explorer Shell Extension for a networked file system on Windows 7, and I've hit a snag while implementing the Delete functionality.
Let's say my remote filesystem hierarchy is as follows:
Dir1
+-Dir2
| +-A
| +-B
+-C
My understanding is that you need to implement ITransferSource::RemoveItem (which I've done), but I expected to be called recursively from the furthest child in the filesystem tree first (i.e. a depth-first recursive traversal):
(A, B, Dir2, C, Dir1)
What happens is that I'm called for the root first, then each children, iteratively:
(Dir1, C, Dir2, A, B)
This is a bit weird to me since the Shell will already recursively iterate through all items to be deleted in order to show the progress bar for the operation (the "discovering items" dialog). My remote filesystem does not support deleting non-empty directories; as far as I know, the local filesystem on Windows has the same limitation. I could not find any hints on MSDN about changing the iteration order.
I presume that the actual iteration order varies depending on the creation order of the items in the filesystem.
When implementing this interface method, you can return COPYENGINE_S_DONT_PROCESS_CHILDREN if you recurse and delete entire trees yourself, but I think this will not allow the user to Cancel a deletion in progress (like the standard Explorer shell would). I consider this a sub-optimal solution, but it may have to do if I don't find a better solution.
My first thought was to queue up the non-empty directory deletion requests for later, but I don't think this will work, because the extension will not know when the Delete operation for all children of a directory is completed. I could also spawn a thread to delete these items "later" but that's almost certain to create weird unexplained behaviors and crashes.
So, I guess my question is, what is the proper way to implement the Delete operation in a Windows 7 Shell Extension?
PS: as you can probably tell, Windows Shell Extensions are a completely new topic for me, so I apologize in advance if the question is incomplete; I will refine my question as needed.
Thanks!
A: From the documentation it looks like the EnterFolder and LeaveFolder methods will help you out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dynamic Multi-Column SQL I have two tables with structures like this:
VelocityBase
Aisle | ItemId | ConfigId | InventSizeId | InventColorId | InventLocationId | DataAreaId | VelocityCategory
VelocitySalesCount
ItemId | ConfigId | InventSizeId | InventColorId | InventLocationId | DataAreaId | Sales
Every row in the Base table represents a SKU and the sum of the related SalesCount records' "Sales" fields determines the "Picks". This query works:
SELECT Aisle, COUNT(*) as '# SKUs',
SUM(Sales) as '# Picks',
SUM(CASE WHEN VelocityCategory = 'Hot' THEN 1 ELSE 0 END) as 'Hot SKUs',
SUM(CASE WHEN VelocityCategory = 'Hot' THEN SALES ELSE 0 END) as 'Hot Picks',
SUM(CASE WHEN VelocityCategory = 'Warm' THEN 1 ELSE 0 END) as 'Warm SKUs',
SUM(CASE WHEN VelocityCategory = 'Warm' THEN SALES ELSE 0 END) as 'Warm Picks',
SUM(CASE WHEN VelocityCategory = 'Cold' THEN 1 ELSE 0 END) as 'Cold SKUs',
SUM(CASE WHEN VelocityCategory = 'Cold' THEN SALES ELSE 0 END) as 'Cold Picks'
FROM [dbo].[VelocityBase] Base
LEFT OUTER JOIN [dbo].[VelocitySalesCount] SalesCount
ON Base.ItemId = SalesCount.ItemId
AND Base.ConfigId = SalesCount.ConfigId
AND Base.InventSizeId = SalesCount.InventSizeId
AND Base.InventColorId = SalesCount.InventColorId
AND Base.InventLocationId = SalesCount.InventLocationId
AND SalesCount.DataAreaId = Base.DataAreaId
GROUP BY Aisle
ORDER BY Aisle
However, the columns are hard coded. What I would like is that the "Hot", "Warm", "Cold", etc be generated based on what values are present in the database for this column. That way if a user added a row that had "Lukewarm" as the VelocityCategory, two new columns would appear with that data.
I'm not sure if something like SQL to generate SQL or maybe a PIVOT function would do the trick.
Thanks in advance!
EDIT:
I'm narrowing in. I've got the Sum of the Sales figures using this:
DECLARE @SQLStatement NVARCHAR(4000)
,@PivotValues NVARCHAR(4000);
SET @PivotValues = '';
SELECT @PivotValues = @PivotValues + ',' + QUOTENAME(VelocityCategory)
FROM
(
SELECT DISTINCT VelocityCategory
FROM dbo.VelocityBase
) src;
SET @PivotValues = SUBSTRING(@PivotValues,2,4000);
SELECT @SQLStatement =
'SELECT pvt.*
FROM
(
SELECT Aisle, VelocityCategory, Sales
FROM VelocityBase Base
LEFT OUTER JOIN [dbo].[VelocitySalesCount] SalesCount
ON Base.ItemId = SalesCount.ItemId
AND Base.ConfigId = SalesCount.ConfigId
AND Base.InventSizeId = SalesCount.InventSizeId
AND Base.InventColorId = SalesCount.InventColorId
AND Base.InventLocationId = SalesCount.InventLocationId
AND SalesCount.DataAreaId = Base.DataAreaId
) VelocityBase
PIVOT ( Sum(Sales) FOR VelocityCategory IN ('+@PivotValues+') ) pvt';
EXECUTE sp_executesql @SQLStatement;
Thanks for the link to the previous question which got me this far.
A: I usually do not use PIVOT, just "usual" dynamic SQL like this:
DECLARE @sSQL NVARCHAR(MAX)= '' ,
@sSQLSum NVARCHAR(MAX)= '' ,
@sSQlBegin NVARCHAR(MAX)= '
SELECT Aisle, COUNT(*) As ''# SKUs'',
SUM(Sales) As ''# Picks'',
' ,
@sSQLEnd NVARCHAR(MAX)= 'FROM [Dbo].[VelocityBase] Base
LEFT OUTER JOIN [Dbo].[VelocitySalesCount] SalesCount
ON Base.ItemId = SalesCount.ItemId
AND Base.ConfigId = SalesCount.ConfigId
AND Base.InventSizeId = SalesCount.InventSizeId
AND Base.InventColorId = SalesCount.InventColorId
AND Base.InventLocationId = SalesCount.InventLocationId
AND SalesCount.DataAreaId = Base.DataAreaId
GROUP BY Aisle
ORDER BY Aisle' ;
WITH c AS ( SELECT DISTINCT
VelocityCategory N
FROM Dbo.VelocityBase
)
SELECT @sSQLSum = @sSQLSum + 'SUM(CASE WHEN c.N=''' + c.N
+ ''' THEN 1 ELSE 0 END ) AS ''' + c.N + ' SKUs'',' + CHAR(13)
+ 'SUM(CASE WHEN c.N=''' + c.N
+ ''' THEN SALES ELSE 0 END ) AS ''' + c.N + ' Sales'',' + CHAR(13)
FROM c
IF(LEN(@sSQLSum))>0
SET @sSQLSum = LEFT(@sSQLSum, ( LEN(@sSQLsum) - 2 ))
SET @sSQL = @sSQlBegin + @sSQLSum + CHAR(13) + @sSQLEnd
EXEC (@sSQL)
A: Unless you generate the query dynamically, I don't think there's a way to generate what you want.
Your problem could be solved easily if your tables were normalized. For instance, the VelocityBase table should have a VelocityCategoryID column instead of a VelocityCategory column. This new column should be a foreign key to a new table called VelocityCategory (or something like that) then your query for this calculation becomes almost trivial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Need simple SQLite database example
Possible Duplicate:
sqlite example program in android
I need to open a database where I know the path/name, I need to read a known value, and write a value. I don't want to write 100 line "helper classes," I simply want to use the classes/functions that already exist. Can anybody provide a a simple example for this? It really shouldn't be more than a few lines of code.
1: Open database:
maybe this? openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
2: Execute SQL to display value (in a Toast perhaps)
3: Close database
Once I understand this basic functionality I will then worry about helper classes etc. Thanks in advance.
EDIT:
Fascinating that every single answer so far links to articles that do EXACTLY what I asked not to do. I just want a simple 3 line example of how to directly open a database and read from it.
A: A very good SQLite tutorial.
A: Run through the notepad tutorial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Tooltip not working with my css Why doesn't my tooltip work with my css in here? http://jsfiddle.net/BG4Sn/
Please see the jsfiddle, the problem is, that with my css included, the tooltip won't show up true box tooltip after mouse enter on links tooltip1 & tooltip2 & tooltip3 . When I remove the link to my css in the html head, it works true.
function tool_tip() {
//var tip = $('.tool_tip').closest('li').find('div').clone();
$('.tool_tip').mouseenter(function () {
var $this = $(this),
$div = $this.closest('li').find('div');
$(this).attr('title', '');
$div.fadeTo(300, 0.9);
}).mousemove(function (e) {
$('.tooltip').css('bottom', e.pageY + -10);
$('.tooltip').css('left', e.pageX + 10);
}).mouseleave(function () {
$('.tooltip').hide();
})
}
tool_tip();
A: The CSS being applied to .tooltip in your style_s.css is different from your JSFiddle. Copy and paste this .tooltip style into style_s.css:
.tooltip {
background-color: #E5F4FE;
display: none;
padding: 5px 10px;
background-color: #E5F4FE;
border: #5A5959 1px solid;
position: fixed;
z-index: 9999;
color: #0C0C0C;
font-size: 0.688em;
}
Then linking to style_s.css will produce the same style.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Output precision is higher than double precision I am printing some data from a C++ program to be processed/visualized by ParaView, but I am having a problem with floating point numbers. Paraview supports both Float32 and Float64 data types. Float64 is equivalent to double with the typical limits +/-1.7e +/- 308. But, my code is printing numbers like 6.5e-318. This is throwing errors in ParaView when reading the data. I have verified that rounding those smalls numbers to zero make the errors in ParaView disappear. I am not sure why I have such "high precision" output, maybe is because some numbers are stored in higher precision than double. For example, the following code reproduces the same behavior on my system:
#include <iostream>
int main(void)
{
const double var1 = 1.0e-318, var2 = 1.5e-318;
std::cout << 1.0e-318 << std::endl;
std::cout << var1 << std::endl;
std::cout << var1 - var2 << std::endl;
std::cout.setf(std::ios_base::fixed | std::ios_base::scientific, std::ios_base::floatfield);
std::cout << 1.0e-318 << std::endl;
std::cout << var1 << std::endl;
std::cout << var1 - var2 << std::endl;
return 0;
}
My output is:
9.99999e-319
9.99999e-319
-4.99999e-319
9.99999e-319
9.99999e-319
-4.99999e-319
My system is a Mac OS X Snow Leopard and I tested the above with GCC 4.2 and GCC 4.6 with the flags -m32, -m64 and -ffloat-store (not sure if this is useful).
Actually the output for me is fine, but for ParaView is not. I just want to know why I have this difference. I am very likely ignoring something related with floating point numbers which could be important. Could you please please give me some clue about this output/numerical behavior for doubles?
A: Subnormal numbers, i.e. numbers with the smallest-possible exponent and leading zeros in the fraction, can be smaller than 1E-308, down to 1E-324. You can probably filter them out using std::numeric_limits.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: count tabs gather data from tabbed delimited text .JSX Adobe InDesign I need to know how to read data from tabbed delimited text file in order to export merged documents to correct location.
-- will always be 4th tab 2nd row (group number) directory will be named by group number
-- have directories already created by privious .vbs script
data will have to be placed:
app.open(File(dirPath + "Card~" + (group number) + ".indd"));
and also:
fileName = (group number) + " " + myPageName + " " + date + ".pdf";
myFilePath = dirPath + docType + "/" + fileName;
myFile = new File(myFilePath);
myDocument.exportFile(ExportFormat.pdfType, myFile, false);
within previous .vbs script to work with this data file was written as so:
Call TwoDimensionArrayTest
Sub TwoDimensionArrayTest
Dim fso
Dim oFile
Dim arrline
Dim arrItem
Dim i
Dim arrMain()
Dim sFileLocation, strResults
Dim filesys, folder, path
Const forReading = 1
strFolder = "P:\RxCut\In Design Implementation\build\Co-Brand\"
mkdir = "P:\RxCut\In Design Implementation\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFile In objFSO.GetFolder(strFolder).Files
If Right(LCase(objFile.Name), 4) = LCase(".txt") Then
' The file contains on each line:
' Text1 (tab) Text2 (tab) Text3 (tab) Text4
' Text5 (tab) Text6 (tab) Text7 (tab) Text8
'etc etc
Set fso = CreateObject("Scripting.FileSystemObject")
sFileLocation = objFile.Name
Set oFile = fso.OpenTextFile(objFile.Name, forReading, False)
Do While oFile.AtEndOfStream <> True
strResults = oFile.ReadAll
Loop
' Close the file
oFile.Close
' Release the object from memory
Set oFile = Nothing
' Return the contents of the file if not Empty
If Trim(strResults) <> "" Then
' Create an Array of the Text File
arrline = Split(strResults, vbNewLine)
End If
For i = 0 To UBound(arrline)
If arrline(i) = "" Then
' checks for a blank line at the end of stream
Exit For
End If
ReDim Preserve arrMain(i)
arrMain(i) = Split(arrline(i), vbTab)
Next
path = arrMain(1)(3)
dir = mkdir & path
set filesys=CreateObject("Scripting.FileSystemObject")
If Not filesys.FolderExists(dir) Then
Set folder = filesys.CreateFolder(dir)
End If
dir = mkdir & path
Set folder = filesys.CreateFolder(dir & "\Web")
Set folder = filesys.CreateFolder(dir & "\Web\Web Cards")
Set folder = filesys.CreateFolder(dir & "\Web\Web Headers")
fso.MoveFile sFileLocation, arrMain(1)(3) & ".txt"
End If
Next
End Sub ' TwoDimensionArrayTest
How can I achieve something similar in .jsx?
A: Figured it out this will read 1,3 and create a variable for group number 1,3
var aFile = File("P:/RxCut/In Design Implementation/build/automate/automate.txt");
var fileData = readTabDelimitedFile ( aFile ) ;
//$.writeln(fileData[1][3]); //should contain first tab on second line
tstdata = fileData[1][3];
var group = tsdata
function readTabDelimitedFile ( fPath ) {
var returnArray = new Array ( ) ;
//-- Verify that the file exists
var fileObject = File ( fPath ) ;
if ( ! fileObject.exists ) {
return returnArray ; // an empty array because the file doesn't exist.
}
//-- Create a regular expression for a tab.
var tabExpression = new RegExp ( '\\t' ) ;
//-- Read the file.
try {
//-- The file has to be open.
fileObject.open ('r') ; //-- Open for reading.
while ( ! fileObject.eof ) {
var currentLine = fileObject.readln () ;
if ( tabExpression.test( currentLine ) ) {
returnArray.push(currentLine.split ('\t')) ;
}
}
fileObject.close() ;
}
catch (errMain) {
try {
fileObject.close() ;
}
//-- if the close generates an error skip it.
catch (errInner ) { /* nothing here */ }
}
return returnArray ;
var group = returnArray
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Know Active Timer In Android, after starting any timer using TIMER or CountDownTimer, is there any way to track them?
For example, if we start 5 timer and we want to stop the second one(or update it), how to do that stuff?
Thanks in advance.
A: put all of them in a list, set timer's tag an id (id from the list) and set listener. so when any of the timers are ticking or finish, you will be notified and you can identify them by id from the tag
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can FindComponent Be Used To Find A Ruler on a PageControl Created at Runtime Actually I am using a ImageEN TRulerBox and a TAdvOfficePager (TMS) rather than a TPageControl; however, the TAdvOfficePager functions the same way as a TPageControl aside from property names.
Two ImageEN TRulerBoxes and a TImageENView are added to a TAdvOfficePage at runtime. The ruler orientation is set by the RulerDir property of the TRulerBox. Can FindComponent be used to find a HorzontalRulerBox and a VerticalRulerBox?
The controls are created at runtime like this:
procedure TFormMain.AddPage;
var
AdvOfficePage: TAdvOfficePage;
PixelPanel: TPanel;
begin
AdvOfficePage := TAdvOfficePage.Create( Self );
AdvOfficePage.Parent := AdvOfficePager1;
AdvOfficePager1.AddAdvPage( AdvOfficePage );
AdvOfficePage.AdvOfficePager := AdvOfficePager1;
AdvOfficePage.Caption := 'ImageEnView ' + IntToStr( AdvOfficePager1.AdvPageCount );
AdvOfficePage.TabHint := 'ImageEnView ' + IntToStr( AdvOfficePager1.AdvPageCount );
TopPanel := TPanel.Create( Self );
TopPanel.Parent := AdvOfficePage;
TopPanel.Height := 34;
TopPanel.Align := alTop;
TopPanel.Color := $00fcebdc;
TopPanel.BorderStyle := bsNone;
TopPanel.BevelOuter := bvNone;
PixelPanel := TPanel.Create( TopPanel );
PixelPanel.Parent := TopPanel;
PixelPanel.Height := 40;
PixelPanel.Width := 34;
PixelPanel.Caption := 'Pix';
PixelPanel.Align := alLeft;
PixelPanel.Color := $00fdf3eb;
PixelPanel.ParentBackground := False;
PixelPanel.BorderStyle := bsNone;
PixelPanel.BevelOuter := bvNone;
HorzontalRulerBox := TRulerBox.Create( TopPanel );
HorzontalRulerBox.Name := 'HorzontalRulerBox' + IntToStr( AdvOfficePager1.AdvPageCount );
HorzontalRulerBox.Parent := TopPanel;
HorzontalRulerBox.Align := alClient;
HorzontalRulerBox.BackGround := $00fdf3eb;
HorzontalRulerBox.RulerColor := $00fdf3eb;
HorzontalRulerBox.GripBaseDim := 1;
HorzontalRulerBox.RulerDir := rdHorizontal;
LeftPanel := TPanel.Create( Self );
LeftPanel.Parent := AdvOfficePage;
LeftPanel.Width := 30;
LeftPanel.Align := alLeft;
LeftPanel.Color := $00fdf3eb;
LeftPanel.BorderStyle := bsNone;
LeftPanel.BevelOuter := bvNone;
VerticalRulerBox := TRulerBox.Create( LeftPanel );
VerticalRulerBox.Name := 'VerticalRulerBox' + IntToStr( AdvOfficePager1.AdvPageCount );
VerticalRulerBox.Parent := LeftPanel;
VerticalRulerBox.Align := alClient;
VerticalRulerBox.BackGround := $00fdf3eb;
VerticalRulerBox.GripBaseDim := 1;
VerticalRulerBox.RulerDir := rdVertical;
VerticalRulerBox.BackGround := $00fdf3eb;
VerticalRulerBox.RulerColor := $00fdf3eb;
ImageENView := TImageEnView.Create( Self );
ImageENView.Parent := AdvOfficePage;
ImageENView.Left := 0;
ImageENView.Top := 0;
ImageENView.Align := alClient;
ImageENView.Center := True;
ImageENView.Visible := True;
ImageENView.BorderStyle := bsNone;
ImageENView.MouseInteract := [ miSelect ];
AdvOfficePager1.ActivePage := AdvOfficePage;
end;
If FindComponent can not be used how do you get the handle to each of the two rulers at runtime? I hope I have asked this question correctly and the information provided is clear.
I tried this but it returns nil:
function TFormMain.GetHorzontalRuler: TRulerBox;
// find horzontal TRulerBox component on a TPanel on a TAdvOfficePage
var
rb: TRulerBox;
begin
rb := AdvOfficePager1.ActivePage.FindComponent( 'HorzontalRulerBox' + IntToStr( AdvOfficePager1.ActivePageIndex ) )
as TRulerBox;
if Assigned( rb ) then
Result := rb
else
Result := nil;
end;
NEW: - this works
function TFormMain.GetHorzRuler: TRulerBox;
var
tp: TPanel;
rb: TRulerBox;
begin
Result := nil;
tp := FindComponent( 'TopPanel' + IntToStr( AdvOfficePager1.ActivePageIndex + 1 ) ) as TPanel;
if Assigned( tp ) then
begin
rb := TRulerBox( tp.FindComponent( 'HorzontalRulerBox' + IntToStr( AdvOfficePager1.ActivePageIndex + 1 ) ) );
if Assigned( rb ) then
Result := rb;
end
else
Result := nil;
end;
function TFormMain.GetVertRuler: TRulerBox;
var
tp: TPanel;
rb: TRulerBox;
begin
Result := nil;
tp := FindComponent( 'LeftPanel' + IntToStr( AdvOfficePager1.ActivePageIndex + 1 ) ) as TPanel;
if Assigned( tp ) then
begin
rb := TRulerBox( tp.FindComponent( 'VerticalRulerBox' + IntToStr( AdvOfficePager1.ActivePageIndex + 1 ) ) );
if Assigned( rb ) then
Result := rb;
end
else
Result := nil;
end;
Thanks All
A: You made TopPanel the owner of HorzontalRulerBox (btw, it's HorIzontal :) ), so you need to search it with FindComponent instead, but you'll have to first search TFormMain for TopPanel,and give TopPanel a name in your code.
var
TP: TPanel;
rb: TRulerBox;
begin
TP := FindComponent('TopPanel') as TPanel;
if Assigned(TP) then
begin
rb := TP.FindComponent('HorzontalRulerBox` + IntToStr(whatever));
if Assigned(rb) then
// Work with ruler box
end;
end;
A: The function FindComponent must be used by the Owner component.
The owner can be different than the parent, so be carefull.
In your example, the owner component is maybe the form, or the OfficePager.
Try replacing AdvOfficePager1.ActivePage by self (to reference the form) or AdvOfficePager1 - I don't use these components so I'm not sure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery event delegation variable scope with consecutive calls With event delegation in jQuery 1.6, you can respond to events that have bubbled up to a common parent.
A sample implementation is like this:
(function($){
$.fn.myeventhandler = function () {
return this.delegate('a.next, a.prev', 'click customEvent', function (event) {
var target=$(event.target);
var bar = null;
if('click' == event.type) { /*~[ call this 'a' ]~*/
// handle the click event
$('#next-element').animate({width:'200px'},1300,function(){
bar = 'value1';
$('#next-element').animate({width:'100px'},1300,function(){
bar = 'value2';
console.log(bar);
});
});
} else if('customEvent' == event.type) { /*~[ call this 'b' ]~*/
// handle the customEvent event
$('#my-element').animate({height:'200px'},1300,function(){
bar = 'my-event1';
console.log(bar);
});
}
return false;
});
}
})(jQuery);
This kind of structure can work really well when you have many event triggers you want to have bound on a page. However, I've noticed a curious behaviour and wondered if someone could enlighten me on the scope of the following:
If you define a variable 'var bar;' before 'a' and use it in 'a' and 'a' takes a long time to execute, then if 'click' is triggered a second time, would the 'bar' variable be reassigned the value or would a new one be created?
The reason for the question is that I've got an 'unfinished' animation in which the animation takes 1.3 seconds to complete. If I trigger two consecutive click events, the target and type are correctly set, but the second animation appears to be affecting the first one and the two scopes appear to be available to each other.
I haven't yet finished the animation, so I haven't got a working set to put online in jsFiddle, but is there any rule of thumb for scope here that I should be researching or some clearer explanation of scope available someone may have found?
EDIT:
In the above, I've added in a situation similar to what I'm using. In the simplified case above, the value of 'bar' still holds the expected value on 2 consecutive calls, but in the more complicated case I am working through (still), unless I pass the parameters into the callback function specifically, there is still a condition that's allowing 2 consecutive calls to change the value of the parameter such that the callback sees a value created by a subsequent call - not the value that was logically set in its own triggered call. If anyone can replicate this effect on a simplified example, I'd appreciate it. I'm whittling down my functions to try to produce a jsFiddle that replicates it.
Thanks,
AE
A: If you click it a second time then a new bar variable would be created, both bar values would be independent of each other. To see this in action i created a fiddle. Click twice fast and you will notice that the second time bar takes the default value and not the value that the initial bar variable had, which is expected.
A: The event object is passed around instead of being newly created with various events, therefore, 'a' would not be re-assigned, but would be affected by both event actions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: display:table adds padding/margin in webkit browsers but not FF or IE I'm working on some boxes where I'm forced to using the following css on a div in order to make it look right:
display:table;
It works fine in Firefox + Internet Explorer, but I just noticed that it adds a 1px border/margin/padding in webkit browsers (Safari / Chrome), which moves the box a bit... How can I get rid of this?
I've uploaded a picture example of how it's rendered:
http://imageshack.us/photo/my-images/854/examplez.jpg/
Is there a "simple way" of determining in the stylesheet whether you are using a webkit browser or not? Because then I could just add a "margin-left:-1px".. I know there is a way of determining the browsertype in jQuery, but I think it's kind of overkill for this..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Extreme XSLT XML Flattening I have the following input XML file:
<root>
<a>
<b>1</b>
</a>
<c>
<d>
<e>2</e>
<f>3</f> or <e>3</e>
</d>
<g h="4"/>
<i>
<j>
<k>
<l m="5" n="6" o="7" />
<l m="8" n="9" o="0" />
</k>
</j>
</i>
</c>
</root>
I would like to use XSLT to transform it into the follow outputs:
OUTPUT 1
<root>
<row b="1" e="2" f="3" h="4" m="5" n="6" o="7" />
<row b="1" e="2" f="3" h="4" m="8" n="9" o="0" />
<root>
OUTPUT 2
<root>
<row b="1" e="2" h="4" m="5" n="6" o="7" />
<row b="1" e="2" h="4" m="8" n="9" o="0" />
<row b="1" e="3" h="4" m="5" n="6" o="7" />
<row b="1" e="3" h="4" m="8" n="9" o="0" />
<root>
Can anyone help my XSLT isn't very strong. Thanks.
A: It will be easier if you let the occurrence of <e> determine the outer loop constructing your <row>s and have a inner loop iterating over all <l>s.
Try something like this:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="root">
<root>
<xsl:apply-templates />
</root>
</xsl:template>
<xsl:template match="e">
<!-- store values of 'e' and 'f' in params -->
<xsl:param name="value_of_e" select="." />
<xsl:param name="value_of_f" select="ancestor::d[1]/f" />
<!-- iterate over all 'l's -->
<xsl:for-each select="//l">
<xsl:element name="row">
<xsl:attribute name="b">
<xsl:value-of select="//b" />
</xsl:attribute>
<xsl:attribute name="e">
<xsl:value-of select="$value_of_e" />
</xsl:attribute>
<!-- only include 'f' if it has a value -->
<xsl:if test="$value_of_f != ''">
<xsl:attribute name="f">
<xsl:value-of select="$value_of_f" />
</xsl:attribute>
</xsl:if>
<xsl:attribute name="h">
<xsl:value-of select="ancestor::c[1]/g/@h" />
</xsl:attribute>
<xsl:attribute name="m">
<xsl:value-of select="./@m" />
</xsl:attribute>
<xsl:attribute name="n">
<xsl:value-of select="./@n" />
</xsl:attribute>
<xsl:attribute name="o">
<xsl:value-of select="./@o" />
</xsl:attribute>
</xsl:element>
</xsl:for-each>
</xsl:template>
<xsl:template match="b" />
<xsl:template match="f" />
<xsl:template match="g" />
</xsl:stylesheet>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I get "undefined method" calling by Rails model, but works fine calling by Rails console I receive undefined method scan for User:Class when scan method
(line 13: last = resp.headers['Link'].scan(/\d+/).last)
is called by Rails User model (inside class method self.create_user(auth)) :
class User
include Mongoid::Document
field :email
field :nickname
embeds_many :posts
def self.create_user(auth)
conn = FaradayStack.build 'https://api.example.com'
resp = conn.get "/users/#{auth.nickname}/list"
last = resp.headers['Link'].scan(/\d+/).last # <== error occurs here
n = 0
create! do |user|
user.email = auth["user_info"]["email"]
user.nickname = auth['user_info']['nickname']
while n <= last.to_i do
resp = conn.get "/users/#{auth.nickname}/list?page=#{n=n+1}"
resp.body.each do |repo|
user.posts.build( html_url: "#{repo['html_url']}",
description: "#{repo['description']}",
created_at: "#{repo['created_at']}",
pushed_at: "#{repo['pushed_at']}",
avatar_url: "#{repo['owner']['avatar_url']}" )
end
end
end
end
end
If I call the same code by Rails console it works fine :
ruby-1.9.2-p136 :158 > last = resp.headers['Link'].scan(/\d+/).last
=> "16"
ruby-1.9.2-p136 :159 > last = resp.headers['Link'].scan(/\d+/).last.to_i
=> 16
ruby-1.9.2-p136 :160 >
Something related to istance and class method concept I guess,
but I can't fix it.
UPDATE:
On suggestion of jimworm, I put rails logger instead of "offending" line :
Rails.logger.info "\r\n" + "#{Time.now} " + "resp.headers['Link']: #{resp.headers['Link']}" + "\r\n"
what I get is :
2011-09-30 16:40:03 +0200 resp.headers['Link']:
Redirected to http://localhost:3001/
Completed 302 Found in 3151ms
MONGODB blumb_dev['users'].find({:_id=>BSON::ObjectId('4e85d4c41d41c8103f000006')})
while in Rails console it is :
ruby-1.9.2-p136 :181 > resp.headers['Link']
=> "<https://api.example.com/users/lgs/list?page=18>; rel=\"next\", <https://api.example.com/users/lgs/list?page=51>; rel=\"last\""
ruby-1.9.2-p136 :182 >
Any idea ?
A: Our hero was perplexed... it worked in the console, surely it'll work from the controller? The village will be doomed if the bug wasn't caught. He decided to take a snapshot of the bug, catch it in the act.
Rails.logger.info...
The trap was set, then he waited. The screen flashed. A hit! The bug has left its traces in our trap. Our hero looked and...
to his surprise, the trap was empty!
2011-09-30 16:40:03 +0200 resp.headers['Link']: #nothing here#
"Now how could that be" he wondered, "a bug that left no traces? What kind of bug leaves no traces?"
Then it came to him. "Eureka, a nil!" he smacked the table triumphantly, "a nil appears as nothing in the log! That's why I couldn't scan it!"
The identity of the bug was revealed, and it wasn't long before our hero traced it back to its home at api.example.com and mashed it once and for all. Turns out it was the messages that the village was sending to api.example.com that lured the bug out of hiding. Now with the bug gone, the village was saved and everyone lived in peace, happily ever after.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XCode include necessary header files In Eclipse you can press Cntrl + Shift + O and all of the necessary includes will be added to your file automatically. Is there anything similar to this in XCode?
A: No, there isn't. You have to add them yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hashing function of any live object (hash table)? Not sure whether it is sensible reopen my earlier thread on Hashing URL.
Nonetheless, I am still curious know how this work undercover.
Assumption: We have a hashtable with n (where n < Infinity) element where asymptotic time complexity is o(1); we (CLR) have achieved this while applying some hashing function ( Hn-1 hash function where n>1).
Question: Can someone explain me how CLR map Key to the hash code when we seek (retrieve) any element (if different hashing functions are used)? How CLR track (if it) the hashing function of any live object (hash table)?
Thanks in advance.
A: A hash code does not uniquely identify an object. It's just used to quickly put that object into a bucket. The elements in one bucket may but need not be equal, but elements in different buckets must be unequal.
Conceptually you can think of the default GetHashCode() implementation on reference types as using a field in every instance containing a random value for the hashcode which gets initialized on object creation. The actual implementation is a bit more complex but that doesn't matter here.
Since there are only 2 billion different hash codes, the O(1) runtime of most hash table implementations will break down if you have more elements than that. And of course the distribution must be good, i.e. there must not be too many hash collisions, but having a few is no big problem.
For types with value semantics you override both Equals and GetHashCode consistently to use the fields which determine equality.
A: Conceptually, there are two hash functions. The first hash function, as you probably have guessed, is the key object's GetHashCode method. The second hash function is a hash of the key returned by the first hash function.
So, imagine a hash table that has a capacity of 1,024 items, and you're going to insert two keys: K1 and K2.
K1.GetHashCode() returns 1,023. K2.GetHashCode() returns 65,535
The code then divides the returned key by the hash table size and takes the remainder. So both of the keys map to position 1,023 in the hash table.
K1 is added to the table. When it comes time to add K2, there is a collision. So the code resorts to the second hash function. That second hash function is probably a "bit mixer" (often the last stage in calculating a hash code) of some sort that randomizes the bits in the returned key. Conceptually, the code would look something like this:
int hashCode = K2.GetHashCode();
int slot = hashCode % 1024;
if (table[slot] != null)
{
int secondHashCode = BitMixer(hashCode);
slot = secondHashCode % 1024;
}
The point here is that the code doesn't have to keep track of multiple hash functions for the different keys. It knows that it can call Key.GetHashCode() to get the object's hash code. From there, it can call its own bit mixer function or functions to generate additional hash codes.
A: Not sure if I understand you question well, but every object in .NET implements GetHashCode function which returns a hash code usable (and used) in dictionaries / hashtables, so the object itself is responsible for generating a good hash code.
Of course, there may (and will) be conficts as the hash code is an int. The conflicts are handled / resolved by the dictionary / hashtable.
A: Every object implements the GetHashCode() function and Equals() function.
The default implementations for these are related to the object references. For example a.Equals(b) would return the same as object.ReferenceEquals(a,b). This would mean if two object references are equal so is their Hash Codes.
There are cases that you need to provide a different semantic to the Equals() function. In these cases you must maintain the contract that if a.Equals(b) then a.GetHashCode() == b.GetHashCode().
Hashing functions used are many and each with its own advantages and disadvantages. There is a useful explanation here. The actual function used is not something you should worry about, what is most important to keep the average o(1) lookup time in the Hashtable is (ideally) ensure that the objects which will be inserted have their GetHashCode() result is as close to uniformly distributed as possible.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: fatal: remote error: Could not find Repository octocat/myapp I am using Git for the first time and just forked one open source project following GitHub's instructions.
I am able to clone my fork on local computer but I get an error when running these commands:
$git remote add upstream git://github.com/octocat/myappname.git
$ git fetch upstream
git fetch gives me this error:
fatal: remote error: Could not find Repository octocat/myappname
How can I resolve this error and fetch the project?
A: It doesn't look like you did a straight copy/paste from the docs, but just to be sure, your environment might not be set up correctly. If the repo you're forking is called testproject , your username is me and their username is they :
You should have forked and then cloned your repo. Your repo's address is ssh://git@github.com/me/testproject notice the ssh protocol
Then, you should have added they's repo as an upstream repo (that's the git remote add upstream). Github provides a link you can copy there, but you should use the git protocol if possible (see VonC's note about git, http and firewall). The command to add the upsteam repo is git remote add upstream git://github.com/they/testproject Note that upstream is arbitrary. You can name it upstream or anything else you want. Also, make sure to get the /they and /testproject right as that will cause errors if the repo doesn't exist in that user's account
A: You should put your username instead of octocat. The account octocat just has the repositories Spoon-Knife and Hello-World and is an testaccount from the company Github.
Or did you fork the Spoon-Knife repository from octocat?
A: Try using http address (or https address if you need to also push)
git remote add upstream http://github.com/octocat/myappname
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Recommendations for optimizing NHibernate with Large Amounts of Data I have a rather complex mapping for some of my class objects for NHibernate. I have everything mapping correctly; however, it is taking approximately 10-15 minutes to save the items and over 21 minutes to load them, which of course is unacceptable.
Here is my situation.
I have 3 classes, lets call them Foo, Bar, and Test. Class Foo has a property that is a list with a many-to-one mapping of class Bar. Bar has a property that is a list with a many-to-many mapping of class Test. Finally Test has a property that is a list with a many-to-many mapping of class Bar. All three classes have various other properties associated with them of other class types which are being loaded.
I currently don't have lazy loading enabled at the moment, which I plan on trying to implement soon, but the problem I am facing is that many of the properties for the 3 classes are needed right away.
My first question is this. I have 250 Foo classes saved, 500 Bar classes, and 1000 Test classes. On loading my first Foo class, it is loading the Bar's that are in its list, which conversely contain a List of all 1000 Test classes, each Test class has a list of all the 500 Bar classes. Is NHibernate data aware enough to know that the 1000 Test classes have been loaded and the 500 Bar classes have already been loaded, so when it moves to the next Foo class it doesn't have to reload all the Bar and Test classes again?
What would you guys recommend to boost the performance?
A: *
*Enable Lazy-Load
*Check NHibernate logs to see what is exactly selected or use NHibernate Profiler
*Consider using cache
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I fix the indentation of selected lines in Visual Studio In vim I can use = to reindent badly indented lines so
foo;
bar;
baz;
becomes
foo;
bar;
baz;
Is there an equivalent keyboard-shortcut for visual studio? Where can I find a list of such shortcuts for future reference?
Edit: Is there a way to do fix just the horizontal indentation? There are some cases where the CTRLK,CtrlF is "fixing" too much. (In the meantime I'll see if I can edit the formatting options to my satisfaction...)
A:
For the Mac users.
For selecting all of the code in the document => cmd+A
For formatting selected code => cmd+K, cmd+F
A: I like Ctrl+K, Ctrl+D, which indents the whole document.
A: To fix the indentation and formatting in all files of your solution:
*
*Install the Format All Files extension => close VS, execute the .vsix file and reopen VS;
*Menu Tools > Options... > Text Editor > All Languages > Tabs:
*
*Click on Smart (for resolving conflicts);
*Type the Tab Size and Indent Size you want (e.g. 2);
*Click on Insert Spaces if you want to replace tabs by spaces;
*In the Solution Explorer (Ctrl+Alt+L) right click in any file and choose from the menu Format All Files (near the bottom).
This will recursively open and save all files in your solution, setting the indentation you defined above.
You might want to check other programming languages tabs (Options...) for Code Style > Formatting as well.
A: Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works.
However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker.
ymmv.
A: Selecting all the text you wish to format and pressing CtrlK, CtrlF shortcut applies the indenting and space formatting.
As specified in the Formatting pane (of the language being used) in the Text Editor section of the Options dialog.
See VS Shortcuts for more.
A: Update for Visual Studio 2022: You can click this button to format the entire document:
You can also see the keyboard shortcut on hover. Note: this may apply additional formatting other than just indentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "104"
}
|
Q: Populate Object using Ajax and Jquery As the title says, I'm trying to populate the properties of an object using jQuery-Ajax. I've been trying to find the right way to do it for hours, but couldn't make it work...
This is my code:
function Persona(){
this.nombre;
this.apellido;
this.buscarNombre= function(callback){
$.get("nombre.php", function(datos){
datos = eval("(" + datos + ")");
this.nombre = datos.nombre;
this.apellido = datos.apellido;
alert(this.nombre);
})
};
}
$(document).ready(function(){
var pp = new Persona();
alert(pp.nombre);
}
I think the problem is the scope of the function that retrieves the data from the server it's different from the scope of the object, but I don't realize how to pass the data from one place to the other...
The data is arriving perfectly from the web server... I used FireBug to be sure...
Thanks in advance!
A: if you replace alert(pp.nombre); with pp.buscarNombre();. You will get the desired results. And your this reference is wrong:
function Persona(){
var self = this;
this.nombre;
this.apellido;
this.buscarNombre= function(callback){
$.get("nombre.php", function(datos){
datos = eval("(" + datos + ")");
self.nombre = datos.nombre;
self.apellido = datos.apellido;
alert(self.nombre);
})
}
}
$(document).ready(function(){
var pp = new Persona();
pp.buscarNombre();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Relative positioning of geom_text in ggplot2? I am using geom_text to annotate plots in gglot2 and I want use relative positioning rather than absolute. That is, I want a position of (0.5, 0.5) to be dead center regardless of the x and y axis limits. Is that possible?
Alternatively I could of course transform a relative position to an absolute one if I had the x and y limits. Is it possible to extract those from a plot?
A: If you know the range of the data in your plot, you can calculate the "true" x and y limits using the fact that ggplot using an additive expansion factor of 0.05 by default, so that the extents of the graph extend just slightly beyond the actual data values.
You can specify and multiplicative and additive expansion factor when specifying scales using expand = c(mult, add) where mult is the multiplicative factor and so on. So the default setting is expand = c(0,0.05).
A: Yes, it is possible to extract the x and y limits from a ggplot2-plot. This function returns the x and y coordinate of the center of a ggplot2 plot object:
center.position <- function(plot) {
xpos <- (ggplot_build(plot)$panel$ranges[[1]]$x.range[2]-ggplot_build(plot)$panel$ranges[[1]]$x.range[1])/2+ggplot_build(plot)$panel$ranges[[1]]$x.range[1]
ypos <- (ggplot_build(plot)$panel$ranges[[1]]$y.range[2]-ggplot_build(plot)$panel$ranges[[1]]$y.range[1])/2+ggplot_build(plot)$panel$ranges[[1]]$y.range[1]
return(data.frame(x=xpos,y=ypos))
}
If your x-Data is in POSIXct-format, you still have to transform it:
center.coords <- center.position(myplot)
myplot <- myplot + annotate("text",x=as.POSIXct(center.coords$x,origin="1970-01-01"), y=center.coords$y, label="X")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: How to initialize constant member C array in an Objective-C class? how can I create a constant C array member in an Objective-C class? The lifecycle should be limited to the classes lifecycle and I don't want to use malloc.
At the moment I'm doing this:
@interface Bla
{
int myArray[3];
}
@implementation Bla
{
-(id)init
{
myArray[1] = 5;
myArray[2] = 6;
myArray[3] = 7;
return self;
}
}
But I want it constant and initialize it directly, like:
@interface Bla
{
const int myArray[3];
}
@implementation Bla
{
-(id)init
{
myArray[] = { 5, 6, 7 };
return self;
}
}
A: you could take the C approach and use a constant array in your .m:
static const int myArray[3] = { 5, 6, 7 };
the lifetime of this array is the duration of the program, and it does not require malloc or storage per instance.
otherwise, there is really no such thing as a constant value for an objc type's variables (unless you are content with immutable zeroed memory). the best you can do is to make the ivar private and not provide a setter. a const ivar doesn't have much applicability either, since there are few optimizations the compiler could make in this case. of course, you could cast away constness, but that is a bad idea.
one final alternative: you can use a c++ instance which is created using its default constructor.
otherwise, you will have to use a dynamic allocation to create a dynamically populated const member variable.
A: Just as a convention, you shouldn't put curly braces around @implementation.
About your question: the problem I see with the way you're trying to assign you array has the following error:
When you initialize a new ObjC instance of an object, its instance variables are set to zero, so your array will be a[0] == a[1] == a[2] == 0. This is because the allocator will ask for heap memory the size of your object + its ancestors. But later in the code, you're trying to copy memory from the stack to the heap: the { 4, 5, 6} array is created on the stack, and array[] lives on the heap. Do you see the problem here? What I would do, if you insist in doing it this way would be the following:
// compile from command line with
// gcc -framework Foundation -g -Wall -o test test.m
//
#import <Foundation/Foundation.h>
@interface Bla : NSObject
{
int array[3];
}
- (void)checkArray;
@end
@implementation Bla
- (id)init
{
self = [super init];
if (self) {
// init here
int tmpArray[3] = { 4, 5, 6};
memcpy(array, tmpArray, 3 * sizeof(int));
}
return self;
}
- (void)checkArray
{
NSAssert(array[0] == 4, @"invalid array initialization (4)");
NSAssert(array[1] == 5, @"invalid array initialization (5)");
NSAssert(array[2] == 6, @"invalid array initialization (6)");
}
@end
int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
{
Bla *bla = [[Bla alloc] init];
[bla checkArray];
NSLog(@"done");
[bla release];
}
[pool release];
return 0;
}
It's not the best way, and probably you want to stick to using malloc, but this way you won't have to free the array later. Also, keep in mind that doing it this way you won't be able to change the size of array[], doing so will get in trouble for sure :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to manage Infopath VSTA code Situation
We are currently developing a Sharepoint 2010 site that uses Infopath 2010 forms. However most of these forms require more advanced functionality thus these became Adminstrator-approved forms and have c# code on them (VSTA).
Question
Since each infopath form would have its own c# project, we are now having difficulties managing the code as more infopath forms are needed. Is there a better way to manage the code? Or is there a mechanism to have all of the VSTA code in one central location/solution?
A: Here's a link to the InfoPath blog on how to manage InfoPath source code: http://blogs.msdn.com/b/infopath/archive/2010/06/10/using-tfs-for-source-control-in-infopath-2010.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Regarding the differences between malloc and new in terms of their respective mechanisms of handling memory allocation? What are the differences between malloc and new in terms of their respective mechanisms of handling memory allocation?
A: *
*malloc doesn't throw bad_alloc exception as new does.
*
*Because malloc doesn't throw exceptions, you have to check its result against NULL (or nullptr in c++11 and above), which isn't necessary with new. However, new can be used in a way it won't throw expections, as when function set_new_handler is set
*malloc and free do not call object constructors and destructors, since there is no objects in C.
*see this question and this post.
A: Well, malloc() is a more low-level primitive. It just gives you a pointer to n bytes of heap memory. The C++ new operator is more "intelligent" in that it "knows" about the type of the object(s) being allocated, and can do stuff like call constructors to make sure the newly allocated objects are all properly initialized.
Implementations of new often end up calling malloc() to get the raw memory, then do things on top of that memory to initalize the objecs(s) being constructed.
A: Do you mean how they are implemented?
They can be implemented as anything, just malloc may not call new, and all standard news must call the global operator new(void*). Often new is even implemented as calling malloc but there is no requirement on how that is implemented. There are even dozens of allocators out there, each with some strengths and some weeknesses.
Or do you mean how they differ on the language level?
*
*new throws (unless it is called with std::nothrow) on allocation error. new expressions (not the operator new) calls the ctor.
*malloc returns 0 on allocation failures.
A: If the call fails, new will throw an exception whereas malloc will return NULL.
For malloc, the caller has to specify the amount of memory to be allocated, while new automatically determines it.
These differences are concerning allocation, there are tons of others - new will call constructor, new can be overloaded, new is an operator whereas malloc is a function...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to represent current state or status and maintain data/referential integrity? - Database Design I have a table that maintains specific business transactions, let's call it LOANS. Each record can at any given time have one of several "states", for example "in re-payment / open", "defaulted", "voided", or "paid".
The status of a record can only change due to an "event" or action taken by the user of the application (some events do not cause a state change, eg a payment modifies the record but does not change the state). While keeping track of the current status, it is also important that we can easily track the "event" that put the transaction in this state.
I have seen other databases setup such that LOANS contains a status column, and a letter (or even a foreign key to a table of possible states) is used to designate current status. Then the EVENTS table has a column that is a FK to LOANS.
This solution works, but I am concerned that this allows for a possible loss of data integrity. In other words, there is nothing to prevent status from being set to "defaulted" with no EVENT to support the change. It would be left solely to the application to ensure this never happens (there is no referential integrity in this solution as I see it).
My alternate solution is to scrap the status column in LOANS and instead use a lastEvent column which is an FK to EVENTS. The EVENTS table would then maintain the "type" of event which would in turn describe the state change (eg if the lastEvent was of type 'payoff' then naturally the state is 'paid').
My questions are:
*
*Should I even be concerned about the data integrity (is this such a common thing to do because it is ok to do it)?
*Is my proposed solution sound, or is there a better solution?
*Are there any pitfalls in my solution that I should be aware of?
In case it matters, I am using MS SQL SERVER 2005.
A: *
*Only you know what the risks are if you don't have referential integrity here - but in general, yes, it's worth designing your database so you can use referential integrity. It reduces errors, and increases the chances future developers will understand your schema.
*I'd have a schema along the lines of...
Loans
Loan_Id (PK)
amount
....
Events
Event_id (PK)
Loan_ID (FK)
Event_type_id (FK)
Date
status_id (fk)
event_type
event_type_id (pk)
description
status
status_id (pk)
description
To find the current status of any load, you'd need to find the newest entry in the events table for that loan. To see the history of a loan's status changes, you can query the events table.
When you record events which do not change the status, the record with the new event simply contains the current status of the event - so you might get a table like:
Event_id Loan_ID Event_type_id Date status_id
------------------------------------------------
1 1 NEW 1 Jan 2011 NEW
2 1 APPROVE 2 Jan 2011 NEW
3 1 DEFAULT 1 Feb 2011 DEF
...
This way, you always retrieve the current status by finding the latest record.
It dramatically reduces the risk of bugs - if your logic for "events" changes, and an event does change the status of a loan, you only have to change this in one place - the code which creates the record in the event database. You don't have to remember to also change the "loan" record.
As for performance - I'd only optimize for this if you really need to - on a well-tuned database, the join and max should not be show stoppers.
You can refine the model by creating a table which maps valid status transitions and their associated events; depending on your database, you could enforce this through triggers.
I think this is better than a "last event" foreign key, because it's redundant - by definition, the last event is the record with the MAX(date) for that loan.
A: I think your concern about integrity is valid. You have specified a business rule that states, actually Status is not a writeable property it is inferred - from events.
I'd make it a computable column based on your Events data.
Can only guess your db implementation, so the other alternative is a trigger updated column but how would you then make sure its read-only? (presumably with locks/permissions)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: getting current latitude and longitude I want to get current location, I see with this code but how can I assign to this latitude and longitude to label when click a button?
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSLog(@"latitudeAAAAA %f",newLocation.coordinate.latitude );
NSLog(@"longitudeAAAA %f",newLocation.coordinate.longitude);
[corelocation stopUpdatingLocation];
}
A: label.text = [NSString stringWithFormat:@"%lf,%lf", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
A: You need set your own class as a delegate of the your CLLocationManager and then callstartUpdatingLocation (docs) to make it call the method you mention. The callback will come at some point after you've asked it to start updating location, and keep coming until you ask it to stop. You'll have to figure out for your use case if it should start by itself, but then only save the location (or what ever it is you want to do with it) when the user clicks a button, or if the updates should start when the user clicks (I'm not quite sure what you mean from your question).
https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/CLLocationManager/CLLocationManager.html#//apple_ref/doc/uid/TP40007125-CH3-SW2
A: In the interface builder, set the touchUpInside event to call - (IBAction)buttonClicked:(id)sender (or set action programatically) then set your buttons delegate to self. On viewDidLoad setup your locationManager:
- (void)viewDidLoad {
[super viewDidLoad];
self.locationManager = [[[CLLocationManager alloc] init] autorelease];
[locationManager setDelegate:self];
[locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationManager setDistanceFilter:kCLDistanceFilterNone];
[locationManager startUpdatingLocation];
}
Button action:
- (IBAction)buttonClicked:(id)sender {
myLabel.text = [NSString stringWithFormat:@"%+.6f,%+.6f", locationManager.location.coordinate.latitude, locationManager.location.coordinate.longitude];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Button clicked" message:myLabel.text delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
Location Manager delegate methods:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSDate* eventDate = newLocation.timestamp;
NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];
if (abs(howRecent) < 5.0) {
NSLog(@"New Latitude %+.6f, Longitude %+.6f", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Internet explorer z-index issue On this website: http://rwl.rwlwater.com/ when I have more menus, it moves the search bar on the next line, but it's still visible over the featured slider. In firefox this doesn't happen and the search bar is not visible.
I tried changing the z-index for the slider div, for the search bar div, but it doesn't work.
A: Because the divs you're trying to stack are in two different contexts (i.e. they are nested in other divs so they are not sibilings) you're not going to be able to set their z-index directly.
I think you'll have to set the z-index of the parent that is an actual sibling of the other...so since #top and #content-full are sibilings, you can need to set the z-index of #top with a higher number. This also means you'll have to position #top to something other than it's default static.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JS/JQuery: I'm trying to move an li node under the one it matches $(document).ready(function() {
var a = $("li.comment").attr("id");
var b = $("li.comment[id='"+a+"']");
var c = $("li.comment > div.comment-body div > p > a").attr("href");
var d = $("li.comment > div.comment-body div > p > a[href='"+c+"']");
var e = new RegExp("[#+'+b+']b")
if (d===e) {
d.parent().append(a);};
};)
If d matches b, I'm trying to move d (starting from the li node) to right under b who's id it matches. I can't figure it out.
Sample:
<li id="wow" class="comment">
<div class="comment-body">
<div>
<p>Any comments?</p>
</div>
</div>
</li>
<li id="rebble" class="comment"><div class="comment-body"><div><p>Wakatow</p></div></div></li>
<li class="comment" id="det">
<div class="comment-body">
<div>
<p>
<a href="#wow">Yeah! Hold on a sec...</a>
</p>
</div>
</div>
</li>
I'm trying to work it out on jsfiddle, but I can't get it done. When it comes out right, the li with the link is supposed to move under the first one
A: Can you compare strings?
$(document).ready(function() {
var a = $("li.comment").attr("id");
var b = $("li.comment[id='"+a+"']");
var c = $("li.comment > div.comment-body div > p > a").attr("href");
if( '#'+a == c ){
var d = $("li.comment > div.comment-body div > p > a[href='"+c+"']");
d.parent().append(a);
}
});
http://jsfiddle.net/FjH79/
A: You cannot compare selectors and string.
What you could do is:
var e = b.attr('id');
if ("#" + d.attr('id')===e) {
d.parents().insertAfter(a);
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I securely add a random padding to all ASP.NET AJAX HTTPS responses? Apparently, it is possible to leak data in an SSL connection based on the size of the HTTPS request and response.
Considering the complexity of the ASP.NET pipeline, how do I securely add a random amount of data that rounds each size up to the nearest 500K?
The security constraints (as I'm aware of now) are
*
*Don't leak timing information, and always take the same amount of time when generating the extra data
*Always round up to the next 500K value
*The data used as padding doesn't have to be random, our goal is to change the size of the HTTPS response
I'll post the related javascript question (HTTP POST) in a separate question as a courtesy to the PHP users who may not be looking at ASP implementations ;)
A: Having read the linked articles, I first want to say that best security would probably be clientside; a trusted, secure proxy -- this type of analysis relies upon intimate knowledge of the application, if the attacker can't tell what website your visiting, it can't analyze the responses.
That said, there are things you can do to make YOUR site less vulnerable. But its going to be more complex than just simple padding. One of the examples given is picking a doctor. The list of available doctors is available to all visitors. If you have an auto complete its not hard at all to reduce the number of potential doctors down significantly given that you can watch the traffic. An extreme example would be 500 doctors, only one with a name starting with Z: Dr Zhivago. Thus a 1 letter send that returns one doctor is probably him. Padding the send and receive data won't be enouh to hide this if it is based on a simple rounding up to the nearest 500 bytes. One send and receive that then moves on to the next action on the page is still going to be him. In this type of situation you can do several things -- first is always return MORE than one possibility, even when there is only one, reduce it to just one on the client. Secondly pad the number of REQUESTS, not just the data in the request.
Back to your question, compression makes padding something of a problem as the compressed size leaks. Pad as much as you can with valid data that is filtered out on the client, this will make any attempt to analyze it harder. Be sure that you don't leak padding time when doing your padding.
Finally -- this type of attack would have to be application and possibly user specific. Does anyone really care that much about your traffic?
A: Well you can create a filter to modify response before sending it to client. All you have to do is create a IHttpModule and intercept ASP.NET request pipeline. You can set Filter Stream, which will buffer your response, and at the end, ASP.NET pipeline will call "Close" method, that time you can modify buffer and send back to client.
To improve performance, you can also intercept Write method and write better logic instead of buffering whole response. But I will leave it on you.
First configure your web.config as,
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="RandomPaddingModule"
type="Namespace.RandomPaddingModule, AssemblyName"/>
</modules>
</system.webServer>
And add following code
public class RandomPaddingModule : IHttpModule{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
// Apply filter immediately
context.BeginRequest += (s, e) =>
{
context.Response.Filter =
new RanndomPaddingStream(context.Response.Filter,
context.Context);
};
}
}
public class AtomPreCompilerStream : ResponseFilterStream
{
private HttpContext context;
public RanndomPaddingStream(Stream s, HttpContext c)
: base(s)
{
this.context = c;
}
// process buffer before sending it to client...
protected override byte[] ProcessBuffer(byte[] p)
{
if(string.Equals(
context.Response.ContentType,
"application/json",
StringComparison.OrdinalIgnoreCase)){
// do some padding....
}
return p;
}
}
public class ResponseFilterStream: Stream
{
/// <summary>
/// The original stream
/// </summary>
Stream _stream;
/// <summary>
/// Stream that original content is read into
/// and then passed to TransformStream function
/// </summary>
MemoryStream _cacheStream = new MemoryStream(5000);
public byte[] Buffer
{
get
{
return _cacheStream.ToArray();
}
}
/// <summary>
///
/// </summary>
/// <param name="responseStream"></param>
public AtomPreCompilerFilterStream(Stream responseStream)
{
_stream = responseStream;
}
/// <summary>
///
/// </summary>
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return true; }
}
/// <summary>
///
/// </summary>
public override bool CanWrite
{
get { return true; }
}
/// <summary>
///
/// </summary>
public override long Length
{
get { return 0; }
}
/// <summary>
///
/// </summary>
public override long Position
{
get { return _cacheStream .Position; }
set { _cacheStream .Position = value; }
}
/// <summary>
///
/// </summary>
/// <param name="offset"></param>
/// <param name="direction"></param>
/// <returns></returns>
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return _cacheStream.Seek(offset, direction);
}
/// <summary>
///
/// </summary>
/// <param name="length"></param>
public override void SetLength(long length)
{
_cacheStream .SetLength(length);
}
/// <summary>
///
/// </summary>
public override void Close()
{
byte[] data = ProcessBuffer(_cacheStream.ToArray());
_stream.Write(data, 0, data.Length);
_stream.Close();
}
protected virtual byte[] ProcessBuffer(byte[] p)
{
return p;
}
/// <summary>
/// Override flush by writing out the cached stream data
/// </summary>
public override void Flush()
{
// default flush behavior
//_stream.Flush();
}
/// <summary>
///
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <returns></returns>
public override int Read(byte[] buffer, int offset, int count)
{
return _cacheStream.Read(buffer, offset, count);
}
/// <summary>
/// Overriden to capture output written by ASP.NET and captured
/// into a cached stream that is written out later when Flush()
/// is called.
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
public override void Write(byte[] buffer, int offset, int count)
{
_cacheStream.Write(buffer, offset, count);
//_stream.Write(buffer, offset, count);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Accessing Visual Studio 2010 debugging website I am going to develop a ASP.net website for mobiles. But I found that my mobile cannot access the website during debugging the website.
How to let the VS 2010 can be accessed form my mobile during debugging website?
A: To be able to access it and debug it from your mobile device you have to deploy it to your local IIS on the default website. If you connect your mobile device on the same wifi/local network you should be able to browse the site from your mobile using the computers hostname.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .Net DLL referencing another DLL I have one .Net 4.0 dll project that references third party PDF converter DLL. I have exposed this dll for COM. Now when I am trying to add my .tlb file to VB6 project it comes up with runtime error. Error says the dll which is third party pdf converter cannot be found.
Is there any way I can avoid this?
Many Thanks
Ni
A: Yes, VB6 dates from the days of DLL Hell. There's no good scenario to help the CLR find the DLL in some random directory when the VB6 IDE is in charge. It isn't clear whether the helper DLL is a .NET assembly or a native DLL. Either way, what works best is copying the DLL into the same directory as vb6.exe, c:\program files\microsoft visual studio\vb98 by default. Keeping that copy up to date is your bit of dll hell.
A: Either GAC the third party dll, or put it in the same path as the registered COM dll
A: Ok at last it worked. All I did: open up .tlb file in Visual studio and added third party pdf dll using custom library. It started working.. Thanks everyone for help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Displaying XML with XSLT formatting in MVC I'd like my view to display a raw XML file formatted with an XSLT file inside an iframe. The XML file actually shown is variable and depends on the user's selection from a form (the XML file's address is determined in the controller).
Is it possible to return the XML information directly from my controller, and if so, how? My main consideration is how to use an iframe in my view and have the id updated by my AJAX form. Initially, my controller action merely returned a string representing the XML file address, but I had trouble manipulating my JavaScript to accept this return value and parse it into document.getElementById.src = url.
Current code:
Dim docXML As New XmlDocument()
docXML.Load("C:\SharpSVN\" + cprotocols + "_Config.xml")
Using nodeReader = New XmlNodeReader(docXML)
nodeReader.MoveToContent()
Dim xRoot As XElement = XElement.Load(nodeReader)
Return xRoot.ToString()
End Using
This is without XSLT, and the xRoot also only returns the data in one line (I'd like to see the element tags as well as correct formatting with spaces).
A: Use a pretty-print stylesheet or a serialize stylesheet to format the raw XML with the correct whitespace and line breaks.
References
*
*Mozilla: XML Pretty Print
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: the connection with the server was terminated abnormally xmlhttp I have this asp page test1.asp in the same server (different website) than this webservice. Thing is when i try to run this code
sUrl = "http://chat.xxxxx.com/UCWebServices/Chat.asmx/GetChatQueueByAddress?queueAddress=SALESCHAT"
result = HTTPPost(sUrl)
response.Write result
Function HTTPPost(sUrl)
set oHTTP = CreateObject("Msxml2.ServerXMLHTTP")
oHTTP.open "GET", sUrl,false
oHTTP.send <-- it fails here <-- it fails here <-- it fails here <--
if oHTTP.Status = 200 Then
HTTPPost oHTTP.responseText
End if
End Function
%>
i get the following error
msxml3.dll error '80072efe'
The connection with the server was terminated abnormally
i googled up this issue thinking that maybe this was some little bs i could easily solve, but i am getting into some problems. It's not easy to make it work.
if we run the same page from anywhere else, then it works.
Any ideas?
A: This error code is ERROR_INTERNET_CONNECTION_ABORTED. The most common reasons are a firewall or anti-virus interfering with the connection, a proxy borking the connection data. I can also be caused by a name resolution issue -- for example, if the host name resolves to 127.0.0.1 locally and the web server is bound to the public IP address only.
A: Another possibility; the server at the far end may be filtering (and dropping) requests based on browser agent strings, to prevent programmatic scraping.
What happens when you just request that URL in a regular browser?
A: Some servers need a content-length header set for an HTTP POST to function properly.
In our case (using serverXMLHttp) this was needed:
xmlhttp.Open "POST", URL , false
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xmlhttp.setRequestHeader "Content-Length", Len(postdata)
A: (answering an old thread because its the first result for this message in Google)
I just ran in to this issue. It turned out that I was POSTing an empty string:
myString = FunctionThatWasReturningEmptyString()
set oHTTP = CreateObject("Msxml2.ServerXMLHTTP")
oHTTP.open "GET", sUrl, false
oHTTP.send myString
Once I fixed the function to return an empty XML set instead of an empty string, my error went away
A: When I got this error, the Event Logs indicated that w3wp.exe (the IIS App Pool) had crashed.
With Visual Studio, I opened the memory dump file that Event Viewer mentioned and the "Exception Information" had the message "The thread used up its stack."
It turned out that the code had a StackOverflowException that was crashing the app pool.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Retrieve all folder in a directories and change all folders' name that are in it I want to retrieve all folders in a directory folder and change all the subfolder that in it. For example,
in root folder Root, I want to change all subfolders A, B, C, D, .. to 1,2,34,... May I know how can I do it with php? Thanks.
A: Something like this:
$count = 0;
foreach(new DirectoryIterator('Root') as $fileInfo) {
if ($fileInfo->isDir() && !$fileInfo->isDot()) {
$count++;
rename($fileInfo->getPathName(), $fileInfo->getPath() . "/$count");
}
}
Links:
*
*DirectoryIterator
*rename
*RecursiveDirectoryIterator (if you with to do the same for sub-directories)
A: <?php
$basedir = "/tmp"; //or whatever your "to change" home directory is
$contents = scandir($basedir);
$count = 1;
foreach ($contents as $check) {
if (is_dir($basedir . "/" . $check) && $check != "." && $check != "..") {
rename($basedir . "/" . $check, $basedir . "/" . $count);
$count++;
}
}
?>
Of course, you will need to have proper CHMOD depending on where you run the script from.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android StartActivtyForResult() from a Service First I'm sorry for my english that is not so good :).
I am facing a problem to develop my app.
That is a general architecture scheme of my solution.
http://i.stack.imgur.com/ooTmE.png
To be quick, the app has to decode code bare but with two possible ways:
*
*using exernal device (The constructor provides a sdk containing an android Service to communicate with the device),
*use the camera of the mobile using the library Zxing which is possible to manage it with intent.
The goal of my own service is to manage some business code and make transparent the choice of the tool for the user.
I believed that was a good solution but I wanted to implement it and I had different problems.
My main trouble is that I cannot execute StartActivityForResult inside the service.
Do somebody have any suggestions for my problem whether a change in the architecture or a solution for the main problem?
@Laurent' : You have totaly right my service acts as an API adapter.
I will try to make the expected behaviour more clear.
I have an app that needs to recognize (real) objects which have QR codes on their top. This recognition action will be done several times by the user during the life of the app.
The user chooses to launch the recognition by clicking on a button (or otherwise but he knows that the recogntion will start). So no notification is needed.
The thing is he doesn't choose the way to do the recogniton. It is why, as you said, I implement an adapter.
The adapter chooses between :
Camera mobile or external device. The first is an activity coming from the Zxing library. The second one is a service that manages the external device. This service provides an interface to get back result.
One more thing, I need that my whole implementation (adapter and co) can be re-used by other apps that will also need to do recognition.
So my thought was to implement a service as an adapter to answer my two conditions (make transparent the choice for the user - and make the recognition available for other apps).
I hope you understand my problematic.
A: Two ways you could solve this problem.
1) Have MyOwnService do a callback into MainActivity telling it to launch your ScanActivity.
- This is a better approach if MyOwnService's task is only going to be running while MainActivity is running and if the user would expect the ScanActivity to come up automatically.
2) Have MyOwnService create a notification that will let the user access the ScanActivity.
- This is a better approach if MyOwnService's task might be running longer than the life span of MainActivity. That way, you can let the user know, unobstrusively, that they might want to access the ScanActivity.
A: Given your architecture, your MyOwnService must act as an API adapter : it should provide a unified scanning API and address each external service specificities transparently.
Your expected behaviour is not clear enough to provide a solution that suits your needs but here are a few remarks that can be of some help.
Passive scanning:
*
*Even if there are some workarounds : no activity should be launched from a service (not directly). Never. Bad. Services are background stuff, the most they will be permitted is to hint users with Notifications (this is point 2 of Justin excellent answer).
As a consequence there's nothing as a 'popup Activities' (and that's good!). If you need to continuously scan for barcodes, even when your activity is not run, then the only way to warn users is by using status bar notification.
Active scanning:
*
*Inside your own activity you can bind to your wrapper service and make it start scanning for codebars. When it finds one it has to message your activity. Your Activity message handler has complete access to the UI to inform the user of your findings.
You selected Active Scanning in your edit, your problem is therefore to find a way for your service to actively notify your main application (the one that started the active scanning) that a new item has been scanned successfully.
You do NOT do this by starting a new activity (remember: this is bad) but you can bind to a service and/or use Messages between the wrapper service and the application.
I advice you take the time to read (and more time to comprehend) this android developer article on BoundServices and especially the part about Messengers.
A full example of Two Way Messaging between a Service and an Activity can be found in the following android examples : Service & Activity
Warning: designing robust, full blown AIDL-based services is a tough job.
A: So finally I changed my architecture.
I make the choice to delete myOwnService and to create an intermediate activity that will be my API Adaptater.
This activity will have a dialog.theme to look like a dialog box indicating that a recognition is under execution.
If the recognition uses the external device this activity will stay at the foreground otherwise the camera activity will start (Being managed by the intermediate activity).
Thank to that I can manage my result from the intermediate activity and do not have an android strange architecture, keeping my business code for the recognition outside my main app.
Service was not the good choice.
Thanks a lot for you help and your time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a reliable way to send email without having the senders smtp? My application will be used in a manner that the user is remote from his computer running the application, receiving data via text messages sent periodically from the PC. Im sending the text message via email, using the number@carrierdomain.com. To simplify determining the user's smtp server, I've been sending the message using the destination phone carrier's smtp, instead of the whatever may or may not be available at the PC. This has worked so far with AT&T and T-Mobile, but not Verizon, as they have discontinued their smtp service.
I'm using mailsend v1.15 http://www.muquit.com/muquit/software/mailsend/mailsend.html
but Im open to alternatives.
I do have a less than ideal workaround, which is to use google or hotmail's smtp, but that requires a login/pass.
If I can send the text through regular email, using outlook, it works. I've looked at outlooks smtp logs, but that doesn't really help.
If its not being sent to a Verizon smtp server, how does it get routed, and is it something that my application can use?
Is there a reliable way to send email without having the senders smtp?
A: Theoretically, any smtp server can send your e-mail. However, due to the overwhelming amount of spaming on the internet, pretty much every isp has locked down their smtp server and will not allow anonymous relaying of e-mail.
If you do have the outlook client on the box you are sending the e-mail you can look at using one of the Outlook APIs:
http://msdn.microsoft.com/en-us/library/gg608200.aspx
to send the e-mail message. You are using the outlook configuration then and don't have to worry about it your code.
A: As long as an SMTP server is configured to allow relay from a remote domain then you can use it send email from/to virtually any address. There are downsides, however, to using any SMTP server to send an email from a specific domain - the most notable of which is that the recipient's domain will likely flag the message as spam because the domain of the SMTP server is different from that of the sender's email address.
There are other non-email APIs that can be used to send text messages, if that is something you're willing to consider. Check out:
*
*Tropo (http://www.tropo.com)
*Zeep Mobile (http://www.zeepmobile.com)
Best of luck to you.
A: Impossible. SMTP is the Simple Mail Transfer Protocol, without this is impossible to access to another account with Email format. You can make a php mail where you don't need to have smtp, but your access will be limited, not all ESP / ISP will allow you to delivery those emails, because they need to identify you using your SMTP and MX Lookup (Reverse MX A records) from your server. It exists more ways, but are 100% SPAMMERS and HACKERS methods and I don't recommend to use them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: honeycomb - add custom button to taskbar While in the application, is it possible to add a custom button to the taskbar thats displayed at the bottom of the screen (next to Home, windows buttons)?
A: No, sorry, you cannot add things to the system bar ("the taskbar thats displayed at the bottom of the screen") except for Notifications, and they appear on the far right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing an unknown type (?) object to a function as a parameter in objective-c How do I pass an unknown type (?) object to a function and then set it to a local ones value in objective-c? The unknown object is an n-th item of a JSON value. I use the JSON framework.
[giveMeTheNthObj:[items objectAtIndex:indexPath.row]]
...
- (void)giveMeTheNthObj:(id)o {
Classname *local = o;
}
The above fails. I think because the local is a pointer that should point to a Classname type. What should be the type of the local variable?
The error log:
GNU gdb 6.3.50-20050815 (Apple version gdb-1705) (Fri Jul 1 10:50:06 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".Attaching to process 37438.
2011-09-30 16:39:21.649 Navig[37438:b303] -[UILabel copyWithZone:]: unrecognized
selector sent to instance 0x4b949a0
2011-09-30 16:39:21.652 Navig[37438:b303] *** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[UILabel copyWithZone:]: unrecognized selector
sent to instance 0x4b949a0'
*** Call stack at first throw:
(
0 CoreFoundation 0x00dde5a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f32313 objc_exception_throw + 44
2 CoreFoundation 0x00de00bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d4f966 ___forwarding___ + 966
4 CoreFoundation 0x00d4f522 _CF_forwarding_prep_0 + 50
5 CoreFoundation 0x00d3edca -[NSObject(NSObject) copy] + 42
6 UIKit 0x000de18b -[UIViewController setTitle:] 95
7 Foundation 0x007b05e5 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 285
8 UIKit 0x0022c30c -[UIRuntimeOutletConnection connect] + 112
9 CoreFoundation 0x00d548cf -[NSArray makeObjectsPerformSelector:] + 239
10 UIKit 0x0022ad23 -[UINib instantiateWithOwner:options:] + 1041
11 UIKit 0x0022cab7 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 168
12 UIKit 0x000e2628 -[UIViewController _loadViewFromNibNamed:bundle:] + 70
13 UIKit 0x000e0134 -[UIViewController loadView] + 120
14 UIKit 0x000e000e -[UIViewController view] + 56
15 UIKit 0x000de482 -[UIViewController contentScrollView] + 42
16 UIKit 0x000eef25 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48
17 UIKit 0x000ed555 -[UINavigationController _layoutViewController:] + 43
18 UIKit 0x000ee7aa -[UINavigationController _startTransition:fromViewController:toViewController:] + 326
19 UIKit 0x000e932a -[UINavigationController _startDeferredTransitionIfNeeded] + 266
20 UIKit 0x000f0562 -[UINavigationController pushViewController:transition:forceImmediate:] + 932
21 UIKit 0x089b9c36 [UINavigationControllerAccessibility(SafeCategory) pushViewController:transition:forceImmediate:] + 77
22 UIKit 0x000e91c4 -[UINavigationController pushViewController:animated:] + 62
23 Navig 0x00002dfd -[RootViewController tableView:didSelectRowAtIndexPath:] + 269
24 UIKit 0x000a7b68 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140
25 UIKit 0x0009db05 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219
26 Foundation 0x007b779e __NSFireDelayedPerform + 441
27 CoreFoundation 0x00dbf8c3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
28 CoreFoundation 0x00dc0e74 __CFRunLoopDoTimer + 1220
29 CoreFoundation 0x00d1d2c9 __CFRunLoopRun + 1817
30 CoreFoundation 0x00d1c840 CFRunLoopRunSpecific + 208
31 CoreFoundation 0x00d1c761 CFRunLoopRunInMode + 97
32 GraphicsServices 0x010161c4 GSEventRunModal + 217
33 GraphicsServices 0x01016289 GSEventRun + 115
34 UIKit 0x0003ec93 UIApplicationMain + 1160
35 Navig 0x00002439 main + 121
36 Navig 0x000023b5 start + 53
)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
Current language: auto; currently objective-c
(gdb)
A: When you say "The above fails."; how exactly does it fail? Exception raised at run-time, warning during compile, etc? Does this help:
- (void)giveMeTheNthObj:(id)o {
if ([o isKindOfClass:[Classname class]]) {
Classname *local = (Classname *)o;
}
}
A: You want NSString *local = NSStringFromClass([o class]);?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where is my mistake using JavaScript and jQuery I have a question actually I need one if/else for hide or show one div, I had wrote the following function but it didn’t work:
jQuery(document).ready(function(){ /*show div OtraUniversidad when option:selected = 165*/
var optionValue = $("#Universidad option:selected").val();
$("#OtraUniversidad").hide();
if(optionValue == 165){
$("#OtraUniversidad").show();
}
});
Actually works: $("#OtraUniversidad").hide();
I don't know what's wrong; I'm new in JavaScript and jQuery
Some help is always welcome.
A: I think this should work:
jQuery(document).ready(function() {
$('#Universidad').change(function() {
var optionValue = $("#Universidad").val();
if(optionValue == 165) {
$("#OtraUniversidad").show();
} else {
$("#OtraUniversidad").hide();
}
}).change();
});
Demo: http://jsfiddle.net/gGX2E/1/
A: optionValue == 165
This comparison is wrong, you must use this:
if(optionValue == "165")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: AsyncTask Issue related to Notifications and IntentService I have a pretty weird problem. I'm setting a notification in my Service in order to launch an Activity. When the Activity launches, an AsyncTask is started. This is how I set up the notification:
CharSequence tickerText = getString(R.string.notificationTextUpdates);
CharSequence contentText = getString(R.string.app_name);
Notification notification = new Notification(icon,
tickerText, System.currentTimeMillis());
Intent notificationIntent = new Intent(
getApplicationContext(), MyActivity.class);
PendingIntent contentIntent = PendingIntent
.getActivity(getBaseContext(), 0,
notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(),
tickerText, contentText, contentIntent);
notifManager.notify(0, notification);
If the application is running, everything works, but if it wasn't running before, the AsyncTask's onPostExecute method doesn't get fired. Instead I get the following exception:
09-30 16:07:52.500: WARN/MessageQueue(27729):
java.lang.RuntimeException: Handler{4057ec78} sending message to a
Handler on a dead thread 09-30 16:07:52.500: WARN/MessageQueue(27729):
at android.os.MessageQueue.enqueueMessage(MessageQueue.java:196) 09-30
16:07:52.500: WARN/MessageQueue(27729): at
android.os.Handler.sendMessageAtTime(Handler.java:457) 09-30
16:07:52.500: WARN/MessageQueue(27729): at
android.os.Handler.sendMessageDelayed(Handler.java:430) 09-30
16:07:52.500: WARN/MessageQueue(27729): at
android.os.Handler.sendMessage(Handler.java:367) 09-30 16:07:52.500:
WARN/MessageQueue(27729): at
android.os.Message.sendToTarget(Message.java:350) 09-30 16:07:52.500:
WARN/MessageQueue(27729): at
android.os.AsyncTask$3.done(AsyncTask.java:214) 09-30 16:07:52.500:
WARN/MessageQueue(27729): at
java.util.concurrent.FutureTask$Sync.innerSet(FutureTask.java:253)
09-30 16:07:52.500: WARN/MessageQueue(27729): at
java.util.concurrent.FutureTask.set(FutureTask.java:113) 09-30
16:07:52.500: WARN/MessageQueue(27729): at
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:311)
09-30 16:07:52.500: WARN/MessageQueue(27729): at
java.util.concurrent.FutureTask.run(FutureTask.java:138) 09-30
16:07:52.500: WARN/MessageQueue(27729): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-30 16:07:52.500: WARN/MessageQueue(27729): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
Strangely enough, this doesn't happen, when I set up the same notification inside another Activity, so everything works as intended.
I'm quiet confused. My Activity runs in SingleTask mode, I also tried SingleTop mode, which basicly didn't change anything.
A: See http://code.google.com/p/android/issues/detail?id=20915, which is a possible root cause of the problem. It includes a workaround for the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Touch events in blackberry torch 9810 doesn't works properly I have written a mobile application for android. When I test it on Samsung Galaxy SII it works like a charm. Same app when I tried on blackberry Torch2 9810 then it works pathetic.
The Problem is with touch events. I am using JQuery mobile touch events. The move events are not working at all in Torch. When it move my finger very slowly on the phone then it works fine but when I increase the finger movement the move event doesn't works properly.
I want to know that is it the problem with the phone or Jquery mobile or I have written some pathetic code.
A: You need to add event.preventDefault() for touchmove to work correctly. This is required as WebKit fires only one touchmove event if the event’s default (scrolling the page) is not prevented.
For more details have a look at Testing BlackBerry WebKit, or how I encountered a browser tester’s worst nightmare.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I trigger Button's OnClick event from Javascript in an asp.net application which is using Callback? I'm using Callback, on a asp.net webforms project. When clicked button, it is working great. However I have a textbox, when user press 'enter' it must trigger button. So I did it,
function search_enter(event) {
if (event.keyCode == 13) {
$("#search_button").click();
}
}
Yes, it triggers first javascript function of callbacks. But it is doing postback not callback :S
How can I fix this?
Update:
I solve the problem, calling callback event at input's keyup event.
function search_enter(event) {
if ($('#search_textbox').val() == '')
return;
WebForm_DoCallback('__Page', Basla(), Istek, null, Hata, true)
}
<input id="search_textbox" onkeyup="search_enter(event)" type="text" />
But if I pressed enter, when cursor in input. It is doing postback. How can I fix this?
A: I found it. if textbox is in <form runat="server"> tag, It is doing postback, when pressed enter. I've removed form tags and it solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails nested models hey I asked a question here Rails association help , this person directed me to learn nested attributes here , http://railscasts.com/episodes/196-nested-model-form-part-1 , and here http://railscasts.com/episodes/197-nested-model-form-part-2 . The link_to 's to add fields wont respond to anything I do
A: I agree with jimworm in that it would be really helpful to see the relevant parts of the code that you are working with. I also want to point out that from those Railscasts Ryan created the nested_form gem which works really well for doing a multi-model form for associated models. I use this gem quite often for my forms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get ".is" to work in older versions of Internet Explorer I'm not getting ".is" to work. It's working great in IE9, firefox and other modern browsers but not IE8 or IE7
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
$('body').click(function () {
if (!$('.myDiv').is(":hover")) {
alert("outside of blue div");
}
});
</script>
<div class="myDiv" style="width:150px; height:150px; background:blue"> </div>
</body>
</html>
Or look here http://jsfiddle.net/uh8RB/
How do I get it to work in IE8 and older?
A: Try using $(document).click instead of $('body').click. Sometimes the <body> tag doesn't take up the full screen height/width, so you may be clicking outside the <body> tag.
Also, instead of .is(":hover"), try !$(e.target).is('.myDiv') $(e.target).closest('.myDiv').length === 0 (.closest is used to detect if we are clicking the div or a child of the div). I don't think IE7 or IE8 support the :hover CSS pseudo-property.
$(document).click(function(e) {
if($(e.target).closest('.myDiv').length === 0) {
alert("outside of blue div");
}
});
Demo: http://jsfiddle.net/uh8RB/5/
More Tests: http://jsfiddle.net/uh8RB/8/
Updated Demo: http://jsfiddle.net/uh8RB/14/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I capture a field name (not field value) with Javascript? I'm trying to find out how I can use javascript to capture the name of a field and assign the name to a variable. I've done a good amount of searching, but I can only find out how to capture the value of a field and not the name of the field itself.
For example, say I have a asp textbox named "ClientFName". I'd like to use javascript to capture the name of the textbox (ClientFName) and assign the name to a variable.
I'm moderately experienced with javascript but I haven't figured out a way to make this happen. Any help would be great!
A: You need to find the element in the DOM (which I assume you can do since you can get the value). Then use .name to access its name property, which you can then assign to a variable.
var myName = document.getElementById("myTextbox").name;
A: By getAttribute() method you can get the attribute value, just check this:
<script>
function check(){
var v= document.getElementById('mytext').getAttribute('name');
alert(v);
}
</script>
<input type="text" id="mytext" value="test" name="mytext1" />
<input type="submit" name="submit" value="submit" onclick="check();"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Do I need to use a web framework for a simple website? The site won't be that complicated and will resemble a modern blog (users, messages, news and other similar features).
Do I need to use a framework for this, and if so, which is best?
Pyramid, Django?
A: You certainly don't need a webframework to create a simple website. Given that you're new to python and interested in building a python website, I imagine this implies: you're interested in learning python. If you're exclusively interested in learning django-python, there's no reason you can't jump in to django, as Ronak said, of course. He's right. It has a lot of documentation. But it will make for somewhat of an odd intro to python.
If I were in your shoes, I'd either start making some offline programs first, or consider an ultra-lightweight framework. Many would advocate web2py or pyramid for ultralightweight. I might consider going even lighter. Something like Bottle, where you're more or less just pairing functions with urls. This way you can at least do a bit of hacking/trial-and-error, instead of launching right into django.
It's not that django doesn't use python-- it will tell you many times that it is in fact 'just python.' But it's adapted at its core to be used in a large business setting (the chicago something or other online, i think). So it enforces various rules that are helpful in managing many different employees working on a project together. You may or may not wish for this kind of 'help.' It also means the scale of projects is assumed to be large and the time-horizon, limitless. If you want to see how a python dictionary works, you may not want to spend a long time configuring settings and creating the pseudo-static-typing you need for your database, and so on, just to execute your project and see a result.
I realize I will automatically get downvoted for this, but I believe it to be sound advice.
A: It depends on what kind of website you are planning to come up with. If the website is going to be just a set of static HTML files, then you don't really need a framework. But if your website will have lots of dynamic content that will get updated on regular basis, you should go with some framework. That will make your life maintaining the website much more simpler.
Django is the most popular framework written in Python. It has very good documentation and a strong community base too.
A: Go with Django - 10,000 Elvis fans can't be wrong.
Or roll your own from scratch. You'll learn a lot, know everything about how you site works, and better appreciate what a framework does for you.
A: As RonakG first pointed, it all depends on the kind of website you intend to have up and running. Actually, your question is too general for a single, definitive answer. There are more aspects to consider other than just being in python. For example, deadlines. This means considering the learning curve to achieve your results. If you don't have much time, a steep learning curve (time to learn it in order to develop it) is certainly something you will want to avoid. Perhaps you already develop in other languages, and need integration and/or migration support, need scalability, reusability, etc, etc, etc.
Another thing that is not so clear in your question is what you mean by "The site won't be that complicated and will resemble a modern blog (users, messages, news and other similar features)". If it really resembles just a modern blog, with users, messages and news, you could google for CMS (Content Management Systems). There are many options available, that could make you have your site up and running in almost no-time. All you'll have to learn is how to customize whatever it has to as to comply to your needs.
That said, if you prefer python, there are some good CMSs available which you can develop your site fast, like Plone. And if you prefer Django, there's Django CMS and there's the excellent Pinax project, which takes the django code reusability to deliver you sample fully customizable, complete websites.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: mod_rewrite from a subfolder with a querystring to a folder or file I am trying to redirect from:
http://www.example.com/folder/product.aspx?prodid=146
to
http://www.example.com/folder2/folder3/
The folders referred to here don't really exist. There are other rewrite rules in place which redirect transparently to the actual content.
If I create a directory called 'folder', and put an .htaccess file in it, I can get the redirect working, BUT, other URLs which refer to that folder no longer work. So I have to try and do the redirect from the .htaccess file in the ROOT folder.
I tried this:
RewriteCond %{QUERY_STRING} prodid=146
RewriteRule ^/folder/product.aspx$ /folder2/folder3/? [R]
...but it doesn't work (I get a 404 error). Using identical syntax but omitting the /folder/ from the 2nd line works if the .htaccess is in the folder directory (so I know the above can't be too far off) - but as I said, I cannot do that. I have tried lots of variations but nothing seems to work. Any assistance appreciated.
A: You need to remove the slash from the start your URL regexp. Like this:
RewriteRule ^folder/product.aspx$ /folder2/folder3/? [R]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a similar way to AlternateItemTemplate to do this I know that with a repeater I can use AlternatingItemTemplate and SeparatorTemplate to adopt a variety of alternating items or for the latter a consistent style / attribute between items.
But in my latest task, I require a SeperatorTemplate but only after every 3 items!
I know I can do this in the ItemDataBound and have a cheeky runningItemCount++ then use runningItemCount % 3 == 0 to place this in.
I also know I can do this using a repeater within a repeater. Just mentioning it is dirty....
I want to keep things clean to be honest, and if it's built in then it's something I want to get in the habit of using, so if anyone knows of how to do so in a nice way (no workarounds please), then please intrigue me.
A: You are doing this correct, but you can use Container.ItemIndex instead of runningItemCount to keep track of the item index.
A: Consider to use the ListView control. It support a GroupTemplate and GroupSeparatorTemplate templates.
A: From looking in to this issue in various areas the conclusion in a nut shell is 'No there isn't'.
I had to use the method I mentioned as unfortunately there is no specific built in feature for this functionality.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: SQL Query - Select Statement I have a table where the data could be like these below:
CusID | Name | State | PhyAddress
160285 | FYZPZ | NULL | 0
160285 | FYZPZ | NJ | 1
160285 | FYZPZ | NJ | 1
or
CusID | Name | State | PhyAddress
160285 | FYZPZ | NJ xx | 1
or
CusID | Name | State | PhyAddress
160285 | FYZPZ | NULL | 0
160285 | FYZPZ | NJ xx | 0
I need to get the default state for the user. And the logic is:
The result should display the physcial state first (PhyAddress = 1) and if
there is no physical address (PhyAddress = 0), then it should display the mailing adress state (PhyAddress = 0). If there are none, the state can be blank.
There are multiple customers in the table and they each can have multiple rows like above and I need to get the default state for each customer.
The resuts needs to show a result of CusID, Name, State
Please help me with the query. TIA
A: use (EDIT after comments):
SELECT DISTINCT Y.CusID, Y.Name, ISNULL (Y.S1, Y.S0) AS State
FROM
(
SELECT
X.CusID,
X.Name,
( SELECT MAX ( State ) FROM Address T WHERE T.PhyAddress = 1 AND T.CusID = X.CusID ) AS S1,
( SELECT MAX ( State ) FROM Address T WHERE T.PhyAddress = 0 AND T.CusID = X.CusID ) AS S0
FROM Address AS X
) AS Y
A: Search the maximum value of PhyAddress:
SELECT CusID,
State
FROM table t1
WHERE PhyAddress =
(
SELECT MAX(t2.PhyAddress)
FROM table t2
WHERE t2.CusID = t1.CusID
)
A: What have you tried?
let me give you something to get you going
Select CusID, Name, case when phyaddress = something then something
when
when
ELSE ' ' END as State
from sometable
where something
A: You could do something like
select CusID, Name, State, PhyAddress from sometable where (CusID, PhyAddress) in
(select CusID, max(PhyAddress) from sometable)
group by CusID, Name, State, PhyAddress
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ctypes definition How could I write the definition copied bellow using ctypes?
unsigned char* x = new unsigned char[10];
Thank you.
A: Depending on how you need to use x, you probably want ctypes.create_string_buffer.
x = ctypes.create_string_buffer(' ' * 10);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: JavasScript Object Literal to jQuery Plugin Could someone explain how to convert the following structure into a jQuery plugin - as I'm really struggling here. I'm mainly lost with object properties, methods - how can they be converted to a single plugin:
var objLit = {
thisObj : null,
propOne : 125,
propTwo : 300,
propThree : null,
methodOne : function(o) {
if (o.length > 0) {
objLit.thisObj = o;
objLit.propOne = o.width();
objLit.propTwo = o.height();
objLit.convert();
}
},
convert : function() {
objLit.thisObj.animate({ 'width' : (objLit.propOne + 20) + 'px', 'height' : (objLit.propTwo + 20) + 'px' }, 300, function() {
var tout = setTimeout(function() {
objLit.propOne = (objLit.propOne - 20);
objLit.propTwo = (objLit.propTwo - 20);
objLit.methodTwo();
}, 2000);
});
},
methodTwo : function() {
etc...
}
};
$(function() {
objLit.methodOne($('.object'));
});
The above is just an example of the object literal - wow would we go around converting this into the jQuery plugin?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Database structure / defined and undefined field values I am using MySQL and have an articles table which has 2 columns: currency and price, but an article can also have a negotiated price, so I can't determine currency and price values.
What should I do to be able to have defined and negotiated prices?
A: If the negotiated price is specific to a user/business... , then this is probably a one to many relationship, you will need a tuple table to hold the price and link the article to the other object.
e.g:
(I'll assume the price is negotiated with a user)
CREATE TABLE user_article_price (
articleid INT,
userid INT,
price DECIMAL(13,2)
)
You then simply need to LEFT JOIN to this table and use NVL(user_article_price.price, article.price)
to get the overridden value.
Note: It is probably a good idea to make a compound primary key using the 2 id columns to stop duplicate values.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Counting substrings in C A friend of mine needed help counting the occurrences of a substring in a string, and I came up with the following code. Does anyone know a better method to do this?
#include "stdio.h"
#include "string.h"
int main(int argc, char *argv[])
{
char str1[50], str2[50];
int i, j, l1, l2, match, count;
printf("String 1:\n");
gets(str2);
printf("String 2:\n");
gets(str1);
l1 = strlen(str1);
l2 = strlen(str2);
count = 0;
for(i = 0; i < l1; i++)
{
match = 0;
for(j = 0; j < l2; j++)
{
if(str1[i + j] == str2[j])
{
match++;
}
}
if(match == l2)
{
count++;
}
}
printf("Substrings: %d\n", count);
}
A: how about this: (using the strstr function, reference here)
int count = 0;
char str1[50], str2[50];
char* tmp = str1;
int count;
printf("String 1:\n");
gets(str2);
printf("String 2:\n");
gets(str1);
while(*tmp != '\0' && (tmp = strstr(tmp, str2))) {
++count;
++tmp;
}
A: Please do not use or encourage the use of gets. Beyond the fact that it will introduce a point of failure in your code, it has been deprecated as of C99 and will be gone completely from C1X.
As others have said, strstr is your friend here:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[50], s2[50];
char *p;
size_t count = 0;
size_t len1;
printf("Gimme a string: ");
fflush(stdout);
fgets(s1, sizeof s1, stdin);
p = strchr(s1, '\n'); // get rid of the trailing newline
if (p)
*p = 0;
printf("Gimme another string: ");
fflush(stdout);
fgets(s2, sizeof s2, stdin);
p = strchr(s2, '\n'); // get rid of the trailing newline
if (p)
*p = 0;
p = s2;
len1 = strlen(s1);
while ((p = strstr(p, s1)) != NULL && p != s1)
{
count++;
p += len1;
}
printf("Found %lu occurrences of %s in %s\n", count, s1, s2);
return 0;
}
A: You might want to take a look at the strstr function (if you're not already familiar with it).
A: int main()
{
char *str = "This is demo";
char *sub = "is";
int i,j,count;
i=j=count=0;
while(str[i]!='\0')
{
if (str[i] == sub[j] && str[i+1] == sub[j+1])
{
count++;
}
i++;
}
cout<<count;
return 0;
}
Above code works but this is static.
A: You can use QString in QT library
QString t = "yourstring";
t.count("yoursubstring");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual Studio Add-In To Automatically Attach to Development Server Is anyone aware of a Visual Studio 2010 Add-In that will automatically allow you to attach to a running instance of the ASP.Net Development Server? And if there is more than one currently running, display a quick dialog that lets you choose from a list of just the ASP.Net Development Servers that are running?
Why do I want this? <-- feel free to skip this part.
The way I usually develop / debug web applications is to launch a browser and navigate through the application until I get to the page I want (could be many pages deep.) I don't want to have the debugger attached through these steps for various reasons (it is slower than not having it attached, extraneous break-points may be hit, I may have break when "thrown" turned on and not want to break earlier in the app when handled errors are thrown, etc...)
I navigate to the page I want, then use the Visual Studio menus to Debug > Attach to Process, and then from within the Attach to Process dialog, I have to scroll all the way down (pages and pages and pages of processes) until I find the WebDev.WebServer40.EXE process I want and choose that.
Doing this makes me take my hands off the keyboard and use a mouse (something I generally try to avoid.)
And doing this seems needlessly repetitive since, if I am debugging an ASP.Net Web Application, I always want to attach to an instance of the WebDev.WebServer40.exe.
A: I prefer to do the exact same thing and it IS possible to bind it all to a keystroke with a macro.
Goto Tools > Macros > Macro IDE
Add a new module and use this code (the funky comments are for syntax highlighting)
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections.Generic
Public Module AttachingModule
Sub AttachToAspNET()
Try
Dim process As EnvDTE.Process
Dim listProcess As New List(Of String)
'' // uncomment the processes that you'd like to attach to. I only attach to cassini
'' // listProcess.Add("aspnet_wp.exe")
'' // listProcess.Add("w3wp.exe")
listProcess.Add("webdev.webserver")
For Each process In DTE.Debugger.LocalProcesses
For Each procname As String In listProcess
If process.Name.ToLower.IndexOf(procname) <> -1 Then
process.Attach()
End If
Next
Next
Catch ex As System.Exception
MsgBox(ex.Message)
End Try
End Sub
End Module
Click on File > Close and return
Click on Tools > Options
Click on Environment > Keyboard
I put the macro in MyMacros, so I look for "Macros.MyMacros.AttachingModule.AttachToAspNET" in the "Show Commands Containing" textbox".
I prefer to use Ctrl+Alt+D but put whatever you want in the "Press Shortcut Keys" textbox and click Assign, then OK
Now all you have to do is hit Ctrl+Alt+D to attach to all cassini instances.
I've seen various versions of this around the internets and this was the most recent I found. I had to modify that slightly to remove the extra web processes and to drop the .exe from WebDev.WebServer.exe, so that it would debug .net 4.0 instances of cassini.
A: I don't know of any such add-in but you can more easily attach to the process using shortcut keys and pressing 'W' to scroll to the WebDev process.
Ctrl+Alt+P - Attach to Process
(process window now has focus)
Press W, which jumps to processes starting with W
Press Enter to attach
Not an addin but you can do it without touching the mouse.
A: Check this answer out: Attach To Process in 2012
This is a simple plugin that gives shortcuts to attaching to nunit agent, IIS and IIS Express. Its pure convenience as compared to Ctrl-Alt-P, but it is convenient.
Direct link to the plugin here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Java, Spring best practices to use variables in properties files I use org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.
There are 3 properties files. So if properties duplicate - last wins.
The first file contains all properties, others substitute some properties.
I use e.g. variable like
log.dir=c:/log.
So I can substitute part of path in properties like
${log.dir}/app1.log
In first file I have 48 uses of this variable.
In second file I have 25 substitutes for properties from first file, and 5 substitutes in third file.
The problem that I need redefine this variable also in second and third file!
I would like use the same name
log.dir
But if I define it in second or third file - redefining go back to first file - but I need use for the rest 18 (48 -25 - 5=18) old properties.
What the best practices in similar cases?
Thanks.
After some analysis I would like have variable that has the same name in all properties files, but values must not be overridden. So for first file log.dir=c:\log, for the second log.dir=d:\log, for the third log.dir=e:\log. And when calculating paths for each file used own. So overridden must be only properties - not variables.
A: What (I think) you'd like to do is to make the log.dir variable changing the value as the configurer steps through the property files and encounters your overriding definitions.
The problem is, the PropertyPlaceholderConfigurer does not work this way; for every encountered ${placeholder} definition it checks only the winning redefinition. It does resolve placeholders taking into account the context of the file they're defined in.
I see only one feasible solution: use a different variable name in each file. Writing your own placeholder configurator is probably very poor gain-to-workload ratio.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Select statement with variables, but not work i try to select statement with variable, but not work maybe i miss something.
<!--Get data from user-->
<?php while ($row_settings = mysql_fetch_array($rs_settings4)) {
$get_id_friend=$row_settings['friend_id'];
} ?>
<!--Get data from user-->
<div id="wrap-box"><!--Loop-box-->
<?php $results = mysql_query("select * from users where id='$get_id_friend'"); ?>
<?php while ($row_friend_loop = mysql_fetch_array($results)) {?>
<div class="img">
<img src="<?php echo $row_friend_loop['img']; ?>" width="49"/>
</div>
<div id="request">
<div class="name">
<p><?php echo $row_friend_loop['user_name']; ?></p>
</div>
<div class="btn">
<a href="#"><img src="images/btn-confirm.jpg" class="hover" /></a><a href="#">
<img src="images/btn-ignore.jpg" class="hover" /></a>
<div class="clear"></div>
</div>
</div>
<?php } ?><!--Loop-box-->
i try to change from
where id='$get_id_friend'");
to
where id='.$get_id_friend.'");
but still not work,
sorry i'm still newbie here
first i want get id from table friend, and if id from table friend is related with table user , all data with related id will be loop .
A: I recommend you read up on sql injection and the PDO library. Also, I have a feeling you do not have a very efficient database structure.
I'm just guessing on your motive and database here, but you should start with something like this:
TABLE friends
int id PRIMARY
int user_id
int friend_id
TABLE users
int user_id
VARCHAR(64) img
VARCHAR(24) user_name
This way, one table holds all the user information, and the second table holds all the 'friend' data. The correct way to access this info would be to use prepared statements and then you can loop through the resulting array, ie: the following:
$sql = "SELECT
friends.friend_id AS friend_id,
users.img AS friend_img,
users.user_name AS friend_user_name,
FROM friends
LEFT JOIN users ON (friend.user_id = users.user_id)
WHERE friend.user_id = :user_id";
$sth = PDO->prepare($q);
$sth->bindParam(":user_id",$user_id_to_get_friends_for);
try{
$sth->execute();
$friends = $sth->fetchAll();
} catch (PDOException $e) {
// Do something with the error
}
// Now loop through the array
foreach($friends as $f) {
echo "<td><img src='".$f['friend_img']."' alt='' />".$f['friend_user_name']."</td>";
}
Now, this is oversimplified i'm sure, but if you follow this format, and do a little research on the functions i'm using here (namely LEFT JOIN and PDO stuff), you should be off to a good start.
I hope this helps you.
A: Syntactically there's absolutely no difference in how your two versions of building the where clause work - if neither works, then $get_id_friend is not set properly. Neither of your queries have any error handling, and you don't show the query string for the initial query, only how you fetch data from it.
A proper minimalist 'safe' query structure is:
$sql = "SELECT ...";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error . "<br />$sql");
}
Since your last comment indicates you're looping over multiple user records and displaying data on those users, you'd be better of using a single joined query, rather than an "outer" query that causes repeated inner queries.
Something like this:
SELECT friends.img, friends.user_name
FROM users AS friends
LEFT JOIN users ON users.friend_id = users.id
WHERE users = $userID;
That's just a guess, since we have very little information about your table structure. But basically: given some userID, fetch the images and user_names of all their friends. Now you've reduced your code to:
$sql = "select query from above";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error() . "<br />$sql");
}
while($row = mysql_fetch_assoc($result)) {
... your html stuff as before ...
}
One loop, one query, less fuss and muss.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java library to split text into smaller files I am looking for a java library that allows me to specify max size or max number of lines in output files, and then splits a large xml/text file into smaller files.
I saw that there is a 2 year old question on SO for the same, however the answers there were for specific cloud platforms....I just want a library for use in java desktop apps.
A: You could use Guava CountingOutputStream to keep track of how much data is written to a file. Write one line at a time, check the number of bytes written and once you exceed the threshold close the file and open a new one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CXF 2.4.2: No conduit initiator was found for the namespace http://schemas.xmlsoap.org/soap/http I have a service client generated from wsdl. I am trying to call the remote service and I recieve the conduit initiator error seen below. I have tried numerous solutions without success.
I found solutions (old posts) that recommend using the http-jetty extensions. I do not believe this makes sense for me because the server is not running locally.
I've also found that closest configuration that helps me is an example cxf.xml file that contains:
<bean class="org.apache.cxf.transport.local.LocalTransportFactory"
lazy-init="false">
<property name="transportIds">
<list>
<value>http://cxf.apache.org/transports/local</value>
<value>http://cxf.apache.org/transports/http</value>
<value>http://schemas.xmlsoap.org/soap/http</value>
<value>http://schemas.xmlsoap.org/wsdl/soap/http</value>
</list>
</property>
</bean>
This configuration provides guidance on how to configure a transport factory and bind it to http://schemas.xmlsoap.org/soap/http . When I try this with the HTTPTransportFactory, I receive an exception that it cannot be initialized (no such method error).
Caused by: org.apache.cxf.BusException: No conduit initiator was found for the namespace http://schemas.xmlsoap.org/soap/http.
at org.apache.cxf.transport.ConduitInitiatorManagerImpl.getConduitInitiator(ConduitInitiatorManagerImpl.java:112)
at org.apache.cxf.endpoint.AbstractConduitSelector.getSelectedConduit(AbstractConduitSelector.java:73)
at org.apache.cxf.endpoint.UpfrontConduitSelector.prepare(UpfrontConduitSelector.java:61)
at org.apache.cxf.endpoint.ClientImpl.prepareConduitSelector(ClientImpl.java:708)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:476)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:309)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:261)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:127)
precaution: At this point, I will stop my attempt to upgrade my CXF client to 2.4.2 and fall back to the oldest version that works (2.2 series). This is not ideal.
I would like to move forward with the upgrade. Any suggestions regarding how to configure CXF 2.4.X so that my client-only HTTP SOAP configuration wires correctly would be much appriciated.
A: I was also facing the same issue. Through IntelliJ everything was working fine but maven surefire was throwing up error. And finally found the answer. Here it is:
Basically the cxf libraries each supply a META-INF/cxf/bus-extensions.txt file and the default behavior of the packager is to replace that file, causing it to be incomplete. By configuring the shader to append instead of replace the cxf stuff will behave correctly.
Add this to your build section of your pom in the plugins section:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/cxf/bus-extensions.txt</resource>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
A: Did you put the cxf-rt-binding-soap-2.4.x.jar into your class path?
A: Recently I upgraded cxf-rt-ws-security to 3.0.0. From then I started getting org.apache.cxf.BusException: No conduit initiator was found for the namespace http://schemas.xmlsoap.org/soap/http.
at org.apache.cxf.bus.managers.ConduitInitiatorManagerImpl.getConduitInitiator(ConduitInitiatorManagerImpl.java:110).
This issue was resolved after i upgraded the below jars to 3.0.0 in my pom.xml
cxf-rt-frontend-jaxws
cxf-rt-ws-policy
cxf-rt-transports-http
A: Like recommended by the old posts, this is solved by adding cxf-rt-transports-http-jetty into the mix.
A: This error can be produced by invalid url format on client. For example, if you use http transport, you should define "http://localhost:8080/services/{smth}" url. And if you define "localhost:8080/services/{smth}" without http prefix - you receive such an error.
A: This doesn't apply specifically to the original poster's example URLs listed, but we got this error when the URL was incorrect. I.e., we had a certain string in the URL path listed twice instead of once.
A: I had a similar situation with this error and for this issue seems to be coming with the older versions of the following jars
cxf-core-2.x.jar
cxf-rt-frontend-jaxrs-2.x.jar
cxf-rt-rs-client-2.x.jar
cxf-rt-transports-http-2.x.jar
When I have switched to the latest releases of these jars (3.2.1, at the time of writing) has resolved the error.
A: Removing this Dependency from my POM Fixed the error for me
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.1</version>
</dependency>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Refreshing website not changed after modification in Django I am new to Django. Recently I am doing a project from my peer. It's a small web interface in Django.
I made some changes to the source code and I am sure I made it in the right way.
The weird thing is that when I refresh the page, nothing changed. However, after few hours or a whole day, the changes displayed, and sometimes the changes disappear again.
For example, there is the drop-down menu in the index page, and code controlling this drop-down menu is PROPERTY_TYPE_CHOICE = [['1','Transducer'],['2','Trajectory'],
['3', 'Error_Detecting'],
['4', 'Error_Correcting']].
Then I made some changes to PROPERTY_TYPE_CHOICE = [
['1', 'Error_Detecting'],
['1', 'Error_Correcting']].
After that when I refresh the website, nothing changed and the first two choices are still there.
Some one can explain that to me? Is it the matter of configuration of IE or Firefox?
A: No. You just need to restart Apache after you make the changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accounting format issue when exporting I have managed to get the report I am working on looking how I would like, setting a column to display using the accounting format which works perfectly when previewing/printing.
However when I try and export this it loses this accounting format and defaulting to it's original format.
I am using version CR 11.5.10.1263
In Crystal Reports
From Exported PDF
Setting accounting format
A: Strange.
This is a hack, but you could replace the field with two separate fields, one on the left which displays only the currency symbol, and another on the right which displays only the number.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)
Possible Duplicate:
R - How to convert a factor to an integer\numeric in R without a loss of information
The following fact about the as.numeric() function has been brought to my attention
> blah<-c("4","8","10","15")
> blah
[1] "4" "8" "10" "15"
> blah.new<-as.factor(blah)
> blah.new
[1] 4 8 10 15
Levels: 10 15 4 8
> blah.new1<-as.numeric(blah.new)
> blah.new1
[1] 3 4 1 2
When I convert a factor with levels 4, 8, 10, and 15 to a quantitative variable using as.numeric(), every number is converted to a ranking, and the original values are lost.
How do I take the vector 'blah.new' that has levels 10,15, 4, and 8, and convert it to the numeric values 10, 15, 4, and 8?
(This issue has arisen because of a dataset where a quantitative variable is read by read.table() to be a factor)
Thank you!!!!
*****Update: FIGURED IT OUT******
blah.new1<-as.numeric(as.character(blah.new))
However, I am wondering where in documentation for as.numeric() does it say that this function converts arguments into a list of rankings?
A: First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.
?as.numeric says that Factors are handled by the default method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: Getting Started with MVCScaffolding I have gone through many of the MVC tutorials and now I want to create a prototype mvc app of an existing database.
I have installed the MVCScaffolding package and I want to use it with an existing database. Has anyone found steps to go about doing this? I have looked but have been unable to figure out how to get it to work.
I want to connect to a sql server database and have the model created from it. Then scaffold out the views and controller.
Is there something I am not understanding here? Is this how MVC Scaffolding works?
A: this might be a little complex to work with at first, but then you will discover the beauty of it. Check this tutorial out, it helped me a lot when I started Asp.Net MVC 3, also Asp.Net site helped me a lot. Scaffolding is nothing more than a bunch of templates to make your life easier, nothing more. You could also check ScottGu's Blog about this same topic.
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: IOS: don't change color UIButton when it's pushed when I push a custom UIButton it change its color and become more dark but I want that its color don't change when I push it, how can I do this?
A: you need to set the buttons colors for each control state you want to customize
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Remove scroll ability from GtkSpinButton I find that GtkSpinButton can be useful for controlled input numbers on GTK GUI.
But here are some nice features of GTK button which can be unwanted in many cases.
If we have GtkSpinButton inside scrolledwindow then user can accidentally change value, or GtkSpinButton can take scroll behaviour from scrolledwindow.
Question: Is here any possibility to make GtkScrollButton insensible to mouse wheel, at way like is GtkEntry. Or better, could GtkSpinButton be shown without up/down buttons.
If not, how to redirect scroll signal from GtkSpinButton to scrolledwindow?
I try this:
SCROLL_numgreen (GtkObject *object, GdkEvent *event, gpointer user_data)
{
switch (((GdkEventScroll *)event)->direction)
{
case GDK_SCROLL_UP:
return TRUE;
break;
case GDK_SCROLL_DOWN:
return TRUE;
break;
... etc...
but this only "eats" scroll signal from GtkSpinButton and block scrolledwindow at place.
I would most like some general solution without intervention to events of every GtkSpinButton.
A: Here a few pointers to your queries:
Is here any possibility to make GtkScrollButton insensible to mouse wheel, at way like is GtkEntry?
Mouse wheel scroll, mouse click are events. The events can be masked. This can be done at two levels.
*
*At GtkWidget level: you can use gtk_widget_get_events() which will return the event mask in the form of GdkEventMask. You can modify this as per your need & set it using gtk_widget_set_events()
*At GdkWindow level: GtkWidget which has its own drawing/eventing area has a GdkWindow associated with it. You can get the event mask of this window using gdk_window_get_events() and change returned GdkEventMask as per your need & set it to the GdkWindow using gdk_window_set_events(). You can modify event mask through bit-wise operations. If GdkWindow is shared between more than one widget then this mask will effect all the widgets. For masking scroll events you can look into GDK_SCROLL_MASK, GDK_BUTTON_PRESS_MASK & GDK_BUTTON_RELEASE_MASK. You can always check the mask for the event which you are looking for is already set or not. Note: GdkWindow related calls will succeed only after GdkWindow is created for GtkWidget. You can make these calls after gtk_widget_show() of the widget or gtk_widget_show_all of the window which contains these widgets.
Or better, could GtkSpinButton be shown without up/down buttons.
AFAIK GtkSpinButton is implemented to have up/down button indicative of the functionality it provides. If you don't want this, then you can choose another widget say GtkEntry (from which GtkSpinButton is "derived") or GtkLabel. Of course you can create your own widget (from scratch or "derive" from an existing GtkWidget) as per your need & use that same; there is no one stopping you from doing this :)
How to redirect scroll signal from GtkSpinButton to scrolledwindow?
It is possible to do this in the "scroll-event" callback of GtkSpinButton. You can stop the emission of the signal on GtkSpinButton & return FALSE to propagate the event.
...
/* Event callback */
gboolean spinbutton_scroll_handler(GtkWidget *widget, GdkEvent *event, gpointer user_data)
{
/* Stop emission on current widget. Default handler also not called */
/* Refer http://developer.gnome.org/gobject/stable/gobject-Signals.html#g-signal-stop-emission-by-name */
g_signal_stop_emission_by_name(widget, "scroll-event");
/* Return FALSE to propagate the event further; thus scroll window will scroll
If TRUE returned other handlers not invoked for this event,
thus no scroll on scroll window */
return FALSE;
}
...
/* Connect scroll-event to the callback */
g_signal_connect(spinbutton, "scroll-event",
G_CALLBACK(spinbutton_scroll_handler),
(gpointer)0);
...
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Navigation Bar background is hiding right button and cannot remove it on next views I'm using the category below to programmatically change the navigation bar background into my app. It works fine but I cannot see the right button I added in the nav bar. The button seems hidden as tapping on right side nav bar still trigger the action connected to the nav bar right button. Also, how do I remove the navigation background that was added with the given category method ?
UINavigationBar+CustomImage.h
#import <Foundation/Foundation.h>
@interface UINavigationBar (CustomImage)
- (void)setBackgroundImage:(UIImage *)image;
- (void)clearBackgroundImage;
UINavigationBar+CustomImage.m
#import "UINavigationBar+CustomImage.h"
@implementation UINavigationBar (CustomImage)
{
if(image==nil) return;
UIImageView *image_view = [[UIImageView alloc] initWithImage:image];
image_view.frame = CGRectMake(0,0,320,44);
[self addSubview:image_view];
}
- (void)clearBackgroundImage
{
NSSArray *subviews = [self subviews];
for(int i=0;i<[subviews count];i++)
{
if([[subviews objectAtIndex:i] isMemberOfClass:[UIImageView class]])
{
[[subviews objectAtIndex:i] removeFromSuperview];
}
}
}
And in my view controller it's called like this:
[[self.navigationController navigationBar] performSelectorInBackground:@selector(setBackgroundImage:) withObject:[UIImage imageNamed:@"header-background.png"]];
Thanks for helping,
Stephane
A: try sending your view to the back:
[self sendSubviewToBack:image_view];
placing it at a specific z-index:
[self insertSubview:image_view atIndex:0];
or below another view:
[self insertSubview:image_view belowSubview:anotherSubview];
or above another view:
[self insertSubview:image_view aboveSubview:anotherSubview];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multi-line NSAttributedString with truncated text I need a UILabel subcass with multiline attributed text with support for links, bold styles, etc. I also need tail truncation with an ellipsis. None of the open source code that supports attributed text inside UILabels (TTTAttributedLabel, OHAttributedLabel, TTStyledTextLabel) seem to support tail truncation for multi-line text. Is there an easy way to get this?
A: Based on what I found here and over at https://groups.google.com/forum/?fromgroups=#!topic/cocoa-unbound/Qin6gjYj7XU, I came up with the following which works very well.
- (void)drawString:(CFAttributedStringRef)attString inRect:(CGRect)frameRect inContext: (CGContextRef)context
{
CGContextSaveGState(context);
// Flip the coordinate system
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGFloat height = self.frame.size.height;
frameRect.origin.y = (height - frameRect.origin.y) - frameRect.size.height ;
// Create a path to render text in
// don't set any line break modes, etc, just let the frame draw as many full lines as will fit
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, nil, frameRect);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attString);
CFRange fullStringRange = CFRangeMake(0, CFAttributedStringGetLength(attString));
CTFrameRef aFrame = CTFramesetterCreateFrame(framesetter, fullStringRange, framePath, NULL);
CFRelease(framePath);
CFArrayRef lines = CTFrameGetLines(aFrame);
CFIndex count = CFArrayGetCount(lines);
CGPoint *origins = malloc(sizeof(CGPoint)*count);
CTFrameGetLineOrigins(aFrame, CFRangeMake(0, count), origins);
// note that we only enumerate to count-1 in here-- we draw the last line separately
for (CFIndex i = 0; i < count-1; i++)
{
// draw each line in the correct position as-is
CGContextSetTextPosition(context, origins[i].x + frameRect.origin.x, origins[i].y + frameRect.origin.y);
CTLineRef line = (CTLineRef)CFArrayGetValueAtIndex(lines, i);
CTLineDraw(line, context);
}
// truncate the last line before drawing it
if (count) {
CGPoint lastOrigin = origins[count-1];
CTLineRef lastLine = CFArrayGetValueAtIndex(lines, count-1);
// truncation token is a CTLineRef itself
CFRange effectiveRange;
CFDictionaryRef stringAttrs = CFAttributedStringGetAttributes(attString, 0, &effectiveRange);
CFAttributedStringRef truncationString = CFAttributedStringCreate(NULL, CFSTR("\u2026"), stringAttrs);
CTLineRef truncationToken = CTLineCreateWithAttributedString(truncationString);
CFRelease(truncationString);
// now create the truncated line -- need to grab extra characters from the source string,
// or else the system will see the line as already fitting within the given width and
// will not truncate it.
// range to cover everything from the start of lastLine to the end of the string
CFRange rng = CFRangeMake(CTLineGetStringRange(lastLine).location, 0);
rng.length = CFAttributedStringGetLength(attString) - rng.location;
// substring with that range
CFAttributedStringRef longString = CFAttributedStringCreateWithSubstring(NULL, attString, rng);
// line for that string
CTLineRef longLine = CTLineCreateWithAttributedString(longString);
CFRelease(longString);
CTLineRef truncated = CTLineCreateTruncatedLine(longLine, frameRect.size.width, kCTLineTruncationEnd, truncationToken);
CFRelease(longLine);
CFRelease(truncationToken);
// if 'truncated' is NULL, then no truncation was required to fit it
if (truncated == NULL)
truncated = (CTLineRef)CFRetain(lastLine);
// draw it at the same offset as the non-truncated version
CGContextSetTextPosition(context, lastOrigin.x + frameRect.origin.x, lastOrigin.y + frameRect.origin.y);
CTLineDraw(truncated, context);
CFRelease(truncated);
}
free(origins);
CGContextRestoreGState(context);
}
A: Heres a Swift 5 version of @Toydor's answer:
let attributedString = NSMutableAttributedString(string: "my String")
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
style.lineBreakMode = .byTruncatingTail
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle,
value: style,
range: NSMakeRange(0, attributedString.length))
A: Maybe I'm missing something, but whats wrong with? :
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"test"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
[text addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, text.length)];
label.attributedText = text;
This works perfectly and will add a ellipsis to the end.
A: I haven't tried this in all cases, but something like this could work for truncation:
NSAttributedString *string = self.attributedString;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CFAttributedStringRef attributedString = (__bridge CFTypeRef)string;
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attributedString);
CGPathRef path = CGPathCreateWithRect(self.bounds, NULL);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);
BOOL needsTruncation = CTFrameGetVisibleStringRange(frame).length < string.length;
CFArrayRef lines = CTFrameGetLines(frame);
NSUInteger lineCount = CFArrayGetCount(lines);
CGPoint *origins = malloc(sizeof(CGPoint) * lineCount);
CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins);
for (NSUInteger i = 0; i < lineCount; i++) {
CTLineRef line = CFArrayGetValueAtIndex(lines, i);
CGPoint point = origins[i];
CGContextSetTextPosition(context, point.x, point.y);
BOOL truncate = (needsTruncation && (i == lineCount - 1));
if (!truncate) {
CTLineDraw(line, context);
}
else {
NSDictionary *attributes = [string attributesAtIndex:string.length-1 effectiveRange:NULL];
NSAttributedString *token = [[NSAttributedString alloc] initWithString:@"\u2026" attributes:attributes];
CFAttributedStringRef tokenRef = (__bridge CFAttributedStringRef)token;
CTLineRef truncationToken = CTLineCreateWithAttributedString(tokenRef);
double width = CTLineGetTypographicBounds(line, NULL, NULL, NULL) - CTLineGetTrailingWhitespaceWidth(line);
CTLineRef truncatedLine = CTLineCreateTruncatedLine(line, width-1, kCTLineTruncationEnd, truncationToken);
if (truncatedLine) { CTLineDraw(truncatedLine, context); }
else { CTLineDraw(line, context); }
if (truncationToken) { CFRelease(truncationToken); }
if (truncatedLine) { CFRelease(truncatedLine); }
}
}
free(origins);
CGPathRelease(path);
CFRelease(frame);
CFRelease(framesetter);
A: Multi Line Vertical Glyph With Truncated. Swift3 and Swift4 version.
Add: Xcode9.1 Swift4 Compatibility. ( use block "#if swift(>=4.0)" )
class MultiLineVerticalGlyphWithTruncated: UIView, SimpleVerticalGlyphViewProtocol {
var text:String!
var font:UIFont!
var isVertical:Bool!
func setupProperties(text: String?, font:UIFont?, isVertical:Bool) {
self.text = text ?? ""
self.font = font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
self.isVertical = isVertical
}
override func draw(_ rect: CGRect) {
if self.text == nil {
return
}
// Create NSMutableAttributedString
let attributed = NSMutableAttributedString(string: text) // if no ruby
//let attributed = text.attributedStringWithRuby() // if with ruby, Please create custom method
#if swift(>=4.0)
attributed.addAttributes([
NSAttributedStringKey.font: font,
NSAttributedStringKey.verticalGlyphForm: isVertical,
],
range: NSMakeRange(0, attributed.length))
#else
attributed.addAttributes([
kCTFontAttributeName as String: font,
kCTVerticalFormsAttributeName as String: isVertical,
],
range: NSMakeRange(0, attributed.length))
#endif
drawContext(attributed, textDrawRect: rect, isVertical: isVertical)
}
}
protocol SimpleVerticalGlyphViewProtocol {
}
extension SimpleVerticalGlyphViewProtocol {
func drawContext(_ attributed:NSMutableAttributedString, textDrawRect:CGRect, isVertical:Bool) {
guard let context = UIGraphicsGetCurrentContext() else { return }
var path:CGPath
if isVertical {
context.rotate(by: .pi / 2)
context.scaleBy(x: 1.0, y: -1.0)
path = CGPath(rect: CGRect(x: textDrawRect.origin.y, y: textDrawRect.origin.x, width: textDrawRect.height, height: textDrawRect.width), transform: nil)
}
else {
context.textMatrix = CGAffineTransform.identity
context.translateBy(x: 0, y: textDrawRect.height)
context.scaleBy(x: 1.0, y: -1.0)
path = CGPath(rect: textDrawRect, transform: nil)
}
let framesetter = CTFramesetterCreateWithAttributedString(attributed)
let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attributed.length), path, nil)
// Check need for truncate tail
if (CTFrameGetVisibleStringRange(frame).length as Int) < attributed.length {
// Required truncate
let linesNS: NSArray = CTFrameGetLines(frame)
let linesAO: [AnyObject] = linesNS as [AnyObject]
var lines: [CTLine] = linesAO as! [CTLine]
let boundingBoxOfPath = path.boundingBoxOfPath
let lastCTLine = lines.removeLast()
let truncateString:CFAttributedString = CFAttributedStringCreate(nil, "\u{2026}" as CFString, CTFrameGetFrameAttributes(frame))
let truncateToken:CTLine = CTLineCreateWithAttributedString(truncateString)
let lineWidth = CTLineGetTypographicBounds(lastCTLine, nil, nil, nil)
let tokenWidth = CTLineGetTypographicBounds(truncateToken, nil, nil, nil)
let widthTruncationBegins = lineWidth - tokenWidth
if let truncatedLine = CTLineCreateTruncatedLine(lastCTLine, widthTruncationBegins, .end, truncateToken) {
lines.append(truncatedLine)
}
var lineOrigins = Array<CGPoint>(repeating: CGPoint.zero, count: lines.count)
CTFrameGetLineOrigins(frame, CFRange(location: 0, length: lines.count), &lineOrigins)
for (index, line) in lines.enumerated() {
context.textPosition = CGPoint(x: lineOrigins[index].x + boundingBoxOfPath.origin.x, y:lineOrigins[index].y + boundingBoxOfPath.origin.y)
CTLineDraw(line, context)
}
}
else {
// Not required truncate
CTFrameDraw(frame, context)
}
}
}
How to use
class ViewController: UIViewController {
@IBOutlet weak var multiLineVerticalGlyphWithTruncated: MultiLineVerticalGlyphWithTruncated! // UIView
let font:UIFont = UIFont(name: "HiraMinProN-W3", size: 17.0) ?? UIFont.systemFont(ofSize: 17.0)
override func viewDidLoad() {
super.viewDidLoad()
let text = "iOS 11 sets a new standard for what is already the world’s most advanced mobile operating system. It makes iPhone better than before. It makes iPad more capable than ever. And now it opens up both to amazing possibilities for augmented reality in games and apps. With iOS 11, iPhone and iPad are the most powerful, personal, and intelligent devices they’ve ever been."
// If check for Japanese
// let text = "すでに世界で最も先進的なモバイルオペレーティングシステムであるiOSに、iOS 11が新たな基準を打ち立てます。iPhoneは今まで以上に優れたものになり、iPadはかつてないほどの能力を手に入れます。さらにこれからはどちらのデバイスにも、ゲームやアプリケーションの拡張現実のための驚くような可能性が広がります。iOS 11を搭載するiPhoneとiPadは、間違いなくこれまでで最もパワフルで、最もパーソナルで、最も賢いデバイスです。"
// if not vertical text, isVertical = false
multiLineVerticalGlyphWithTruncated.setupProperties(text: text, font: font, isVertical: true)
}
}
A: Hi I am the developer of OHAttributedLabel.
There is no easy way to achieve this (as explained in the associated issue I opened on the github repository of my project), because CoreText does not offer such feature.
The only way to do this would be to implement the text layout yourself using CoreText objects (CTLine, etc) instead of using the CTFrameSetter that does this for you (but w/o managing line truncation). The idea would be to build all the CTLines to lay them out (depending on the glyphs in your NSAttributedString it contains and the word wrapping policy) one after the other and manage the ellipsis at the end yourself.
I would really appreciate if someone propose a solution to do this propery as it seems a bit of work to do and you have to manage a range of special/unusual cases too (emoji cases, fonts with odd metrics and unusual glyphs, vertical alignment, take into account the size of the ellipsis itself at the end to know when to stop).
So feel free to dig around and try to implement the framing of the lines yourself it would be really appreciated!
A: You may be able to use follow code to have a more simple solution.
// last line.
if (_limitToNumberOfLines && count == _numberOfLines-1)
{
// check if we reach end of text.
if (lineRange.location + lineRange.length < [_text length])
{
CFDictionaryRef dict = ( CFDictionaryRef)attributes;
CFAttributedStringRef truncatedString = CFAttributedStringCreate(NULL, CFSTR("\u2026"), dict);
CTLineRef token = CTLineCreateWithAttributedString(truncatedString);
// not possible to display all text, add tail ellipsis.
CTLineRef truncatedLine = CTLineCreateTruncatedLine(line, self.bounds.size.width - 20, kCTLineTruncationEnd, token);
CFRelease(line); line = nil;
line = truncatedLine;
}
}
I'm using MTLabel in my project and it's a really nice solution for my project.
A: I integrated wbyoung's solution into OHAttributedLabel drawTextInRect: method if anyone is interested:
- (void)drawTextInRect:(CGRect)aRect
{
if (_attributedText)
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
// flipping the context to draw core text
// no need to flip our typographical bounds from now on
CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, self.bounds.size.height), 1.f, -1.f));
if (self.shadowColor)
{
CGContextSetShadowWithColor(ctx, self.shadowOffset, 0.0, self.shadowColor.CGColor);
}
[self recomputeLinksInTextIfNeeded];
NSAttributedString* attributedStringToDisplay = _attributedTextWithLinks;
if (self.highlighted && self.highlightedTextColor != nil)
{
NSMutableAttributedString* mutAS = [attributedStringToDisplay mutableCopy];
[mutAS setTextColor:self.highlightedTextColor];
attributedStringToDisplay = mutAS;
(void)MRC_AUTORELEASE(mutAS);
}
if (textFrame == NULL)
{
CFAttributedStringRef cfAttrStrWithLinks = (BRIDGE_CAST CFAttributedStringRef)attributedStringToDisplay;
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(cfAttrStrWithLinks);
drawingRect = self.bounds;
if (self.centerVertically || self.extendBottomToFit)
{
CGSize sz = CTFramesetterSuggestFrameSizeWithConstraints(framesetter,CFRangeMake(0,0),NULL,CGSizeMake(drawingRect.size.width,CGFLOAT_MAX),NULL);
if (self.extendBottomToFit)
{
CGFloat delta = MAX(0.f , ceilf(sz.height - drawingRect.size.height))+ 10 /* Security margin */;
drawingRect.origin.y -= delta;
drawingRect.size.height += delta;
}
if (self.centerVertically) {
drawingRect.origin.y -= (drawingRect.size.height - sz.height)/2;
}
}
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRect(path, NULL, drawingRect);
CFRange fullStringRange = CFRangeMake(0, CFAttributedStringGetLength(cfAttrStrWithLinks));
textFrame = CTFramesetterCreateFrame(framesetter,fullStringRange, path, NULL);
CGPathRelease(path);
CFRelease(framesetter);
}
// draw highlights for activeLink
if (_activeLink)
{
[self drawActiveLinkHighlightForRect:drawingRect];
}
BOOL hasLinkFillColorSelector = [self.delegate respondsToSelector:@selector(attributedLabel:fillColorForLink:underlineStyle:)];
if (hasLinkFillColorSelector) {
[self drawInactiveLinkHighlightForRect:drawingRect];
}
if (self.truncLastLine) {
CFArrayRef lines = CTFrameGetLines(textFrame);
CFIndex count = MIN(CFArrayGetCount(lines),floor(self.size.height/self.font.lineHeight));
CGPoint *origins = malloc(sizeof(CGPoint)*count);
CTFrameGetLineOrigins(textFrame, CFRangeMake(0, count), origins);
// note that we only enumerate to count-1 in here-- we draw the last line separately
for (CFIndex i = 0; i < count-1; i++)
{
// draw each line in the correct position as-is
CGContextSetTextPosition(ctx, origins[i].x + drawingRect.origin.x, origins[i].y + drawingRect.origin.y);
CTLineRef line = (CTLineRef)CFArrayGetValueAtIndex(lines, i);
CTLineDraw(line, ctx);
}
// truncate the last line before drawing it
if (count) {
CGPoint lastOrigin = origins[count-1];
CTLineRef lastLine = CFArrayGetValueAtIndex(lines, count-1);
// truncation token is a CTLineRef itself
CFRange effectiveRange;
CFDictionaryRef stringAttrs = CFAttributedStringGetAttributes((BRIDGE_CAST CFAttributedStringRef)_attributedTextWithLinks, 0, &effectiveRange);
CFAttributedStringRef truncationString = CFAttributedStringCreate(NULL, CFSTR("\u2026"), stringAttrs);
CTLineRef truncationToken = CTLineCreateWithAttributedString(truncationString);
CFRelease(truncationString);
// now create the truncated line -- need to grab extra characters from the source string,
// or else the system will see the line as already fitting within the given width and
// will not truncate it.
// range to cover everything from the start of lastLine to the end of the string
CFRange rng = CFRangeMake(CTLineGetStringRange(lastLine).location, 0);
rng.length = CFAttributedStringGetLength((BRIDGE_CAST CFAttributedStringRef)_attributedTextWithLinks) - rng.location;
// substring with that range
CFAttributedStringRef longString = CFAttributedStringCreateWithSubstring(NULL, (BRIDGE_CAST CFAttributedStringRef)_attributedTextWithLinks, rng);
// line for that string
CTLineRef longLine = CTLineCreateWithAttributedString(longString);
CFRelease(longString);
CTLineRef truncated = CTLineCreateTruncatedLine(longLine, drawingRect.size.width, kCTLineTruncationEnd, truncationToken);
CFRelease(longLine);
CFRelease(truncationToken);
// if 'truncated' is NULL, then no truncation was required to fit it
if (truncated == NULL){
truncated = (CTLineRef)CFRetain(lastLine);
}
// draw it at the same offset as the non-truncated version
CGContextSetTextPosition(ctx, lastOrigin.x + drawingRect.origin.x, lastOrigin.y + drawingRect.origin.y);
CTLineDraw(truncated, ctx);
CFRelease(truncated);
}
free(origins);
}
else{
CTFrameDraw(textFrame, ctx);
}
CGContextRestoreGState(ctx);
} else {
[super drawTextInRect:aRect];
}
}
A: Ran into this issue here in 2021.
I wrapped @Toydor's and @gypsyDev's answer into a UILabel extension so it can be applied where needed. Swift 5.
extension UILabel {
func ensureAttributedTextShowsTruncation() {
guard let text = attributedText else { return }
let attributedString = NSMutableAttributedString(attributedString: text)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingTail
attributedString.addAttribute(.paragraphStyle,
value: paragraphStyle,
range: NSRange(location: 0, length: attributedString.length))
attributedText = attributedString
}
}
A: I used as sample MTLabel. It allows to manage line height.
I needed the draw method exactly, so i just put away most stuff i did not need.
This method allows me to draw multilined text in rect with tail truncation.
CGRect CTLineGetTypographicBoundsAsRect(CTLineRef line, CGPoint lineOrigin)
{
CGFloat ascent = 0;
CGFloat descent = 0;
CGFloat leading = 0;
CGFloat width = CTLineGetTypographicBounds(line, &ascent, &descent, &leading);
CGFloat height = ascent + descent;
return CGRectMake(lineOrigin.x,
lineOrigin.y - descent,
width,
height);
}
- (void)drawText:(NSString*) text InRect:(CGRect)rect withFont:(UIFont*)aFont inContext:(CGContextRef)context {
if (!text) {
return;
}
BOOL _limitToNumberOfLines = YES;
int _numberOfLines = 2;
float _lineHeight = 22;
//Create a CoreText font object with name and size from the UIKit one
CTFontRef font = CTFontCreateWithName((CFStringRef)aFont.fontName ,
aFont.pointSize,
NULL);
//Setup the attributes dictionary with font and color
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)font, (id)kCTFontAttributeName,
[UIColor lightGrayColor].CGColor, kCTForegroundColorAttributeName,
nil];
NSAttributedString *attributedString = [[[NSAttributedString alloc]
initWithString:text
attributes:attributes] autorelease];
CFRelease(font);
//Create a TypeSetter object with the attributed text created earlier on
CTTypesetterRef typeSetter = CTTypesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
//Start drawing from the upper side of view (the context is flipped, so we need to grab the height to do so)
CGFloat y = self.bounds.origin.y + self.bounds.size.height - rect.origin.y - aFont.ascender;
BOOL shouldDrawAlong = YES;
int count = 0;
CFIndex currentIndex = 0;
float _textHeight = 0;
CGContextSaveGState(context);
CGContextSetTextMatrix(context, CGAffineTransformIdentity);
CGContextTranslateCTM(context, 0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
//Start drawing lines until we run out of text
while (shouldDrawAlong) {
//Get CoreText to suggest a proper place to place the line break
CFIndex lineLength = CTTypesetterSuggestLineBreak(typeSetter,
currentIndex,
rect.size.width);
//Create a new line with from current index to line-break index
CFRange lineRange = CFRangeMake(currentIndex, lineLength);
CTLineRef line = CTTypesetterCreateLine(typeSetter, lineRange);
//Check to see if our index didn't exceed the text, and if should limit to number of lines
if (currentIndex + lineLength >= [text length])
{
shouldDrawAlong = NO;
}
else
{
if (!(_limitToNumberOfLines && count < _numberOfLines-1))
{
int i = 0;
if ([[[text substringWithRange:NSMakeRange(currentIndex, lineLength)] stringByAppendingString:@"…"] sizeWithFont:aFont].width > rect.size.width)
{
i--;
while ([[[text substringWithRange:NSMakeRange(currentIndex, lineLength + i)] stringByAppendingString:@"…"] sizeWithFont:aFont].width > rect.size.width)
{
i--;
}
}
else
{
i++;
while ([[[text substringWithRange:NSMakeRange(currentIndex, lineLength + i)] stringByAppendingString:@"…"] sizeWithFont:aFont].width < rect.size.width)
{
i++;
}
i--;
}
attributedString = [[[NSAttributedString alloc] initWithString:[[text substringWithRange:NSMakeRange(currentIndex, lineLength + i)] stringByAppendingString:@"…"] attributes:attributes] autorelease];
CFRelease(typeSetter);
typeSetter = CTTypesetterCreateWithAttributedString((CFAttributedStringRef)attributedString);
CFRelease(line);
CFRange lineRange = CFRangeMake(0, 0);
line = CTTypesetterCreateLine(typeSetter, lineRange);
shouldDrawAlong = NO;
}
}
CGFloat x = rect.origin.x;
//Setup the line position
CGContextSetTextPosition(context, x, y);
CTLineDraw(line, context);
count++;
CFRelease(line);
y -= _lineHeight;
currentIndex += lineLength;
_textHeight += _lineHeight;
}
CFRelease(typeSetter);
CGContextRestoreGState(context);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: Can someone explain what REF, CREATEREF, DEREF, KEY in Entity SQL do? I can't find good documentation on these operators. Can someone provide some examples of use and explain what they do?
A: Entity SQL's CREATEREF reference: http://msdn.microsoft.com/en-us/library/bb386880(v=VS.90)
It's used to "Fabricates references to an entity in an entityset". You can also find references of REF and DEREF from the link.
For VS 2010, the reference is: http://msdn.microsoft.com/en-us/library/bb386880(v=VS.100)
Sample from MSDN:
In the example below, Orders and BadOrders are both entitysets of type
Order, and Id is assumed to be the single key property of Order. The
example illustrates how we may produce a reference to an entity in
BadOrders. Note that the reference may be dangling. That is, the
reference may not actually identify a specific entity. In those cases,
a DEREF operation on that reference returns a null.
select CreateRef(LOB.BadOrders, row(o.Id))
from LOB.Orders as o
Sample code of using entity framework SQL:
using (EntityConnection conn =
new EntityConnection("name=AdventureWorksEntities"))
{
conn.Open();
// Create a query that takes two parameters.
string esqlQuery =
@"SELECT VALUE Contact FROM AdventureWorksEntities.Contact
AS Contact WHERE Contact.LastName = @ln AND
Contact.FirstName = @fn";
try
{
using (EntityCommand cmd = new EntityCommand(esqlQuery, conn))
{
// Create two parameters and add them to
// the EntityCommand's Parameters collection
EntityParameter param1 = new EntityParameter();
param1.ParameterName = "ln";
param1.Value = "Adams";
EntityParameter param2 = new EntityParameter();
param2.ParameterName = "fn";
param2.Value = "Frances";
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
using (DbDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
// Iterate through the collection of Contact items.
while (rdr.Read())
{
Console.WriteLine(rdr["FirstName"]);
Console.WriteLine(rdr["LastName"]);
}
}
}
}
catch (EntityException ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Julian Day to ISO 8601 string in SQLite I have a table that stores date/time values as julian days in SQLite (using the julianday() function). I can't seem to figure out how to convert them back to ISO 8601 style strings (YYYY-mm-ddThh:m:ss.sss) when I read them?
A: Just feed the Julian day number to the datetime function:
A time string can be in any of the following formats:
[...]
12. DDDDDDDDDD
[...]
Format 12 is the Julian day number expressed as a floating point value.
So datetime(julianday_output) goes in the opposite direction as the julianday function:
sqlite> select datetime(julianday(current_timestamp)) as dt_from_jd, current_timestamp as dt;
dt_from_jd | dt
2011-09-30 14:46:52 | 2011-09-30 14:46:52
A: Have you tried strftime? http://www.sqlite.org/lang_datefunc.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: nginx + uwsgi 502 Bad Gateway python I'm running a script in python and takes a long time to process. The thing is if the function takes to long to run, i guess the nginx has a timeout, in his configuration and that prevents somekind of errors, and prevents the function to run completely.
I just want to know were i can increse the value of the timeout. Because i've tried some commands in the file conf of nginx such as:
uwsgi_connect_timeout 75;
uwsgi_send_timeout 75;
uwsgi_read_timeout 75;
keepalive_timeout 650;
but none of this worked.
Thks in advance
A: The problem with just extending the timeout is that no matter how much longer you set it to you will run into limitations somewhere along the line. Either with the web server, the browser or your geocode calls. If it is something that routinely fails n times in a request, then you can't really make any guarantees.
So rather than having the client request hanging on a long running process (and by extension risking a server timeout), why don't you use something like celery to run those geocode tasks and on the client-side, submit your client-side request via javascript and poll the server for the answer via ajax until it get's a response?
A: I also had Bad gateway error in NGIX + uWSGI configuration, and for sake of people who google this question: it might be missing uwsgi python plugin. Please see: uWSGI configuration issue: uwsgi fails without any error message..
A: I tried everything written in the above response as well as other places but they did not work.
My solution was changing my socket in both the uwsgi.conf and nginx.conf files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Higher Query result with the DISTINCT Keyword? Say I have a table with 100,000 User IDs (UserID is an int).
When I run a query like
SELECT COUNT(Distinct User ID) from tableUserID
the result I get is HIGHER than the result from the following statement:
SELECT COUNT(User ID) from tableUserID
I thought Distinct implied unique, which would mean a lower result. What would cause this discrepancy and how would I identify those user IDs that don't show up in the 2nd query?
Thanks
**
UPDATE - 11:14 am est
**
Hi All
I sincerely apologize as I should've taken the trouble to reproduce this in my local environment. But I just wanted to see if there was a general consensus about this. Here are the full details:
The query is a result of an inner join between 2 tables.
One has this information:
TABLE ACTIVITY (NO PRIMARY KEY)
UserID int (not Nullable)
JoinDate datetime
Status tinyint
LeaveDate datetime
SentAutoMessage tinyint
SectionDetails varchar
And here is the second table:
TABLE USER_INFO (CLUSTERED PRIMARY KEY)
UserID int (not Nullable)
UserName varchar
UserActive int
CreatedOn datetime
DisabledOn datetime
The tables are joined on UserID and the UserID being selected in the original 2 queries is the one from the TABLE ACTIVITY.
Hope this clarifies the question.
A: This is not technically an answer, but since I took time to analyze this, I might as well post it (although I have the risk of being down voted).
There was no way I could reproduce the described behavior.
This is the scenario:
declare @table table ([user id] int)
insert into @table values
(1),(1),(1),(1),(1),(1),(1),(2),(2),(2),(2),(2),(2),(null),(null)
And here are some queries and their results:
SELECT COUNT(User ID) FROM @table --error: this does not run
SELECT COUNT(dsitinct User ID) FROM @table --error: this does not run
SELECT COUNT([User ID]) FROM @table --result: 13 (nulls not counted)
SELECT COUNT(distinct [User ID]) FROM @table --result: 2 (nulls not counted)
And something interesting:
SELECT user --result: 'dbo' in my sandbox DB
SELECT count(user) from @table --result: 15 (nulls are counted because user value
is not null)
SELECT count(distinct user) from @table --result: 1 (user is the same
value always)
I find it very odd that you are able to run the queries exactly how you described. You'd have to let us know the table structure and the data to get further help.
A:
how would I identify those user IDs that don't show up in the 2nd query
Try this query
SELECT UserID from tableUserID Where UserID not in (SELECT Distinct User ID from tableUserID)
I think there will be no row.
Edit:
User is a reserved keyword. Do you mean UserID in your requests ?
Ray : Yes
A: I tried to reproduce the problem in my environment and my conclusion is that given the conditions you described, the result from the first query can not be higher than the second one. Even if there would be NULL's, that just won't happen.
Did you run the query @Jean-Charles sugested?
I'm very intrigued with this, please let us know what turns out to be the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: rails syntax "render json: @products" I've been using rails in windows for some time, and i've decided to try it on linux recently. So i've been setting everything up, but now the project i had created on windows doesn't run properly on ubuntu: it fails to interpet the following syntax:
render json: @products
Producing the following error:
/home/dcastro/workspace/teste/app/controllers/products_controller.rb:9: syntax error, unexpected ':', expecting '}'
format.json { render json: @products }
^
/home/dcastro/workspace/teste/app/controllers/products_controller.rb:20: syntax error, unexpected ':', expecting '}'
format.json { render json: @product }
And only works if i change it to:
render :json => @products
At first i thought it was because i was using an older version of ruby (namely, 1.8.7). So i installed 1.9.2p290, but that didn't work.
If it matters, i'm using rails 3.1.0 and ubuntu 11.04.
Does anyone know what's causing this? And how can i fix it? Thanks in advance!
A: { foo: 'bar' } is the new hash literal syntax, introduced in Ruby 1.9 (not sure which release). So, it should (and does, on my system) work with Ruby 1.9.2p290.
A: The following is correct!
render :json => @products
If you setup a as_json class method in your Product model, whatever you place in that hash will be included in the response at your JSON endpoint.
As per the official 3.1 rails guide, this is the correct syntax.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Razor intellisense and code formatting with MVC 4 I have just integrated MVC into my Asp.Net website project.
Its working, but my Razor code is missing formatted as code (e.g. yellow background for the @ character.
Additionally there is no intellisense:
Here are my MVC related references from web.config
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
A: Please try building the project and see if that helps.
A: Check the Web.config under the View folder
configSections->sectionGroup and sections. The Version numbers should be 2.0.0.0
All other version in the file should be 4.0.0.0
A: I'm not sure what fixed this:
I uninstalled all versions of MVC framework, re-installed MVC 4, and upgraded ReSharper to v 6
However, I am still not getting syntax highlighting ( the @ character is not yellow)
A: On december 5 2013 i installed the latest updates for visual Studio 2012. Right after that, the cshtml in my mvc4 project went like it apprears in Notepad: not good!
I uninstalled via the package manager, MVC4, restarted VS2012 and installed it again. After that everything looked right again: the syntax highlighting worked again.
I use VS2012 professional.
A: For me, the .cshtml file was not included in the project.
I checked in Solution explorer, it was not showing under my View folder.
I chose "Show All files" at top of solution explorer buttons.
My cshtml file started showing but icon in dotted lines, so right click on it >> Include in the project.
and building the solution, includes my cshtml file in the project. and now everything's works fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Writing Views using Jquery UI widgets Our company is about to start a new web based product on asp.net mvc. We have different clients who require different themes on our application. To make user interface to support different themes, we are thinking to develop our UI completely using JQuery UI widgets (buttons, dropdown and everything using jquery UI). This way we won't have to deal with re-writing CSS for every client. Can you guys please provide me with your feedback, do you think it's a good idea to create UI entirely using jquery UI?
A: No. Use Razor to generate the markup. You shouldn't have to reqrite javascript for each client unless they want different client-side functionality.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What may be the reason for JMS or OS not to recognize connection drop? We have a system with servers communicating over JMS. Sometimes some of the servers can not reconnect after loosing connection to JMS. Loss of connection happens when server restarts, bad network... The reason that prevents reconnecting is "ClientID already in use." error.
excerpt from JMS log:
"A client on connection guest@10.0.0.106:2390 tried to use client id ABC which is already in use
In-conflict clientID ABC is owned by local connection guest@10.0.0.106:1098"
All servers have distinct clientID. Connection on remote port 1098 existed before server 10.0.0.106 lost connection to JMS. Port 1098 on server ABC is not even open.
I tried using TCPview when the problem occurred. Old connection to server on port 1098 still exists.
I have 2 questions:
Is it possible that JMS sends control packets to nonexistant remote port 1098 without error?
What may be the reason for OS not to recognize connection drop?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error when trying to install RVM on Linux Mint: No command RVM found I'm following this tutorial:
http://www.christopherirish.com/2010/08/25/how-to-install-rvm-on-ubuntu-10-04/
When I get to the part where he tells us to modify the .bashrc file, I get stuck. For one thing, the .bashrc file is nowhere to be found.
Second, I tried manually creating the file myself and put this as it's contents:
if [[ -n "$PS1" ]]; then
if [[ -s $HOME/.rvm/scripts/rvm ]] ; then source $HOME/.rvm/scripts/rvm ; fi
fi
But when I try running the command rvm notes I get the following error:
No command 'rvm' found, but there are 20 similar ones rvm: command not
found
What can I do to use RVM properly?
A: It's seems to me the last time I assisted someone with an RVM install, Wayne changed it so that the install automatically added the proper lines to the .bashrc file. I am not that familiar with Linux Mint, but know that you can sometimes also see it as .bash_profile, or simply .profile. Another recommendation from me, and something that has caused me a lot of heartache when installing RVM is remembering to restart the terminal session after installing RVM. The easiest way of course is to simply close your terminal session and start a new one, or if you know your shell configuration profile, simple source ~/.bashrc in your open terminal.
A: Please be sure to follow the directions listed on https://rvm.beginrescueend.com/rvm/install/ as they detail the exact set of steps needed for both Per-User and Multi-User installation types. They work for 1.6.x and up exactly as detailed, and were tested up to and including against 1.8.5 which is the current release.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to convert a json formatted string into a json array in javascript I am using the $.post() method to retrieve a json formatted string which looks like this:
{elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}
In the success callback function of $.post(), I would like to loop the values of this json formatted string but I can't figure out how to do it.
// data returns {elementid:10},{elementid:11},{elementid:12},{elementid:14}, etc.
$.post('form.php',
{'postvalues' : input_ids},
function(data){
var elements = Array();
elements = [data];
for(var i=0; i<elements.length; i++) {
var value = elements[i]['elementid'];
alert('value = '+value);
}
});
When I do this, instead of getting value = 10, value = 11, value = 12, etc. in the alert box,
I get value = undefined
What must I change in the format of the variable 'data' so that it will be interpreted as array values and not a string?
thanks for your help
A: Your string isn't valid JSON if you don't have the '[' and ']' characters.
You can add those in , then parse it using the jQuery.parseJSON()[docs] method.
elements = jQuery.parseJSON( '[' + data + ']' );
...but it would be better if you sent correct JSON data from the server.
Also, your JSON keys must be wrapped in double quotes.
{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}
A: Your query isn't returning valid JSON. It should be [{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}] and not {elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}. Is there any way you can fix that? Otherwise, you will have to do this:
elements = jQuery.parseJSON("[" + data + "]");
The right thing to do, however, is to return valid JSON from the server (if you have any control over that).
A: use JSON.parse(data) to put a string which contains a JSON object in a variable
A: Try this, it looks like you are getting passed an array (apart from the missing surrounding []), and if you tell jquery that it's json it'll parse it for you properly:
$.post('form.php', {'postvalues' : input_ids}, function(data){
for(var i=0; i<data.length; i++) {
var value = data[i]['elementid'];
alert('value = '+value);
}
}, 'json'); // telling it that the content received is json
A: Use the "for in" statement. Such as:
for (var x in data) {
console.log(data[x]['elementid']);
}
I tested it and it perfectly worked!
Hope this helps.
Ps. Console.log() output the result in the browser console (so it won't work in IE, of course).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: An alternative to Android's webview Does anyone knows an alternative to Android's webview component ? For some reasons, it's functionality's are insufficient for me : I need to be able to catch every single request to some url, when i'm browsing a wml page (wap). Anyway, I need to be able to do stuff that Android's webview is not made for.
I thought "hey, let's play with the source code, I'm pretty sure that webviews are using apache.org librairies to access internet".
Oh boy was I mistaken. Webviews use native code, and that's where I'm stuck.
So I was wondering if anyone knew of another web browser view, in pure java, that would be open source and nice. It's not a problem if it's slow, i'm displaying some basic wap pages...
Thanks in advance.
A: You can extend WebView's functionality by using setWebViewClient & setWebChromeClient.
WebView.setWebViewClient(new MyWebViewClient());
WebView.setWebChromeClient(new WebChromeClient() {..}
You can handle each and every request sent/received from the WebView by overriding the below methods:
public boolean shouldOverrideUrlLoading(WebView view, String url) {..}
public void onPageStarted(WebView view, String url, Bitmap favicon) {..}
public void onPageFinished(WebView view, String url) {..}
A: The crosswalk project: https://crosswalk-project.org/ might be what you need. But beware, there are places where it differs from the stock webview. In some ways better, in some ways worse. For example, it supports WebGL (good), but currently the background cannot be transparent (bad). The really good news, it seems to be very actively supported, running it's own Jira to track and fix and Intel seems to be very involved.
A: Try this:
goButton4.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Uri uri = Uri.parse("http://tory.com/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
A: Try to see how was Opera Mini programmed.
But I think you must program it if you want another one . But i would be surprised if it has a nice performance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: Change language of the ios application I've put my app settings into iPhone Settings panel. I want to switch between languages independently of the iPhone system language. Is it possible? I'm using this advice:
How to force NSLocalizedString to use a specific language
But it translates only string inside app, but my nib files are same. How to reload my nibs?
A: The key is to override the NSUserDefaults language key before UIApplicationMain() is called in your main() function in main.m. Try something like this in your main() function:
// use whatever language/locale id you want to override
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"de_DE", nil]
forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];
int retVal = UIApplicationMain(argc, argv, nil, nil);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: does not recognize query string containing ' I am querying some data from the database and inserting data. Whenever the user inserts with ' I have a problem that the query does not regconize.
How can I get rid of that? should I use: string.replace(''', '"') ? or any other trick?
Thanks in advance.
A: You should be using parameterized queries. It's dangerous to insert unprocessed user input on a query, it's an open door to SQL-Injection attacks.
Those are queries in the form
SELECT * FROM USERS where USER_ID = ?
The value of ? is set programmatically with a query.setString(1, userId) call, and the driver takes care of escaping everything correctly. It's not a burden you want to have on your shoulders.
A: Besides to what Xavi López has posted (and you really should keep that in mind), to have a single quote in a string you need to write two single quotes, e.g.:
myString := 'I''m writing an answer';
This represents the string I'm writing an answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: moq returning dataReader I'm having a strange experience with moq/mocking.
Im trying to mock the data going into a method so that i dont have to have adatabase available at test time.
So im loading in some data ive previously seralised.
Loading it into a dataTable, then creating a data reader from there, because my business layer method expects a data reader.
Then creating a mock for my data layer. and setting the return value for a particular method to my new datareader.
I am then setting (injecting) my mock data layer into my business layer so it can do the work of returning the data when the time comes..
var dataTable = DataSerialisation.GetDataTable("C:\\data.xml");
IDataReader reader = dataTable.CreateDataReader();
var mock = new Mock<IRetailerDal>();
mock.Setup(x => x.ReadRetailerDetails("00")).Returns(reader);
retailersBusinessLayer.RetailerDal = mock.Object;
var r = retailersBusinessLayer.GetRetailerDetail("00");
Now.. when the "GetRetailerDetail" is called is basically gets to "while(data.Read())" and crashes out but only sometimes.
I get the exception:
System.InvalidOperationException : DataTableReader is invalid for current DataTable 'Table1'.
Othertimes it move past that and can read some columns data, but other columns dont exist. (which must be to do with my serialisation method)
A: Well, this isnt exactly a satisfactory answer, but the code works now..
its similar to this.. in that no reason was found.
here
Anyway... as stated above the issue was ocuring inside my GetRetailerDetail method, where the code hits while(data.Read()) it throws the error..
The fix.. change the name of the data reader variable.. i.e. its was "data" and its now "data2".. thats all i changed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Checking if Two Massive Python Dictionaries are Equivalent I have a massive python dictionary with over 90,000 entries. For reasons I won't get into, I need to store this dictionary in my database and then at a later point recompile dictionary from the database entries.
I am trying to set up a procedure to verify that my storage and recompilation was faithful and that my new dictionary is equivalent to the old one. What is the best methodology for testing this.
There are minor differences and I want to figure out what they are.
A: >>> d1 = {'a':1,'b':2,'c':3}
>>> d2 = {'b':2,'x':2,'a':5}
>>> set(d1.iteritems()) - set(d2.iteritems()) # items in d1 not in d2
set([('a', 1), ('c', 3)])
>>> set(d2.iteritems()) - set(d1.iteritems()) # items in d2 not in d1
set([('x', 2), ('a', 5)])
Edit
Don't vote for this answer. Go to Fast comparison between two Python dictionary and add an upvote. It is a very complete solution.
A: You could start with something like this and tweak it to suit your needs
>>> bigd = dict([(x, random.randint(0, 1024)) for x in xrange(90000)])
>>> bigd2 = dict([(x, random.randint(0, 1024)) for x in xrange(90000)])
>>> dif = set(bigd.items()) - set(bigd2.items())
A: The most obvious approach is of course:
if oldDict != newDict:
print "**Failure to rebuild, new dictionary is different from the old"
That ought to be the fastest possible, since it relies on Python's internals to do the comparison.
UPDATE: It seems you're not after "equal", but something weaker. I think you need to edit your question to make it clear what you consider "equivalent" to mean.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to load data while scrolling horizontally and on a DIV overflow? I’m working on this horizontal scrollbar that grabs content from the database when you scroll to the farthest right. Here's an example of what we want to do:
http://designarchives.aiga.org/#/entries/%2Bcollections%3A%2250%20Books%2F50%20Covers%20of%202009%22/_/grid/relevance/asc/0/48/120
I found useful tutorial here but its vertical scroll:
http://www.9lessons.info/2009/07/load-data-while-scroll-with-jquery-php.html
So far it is working vertically, but how do you load data while scrolling horizontally and on a DIV overflow, not the window?
A: Your URL is broken but I wrote an accepted answer on how to work with horizontal scrolling divs here. Hopefully that helps you.
Here's the working fiddle in case it wasn't obvious where to look. jsfiddle.net/gAMyR/26
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: sorting an NSMutableArray of objects in cocoa gives SIGABRT I am creating a program that requires me to build an NSMutable array and then add objects to that array as buttons are clicked.
After the user has clicked all the buttons that they want (therefore adding all the objects that they need into the mutable array) I need to sort the array based on the objects name.
The objects are NSImageViews that are added to the array with names like view1, view2, view40.
I need a way to sort the objects in the array according to the numbers in the last digit of their name.
I was using
[nameOfArray sortUsingSelector:@selector(caseInsensitiveCompare:)];
but when I run the app I get SIGABRT at that line.
I have looked at many many other threads and can not find a solution.
Any help is greatly appreciated, as I have been working on this for several weeks now,
Anybody know what I am doing wrong?
EDIT , Here is what the debugger said afterwords
2011-09-30 08:16:06.669 CAP helper[9874:b303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImageView caseInsensitiveCompare:]: unrecognized selector sent to instance 0x4e5f650'
*** Call stack at first throw:
(
0 CoreFoundation 0x00de05a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x00f34313 objc_exception_throw + 44
2 CoreFoundation 0x00de20bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x00d51966 ___forwarding___ + 966
4 CoreFoundation 0x00d51522 _CF_forwarding_prep_0 + 50
5 CoreFoundation 0x00d472f6 __CFSimpleMergeSort + 374
6 CoreFoundation 0x00d4706c CFSortIndexes + 268
7 CoreFoundation 0x00dda642 -[NSMutableArray sortRange:options:usingComparator:] + 274
8 CoreFoundation 0x00d598cf -[NSMutableArray sortWithOptions:usingComparator:] + 95
9 CoreFoundation 0x00d5983c -[NSMutableArray sortUsingSelector:] + 108
10 CAP helper 0x0000cf81 -[RibbonStacker stackit:] + 305
11 UIKit 0x000324fd -[UIApplication sendAction:to:from:forEvent:] + 119
12 UIKit 0x000c2799 -[UIControl sendAction:to:forEvent:] + 67
13 UIKit 0x000c4c2b -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
14 UIKit 0x000c37d8 -[UIControl touchesEnded:withEvent:] + 458
15 UIKit 0x00056ded -[UIWindow _sendTouchesForEvent:] + 567
16 UIKit 0x00037c37 -[UIApplication sendEvent:] + 447
17 UIKit 0x0003cf2e _UIApplicationHandleEvent + 7576
18 GraphicsServices 0x01019992 PurpleEventCallback + 1550
19 CoreFoundation 0x00dc1944 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
20 CoreFoundation 0x00d21cf7 __CFRunLoopDoSource1 + 215
21 CoreFoundation 0x00d1ef83 __CFRunLoopRun + 979
22 CoreFoundation 0x00d1e840 CFRunLoopRunSpecific + 208
23 CoreFoundation 0x00d1e761 CFRunLoopRunInMode + 97
24 GraphicsServices 0x010181c4 GSEventRunModal + 217
25 GraphicsServices 0x01018289 GSEventRun + 115
26 UIKit 0x00040c93 UIApplicationMain + 1160
27 CAP helper 0x00002219 main + 121
28 CAP helper 0x00002195 start + 53
29 ??? 0x00000001 0x0 + 1
)
terminate called throwing an exception
Current language: auto; currently objective-c>
A: Your array contains UIImageViews and your sort calls caseInsensitiveCompare: on those instances of UIImageView, but that class doesn't have any method by that name. You should do something like this:
[nameOfArray sortUsingComparator:^(id obj1, id obj2) {
UIImageView *view1 = obj1;
UIImageView *view2 = obj2;
// Somehow compare the views and return NSOrderedAscending,
// NSOrderedDescending or NSOrderedSame, for example by calling
// appropriate "compare:" methods.
return myComparisonResult
}];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generic method with a generic interface I'm trying to create a generic method where the type is a generic interface.
private void ShowView<T>(string viewName) where T : IView<Screen>
{
IRegion mainRegion = _regionManager.Regions[RegionNames.MainRegion];
T view = (T)mainRegion.GetView(viewName);
if (view == null)
{
view = _container.Resolve<T>();
mainRegion.Add(view, viewName);
}
mainRegion.Activate(view);
view.LoadData();
view.ViewModel.IsActive = true;
}
Interface is IView<T> where T : Screen.
So I have ConcreteView : IView<ConcreteViewModel> and ConcreteViewModel : Screen where Screen is the base class. When I try to do ShowView<ConcreteView>("concrete"); I get an UnknownMethod error.
Is it because ConcreteView uses ConcreteViewModel instead of Screen for it's IView implementation? Is there a way to rewrite the method so that it works?
A: IView<ConcreteViewModel> is not an IView<Screen> without providing variance to the interface
interface IView<out T>
{
}
(The above can be done starting in C# 4.0)
Otherwise, you should be able to write your method signature like below
void ShowView<T, U>(string viewName) where T : IView<U> where U : Screen
{
// code
}
And invoke it like ShowView<ConcreteView, ConcreteViewModel>("blah");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: It seems that I have a rounding issue with SAS PROC FORMAT It seems that I have a rounding issue with SAS PROC FORMAT. The code is as below:
proc format;
value testf
-1.85E-13--1.85E-13 = 'negative'
0-0 = 'zero';
run;
data test;
input number best32.;
cards;
0
;
run;
data test2;
set test;
format varlabel $50.;
varlabel = put(number, testf.);
run;
The code is easy: first, create a format, with two options, a negative number really closed to zero and zero itself. Second, create dataset test, with a single observation whose number variable equals to 0. Third, create another dataset, with applied format. I expect to see test2 with number = 0 and varlabel = 'zero' but actually I see test2 with number = 0 and varlabel = 'negative'. Anyone knows why and how to fix this problem? Much appreciated for any suggestion/help.
A: This is a floating point precision problem. When testing floating point values for equality SAS employs a "fuzz" value of 1e-12 (by default). The expression a = b evaluates to true if abs(a-b) < 1e-12. In your case, 1.85e-13 is sufficiently close to zero that SAS will give it the format 'negative' (why it always assigns this and never 'zero' I don't know).
One way of handling this is to reduce the fuzz value SAS associates with your format:
proc format;
value testf (fuzz=1E-13) -1.85E-13--1.85E-13 = 'negative' 0-0 = 'zero';
run;
This format assigns the expected varlabel 'zero'.
If this sort of thing is a practical problem for you, you might want to think carefully about potential numeric precision issues in your code, as they're capable of generating some nasty and difficult-to-spot bugs in the wrong circumstances.
This link gives some information on numeric representation issues in SAS which may prove helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP pass a var into $_FILES inside function I am working on an admin area that will have file uploads on several pages. Regardless of the name of the form field I want to do some specific processes, but I'm a bit stuck on how to do this in a function. I have the code below, which I knew going in wouldn't be correct, but I'm not sure how to achieve what I'm trying to do.
function fileprocessor ($file)
{
echo $_FILES['$file']['tmp_name'];
}
Any thoughts?
A: function fileprocessor ($file)
{
echo $_FILES[$file]['tmp_name'];
}
From manual:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
A: $_FILES is the process of a form submit. to pass it to a function you need to pass the field name through the function.
function fileprocessor($file) {
$name = $_FILES[$file]['tmp_name'];
echo $name;
}
In the Code you will have
fileprocessor('userfile'); # Enter field name from upload form
This way you can have what ever you may like in the file processor
EDIT
You can test my version here http://jawilliams.site11.com/filestest.php
A: That's quite common mistake.
Many newbie programmers take single quotes as a part of array syntax.
While it's merely string delimiters and has actually nothing to do with arrays.
This mistake can lead to some funny or dramatic consequences.
So, to use a variable just use this variable, without quotes or other symbols.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Detect IBeam cursor Is there a way for detect IBeam cursors on windows from c++ code?
I wonder is it even possible, for example just the MS Word has several IBeam like cursor (eg. text near or below the IBeam).
Thanks,
Abe
A: I think there are two ways you can go about this, the easier way requires Vista. Both start with calling GetCusorInfo. You can take the HCURSOR you get from that and pass it into GetIconInfoEx on Vista or GetIconInfo on XP, casting it to a HICON. The Ex version includes the resource name which you can search for the word "beam" or other hints about what it might be. For the older version you have to do image analysis on the HBITMAP mask. Since you are looking for the type of cursor, this might not be too hard. Or it could be really difficult, I have never tried anything like this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write a jQuery/JS function so that it returns a value? How do I write a jQuery function so that it returns a value that I can access outside the function? I did something like this but when I tried to access it outside the function, it says "undefined":
$(document).ready(function(){
function add(y, z) {
$('p').click(function() {
x = y + z;
console.log(x); // shows 3
return x;
});
}
var sum = add(1, 2);
console.log(sum); // shows "undefined"
});
A: This should work. Not sure why you added the click event there
$(document).ready(function(){
function add(y, z) {
x = y + z;
console.log(x); // shows 3
return x;
}
var sum = add(1, 2);
console.log(sum);
});
A: Simple answer - you can't.
The method registered by .click() is called asynchronously as part of the Javascript event loop.
Your add function has no return value at all.
If instead what you're trying to do is to create a jQuery style utility function, rather than a method that acts on elements, you would do this:
(function($) {
$.add = function(y, z) {
return y + z;
}
})(jQuery);
usage:
var x = $.add(1, 2);
A: function add(y, z) {
$('p').click(function() {
x = y + z;
console.log(x); // shows 3
return x;
});
return y + z;
}
A: The function, in that case, is an anonymous callback function that is called when the click event occurs. The way you set it up, what function add(x, y) does is create a new handler for click events on tags.
A: I don't know why click event is added to the function. It should be handled separately. The code should look like this which makes sense according to me.
$(document).ready(function() {
function add(y, z) {
var x = y + z; // good to make it local scope
console.log(x); // shows 3
return x;
}
var sum = add(1, 2);
document.write(sum); // shows "undefined"
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calling Service Now Webservice with .Net I am trying to call Service Now's webservice from .Net and I can make it work fine for inserting a record, but I can not get any GETs to work. Here is my working INSERT code:
public void insertTable(string tableName, string schema, string columnInfo, string shortDesrcipt, string longDescript)
{
using (ServiceNow_u_database_table tableReference = new ServiceNow_u_database_table())
{
insertResponse response = new insertResponse();
System.Net.ICredentials cred = new System.Net.NetworkCredential(Properties.Settings.Default.UserName, Properties.Settings.Default.Password);
tableReference.Credentials = cred;
insert tableInsert = this.getTableData(tableName, schema, columnInfo, shortDesrcipt, longDescript);
try
{
response = tableReference.insert(tableInsert);
}
catch (Exception error)
{
Console.WriteLine(error.Message);
}
}
}
That works fine. Here is the code that does not work for GET:
using (ServiceNow_u_database_table tableReference = new ServiceNow_u_database_table())
{
ServiceNowExport.com.servicenow.libertydev.u_database_table.getRecords recordGet = new getRecords();
System.Net.ICredentials cred = new System.Net.NetworkCredential(Properties.Settings.Default.UserName, Properties.Settings.Default.Password);
tableReference.Credentials = cred;
recordGet.name = this._tablePrefix + tableName;
getRecordsResponseGetRecordsResult[] response = tableReference.getRecords(recordGet);
if (response != null && response.Count() > 0)
{
return true;
}
}
When I run that code, response is always null. I am following the instructions on this page.
I know that it is connecting because if I kill the credentials line I get an unauthorized error. Any ideas what I am doing wrong here? Thanks!
A: From the ServiceNow wiki on C# Web Services: here
If you are receiving a "null" response from your web service in your
client code, then you may have missed the step in this tutorial for
setting the elementFormDefault setting to "False" ... Please remember
to recompile your code against the WSDL after you have changed this
setting and saved it.
The property can be found within the ServiceNow instance at: System
Properties > Web Services. Set it to false, and you should no longer
receive null from the getRecords response.
Here's a screenshot of the property:
A: If you're interested I've written a set of soap classes to get and put some information into servicenow. It's pretty limited at the moment to just what I need to be able to do at work, but should work for anyone.
https://github.com/jeffpatton1971/mod-ServiceNOW
Feel free to check it out
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Dynamics CRM 2011 E-Mail Router & Exchange 2010 Cluster Error "Incoming Status: Failure - No results were found" I have what seems a common problem setting up the router to handle incoming mail, but after spending a couple of days implementing the suggestions I ran out of ideas.
The situation is as follows:
All operating systems Win2k8R2 64 bit.
Domain user names are @domain.local
Mail addresses are @domain.com
Dynamics CRM 2011 installed on server CRM.
Exchange server 2010 cluster consisting of 2 mbx servers and 2 cas servers.
Dynamics CRM E-mail Router installed on cas1 server, running as local system.
Service domain account added to PrivUserGroup in AD.
cas1 & cas2 servers added to PrivUserGroup in AD
Service domain account added to CRM as full read-write System Administrator.
Management Role Assignment given to service account to impersonate all account in the domain.
Global Address Book membership checked for the accounts of interest.
Access to GAB from service account checked.
Logged in successfully to both domain & Outlook with all accounts of interest.
I am getting "Incoming Status: Failure: No results were found." error when i try to test access from e-mail router config tool, with the following exception in event log:
An error occurred while opening mailbox account@domain.com.
Microsoft.Crm.Tools.Email.Providers.EmailException: No results were found.
at Microsoft.Crm.Tools.Email.Providers.ExchangeWSConnector.IsCurrentUser()
at Microsoft.Crm.Tools.Email.Providers.ExchangeWSConnector.GetService()
at Microsoft.Crm.Tools.Email.Providers.ExchangeWSConnector.OpenMailbox()
at Microsoft.Crm.Tools.Email.Providers.ExchangePollingMailboxProvider.InitExchangeConnector()
at Microsoft.Crm.Tools.Email.Providers.ExchangePollingMailboxProvider.OpenMailbox()
at Microsoft.Crm.Tools.Email.Providers.CrmPollingMailboxProvider.Run()
When I check the IIS log on cas1 I see that the respective request contains:
2011-09-30 14:19:15 192.168.1.128 POST /EWS/Exchange.asmx ;RC:a744e288-62f0-44bf-b506-
54f0753fa283;Init>>Conn:0,HangingConn:0,AD:30000/30000/0%,CAS:54000/54000/0%,AB:30000/30000/0%,RPC:36
000/36000/0%,FC:1000/0,Policy:DefaultThrottlingPolicy_a90f4c5f-dfd1-4e99-8a1f-
3cf7adb8ffa3,Norm,Sub:5000/0;ErrorCode=ErrorNameResolutionNoResults;[C]
Queues:0msec/Execute:51.8605msec;SoapAction=m:ResolveNames;Version=1;RpcC=2;RpcL=3;LdapC=1;LdapL=15;E
nd(54.796ms)
>>Conn:1,HangingConn:0,AD:30000/29986/1%,CAS:54000/53948/1%,AB:30000/30000/0%,RPC:36000/35998/1%,FC:1
000/0,Policy:DefaultThrottlingPolicy_a90f4c5f-dfd1-4e99-8a1f-3cf7adb8ffa3,Norm[Resources:(Mdb)WINDDB
(Health:-1%,HistLoad:0),(DC)DCSRV2.domain.local(Health:-1%,HistLoad:0),],Sub:5000/0; 443
DOMAIN\serviceaccount 192.168.1.120 Mozilla/4.0+
(compatible;+MSIE+6.0;+MS+Web+Services+Client+Protocol+4.0.30319.237) 200 0 0 91
So I understand there is a name resolution issue, but how do I proceed from here?
BTW, Exchange hosts around 10 different Accepted Domains, but the one of interest is set as default one.
Thanks.
A: Ok, so if anyone runs into the same problem the solution in our case was the following:
In CRM E-mail Router Incoming Profile configuration, account credentials were entered as username@domain. When we changed it to domain\username, the thing worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Extjs, How to remove tab panel's content I want to destroy the tab panel's content because when I open the panel again, it remains the before contents. so it show 2 same content.
So I want to put the code to destroy tab panels content into beforeclose event handler.
and I tried like this,
tempTab.on('beforeclose',function(obj){
this.items.each(function(c){this.remove(c)});
});
but it does not work.
Can anyone help?
source :
ManuBar Area (MENU)
menubar.add({
text : 'Administrator',
iconCls : 'plugin',
menu : {
items : [
{
text : 'Menu Management',
id : 'menuManagement',
iconCls : 'tabs',
url : 'main/test2',
handler : onMenuClick
},{
text : 'User Management',
id : 'useManagement',
iconCls: 'user',
url : 'main/test',
handler : onMenuClick
}]
}
})
Manu Handler
function onMenuClick(item) {
if(!Ext.getCmp('tab_'+item.id)){
var tempTab = Ext.getCmp('mainTabPanel').add({
id : 'tab_'+item.id,
margins : '0 5 5 0',
deferredRender : false,
closable : true,
title : item.text,
plain : true, //
defaults : {autoScroll : true},
autoLoad : {
url : '/ext/main/test2/',
scripts : true
},
listeners : {
'beforeclose' : function(){
alert(this.items.get(0).id); // output : testPanel
this.removeAll();
alert(this.items.get(0).id); // output : undefined
}
}
});
tempTab.on('beforeclose',function(){
//console.log(this);
this.removeAll(); ////////////////////////////////////
});
Ext.getCmp('mainTabPanel').setActiveTab(tempTab);
}else {
var tempTab = Ext.getCmp('tab_'+item.id);
Ext.getCmp('mainTabPanel').setActiveTab(tempTab);
}
}
and Content(test2.php) (it load using autoLoad and scripts :true)
test = function(){
return {
init : function() {
Ext.QuickTips.init();
var app = new Ext.Panel({
id : 'testPanel',
html : 'My Second Panel'
});
var tab = Ext.getCmp('tab_menuManagement');
//app.relayEvents(tab, ['activate', 'deactivate', 'beforeclose']);
tab.add(app);
tab.doLayout();
tab = null; app = null;
}
}
}();
Ext.onReady(test.init, test, true);
I think the item removed successfully. but still when close and open the tab again.
it show 2 same contents.
My Second Panel
My Second Panel
I don't know what is wrong....
---Updated ---
I changed the test2.php file like this
var tab = Ext.getCmp('tab_menuManagement');
tab.removeAll(); // I added
tab.add(app);
tab.doLayout();
then it works. it's weird. before close exactly it was removed. but How
it alive again....?? anybody help??
Thanks!
A: try to
tempTab.on('beforeclose',function(obj){
this.removeAll();
});
Note:
removeAll( [Boolean autoDestroy] ) : Array
*Removes all components from this container*.
A: You are using some bad practices. For example:
variabile.on('event', handler, scope)
this will let variable alive since there is an unmanaged event (unmanaged by Ext, since it's managed by you). If you manually listen to an event, you have to uninstall it before destroy variable. Or if you are like me (lazy :-) just use this.mon.
Another bad thing is Ext.getCmp (and id) -- it should be used only for debugging purposes, not for development. When I started with Ext I used ids and I had very weird issues with TabPanel when I created multiple instances of them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to make a php array I tried transfer $str to be an array group.
$str = '1,2,3,4,5';
print_r(array($str)); //this get Array ( [0] => 1,2,3,4,5 )
I tried compact
print_r(array(compact($str))); // Array ( [0] => Array ( ) )
but how to make $str to be
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
A: You should try to use explode keyword.
$str = '1,2,3,4,5';
print_r(explode(',', $str));
Should print:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
A: Try with:
$str = array(1,2,3,4,5);
Otherwise, if you mean that your input is '1,2,3,4,5' then use explode:
$str = explode(',', '1,2,3,4,5');
In both cases the output of print_r($str); is:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
A: In addition to @stivlo's answer, you can do this to break a string into an array:
$str = '1,2,3,4,5';
$array = explode(',', $str);
preg_split is also an option for more complicated splitting situations.
A: Try explode(',',$str).
Or better yet, array_map('intval',explode(',',$str)) if you want integers.
A: Why not use the explode function?
$arr = explode(",", $str);
A: Use explode() to split the string into array, if the $str must be a string. Or declare it as array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: SVN without server for our Visual Studio development Security is not an issue for our small team.
Is there any compelling reason why we might need to use an SVN server of some sort, rather than just using files on a network share somewhere?
EDIT
Sorry--I don't think I communicated very well.
I want to use SVN for version control. I think that I do not need a "server". The team members can all point their SVN clients to a network location.
Is that good enough?
Or do I need a "server"?
A: Yes, you can create a repository on some folder and point your clients there, no svnserve process or apache2 + mod_svn is really needed.
There are a however a couple of reasons why you should consider a server:
*
*Synchronicity: A file based repository is altered by the clients that access it. If one of your clients' clock is out of sync with the rest of the team, he/she may in rare cases corrupt the repository data. A server however will always have a unique time.
*Scalability: When the amount of commits per day grows, the file based lock/commit/unlock sequence may cause unexpected load on the file server and frustrate your team with long response times.
*Extensibility: Better sooner than later you or your team will discover the need for a ticket system (for QA/QC or 3rd level support, e.g. Trac, Redmine, Bugzilla) and then having issues and their fixes associated with revision control will indeed become a must have. These ticket systems always accept a svn:// URL but will most likely reject a file based repository.
I don't know if these reasons are compelling enough for you, but you can indeed postpone the decision to go server until it starts to become unavoidable - even indefinitely if your team does never grow.
A: Agent SVN is a Subversion plug-in for Visual Studio and it can be configured to use a file location for the repository and as such no server is required.
A: The main purpose of svn is for version control.
Using files is not easy to keep versioning. And btw, you may setup the "svn server" local in your own pc
A: Subversion uses three main protocols:
*
*svn:
*http:
*file:
There are a few others (svn+ssh and https), but they're related to the above.
If you use the file: protocol, you don't need a Subversion server. All you have to do is point the file protocol to the directory where your Subversion repository lives:
C> svnadmin create C:\svnrepos\myrepos
C> cd C:\workspace
C> svn co file://C:/svnrepos/myrepos repos
In the above, I created a Subversion repository in C:\svnrepos\myrepos and then went to another directory (very important!) and did a checkout. No server is running.
There are several issues with this:
*
*The Subversion repository directory must be read/write accessible to everyone which means that anyone can directly modify the repository without going through Subversion.
*I'm not 100% sure how hooks work or how collisions are handled if more than one user attempts to commit at the same time.
*Even if you don't plan to have any security, you probably want to know the name of the person who made the change. The file:// protocol doesn't track that. All you see is that changes were made, but not by whom.
And, finally:
*
*Running a server isn't all that difficult.
So, although you could put the Subversion repository on a network share and everyone can use the file:// protocol, there really isn't a very good reason to do that. In fact, I use Subversion as my own personal repository where I'm the only one using it, and I don't use the file:// protocol.
You can easily run svnserve as a Windows service, so it automatically starts whenever your machine starts up. And, it's very simple to setup. There's simply no reason not to use it.
So, might as well go ahead and do it the right way anyway.
By the way, how are you using Subversion through Visual-Studio? I suggest you look at ankhsvn which allows you to access Subversion directly in Visual-Studio.
A: SVN isn't about security; it's about maintaining history of your source code.
I can't think of a compelling reason why you would not want to set up an SVN server. I use one at home on my personal desktop for my own development. It's not about security; it's about keeping my source code history in case I screw up and want to revert.
It's also about habits: "First we make our habits, then our habits make us." Learn to do it right all the time, even in simple situations.
A: Imagine working on the same project with multiple people. And both are modifying the same file at the same moment. If you both work on that same fileshare that is going to be bad.
Another reason for using some kind of source control is being able to keep track of changes.
This way you can notify your collegue where he screwed up. :-)
A: hmmm, subversion is not the right tool if you need security, it is the right tool :
*
*if you want to have a team working on the same sources at the same time (and be able to revert a bad commit)
*if you want to avoid that the last one who save a file erase all the modifications made by the other (in case of files on the same network share)
*if you need to make parallel developement (and create branches for that)
*if you need to be able to re-extract a tagged version (usefull when delivering the application)
A: Setting up a server is almost trivial, so I would ask why would you NOT want a server. But here are some other reasons:
*
*Reliability. Network filesystems such as SMB share are not as
reliable, especially when it comes to multiple users writing to the
same files at the same time. SVN specifically does not claim to
support this.
*Performance. Providing access to the files via a
server will be significantly faster than doing it over network
share.
*Auditing. You want your changes to be associated with a user, even if you do not care about security. Going through a server forces a login and the server can use that username to record who made the change.
*Safety. If you use a network share, then all users have direct read/write access to the repository files. I know you are not concerned with security, but what about simple mistakes? Such as someone accidentally deleting files from the repository.
Download and install something like Subversion Edge. This is trivial to install on Windows and it gives you a web UI to manage the server. You also get a web UI for browsing repositories which can be useful when researching a bug.
A: On a team of as little as two people, some sort of version control is a huge advantage over no version control. Being able to back-track through changes, branch code if you need multiple versions for demoing purposes, and using lock/unlock + merge to keep developers from murdering each others code is why you use SVN. Comes in handy when working alone on a project, too.
You can host SVN easily on Linux, Mac, Windows - you just need that machine to be network-connectable from the development machines.
A: You need an SVN server process running somewhere. You cannot avoid it. It is a fundamental part of SVN, it is what provides access to your repository, and it is what the clients must point to.
We use VisualSVN. It takes almost no effort to install.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Get Files count from FileSystemWatcher Created event? I'm wondering if there's a way to get the amount of files that are going to be copied? What I mean is following...
I'm writing an app that contains grid, which functions like windows explorer. When I'm drag-droping files, they are copied to a destination folder and my grid is supposed to refresh. My FileSystemWatcher sends me events about created files & grid refreshes, but for multiple files it refreshes multiple times =/ So is there a way to find out how many files were copied, or to get a collection of files just in one event?
A: I would build an adapter that throttles and raises similar events after a delay. This ThrottlingFileSystemWatcher would look virtually identical to a standard FileSystemWatcher but instead of raising an event for every file, it would queue up the files and raise an event some TimeSpan later (say 5 seconds, but make it configurable) and include all the files it saw in its EventArgs.
A: I would make the refresh less accurat an let it only refresh again after a defined time.
So it could solve this problem for all future refresh Problems and or user refreshes. I also would make the refresh time configurable and every user is happy with it.
A: I once coded a solution similar to @Austin Salonen's.
When a new file event is received, check to see if a count down timer is running.
*
*If not, start it
*If it is running, reset it to 3 seconds (time
depends on file size and speed of file transfers).
When the count down timer triggers, THEN update the GUI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Building queries with PDO? I have some ancient code which I want to convert to PDO:
<?php
function build_query() {
// db connection here
$the_query = "";
if ( empty( $_GET['c'] ) ) {
$the_query = "select * from table1";
if ( ( isset( $_GET['y'] ) ) && ( isset( $_GET['m'] ) ) ) {
$the_query .= " where y = " . $_GET['y'] . " and m = " . $_GET['m'];
}
} elseif ( ( $_GET['c'] == "1" ) || ( $_GET['c'] == "2" ) ) {
$the_query = "select * from table1 where GGG = " . $_GET['c'];
if ( ( isset( $_GET['y'] ) ) && ( isset( $_GET['m'] ) ) ) {
$the_query .= " and y = " . $_GET['y'] . " and m = " . $_GET['m'];
}
} else {
$the_query = "select * from table1";
if ( ( isset( $_GET['y'] ) ) && ( isset( $_GET['m'] ) ) ) {
$the_query .= " where y = " . $_GET['y'] . " and m = " . $_GET['m'];
}
$the_query .= " and c = " . $_GET['c'];
}
return // use the query to return results $the_data;
}
?>
I can't seem to figure out how to recode this using PDO. I have made a start below, but can't seem to get any further:
<?php
function build_query() {
$the_data = "";
$DBH = new PDO( "mysql:host=server;dbname=database", "user", "pass" );
$DBH -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH -> prepare( "build query here" );
$STH -> bindParam( ':c', $_GET['c'], PDO::PARAM_INT );
$STH -> bindParam( ':y', $_GET['y'], PDO::PARAM_INT );
$STH -> bindParam( ':m', $_GET['m'], PDO::PARAM_INT );
$STH -> execute();
$ROWS = $STH -> fetchAll();
foreach($ROWS as $ROW) {
$output .= $ROW["a"] . " - " . $ROW["b"] . " - " . $ROW["c"] . " - " . $ROW["d"] . "<br />";
}
$DBH = null;
return $output;
}
?>
A: Well, it's quite tricky with prepared statements
(that's why I prefer my home-brewed placeholders over prepared statements)
First of all you have to make this ancient code sensible, without all that current mess.
Check every parameter only once.
here is a code to give you an idea
$w = array();
if ( !empty($_GET['c']) AND ($_GET['c'] == "1" ) || ( $_GET['c'] == "2") )
{
$w[] = $db->parse("GGG = ?i", $_GET['c']);
}
if ( isset($_GET['y']) && isset($_GET['m']) )
{
$w[] = $db->parse("where y = ?i and m = ?i",$_GET['y'],$_GET['m']);
}
$where = '';
if ($w) $where = implode(' AND ',$w);
$query = "select * from table1 $where";
to make use of prepared statements you have to add your values into array and then use it with execute()
A: You are changing your function to do a lot more that it used to do. If you want to stick to the original design (that is consistent with the name of your function...), you need to change your function so that it still returns a query but does not execute it as the old version did not connect to a database or query a database either.
To solve your problem, you can have the function return an array with 2 elements, the query with the named parameters and another array with the name - value pairs.
If you do want to return the results of the query, you can use a global variable for your database connection or pass it as a variable to the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Error using Code-first in EF with an Existing Database I followed Using EF “Code First” with an Existing Database tutorial step by step but getting the following Error :
Invalid column name Category_CategoryID
Following is the code Excerpt :
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal? UnitPrice { get; set; }
public bool Discontinued { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public byte[] Picture { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Why does this happen.
EDIT - I am able to make this work by including public int CategoryID in Product Class but dont know the details.
A: You need to let EF know that Products.Category is the inverse of Category.Products. I'm not sure why that's not shown in ScottGu's blog post.
The code you need would be something like this in your DbContext subclass:
protected override void OnModelCreating(ModelBuilder modelBuilder {)
modelBuilder.Entity<Product>().HasOne(p => p.Category).WithMany(c => c.Products);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Minimum time lock in java I'm looking for a way to limit access to a method in java to no more than once every X seconds. Here's my situation :
I want to run this code in parallel with multiple threads :
private MyService service;
public void run() {
// Send request to remote service
InputStream response = service.executeRequest();
// Process response
... some more code
}
The executeRequest() method sends an http request to a remote server (which isn't mine, I have no access to its implementation) and waits for the response from the server. It then does some processing of the data.
I would like to have many threads run this in parallel. My problem is that the remote server will crash if too many requests are sent simultaneously. So I want some way of making sure that the executeRequest() method will never be called more than once every second.
Do you know how I could do that in java ? Thanks
A: Hrm, I'm not sure that restricting the frequency of access to a method will result in prevention of overload.
Perhaps there isn't enough info in the above post, but it seems that a WorkerThread + JobQueue setup would work just fine here.
Food for thought:
Multithreaded job queue manager
EDIT: Trying to be a bit less vague...
*
*Have the server collect the requests into some data structure,
perhaps a class called Job.
*Have Jobs then be placed into the bottom
of a Queue.
*Have WorkerThread objects pop Job objects off the
top of the Queue and process them.
*Make sure to only instantiate as
many WorkerThread objects as you need to maintain proper server load.
Only experimentation will determine this number, but as a very rough
rule, start with # of processing cores - 1. (aka start 7 workers on
an 8 core machine)
EDIT #2 In light of new information:
*
*Setup a Queue on the client side
*Make a Worker that can track what Jobs have been submitted, which Jobs have gotten a response and which Jobs are still processing. This will allow for limiting the number of Jobs being submitted at any one time.
*Make Worker track 'lastSubmissionTime' to prevent any submission occuring < 1 second from previous
A: You could use a Semaphore to throttle the number of threads able to call executeRequest():
http://download.oracle.com/javase/1,5,0/docs/api/java/util/concurrent/Semaphore.html
The executing thread could increment the semaphore prior to entering the execute and other threads could wait for it to fall to either 0 or a number which reflects how many are allowed to run in parallel.
A Timertask:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/TimerTask.html
Could be used to decrement the semaphore after 3 seconds... Throttling the entry to no more than 1 new entrant every 3 seconds:
A: Limiting concurrency on the client side is not a good pattern — how are clients supposed to know about each other?
A: Have you thought about using sleep to have the threads pause before jumping to hit the remote call? You could have the threads sleep for a random # of seconds between 1 and 5 which would limit the number of threads hitting the method at any one time.
You could also put a lock on the method that expires after 1 second so each thread "grabs" the lock, executes the method, but its lock expires so the next thread can grab it and execute. Put the lock at the beginning of the method -- and have it do nothing except hold the thread for one second thread.sleep(1000) and then continue execution. That will limit you to one thread hitting the method at a time.
EDIT: Response to OP's Comment Below
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
thread.sleep(1000) //added to example by floppydisk.
} finally {
lock.unlock()
doYourConnectionHere();
}
}
}
Modified from: ReentrantLock. Inside the try/catch, all you do is thread.sleep(1000) instead of actually doing something. It then releases the lock for the next thread and continues executing the rest of the method body--in your case the connection to the remote server.
A: Using dynamic proxy you can wrap your service and handle max execution in the InvocationHandler:
MyService proxy = (MyService) Proxy.newProxyInstance( //
MyService.class.getClassLoader(), //
new Class[] {MyService.class}, //
new MaxInvocationHandler());
where naive implementation of InvocationHandler could look something like this:
class MaxInvocationHandler implements InvocationHandler {
private static final long MAX_INTERVAL = 1000L;
private static final long MAX_INVOCATIONS = 1;
AtomicLong time = new AtomicLong();
AtomicLong counter = new AtomicLong();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long currentTime = System.currentTimeMillis();
if (time.get() < currentTime) {
time.set(currentTime + MAX_INTERVAL);
counter.set(1);
} else if(counter.incrementAndGet() > MAX_INVOCATIONS) {
throw new RuntimeException("Max invocation exceeded");
}
return method.invoke(proxy, args);
}
}
A: In your controller class where you call worker to execute the service, use ExecutorService to start the pool of threads to ultilize the worker class.
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.submit(new MyServiceImpl(someObject));
To add to what others have already suggested, Have a worker class to take task from the queue execute and wait for the number of minutes as you require before taking another task from the queue. I have made this 2min as an example.
Example:
public class MyServiceImpl implements MyService , Runnable {
public static final int MAX_SIZE = 10;
private final BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(MAX_SIZE);
@Override
public void run() {
try
{
Object obj;
while ((obj==queue.take()) != null)
{
executeRequest(obj);
//wait for 2 min
Thread.sleep(1000 * 60 * 2);
}
}
catch (InterruptedException e)
{}
}
public void executeRequest(Object obj)
{
// do routine
}
public MyServiceImpl (Object token)
{
try
{
queue.put(token);
}
catch (InterruptedException e)
{
throw new AssertionError(e);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Object Not Found Exception in hibernate I am really stuck at this error
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.my.farmer.vo.crop.CropProfile#genus]
at org.hibernate.impl.SessionFactoryImpl$1.handleEntityNotFound(SessionFactoryImpl.java:375)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:145)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:179)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878)
at org.hibernate.impl.SessionImpl.internalLoad(SessionImpl.java:846)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:557)
at org.hibernate.type.EntityType.resolve(EntityType.java:379)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:116)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:842)
at org.hibernate.loader.Loader.doQuery(Loader.java:717)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.loadEntity(Loader.java:1851)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:48)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:42)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:2992)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:395)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:375)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:139)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:179)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878)
at org.hibernate.impl.SessionImpl.internalLoad(SessionImpl.java:846)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:557)
at org.hibernate.type.EntityType.resolve(EntityType.java:379)
at org.hibernate.type.ComponentType.resolve(ComponentType.java:584)
at org.hibernate.type.ComponentType.nullSafeGet(ComponentType.java:275)
at org.hibernate.loader.Loader.getKeyFromResultSet(Loader.java:1088)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:553)
at org.hibernate.loader.Loader.doQuery(Loader.java:689)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.doList(Loader.java:2211)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2095)
at org.hibernate.loader.Loader.list(Loader.java:2090)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:388)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:920)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:405)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:373)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:911)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:903)
at com.my.farmer.dao.impl.MarketDAOHibernateImpl.fetchMarket(MarketDAOHibernateImpl.java:46)
at com.my .farmer.bo.impl.MarketBOImpl.fetchMarket(MarketBOImpl.java:32)
at com.my.farmer.service.impl.MarketServiceImpl.triggerAdvisory(MarketServiceImpl.java:32)
at ClientSpringTester.main(ClientSpringTester.java:26)
I have three classes crop, cropprofile and cropspecies.
class crop{ cropId(PK), Cropprofile profile id (FK), Cropspecies speciesId(FK) }
class cropprofile{ profileid(pk), genus(unique), family }
class cropspecies{ speciesid(PK), Croprofile genus(FK) }
To give you the exact source of error, I have
class Marketfeed {
Crop cropId,
Market marketId }
In market feed cropId and marketId are composite key. So, when I do a
.find(from Marketfeed market)
this error message error is generated. I am not using any search criteria.
Can anybody suggest possible causes of this error?
A: It looks like you are using session.load(Object.class,id); in order to solve this issue you should use session.get(Object.class,id);
Now the explaination:
Session.load(Object.class,id) - returns object proxy and in case and this object does not exist it throws the exception you are getting.
session.get(Object.class,id) - returns object itself instead od its proxy, if this object does not exist null returned.
Hope it helps.
A: Whatever you are trying to load does not exist in the database by the primary key that you are specifying.
A:
class crop{ profile id (FK), speciesId(FK) }
This sounds like you have references to the ids in your entity, whereas you should have references to Objects:
@Entity
public class Crop{
@ManyToOne // or @OneToOne
private CropProfile profile;
@ManyToOne // or @OneToOne
private CropProfile profile;
// getters and setters omited
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7611896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.