text stringlengths 8 267k | meta dict |
|---|---|
Q: Index value not getting correctly updated I have a popup and i select the value and it gets updated correctly in my field.
var boolArray = ['Yes', 'No'];
textField.value = boolArray[e.index] == undefined ? textField.value : boolArray[e.index];
But when i send the somevalue to my service, it does update incorrectly. for instance if i select Yes, it send NO and Vice Versa.
var somevalue = e.index === undefined ? '' : e.index;
A: change the first line to var boolArray = ['No', 'Yes'];
I believe you want to show this way:
*
*if e.index=undefined, textField.value=textField.value and
somevalue=""
*if e.index=0, textField.value="No" and somevalue=0
*if e.index=1, textField.value="Yes" and somevalue=1
In short, 1 means yes, 0 means no
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Functions with in Stored Procedure- SQL 2008 I have a SQl Query which returns 30,000+ records, with 15 columns . I am passing a NVARCHR(50) parameter for the store procedure.
At the moment I am using stored procedure to get the data from the database.
As there are 30,000+ records to be fetched and its taking time, What would be the suggestions for me.
Do I get any performance benefits if I use functions with in the stored procedure(to get individual columns based on the parameter I am passing)
Please let me know, if you need more info on the same.
Thank you
A: Functions would probably not be the way to go. 30000 rows isn't that many, depending on how conplex the query is. You would be better to focus on optimising the SQL in the proc, or on checking that your indexing is setup correctly.
A: I wouldn't use functions unless there is no other way to get your data.
From SQL2005 you have extra functionality in stored procedures such as WITH and CROSS APPLY clauses that makes easier certain restrictions we had in previous versions of SQL that could be solved using UDF's.
In terms of performance, the stored procedure will generally be quicker, but it depends how optimized is your query and/or how the tables have been designed, maybe you could give us an example of what you are trying to achieve.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I turn on javascript support on a PHP project in eclipse? Once a project has been created (PHP) is there any way to turn on javascript support for the project or would a new project have to be created? I would prefer not to create a new project.
A: Either create a new PHP project and tick the Javascript support checkbox, or from the Configure menu, there is the option to convert the project to a JavaScript project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get values from controller I am trying to print hello world.
For that i created class and return function in models folder, and the returning value is "hello world".
In controller, i am getting the values from module like this:
$value = new getValue();
$this->view->index = $value->hello_world();
I don't know how to get the values from controllers and print into views php folder.
A: In fac, you put "Hello world" string into the variable "index" of the controller's view when your are doing this $this->view->index = $value->hello_world();.
So, if your $value->hello_world(); function correctly return an "Hello world" string, for print it into the controller's view, you just have to do add this php code echo $this->index; into your view file.
A: I really think you should read a tutorial first of all. It can be quite hard to try to figure out how Zend Framework works just by starting to code right away.
*
*The Quick Start guide suggested by @palmplam should be fine.
*In addition, I found the Rob Allen's tutorial really useful when I started using Zend Framework. It contains plenty of sample code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: android ImageView/ RelativeLayout increase size by Dragging the corner of ImageView/ RelativeLayout i want to increase the size of ImageView/ RelativeLayout by Dragging the corner of ImageView/ RelativeLayout. But no difference in width and set it bottom. I set it by using android:layout_alignParentBottom="true" and also set image in imageview. but how to drag i don't know. Is there is any option available in Android? can any one suggest some solution for this? pls help me
A: you can use onTouch() for the ImageView.
Once it is touched show a small image at the edge of the imageview. And on touching that image and moving(onTouch() gives the pixel positions until you touch it) you will be getting the pixel positions. Based on that you can set the height and width of the imageview.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CSS: Two inputs side by side How can I make this:
Look like this:
I.e have the two fields and the sign in buttons side by side? Thanks
A: Give both fields a different class and assign to the most left one float:left;
HTML:
<input type="text" class="field1"/>
<input type="text" class="field2"/>
CSS:
.field1 {
float:left;
}
A: I assume this is more what you need:
http://jsfiddle.net/mrchris2013/NtVuq/12/
HTML:
<label>Username</label>
<label>Password</label>
<input type="text" />
<input type="text" />
<input type="button" value="Login" />
CSS:
label, input[type=text] {
width: 150px;
float: left;
}
label + input[type=text] {
clear: left;
}
input[type=button] {
float: left;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: query MS access database with LINQ in c#
Possible Duplicate:
Query Microsoft Access MDB Database using LINQ and C#
Im working with MS access database and wanted to know if i could use LINQ to query this database? I read about datasets, but by reading this: http://blogs.msdn.com/b/adonet/archive/2007/01/26/querying-datasets-introduction-to-linq-to-dataset.aspx
i see that not much of a database can be accesed through datasets. Can anyone help me as to how i could go bout this? Thanks :)
A: Unfortunately LINQ does not support access database. As work around you could use Ado.net DataSet to pull out the data from your database
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb";
//create the database query
string query = "SELECT * FROM MyTable";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
Then you can use LINQ to object to do your query (even if I won’t recommend you to use this approach because of the performance are not very good)
var results = from myRow in dTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;
A: These guys have developed a Linq2Access project. I have never used it and have no idea of the quality or maturity but it's probably worth checking out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: manipulate visio format file programmatically I want to extract information from a Visio file and do some change on them(like using C++), then write them back?
My question is:
Is manipulating visio files(mainly reading and writing) programmingly possible?
If so, any tutorial lin is preferred
A: Reading/Writing Visio VSD Files
This is a binary format and as far as I know, it is not documented. However, check out what has been going with support for reading Visio VSD files in LibreOffice.
Reading/Writing Visio VDX files
These are just the XML equivalent of VSD files and relatively straightforward to read and write if you are familiar with Visio. For simple tasks such as finding and manipulating all shape custom properties or formatting it will be very straightforward to load the XML into a DOM, process it, and then save it back out. For example, I once wrote a small tool that used this technique to search and replace text in a set of VDX files. One warning: the more complex a task you want to perform, the more you will need to be very familiar with Visio and how it works with Shapesheets, etc.
Here's a link to get started: http://msdn.microsoft.com/en-us/library/aa218409(v=office.10).aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: php RegExp: how to use newline in expression? For example it works:
{<div\s+class=\"article\"><h2(.*)</div>}s
If I do this way, I get nothing:
{<div\s+class=\"article\">
<h2(.*)
</div>}s
I suspect that I should use some modifier, but I know which one from here: http://php.net/manual/en/reference.pcre.pattern.modifiers.php
A: That would be the /x modifier:
x (PCRE_EXTENDED)
If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.
It also allows commenting the pattern, which is extremely useful:
{<div\s+class=\"article\"> # many spaces between the div and the attribute
<h2(.*) # don't really care about closing the tag
</div>}sx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: UIPopOverController issues while autorotation I am presenting a UIPopovercontroller using PresentPopOverFromRect: method. in Portrait Orientation. When i autorotate to Landscape UIPopoverController is not presenting at the proper position. How to position the UIPopoverController while autorotating the device.
A: You need to override this function:
- (void)willAnimateRotationToInterfaceOrientation:
(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
where you can change the dimension and position of the UIPopovercontroller depending of your current orientation. This function is convenient because it is called just before the screen is being redrawn and just before the user interface begins to rotate.
You should check this tutorial for an understanding of how you should handle the layout for different orientations of the IPad.
A: Yes, as tiguero says, in your custom UIViewController, you can override the method:
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
[self.popOverViewController dismissPopoverAnimated:NO];
CGRect yourNewRect = CGRectMake(0.0, 0.0, 20, 20);
[self.popOverViewController presentPopoverFromRect:yourNewRect inView:yourView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
You can have a try!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Any harm in using global domain validity when obtaining ReCAPTCHA public/private keys? Just curious - is there any risk in using a public/private key obtained from ReCAPTCHA for intended use only on one domain, but then we ending up using it for another one.
I intended to obtain it for a specific domain, but mistakenly took the public/private key as a 'global key':
This is a global key. It will work across all domains.
Is it a 'bad thing' to use 'global keys' as opposed to one for a specific domain?
A: This question was about the general subject of Google recaptcha public and private key. In one of the answers https://stackoverflow.com/q/5839628/321143 your question, about the safety of using the same key for more than one website, is addressed. It seems to be okay to do so:
Yes that's perfectly ok to use the same key pair for both local
testing and server deployment (as long as you keep your private key a
secret).
and
I personally use same pair of keys at 3 of my seperate web sites + at
my home computer at localhost:80 for testing purposes. They all work
very well
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: how to make RTSP server at android phone? I want send streaming video from android phone to computer server on RTSP.
the server is coded using java.
how can I do that?
A: RTSP is just a streaming protocal which only includes information about a stream and no data. you can use it as a "tunnel" for data streams (e.g. RTP). you can use RTSP as a tcp connection to support your udp stream. so necessary data can't get lost.
here is a simple example of a RTSP server-client communication: Streaming Video with RTSP and RTP.
there are only the basics of the connection (communication) at this exercise and it's for a java application, so you have to modify it a little bit.
to get some more information about the RTSP connection and the sdp file check out the RFC2326 - RTSP and the RFC4566 - SDP
to stream data from your android device take a look at this thread:
Creating RTP Packets from Android Camera to Send
EDIT:
found this great example project for RTP streaming: SpyDroid
A: Use libstreaming library to stream video / audio RTP over UDP.
Or use twilio as ready solution (hole punching already integrated, so you don't need to care about STUN / TURN servers).
A: With rtsp you should also specify the sdp file where the rtp and other info are stored.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Solr DataImportHandler with optional sub-entities I'm configuring DataImportHandler to index my db but I run into this problem.
I have a table A with a nullable integer field F that is the fk to another table (call it B).
I was modeling this way:
...
<entity name="main" query="select ..., F from A">
...
<entity name="sub" query="select ... form B where Id = ${main.F}">
...
</entity>
<entity>
...
The problem is that when F is NULL i get a runtime error because ${main.F} get replaced with nothing and it try to execute the following query:
select ... from B where Id =
Is there a way to handle this situation?
A: is there a reason where you cannot use "WHERE F is NOT NULL",
alternatively you can replace F with some unused value using immedate if in sql.
using OnError =SKIP will be similar to "WHERE F is NOT NULL" , but usng IF in sql to replace with an unused value will ensure the main part is indexed only ignoring th esub part, if that is your requirement.
A: We use dataimport handler, but frankly haven't come across this scenario yet.
May be you want to try the onError attribute with the entity, which will allow you the skip or continue when an error occurs.
http://wiki.apache.org/solr/DataImportHandler#Configuration_in_data-config.xml
A: Just for record this is the solution I'm using at the moment.
I changed the sub-entity definistion as:
<entity name="sub" query="select ... form B where Id = '${main.F}'">
This is not the best solution because F is a numeric field, not a string and surrounding it with ' may cause problems with some databases (performance problem in Oracle).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I know my app is being Run inside Facebook If I have an app and it is run inside facebook. the first load I will get the
$_REQUEST['signed_request']
but if you click on any link inside my app and navigate within the app you will lose that $_REQUEST['signed_request'].
Is there any other way to know if my app is being run in a browser or inside facebook?
A: You can continue to pass the signed_request around. Within your app, all your links should end with ?signed_request=<whatever> (or &signed_request=<whatever> if there is already a query string), and all your POST forms should include signed_request as a hidden input. Then you will always have access to signed_request.
A: You can save value of signed_request in php session, something like this:
session_start();
if (isset($_REQUEST['signed_request'])){
$_SESSION['signed_request'] = $_REQUEST['signed_request'];
}
Later you can check if signed_request value is saved in session:
if (isset($_SESSION['signed_request'])){
//do something
}
A: If you really only need to know whether your app is being accessed through Facebook, the simplest way is to use a unique url in your app settings -- either a unique hostname like fb.yoursite.com, or a unique directory name like www.yoursite.com/fbapp/ . Then you configure your server so the unique hostname/directory points the same place as the regular hostname/directory. That way the same files can be reached either way, but your scripts can check the $_SERVER info to tell whether it's a Facebook request.
HOWEVER...unless you are strictly dealing with non-authorized access, you have to consider whether that will really solve anything. If you have to "detect" things like this, you must not be carrying any persistent state info, and your user will lose his "identity" as soon as he goes to page 2. So most likely, what you need to be considering is not a way to tell on each page whether the user is in Facebook, but rather a way to parse all the info you need on the first page and then make that available in all other pages. Many people use PHP sessions for this. Personally I think that's a bad idea, and would do something more like what Ben suggested in his answer (using GET and POST to pass the info you need).
A: Personally, a very simple yet effective solution I've used is some client side javascript (which can obviously be disabled etc) - this works nicely for a simple redirect and it won't work in every case.
// Redirect if the page is not an iframe
if (window.location == window.parent.location){
window.top.location = '{{ facebook_tab_url }}';
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SSRS report export to Excel: need a column in "Number" format I'm using SSRS 2005 and I have a financial report. I would like a column to be in number format when exported to Excel.
How can I specify a column to be exported in number format?
A: Make sure your
<MarkupType>None</MarkupType> not <MarkupType>HTML</MarkupType>for the textbox in your tablix or Table.
Then change the Expression of the textbox to =CInt(Format(Fields.DumpValue.Value, "#,###.0"))
Hope it helps
A: For every textbox in the column that contains numeric values, select it and set the Format property to N (number)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can't get sensible co-ordinates for note blocks I've been trying to resurrect an existing drawing check macro, and want to find the co-ordinates of any note blocks on each sheet. I've been modifying code found here using the GetAttachPos method from this page, but for some reason any co-ordinates returned come back around (8.80942311664557E-03,2.24429295226372E-03).
I'm thinking that the problem is that I've missed a reference somewhere, but I'm not sure where. Although it's definitely finding the notes since it passes back their text. Anyway, here's the method I'm testing at the moment:
Sub Main()
Dim swApp As SldWorks.SldWorks
Set swApp = CreateObject("SldWorks.Application")
Dim NoteNumbersText As String
Dim NoteText As String
Dim NumberofSheets As Integer ' The number of sheets in this drawing
Dim NamesOfSheets As Variant ' Names of all of the sheets
Dim sheet As SldWorks.sheet ' The Sheet that we are working on
Dim LocalView As SldWorks.View ' Current View that we are looking at
Dim LocalNote As SldWorks.Note ' Current Note that we are looking at
Dim TextFormat As SldWorks.TextFormat ' Current text format object of a note
Dim Xpos As Double ' X, Y Z position on the drawing in Metres
Dim Ypos As Double
Dim SizeOfSheet As Double
Dim x As Integer ' general Loop Variables
Dim j As Integer
Dim k As Integer
Dim l As Integer
Dim vPosition As Variant
Dim vNote As Variant ' Single note
Dim swNote As SldWorks.Note ' Single Solidworks Note Object
Dim ThisAnnotation As SldWorks.Annotation
Dim swBlockInst As SldWorks.SketchBlockInstance
Dim swBlockDef As SldWorks.SketchBlockDefinition
Dim NumofNotes As Integer
Dim ArrayOfNotes() As NoteInfo
Dim LocalDrawingDoc As SldWorks.DrawingDoc ' Declared as an Object so that non Drawings can be detected!
Dim LocalPart As SldWorks.ModelDoc2 ' Declared as an Object so that non Drawings can be detected!
Dim strShtProp As Variant
Set LocalDrawingDoc = swApp.ActiveDoc
Set LocalPart = swApp.ActiveDoc
ReDim ArrayOfNotes(0)
' Get the sheet names and the number of them
NamesOfSheets = LocalDrawingDoc.GetSheetNames()
NumberofSheets = LocalDrawingDoc.GetSheetCount
' store this sheet name
Set sheet = LocalDrawingDoc.GetCurrentSheet()
strShtProp = sheet.GetProperties() ' get the sheet properties use much later for converting position into ref
SizeOfSheet = strShtProp(5)
Dim SwSketchMgr As SldWorks.SketchManager
Set SwSketchMgr = LocalDrawingDoc.SketchManager
Dim i As Integer
Dim vBlockDef As Variant
Dim vBlockInst As Variant
Dim strReturn As String
' Dim bret As Boolean
vBlockDef = SwSketchMgr.GetSketchBlockDefinitions
For x = NumberofSheets - 1 To 0 Step -1
If LocalDrawingDoc.GetCurrentSheet.GetName <> NamesOfSheets(x) Then LocalDrawingDoc.ActivateSheet NamesOfSheets(x)
Set LocalView = LocalDrawingDoc.GetFirstView
While Not LocalView Is Nothing
If Not IsEmpty(vBlockDef) Then
For i = 0 To UBound(vBlockDef)
Set swBlockDef = vBlockDef(i)
vBlockInst = swBlockDef.GetInstances
vNote = swBlockDef.GetNotes
If Not IsEmpty(vNote) Then
For j = 0 To UBound(vNote)
Set swNote = vNote(j)
NoteNumbersText = Trim(swNote.GetText)
If Left(NoteNumbersText, 1) = "n" And Len(NoteNumbersText) > 1 And Len(NoteNumbersText) < 4 Then
Set ThisAnnotation = swNote.GetAnnotation
'vPosition = swNote.GetAttachPos
vPosition = ThisAnnotation.GetPosition
Xpos = vPosition(0)
Ypos = vPosition(1)
Debug.Print ("Note " & NoteNumbersText & ": " & Xpos & "," & Ypos)
End If
Next j
End If
Next i
End If
Set LocalView = LocalView.GetNextView
Wend
Next x
End Sub
A: Turns out that SolidWorks is set up to return positions of blocks relative to the drawing view on which they're placed. Calling GetXForm for the view which they are placed on then provides a way of calculating the absolute position of each note.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can you access your online postgresql database when developing on your local machine? I want to start developing a django app on heroku which uses the postgresql database. I already got my hello world django app working on heroku, but now I am wondering how to develop with the postgresql database.
How do people do this? Can I link to the heroku postgresql database in the settings.py and develop on my local 'django runserver' server?
How do people do this? Do they use a postgresql database on their own machine? How would you keep the online one and your local one the same?
A: I think one of the best way - it is to copy database to your local machine, but it will be hard, if you have got huge database.
You can also use working database from remote server. Just type ip/host and other settings for database on your server and you'll get access.
A: Not sure about python and how you interact with heroku (do you use the heroku cli??) but in the Ruby land we can do heroku db:pull which will pull the DB from heroku and magically transpose it into whatever DB you use locally, the same for pushes. It also supports individual/combintations of tables to push/pull.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++: insert into std::map without knowing a key I need to insert values into std::map (or it's equivalent) to any free position and then get it's key (to remove/modify later). Something like:
std::map<int, std::string> myMap;
const int key = myMap.insert("hello");
Is it possibly to do so with std::map or is there some appropriate container for that?
Thank you.
A: In addition to using a set, you can keep a list of allocated (or free)
keys, and find a new key before inserting. For a map indexed by
int, you can simply take the last element, and increment its key. But
I rather think I'd go with a simple std::vector; if deletion isn't
supported, you can do something simple like:
int key = myVector.size();
myVector.push_back( newEntry );
If you need to support deletions, then using a vector of some sort of
"maybe" type (boost::optional, etc.—you probably already have
one in your toolbox, maybe under the name of Fallible or Maybe) might be
appropriate. Depending on use patterns (number of deletions compared to
total entries, etc.), you may want to search the vector in order to
reuse entries. If your really ambitious, you could keep a bitmap of the
free entries, setting a bit each time you delete and entry, and
resetting it whenever you reuse the space.
A: You can add object to an std::set, and then later put the whole set into a map. But no, you can't put a value into a map without a key.
A: The closest thing to what you're trying to do is probably
myMap[myMap.size()] = "some string";
The only advantage this has over std::set is that you can pass the integer indexes around to other modules without them needing to know the type of std::set<Foo>::iterator or similar.
A: It is impossible. Such an operation would require intricate knowledge of the key type to know which keys are available. For example, std::map would have to increment int values for int maps or append to strings for string maps.
You could use a std::set and drop keying altogether.
A: If you want to achieve something similar to automatically generated primary keys in SQL databases than you can maintain a counter and use it to generate a unique key. But perhaps std::set is what you really need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the use of setupUi(this) in Qt I am new to Qt. I have downloaded a source from net.
The header file contains the following
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
ainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui; // Need for this line. Any one please help
};
#endif // MAINWINDOW_H
in mainwindow.cpp file ui->setupUI(this) has been called in constructor. Please help what is the need for the creation of ui variable
A: You need a MainWindow.ui file which is then processed by Qt's UIC mechanism, which is triggered if you run qmake.
If you are using an IDE like Visual Studio with the Qt Plugin or Qt Creator, just create a new Qt GUI class through the wizard and you will have everything you need.
This page discusses usage of UI files in depth.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Shift bytes of file in bash How can I shift some bytes of a file in bash? What I want to do is make a file corrupt to check that my program will handle corrupt files correctly.
Thanks!
A: To shift by, say, 3 bytes "left" and discard the shifted bytes:
$ tail -c +3 file > file.shifted
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I find files within a directory containing paths to /bin but not shbangs? I want find all files inside of a directory that make a call to /bin executable, but I do not want to include shbangs, like so:
#!/usr/bin/perl
#!/bin/bash
All other files containing the path should be listed and show the code making the call.
A: Or with only 2 greps:
grep -r /bin * | grep -Pv '.*?:#!'
A: Give this a try:
$ grep -H -r '.*' *|grep -v '^#!'|grep /bin/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Where to modify threadcount in Weblogic 10.0 MP2 I need to modify the number of threads available in my Weblogic 10.0 MP2 environment for some perf benchmarking but I cannot seem to be able to find where exactly that option lies.
Can anyone share this info please? thank you.
A: Weblogic 10 does not use execute thread queues like in previous versions (i.e. Weblogic 8.1 and older)
This concept is now replaced with Work Managers.
These are self-tuned, i.e. WLS will auto-tune the number of threads every 2 seconds based on how it sees the need to increase threads for the application load.
You can confirm this from the console, it will show the increasing number of execute threads as the load increases.
You can use the work manager and constraints to make sure your applications get certain criteria met.
Such as certain web apps or EJBs can get a higher share of threads and so on.
For a quick read see http://www.oracle.com/technetwork/articles/entarch/workload-management-088692.html
and
http://m-button.blogspot.com/2009/02/tuning-default-workmanager-on-weblogic.html
Secondly, are you running in dev mode or production mode.
If dev mode, you can try this cmd line parameter
-Dweblogic.threadpool.MinPoolSize=100
but I am not sure if it will work, so it's better to leave it to Work Managers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: HTML5 and Internet Explorer? May be my question sounds stupid but I was wondering if it is possible to make Internet explorer (7 and 8) to recogonize HTML5 tags such as header, footer, section, aside etc, without using javascript ie. with css only?
Thanks
A: nope, it's not possible, you have to use JS
you could create elements.. e.g
document.createElement("header");
document.createElement("footer");
document.createElement("section");
document.createElement("aside");
or
this link may help How can I use HTML5 in all browsers including IE7,8?
A: IE8 was released long before the HTML5 spec, so it's not surprising that neither IE7 nor IE8 support any of the HTML5 features.
The only way to make IE8 or earlier recognise and support elements which it doesn't know about is to use a Javascript hack. This hack is available stand-alone in the form of HTML5Shiv, and is also built into the Modernizr feature detection library.
There is no other way to make IE work with HTML5. So the basic answer to your question is "No". Sorry. There is no CSS-only solution. (in fact even the Javascript solution is a hack which exists more by luck than anything else; it certainly isn't something that MS intended to write into IE)
If you don't want to do the Javascript hack, then your best bet is simply not to use the HTML5 tags at all; use <div> elements instead, with suitably semantic classnames.
Of course, even with this hack, all you're doing is allowing IE to recognise that the new tags are valid HTML; you aren't actually adding any features to IE, so using any of the HTML5 stuff that provides new functionality (such as Canvas or the new input types) is still not going to work. There are separate Javascript tools for a number of these features, but beware of performance issues if you try to do to much (IE7/8 aren't exactly quick at the best of times).
A: it's possible http://debeterevormgever.nl/en/articles/html5-elements-ie-without-javascript
but it will not validate
html
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:html5="http://www.w3.org/1999/xhtml">
<body>
<html5:section>...</html5:section>
</body>
</html>
css
html5\:section, #element-id, .element-class {
...
}
A: No, it isn't possible. That is why the JS shim is used.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript - can i check if ajax is currently loading? i made a "scroll down, fire ajaxrequest, load more content" function.
but for it to work properly, and not fire many times in succession because the user scrolls more before the ajax data is loaded into the document, i need to prevent firing more ajaxrequests if there is any ajaxrequests loading.
code:
$(document).scroll(function() {
var scrollBottom = $(document).height() - $(window).scrollTop();
if (scrollBottom < 3000) {
var offset = parseInt($("#offset").html()) + 10;
document.getElementById('offset').innerHTML = offset;
$.ajax({
type: "POST",
url: "/",
data: "offset=" + offset <?=$ajaxextra?>,
success: function(data){
$("#mainContent").append(data);
},
error: function(e) {
alert(e);
}
});
}
});
This is what i think i need, in pseudocode:
if (scrollBottom < 3000 && !ajax.isLoading())
How do people do this kind of thing?
A: Since maybe you can start many AJAX requests, I'd argue that one of best solutions - basically, a reliable solution - is first creating an array of requests' state like this:
var ajaxRequestsState = [];
When you start an AJAX request, you should add an element to this array like this one:
ajaxRequestsState.push({ requestId: "some identifier" });
Later, if you need to check if there's no active request, you can have a flag like so:
function isAsyncRequestActive() {
return ajaxRequestsState.length > 0;
}
Finally, whenever a request ends or fails, you must do so:
function releaseRequest(requestId) {
var requestIndex = 0;
var found = false;
while(!found && requestIndex < ajaxRequestsState.length)
{
found = ajaxRequestsState[requestIndex].requestId == requestId;
requestIndex++;
}
if(found) {
ajaxRequestsState.splice((requestIndex-1), 1);
}
}
releaseRequest("identifier of request which ended or failed");
That's simply tracking requests' state and maintaining a collection of requests' states, and you'll have it!
*Edited!
A: I would recommend the use of a flag.
The concept of a flag is to turn something on/off. In this case you could specify a global boolean (true or false) variable (more on Global Variables in JS). When you fire a given ajax request you turn that variable to true and when the ajax completes you turn it back to false.
The only thing you need to do is check that global variable when you request any ajax request.
Taking into account your example:
// Global variable. It needs to be outside any function, you can make it the first line in your .js file.
var isAjaxLoading = false;
$(document).scroll(function() {
var scrollBottom = $(document).height() - $(window).scrollTop();
if (scrollBottom < 3000 && !isAjaxLoading) {
var offset = parseInt($("#offset").html()) + 10;
document.getElementById('offset').innerHTML = offset;
isAjaxLoading = true;
$.ajax({
type: "POST",
url: "/",
data: "offset=" + offset <?=$ajaxextra?>,
success: function(data){
$("#mainContent").append(data);
isAjaxLoading = false;
},
error: function(e) {
alert(e);
isAjaxLoading = false;
}
});
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cross compile Qt source the Angstrom toolchain(any linux supported embedded toolchain would do) I am new to cross compiling and willing to get started with cross compiling Qt for beagleboard. Can some one give me specific instructions for this or recently tried tutorial. Please do not assume any knowledge on my part so can not handle instructions like "you may have to edit this to your architecture". I have a few important questions.
*
*how to build Angstrom tool chain and how to prepare it for cross compiling. (I have tried the anstrom web site and never found such random instrutions in my life).
*How to cross compile Qt after installing.
A: The process is a little daunting for the first time developer. I used this blog to give me a start,
http://treyweaver.blogspot.com/2010/10/setting-up-qt-development-environment.html
but like all of the other instructions, sometimes there will be deviations. It took me a while to sort it all out. You are going to have to read and study to to this. It is a worthy thing to do however. As far as Angstom, there are ready made images available. I started with that. You should use Ubuntu to do all of your work. Linux makes it a lot easier.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Static methods and Singleton in PHP I have the next class:
class MyClass {
private $_instance = null;
private function __clone() {}
private function __construct() {}
public static function instance()
{
if (is_null(self::$_instance)) {
self::$_instance = new self;
}
return self::$_instance;
}
public static function methodOne() {}
public static function methodTwo() {}
public static function methodThree() {}
public static function methodFour() {}
}
And I have a lot of methods method...(). But this methods can be executable only if instance is not null. How can I throw an exception if instance is null?
I need to use only static methods. I can not use non-static. I want to use the next design:
MyClass::instance();
MyClass::methodOne(); // If no instance throws an Exception.
A: Do not make the methods static, only keep instance() static.
It will lead to:
$m = MyClass::instance();
$m->methodOne();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VBA how to loop through a column in Excel I know start cell, and I need to go down through the column. And I need to exit cycle when the next cell is empty. How to do it in VBA code?
Thanks for replies
A: How about;
'//get a range from anchor cell (a1) to the 1st empty cell in the same column;
dim r As Range, cell as Range
set r = Range(Range("A1"), Range("A1").End(xlDown))
'//loop it
for Each cell In r
msgbox cell.Value
next
A: I adjusted AlexK's answer:
dim c As Range
'//loop it
for Each c In Range(Range("A1"), Range("A1").End(xlDown))
msgbox c.Value
next
A: In VBA, everything cell-based can be done with ranges, using offsets to return the value you are looking for:
Dim Anchor as Range
Set Anchor = Range("A1")
i = 0
Do
' Cell in column is Anchor.Offset(0, i)
' i.e., Anchor.Offset(0, 0) = A1
' Anchor.Offset(0, 1) = B1
' Anchor.Offset(0, ") = C1
' etc.
' Do whatever you like with this, here!
i = i + 1
Loop Until Anchor.Offset(0, i) = ""
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot see files uploaded to Windows box running Apache I have Apache set up on our development server (Windows 7 Home Premium). I am creating a CMS site and using TinyMCE to allow for the insertion of images. This all works fine, but I cannot access the images uploaded. I can see and edit them if I view them on the actual Windows box, but cannot view them over the network.
Any help with this would be appreciated.
*
*Alex
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: grid of MouseArea in Qt QML I have made an Item in QT QML which contains a MouseArea element.
Here is the code,
import QtQuick 1.0
Rectangle {
id: base
width: 240
height: 320
x:0; y:0
color: "#323138"
/////////////////////// MAIN FOCUSSCOPE //////////////////////
FocusScope {
id: mainfocus
height: base.height; width: base.width
focus: true
/////////////////////// MAIN GRID ///////////////////////////
GridView {
id: maingrid
width: base.width-10; height: base.height-titlebar.height-10
x: 5; y: titlebar.height+5;
cellHeight: maingrid.height/3; cellWidth: maingrid.width/3-1
Component {
id: myicon
Rectangle {
id: wrapper
height: maingrid.cellHeight-10; width: maingrid.cellWidth-10
radius: 8; smooth: true
color: GridView.isCurrentItem ? "#c0d0c0" : "transparent"
focus: true
MouseArea {
id: clickable
anchors.fill: wrapper
hoverEnabled: true
//onClicked: func()
}
Image {
id: iconpic
source: "./ui6.svg"
anchors.centerIn: wrapper
}
Text {
id: iconname
color: wrapper.GridView.isCurrentItem ? "black" : "#c8dbc8"
anchors.top: iconpic.bottom; anchors.horizontalCenter: iconpic.horizontalCenter
text: name
}
}
}
model: 4
delegate: myicon
focus: true
}
}
//////////////////////// TITLEBAR ///////////////////////
Rectangle {
id: titlebar
x:base.x
y:base.y
height: 25; width: base.width
color : "#356f47"
Text {
color: "#fdfdfd"
anchors.centerIn: titlebar
text: "title"
}
}
}
I want to make a grid of such Items so that it gives me a grid of custom made click-able Items that I created which I can use for different functions.
Using the GridView element, I was able to make such a grid which used number of my custom made Items as a template.
The problem is that when I click anyone of these Items it executes a single function since there was only one MouseArea element in my Item. I am able to detect a click on an Item, but not able to uniquely determine which Item was clicked. How do I achieve this ?
Of course, I might be doing it wrong, so other suggestions are also welcome.
Thanks
A: When the GridView item creates the instances they inherit the index variable. This identifies the unique item.
MouseArea {
id: clickable
anchors.fill: wrapper
hoverEnabled: true
onClicked: {
maingrid.currentIndex=index;
switch (index)
{
case 0:
//Function or method to call when clicked on first item
break;
case 1:
//Function or method to call when clicked on second item
break;
default:
//Function or method to call when clicked on another item
break;
}
}
}
I hope it helps you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone: showing UIWebview in UIActionSheet problem In my universal app I am trying to show webview in a uialertsheet but getting weird results, why is that webview shifted on left? and ok button is on the top? I want to just center and nicely fit to the uisheet window but with the OK button clickable on the bottom
You can also simply ignore my code and may tell how to accomplish this.
tnx
UIActionSheet *msgSheet = [[[UIActionSheet alloc]
initWithTitle:@"x"
delegate:nil
cancelButtonTitle:nil destructiveButtonTitle:nil
otherButtonTitles:@"OK", nil]
autorelease];
UIWebView *w=[[UIWebView alloc] init];
[w loadHTMLString:theString baseURL:nil];
[msgSheet addSubview:w];
[w release];
[msgSheet showInView:self.view];
[msgSheet setOpaque:NO];
[msgSheet setAlpha:0.7];
CGRect wRect = msgSheet.bounds;
w.bounds = wRect;
CGRect menuRect = msgSheet.frame;
CGFloat orgHeight = menuRect.size.height;
menuRect.origin.y -= 150; //height of webview
menuRect.size.height = orgHeight+150;
msgSheet.frame = menuRect;
CGRect wRect = w.frame;
wRect.origin.y = orgHeight;
w.frame = wRect;
CGSize mySize = msgSheet.bounds.size;
CGRect myRect = CGRectMake(0, 0, mySize.width, mySize.height);
UIImageView *redView = [[[UIImageView alloc] initWithFrame:myRect] autorelease];
[blueView setBackgroundColor:[[UIColor APP_TINT_COLOR] colorWithAlphaComponent:0.6]];
[msgSheet insertSubview:blueView atIndex:0];
A: I solved the problem easily simply by reading this article;
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaViewsGuide/Coordinates/Coordinates.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bijection on the integers below x i'm working on image processing, and i'm writing a parallel algorithm that iterates over all the pixels in an image, and changes the surrounding pixels based on it's value. In this algorithm, minor non-deterministic is acceptable, but i'd rather minimize it by only querying distant pixels simultaneously. Could someone give me an algorithm that bijectively maps the integers below n to the integers below n, in a fast and simple manner, such that two integers that are close to each other before mapping are likely to be far apart after application.
A: For simplicity let's say n is a power of two. Could you simply reverse the order of the least significant log2(n) bits of the number?
A: Considering the pixels to be a one dimentional array you could use a hash function j = i*p % n where n is the zero based index of the last pixel and p is a prime number chosen to place the pixel far enough away at each step. % is the remainder operator in C, mathematically I'd write j(i) = i p (mod n).
So if you want to jump at least 10 rows at each iteration, choose p > 10 * w where w is the screen width. You'll want to have a lookup table for p as a function of n and w of course.
Note that j hits every pixel as i goes from 0 to n.
CORRECTION: Use (mod (n + 1)), not (mod n). The last index is n, which cannot be reached using mod n since n (mod n) == 0.
A: Apart from reverting the bit order, you can use modulo. Say N is a prime number (like 521), so for all x = 0..520 you define a function:
f(x) = x * fac mod N
which is bijection on 0..520. fac is arbitrary number different from 0 and 1. For example for N = 521 and fac = 122 you get the following mapping:
which as you can see is quite uniform and not many numbers are near the diagonal - there are some, but it is a small proportion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: generic programming in c++ and typedef inside a class let's say I have the following code in A.cpp file:
template <typename T>
class A{
typedef T myType;
myType foo();
}
If I want to implement the foo function in this file , what is the syntax to write the function declaration?
I thought it'll be:
template <class T>
myType A<T>::foo(){
.
.
.
}
obviously it's wrong.
A: Yes, the typedef is only available within the class, and the return type is not in the class:
template <class T>
typename A<T>::myType A<T>::foo() {}
A: template <typename T>
typename A<T> :: myType A<T> :: foo ()
{
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Landscape mode both side 180 degree I have developed a Flash game for Adobe Air. In the game I set it to only allow the display to be in landscape mode. If the device is rotated 180 degrees I want it to flip the view. However, at no time do I want the display to allow portrait mode. How can I accomplish this?
here is image you can see:
A: You have to set the app to auto-rotate, and also prevent changes to portrait-aspect orientations.
See http://forums.adobe.com/message/3771984 for the details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: java jndi ldap connection timeout I want to control the connection timeout by setting com.sun.jndi.ldap.connect.timeout property. It works well for values under 1000 ms, but if I set values bigger then 1000, the timeout doesn't increase (it remains at 1000).
Here is the code I tried to test it with (the server is down):
long start = System.currentTimeMillis();
try
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");
env.put("com.sun.jndi.ldap.connect.timeout", "10000");
InitialLdapContext context = new InitialLdapContext(env, null);
} catch (NamingException e)
{
System.out.println("Failed because " + e.getRootCause()
.getMessage() + ". Timeout: " + ((System.currentTimeMillis() - start)) + " ms.");
}
What might cause this?
A: If the target host responds to the connect request with an error code, the connection fails as soon as the error code is received. It appears that the target host was up and the target LDAP service wasn't listening at port 10389. So the target host responded to the incoming connect request with an RST, so an exception was thrown immediately at the client. This is expected behaviour. You surely don't want to delay receiving the error? The connect timeout is for the case when the target host is temporarily unreachable or the target service is really busy.
A: This is a post about this topic. Seems this property doesn't really work this way. Maybe this follow-up thread can help to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Recaptcha ErrorMessage I'm using the Recaptcha control in asp.net web forms. And i've faced with the problem about ErrorMessage. How to:
*
*Set ErrorMessage for it?
*Show (hide) the ErrorMessage if the Recaptcha is (isn't) valid?
A: If you grab the latest source code you should find examples in dotnet/test folder.
ErrorMessage can be set through CustomTranslations property like here: recaptcha-plugins/dotnet/test/CustomTranslation.aspx.cs
protected void Page_Init(object sender, EventArgs e)
{
var customTranslation = new Dictionary<string, string>();
customTranslation.Add("instructions_visual", "Scrivi le due parole:");
customTranslation.Add("incorrect_try_again", "Scorretto. Riprova.");
RecaptchaControl.CustomTranslations = customTranslation;
}
The ErrorMessage will be automatically displayed in a ValidationSummary because RecaptchaControl implements IValidator interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: References Tables: all in one or separate table? I have a group table - should option_id or extras_id should be in separate tables or all in one table? See below what I meant:
group table:
mysql> select * from `group`;
+----+-----------+--------+
| id | name | type |
+----+-----------+--------+
| 1 | Group One | extra |
| 2 | Group Two | option |
+----+-----------+--------+
There are two of group (extra or option).
group_extra table:
mysql> select * from `group_extra`;
+----+----------+----------+
| id | group_id | extra_id |
+----+----------+----------+
| 1 | 1 | 123 |
| 2 | 1 | 124 |
+----+----------+----------+
group_id = 1 have a list of ref extra_id
group_option table:
mysql> select * from `group_option`;
+----+----------+-----------+
| id | group_id | option_id |
+----+----------+-----------+
| 1 | 2 | 45 |
| 2 | 2 | 46 |
+----+----------+-----------+
group_id = 2 have a list of ref option_id
group_option_extra table:
mysql> select * from `group_option_extra`;
+----+----------+-----------+----------+
| id | group_id | option_id | extra_id |
+----+----------+-----------+----------+
| 1 | 1 | 0 | 123 |
| 2 | 1 | 0 | 124 |
| 3 | 2 | 45 | 0 |
| 4 | 2 | 46 | 0 |
+----+----------+-----------+----------+
Or should the table look like this, combine group_option and group_extra into one? which one is recommended.
A: Keep them separate.
You don't really need the type column - you can just check if any rows exist in the other tables to see which type it is.
A: Separate.
"together" is known as the "One True Lookup Table" anti-pattern
See
*
*sql performance of a lookup table
*http://tonyandrews.blogspot.com/2004/10/otlt-and-eav-two-big-design-mistakes.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: msbuild: how to register different versions of the same dll? I have the following dll registration within my ms build now using the code below although we work with different code bases which might need different versions of the dll registered, i.e. MyLib.dll that represents the development version and another MyLib.dll that's for a production equivalent. Is it possible to register a DLL this way? I.e. potentially multiple MyLib.dlls but with some unique key or something..(?)
In the example code below it seems to correctly remove any existing dll called MyLib and then to register the newest version.
Thanks,
James
<Target Name="MyLib">
<Exec Command="%WinDir%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe ..\..\Library\MyLib.dll /unregister"></Exec>
<Exec Command="%WinDir%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe ..\..\Library\MyLib.dll"></Exec>
</Target>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to read json I have following JSON object.
{"feed":[
{"news":
{"adopted_from":null,"user_id":null,"description":"this is test","id":2}
},
{"news":
{"adopted_from":null,"user_id":null,"description":"like unlike done","id":1}
}
]}
I want to retrieve the id of news. I tried in many different ways (e.g. feed[0].news.id, feed.news.id, feed[[0].news.id]) but could not access the value. Can anyone help me how can I access it using JavaScript?
A: I copied and pasted your JSON from above and tried the following and it works just fine:
var data = {"feed":[{"news":{"adopted_from":null,"user_id":null,"description":"this is test","id":2}},{"news":{"adopted_from":null,"user_id":null,"description":"like unlike done","id":1}}]};
// alert the first news id
alert(data.feed[0].news.id);
It gets the id from the first news object from the array as intended.
A: this works for me:
var f = {"feed":[{"news":{"adopted_from":null,"user_id":null,"description":"this is test","id":2}},{"news":{"adopted_from":null,"user_id":null,"description":"like unlike done","id":1}}]}
alert( f.feed[0].news.id )
A: var feed = json_decode(yourData)
for(var counter in feed) {
console.log(feed[counter].news.id);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Capture contents of div into an image Does anybody know if it is possible to grab a capture of a particular div using php? What I would like to do is have a drag and drop container where users could potentially position a number of images using javascript and then I would like them to be able to save a copy of the result as a single image.
Thanx in advance
A: My guess would be, work out the coordinates of the images placed with javascript and assign them to a hidden form field. Then save it using PHP and store the coordinates in the database...
A: You can use canvas.toDataURL() from the html 5 canvas element to save it into a image file. You can get more info Here.
A: You can load the images into a canvas field (drawImage()) and implement drag and drop functions. If the user presses the send button, the canvas will be converted to a data URL with canvas.toDataURL().
But I think it's simplier when you only save the coordinates and let PHP merge the images.
A: What you want to achieve can be done only with javascript. And if you need the image on server, you can sent it by ajax.
Take a look at this jQuery tutorial which does something close that you want. (demo)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Testing ActiveSupport::TimeWithZone objects for equality Can someone explain how d1 is greater than d2? They are the same damn dates (or atleast that is how they look to me).
Loading development environment (Rails 3.0.8)
ruby-1.9.2-p180 :001 > d1 = Event.first.updated_at
=> Thu, 22 Sep 2011 02:24:28 PDT -07:00
ruby-1.9.2-p180 :002 > d2 = Time.zone.parse("2011-09-22T02:24:28-07:00")
=> Thu, 22 Sep 2011 02:24:28 PDT -07:00
ruby-1.9.2-p180 :003 > d1.class
=> ActiveSupport::TimeWithZone
ruby-1.9.2-p180 :004 > d2.class
=> ActiveSupport::TimeWithZone
ruby-1.9.2-p180 :005 > d1 > d2
=> true
ruby-1.9.2-p180 :006 >
With regards to my specific application needs ... I have an iOS app that makes a request to my Rails application passing a JSON object that, amongst other items, includes NSDates in the format of "2011-09-22T02:24:28-07:00." I'm attempting to compare that datetime with the "updated_at" which is of type ActiveSupport::TimeWithZone.
Thanks - wg
A: You will find that the updated_at attribute in your Event model has a higher precision than seconds.
Try outputting the milliseconds part of your respective time objects:
puts d1.usec
puts d2.usec
Chances are the former will be > 0 since it was set automatically when the object was persisted, while the latter will equal 0 since you did not specify any milliseconds in the string from which you parsed it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How can we draw a vertical line in the webpage? For horizontal it is <hr>. but for vertical line?
A: You can use <hr> for a vertical line as well.
Set the width to 1 and the size(height) as long as you want.
I used 500 in my example(demo):
With <hr width="1" size="500">
DEMO
A: There are no vertical lines in html that you can use but you can fake one by absolutely positioning a div outside of your container with a top:0; and bottom:0; style.
Try this:
CSS
.vr {
width:10px;
background-color:#000;
position:absolute;
top:0;
bottom:0;
left:150px;
}
HTML
<div class="vr"> </div>
Demo
A: That's no struts related problem but rather plain HMTL/CSS.
I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.
A: <hr> is not from struts. It is just an HTML tag.
So, take a look here: http://www.microbion.co.uk/web/vertline.htm
This link will give you a couple of tips.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: 301 Redirect, mod_rewrite disabled if mod_rewrite disabled, is there any other way to redirect a domain to another one?
Using htaccess too or any other way.
A: To redirect the whole domain to another one use:
Redirect 301 / http://newdomain.com/
Edit: To redirect a specific subdirectory use:
Redirect 301 /dir http://new.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sending data with ajax from a link? (Without using ExtJS, jQuery or similar libraries) I have <a href="">follow me</a> and I want to send very simple post data to the page without reloading the page.
Edit: Oh, onlclick will solve my problem. I've got it.
Edit2: I mean, like <a href="" onclick="alert('jjj');">follow me</a>
A: Use jQuery Ajax to post data without loading page.
A: If you really don't want to use jQuery and ajax, you might want to use an invisible iframe to send the data to. I recommend jQuery ajax though...
A: Look at jQuery Ajax
There are plenty of examples online similar to what you want to achieve.
I could write the code for you, but you will gain so much from trying it yourself (and your question was vague about what serverside language your using).
If you get stuck - edit your question with the code and we will be more than happy to help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Deterministic Finite-state Automaton Questions I have this DFA described as (Q, q1, A, N, F) where
Q = {1,2,3,4},
q1 = 1,
A = {a,b,c},
F = {2,4},
N = {
(1,a) -> 2, (1,b) -> 3, (1,c) -> 4,
(2,a) -> 2, (2,b) -> 4,
(3,a) -> 2, (3,c) -> 4,
(4,b) -> 4, (4,c) -> 4 }
So I have drawn the transition diagram, and that looks fine,
I then need to work out wether or not the following strings are acceptable by this DFA:
*
*aabbcc
*acacac
*cabbac
*babbab
and come up with the following
*
*Correct
*Incorrect (can not move from a -> c ?)
*Incorrect (can not move from c -a ? )
*Incorrect (cannot move from b -> a)
I am not 100% sure those are correct, but think they are on the right track.
I then need to describe the language this accepts, in english, which I do not see being a problem, but where I need help is describing this language using mathematical notation. Could you please help me to understand this.
Thanks so much for your help
A: Your answers about the strings acceptability are right, this can easily be seen by trying to follow them out in the diagram.
Now, about the language:
In the 2-nd vertex we can finish with the words corresponding following regular expression:
b?a+ - we can optionally obtain b my moving to 3-rd vertex first, and then pass over a, or we can move to 2-nd vertex by a at once, and there we can add as much as as we want.
Now about finishing the word in the 4-th vertex:
First, how can we reach vertex 4 ?
1. We can first time reach vertex 4 by moving there by c at once, or by moving to 3-rd vertex first, obtaining b, and then to 4-th by c. Hereby we get strings like b?c
2. We can reach vertex 2 with b?a+ (as described in previous case), and then pass over b. Hereby we get strings like b?a+b.
Totally, we can reach to 4-th vertex with any word matching the b?(a+b|c) regexp.
Now, adding arbitrary count of b and c symbols in the end on vertex 4, we get the answer for this case:
b?(a+b|c)(bc)*
Finally, we can result the whole set of words acceptable by this DFA words as the following regex:
b?( a+ | (a+b|c)(bc)*? )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Question on C# App MessageBox.Show() that called by Cpp App CreateProcess() I have done 2 tests.
I got two applications that ran on the same computer.
1st time, when I click my CsAPP.exe. the MessageBox.Show() works quite well and a new window pop-up the way I wished.
2nd time, when I run CppAPP.exe there is a CreateProcess() to call CsApp.exe. At this point, my MessageBox.Show() doesn't work. I set breakpoint to my CsApp code and verfied that the code ran to MessageBox.Show() but the Pop-up window didn't show up.
C++ code snippet
CreateProcess(apppath.c_str(), NULL, &sa, &sa, FALSE, 0, NULL, appdir.c_str(), &si, &pi);
C# code snippet
MessageBox.Show("Read " + xmlFile + " failed, an invalid XML format file found",
"Critical Warning",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
Any replies and comments are appreciated.
[Updated on Aug 23rd]
I consulted one guy. And He said that the MessageBox showed on another invisible desktop actually for my test2. He recommended me to read a book named 'Windows internals'. If any found I will update my post later. Thanks.
A: Try creating the Process in the user Context.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682429%28v=vs.85%29.aspx
As far as i read, your problem is described here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425%28v=vs.85%29.aspx
If the calling process is impersonating another user, the new process uses the token for the calling process, not the impersonation token. To run the new process in the security context of the user represented by the impersonation token, use the CreateProcessAsUser or CreateProcessWithLogonW function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: -moz and -webkit css no longer needed? I have been using the -moz and -webkit css styles for a while now for things like box shadow, text shadow, etc. And lately I have noticed that each FireFox, Chrome, Safari, and IE (9) all yield the same results with the standard box-shadow and text-shadow and similar css styles.
I was wondering if this is documented anywhere. Because I successfully removed all of the browser-specific ones from a site and it still looks the same in all four of those browsers.
A: The latest browsers support these css3 properties by default. These -moz and -webkit specials should however still be used for backwards compatibility with older browsers. Older browsers implemented these to allow the use of these properties before they became standard.
A: I suppose it depends on the version of the browsers you are targeting.
It sounds like if, and only if, your app or site is intended to only work on the very latest versions of all the browsers, you can afford to omit the -moz and -webkit on the specific properties you have tested.
There are other properties that aren't supported on all browsers, e.g. my personal favourite webkit-transition. Of course in actual reality it's unlikely you can get away with targetting only the latest browsers unless you're making a personal project.
A: If you don't want to write that much and still want backwards compatibility: less.css could be your friend.
Another thing: w3schools.com has an up-to-date database for all CSS commands and which browser supports it. Helped a lot.
A: It might be useful to keep them for older browsers that don't have the standards, but do have the -moz and -webkit css styles.
A: For the latest versions of Firefox, Chrome and Safari that is true.
However, for people using earlier versions of the browsers (Firefox 3.6, as an example) you would still need to leave the -moz and -webkit prefixes.
If you want to target them, you shouldn't remove them.
These properties are progressive enhancement though, so removing them would not be harmful.
A: the best thing to do is to keep them all in there,
example:
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
depending on the user's browser version, they will still see the border-radius, older browsers will still use the -moz and -webkit version, the latest versions of safari / firefox or chrome will use the final implementation of the border-radius property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How to turn a LaTeX Sweave file (Rnw) into HTML? I searched for this, but couldn't find a solution.
I understand that one could use the HTML markdown with Sweave, and then output it to HTML using:
library(R2HTML)
Sweave('temp1.rnw', driver = RweaveHTML)
What I am wondering though, is if there a way to turn the .tex file that is created into an HTML file, but through R.
p.s: I am looking for a solution for windows. I've seen that other OS already has their own solutions.
Thanks.
A: TeX to HTML is a non-trivial task, because TeX is so general. As @richiemorrisroe said, mk4ht is available on Windows. So is tth (the other method suggested at the Vanderbilt page you linked to). I don't think you want to write a TeX parser in R ... Can you tell us why you want a pure-R solution? Is it just for the sake of having the solution self-contained?
I don't think the installation is really that hard. This should get you most of the way there ...
TTHurl <- "http://hutchinson.belmont.ma.us/tth/tth-noncom/tth_exe.zip"
SWconvurl <- "http://biostat.mc.vanderbilt.edu/wiki/pub/Main/SweaveConvert/sweave2html"
download.file(TTHurl,dest="tth.zip")
unzip("tth.zip") ## creates tth_exe
download.file(SWconvurl,dest="sweave2html")
Sys.chmod(c("tth_exe","sweave2html"),mode="0755") ## ???
You will need ImageMagick (binary downloads here) too if you want to convert PDF to PNG on the fly ...
tth is a little less general than mk4ht, which contains a complete (La)TeX parser, but it's also more lightweight -- useful if you want to give this recipe to other users to install and don't want them to have to download oodles of stuff (unfortunately ImageMagick is pretty big -- these days, you can probably concoct a solution where you generate the images in PNG in Sweave in the first place).
A: Well, its not really a pure windows solution, but you can use the tex4ht package, and call htlatex on the latex file after sweaving.
Something like system("htlatex somesweavedfile.tex") following running Sweave from within the R GUI (which is what I presume you mean). Incidentally, this html can also be opened by open office and then converted to word, which is always useful.
I always did this (on Windows) from a command line, and the help page for ?system notes that some commands may not work properly on Windows. From my reading of the relevant help page, it appears that this one will. The only difficulty might be if the htlatex command has a problem and tries to let you know, then I'm not sure if the readings from stderr will come back to the R GUI.
Just to note Tal, the mk4ht package is also available on Windows, but I can see how you might not have gotten that impression from the webpage, which is very Linux-specific (and also quite useful to me, thanks for the link!)
EDIT: in response to Tal's comment below.
If you install MikTeX on windows, it will give you a package manager which you can use to install mk4ht. This should (all paths being set correctly) allow you to carry out my answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: file_get_contents() in php not working I am using file_get_contents() in php that is not working when i am
using like this. the file name is index.php
<?php
$content = "hi";
$content = file_get_contents('index.php');
echo $content;
?>
I thought it prints hi more than one tym.. but it print that only one
time.. why? tell me please...
A: I think what you're trying to do here, is first give a value to $content, and then add whatever is in index.php.
If that's the case, do this:
<?php
$content = "hi";
$content .= file_get_contents('index.php');
echo $content;
?>
With = you redefine a variable, so it doesn't matter what it was before.
With .= you add something to a variable.
A: Step 1 : check path & access rights.
From your codes, your variable $content is overwritten by the result returned by file_get_contents() . Therefore, your echo is printing our the result returned by the function.
p.s. the function should work. Read the manual.
A: I think you’re trying to use recursion here. If you view source it probably says,
hi<?php
$content = "hi";
$content .= file_get_contents('index.php');
echo $content;
?>
The reason it is only printing “hi” is because your browser doesn't recognize the <php tag as valid HTML so it ignores it.
If my assumption is correct, then my question is Why do you want to do this? What are you trying to accomplish?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Maven + Scala + Java + Pelops = trouble I've a project in Java and Scala and I use maven to compile it.
A Java class uses Pelops to access a Cassandra database and it is all fine (maven compile the entire project), but when I try to access Cassandra from a Scala object (using tha same import as in the Java fil) maven give me this error :
[ERROR] error: error while loading Bytes, Missing dependency 'class com.eaio.uuid.UUID', required by /home/dacanalr/.m2/repository/pelops/pelops/1.0/pelops-1.0.jar(org/scale7/cassandra/pelops/Bytes.class)
What this mean and how can I solve ? I don't understand why from Java file it works, but don't from Scala source...
A: 15 seconds in Google to find this page, which I think contains a library you need at runtime
http://johannburkard.de/software/uuid/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Text array to email body I have a backup log file from robocopy and would like to take last lines from that file and send it as email body.
Log example:
Total Copied Skipped Mismatch FAILED Extras
Dirs : 85262 85257 1 0 4 0
Files : 637048 637047 0 0 1 0
Bytes :1558.929 g1558.929 g 0 0 165 0
Times : 19:30:49 19:01:06 0:00:00 0:29:43
Speed : 24448224 Bytes/sec.
Speed : 1398.938 MegaBytes/min.
Ended : Wed Sep 21 15:42:01 2011
Script code:
$report2_tail = Get-Content .\backup2.log )[-12 .. -1]
$encoding = [System.Text.Encoding]::UTF8
Send-mailmessage -Smtpserver smtp.server.address -encoding $encoding -from "Backup-Replication<backup@mm.com>" -to "mm@mm.com" -subject "End of Replication Report" -body "
backup Replication Report
------------------------------------------------------------
$report2_tail
"
Script works fine but the message body is in one line and looks like this:
Total Copied Skipped Mismatch FAILED Extras Dirs : 85262 85257 1 0 4 0 Files : 637048 637047 0 0 1 0 Bytes :1558.929 g1558.929 g 0 0 165 0 Times : 19:30:49 19:01:06 0:00:00 0:29:43 Speed : 24448224 Bytes/sec. Speed : 1398.938 MegaBytes/min. Ended : Wed Sep 21 15:42:01 2011
What is a best way to solve the problem ?
Regards
Marcin
A: Pipe Get-Content result to the Out-String cmdlet:
$report2_tail = Get-Content .\backup2.log )[-12 .. -1] | Out-String
Send-mailmessage ... -subject "End of Replication Report" -body $report2_tail
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: parent class to return subclass Its hard to explain in word what I'm after but hopefully the code example below with the comments is sufficient. Basically I want the SubClass sc = new Subclass().method1() line to return the Subclass instance.
public class SuperClass {
public SuperClass method1()
{
//do whatever
return this
}
}
public class SubClass extends SuperClass {
//we inherit method 1
//method2
public SubClass method2()
{
//do whatever
return this
}
}
//succesfully returns instance of Sublass, but...
SubClass sc = new Subclass().method2()
//...the following line returns an instance of SuperClass and not Sublass
//I want Sublass's instance, without having to using overides
//Is this possible?
SubClass sc = new Subclass().method1()
EDIT: ----------------------------usecase scenario-------------------------------
Message myMessage = new ReverseTransactionMessageBuilder()
.policyNo(POLICY_NO) //on ReverseTransactionMessageBuilder
.audUserId(AUD_USER_ID) //on inherited MessageBuilder
.audDate(new Date()) //on inherited MessageBuilder
.processNo(EProcessConstants.FINANCE_MANUAL_ADJUSTMENT.getProcessCd()) //on inherited MessageBuilder
.serviceName("finance.ProcessReversalCmd") //on inherited MessageBuilder
.create(); //create is overridden so this is ReverseTransactionMessageBuilder
First thing youl notice is that sbrattla way allows me to call these .audDate () .xxx() methods in any order. With the class construct above you are forced to call the method on the sublcass last (or use a really ugly cast)
A: You would need to do something like:
public class SuperClass<T> {
public T method1() {
return (T) this;
}
}
public class SubClass extends SuperClass<SubClass> {
public SubClass method2() {
return (SubClass) this;
}
}
You can read more about Java Generics in the "Generics Introduction", but briefly explained you're telling SuperClass to cast the returned instance to T which represents a type you define. In this case, it's SubClass.
A: I think you can use generic method like the following:
class Parent {
public <T extends Parent> T instance() {
return (T) this;
}
}
class Child extends Parent {
}
class Test {
public static void main() {
Child child = new Parent().instance();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Querying nested documents in mongoDB I want to query my Mongodb collection (name: wrappers) and retrieve all documents that have field 'urls' that end with '.com'
I am not sure on how to query nested documents and also using regex for queries.
I am actually coding it in perl. However queries to run on the mongo shell would also be fine.
Thanks in advance!
Sample Data:
{ "_id" : ObjectId("4e7a34932cd4b16704000000"), "lastArray" : { "desc" : "google", "url" : "google.com", "data" : [
{
"name" : "1",
"xpath" : [ ],
"nodes" : [ ],
"type" : "Any Text"
},
{
"name" : "2",
"xpath" : [ ],
"nodes" : [ ],
"type" : "Any Text"
}
{ "_id" : ObjectId("4e7a34932cd4b16704000001"), "lastArray" : { "desc" : "yahoo", "url" : "yahoo.com", "data" : [
{
"name" : "1",
"xpath" : [ ],
"nodes" : [ ],
"type" : "Any Text"
},
{
"name" : "2",
"xpath" : [ ],
"nodes" : [ ],
"type" : "Any Text"
}
A: db.wrappers.find({"lastArray.url":{$regex:/\.com$/}});
A: I'm not 100% sure if you can use regex to search sub-document attributes or if you'd even want to for performance reasons. In a case like this, it might be easier to add a "tld" attribute and do an exact match query. Something like this { "lastArray.tld" : "com" }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can´t trigger a javaScript method on the onload event of a form I am trying to call a JavaScript method on the onload() event of a form. Here is the code for the javaScript:
<script type="text/javascript">
function gback(){
document.FM.action = "<c:url value='FModificar'/>";
document.FM.method = "get";
document.FM.submit();
}
function DelF() {
jConfirm('Can you confirm this?', 'Confirmation Dialog', function(r) {
if (r == true) {
$("form[name='FEl']").submit();
} else {
return false;
}
});
}
function Check(msg){
if(msg.toString().length > 5){
jAlert('success', msg, 'Success');
}
}
</script>
And here is the html code:
<%-- FornecedorList is requested --%>
<c:if test="${!empty VFornecedorList}">
<table id="ProductTable" class="detailsTable" onload="Check(${CFP})">
<tr class="header">
<th colspan="7" >Fornecedor</th>
</tr>
<tr class="tableHeading">
<td>ID</td>
<td>Nome</td>
<td>Endereço</td>
<td>Descrição</td>
<td>Nº de Celulare</td>
<td>Nº de Telefone</td>
<td>Email</td>
<td>Fax</td>
</tr>
<c:forEach var="VForn" items="${VFornecedorList}" varStatus="iter">
<tr class="${'white'} tableRow">
<td>${VForn.getFid()}</td>
<td>${VForn.getFNome()}</td>
<td>${VForn.getFEndereco()}</td>
<td>${VForn.getFDescricao()}</td>
<td>${VForn.getFNCel()}</td>
<td>${VForn.getFNTel()}</td>
<td>${VForn.getFEmail()}</td>
<td>${VForn.getFFax()}</td>
</tr>
</c:forEach>
</table>
</c:if>
<%-- END FornecedorList is requested --%>
Also the method receives a parameter from the controller. Here is the code:
//Add a Fornecedor
fornece = transManager.addfornecedor(ID, nome, endereço, email, cell, tel, fax, des, Fact);
String Fmsg = "";
if (!fornece.equals(""))
Fmsg = "Fornecedor " + nome + " foi criado";
if(!PFtp.equals("Prodft")){
Fornecedor = transManager.getLEnt("fornecedor");
request.setAttribute("CFP",Fmsg);
request.setAttribute("VFornecedorList",Fornecedor);
userPath = "/Fornecedor";
}
I am using Netbeans 7.0.1 and Firefox 5. So any advice would be much appreciated.
A: Forms don't have a load event. A form is just part of a document, not something that loads independently (such as a whole document, or the content or an iframe, or an image).
If you want to run some JS as soon as a form has been parsed, do this:
</form>
<script> your js here </script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: simplejson in Python throws value error I've got a JSON string that I'm posting to my Python script. This is an example string:
{"uid":"1111111","method":"check_user"}
In my Python code I simply call simplejson.loads( str ) where str is the JSON string from the request. The JSON string seems fine as when I print it at request time it's intact. However I get a ValueError:
Extra data: line 1 column 41 - line 1 column 48 (char 41 - 48)
Traceback (most recent call last): File
"/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/_webapp25.py",
line 703, in __call__
handler.post(*groups) File "/Users/.../app/controller/api_controller.py", line 25, in post
req = simplejson.loads( req ) File
"/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_0_96/django/utils/simplejson/__init__.py",
line 232, in loads
return cls(encoding=encoding, **kw).decode(s) File
"/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django_0_96/django/utils/simplejson/decoder.py",
line 254, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
Any ideas what it may be? I've tried removing new lines, tabs and slashes from the string, even decoding it using .decode('string_escape')
A: You've got some unprintable character in your string. I get the same error if I append a null byte to the end of the string, and printing it doesn't show the problem:
>>> import json
>>> string = '{"uid":"1111111","method":"check_user"}\x00'
>>> print string
{"uid":"1111111","method":"check_user"}
>>> print repr(string)
'{"uid":"1111111","method":"check_user"}\x00'
>>> json.loads(string)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "C:\Python27\Lib\json\__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "C:\Python27\Lib\json\decoder.py", line 369, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 39 - line 1 column 40 (char 39 - 40)
Print the repr of your string at request time and you should see it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SRP Algorithm Design I am reading Uncle Bob's Agile PPP, Specifically i am reading the SRP part of it, while reading about the principle i got a doubt that is it not that SRP is increasing the coupling in our design with so many small-small classes inter-dependent on each other? I know the book says that it reduces coupling but i didn't understand how?
A: If a class has more than one responsibility then you are coupling those responsibilities together in the one class. By separating them out into their own classes the responsibilities are being decoupled and now each class only has one reason to change.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create an update for an extension in Magento My question is about creating update packages for a custom module extension that I have made.
So far I have been able to export mu module by using the "create package extension" function and installing the module on another Magento using the "Direct package file upload" method in Magento connect.
But when I make a newer version of the module, by chancing some code in the modules PHP files, package the extension and try to upload to Magento using "Direct package file upload" method, it says it can't, upload the module because the files already exists.
I have remembered to change the version number in the config.xml file, and I have made an update script for the database. But other than that I can't figure out how to proceed, and I have been unable to find documentation, for how to make extensions upgrades elsewhere.
I hope you will be able to give me a little help in this matter.
A: File already exists means you've already uploaded an update with that version number.
You can't trick the package ;)
You must repackage on the backend with a new version number. Just changing the package.xml doesn't work ;) Trust me.. I've tried for a quick work around.
More here at the FAQ: http://www.magentocommerce.com/wiki/7_-_magento_connect/magento_connect_faq
Also new packaging info here: http://www.magentocommerce.com/magento-connect/new_developer/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to fix exceeded limit of maxWarmingSearchers? Anyone know why and how to resolve this as I have a very busy updates and searches at the same time.
Error opening new searcher.
Exceeded limit of maxWarmingSearchers=2, try again later
A: As per the Solr FAQ: What does "exceeded limit of maxWarmingSearchers=X" mean?
If you encounter this error a lot, you can (in theory) increase the
number in your maxWarmingSearchers, but that is risky to do unless you
are confident you have the system resources (RAM, CPU, etc...) to do
it safely. A more correct way to deal with the situation is to reduce
how frequently you send commits.
What this error means is that you are basically making commits too often and the internal cache can't keep up with the frequency you are saying "clear the cache and let me search with the new data". You need to decrease the frequency you are making commits. You can find more information about this problem here in Near Realtime Search Tuning but the basic idea is the more facets you use the greater the interval you will need between commits.
One way I got around this was I stopped making manual commits (i.e. having my application submit data to solr and then executing a commit request) and turning on solr autocommit.
Here's an example:
<!-- solrconfig.xml -->
<autoCommit>
<maxDocs>10000</maxDocs> <!-- maximum uncommited docs before autocommit triggered -->
<maxTime>15000</maxTime> <!-- maximum time (in MS) after adding a doc before an autocommit is triggered -->
<openSearcher>false</openSearcher> <!-- SOLR 4.0. Optionally don't open a searcher on hard commit. This is useful to minimize the size of transaction logs that keep track of uncommitted updates. -->
</autoCommit>
You will have to figure out how large of interval you will need (i.e. maxTime) but in practice every time I add more faceted search to my application (or more indexes or what have you) I have to increase the interval.
If you need more real time search than the frequency of these commits will allow you can look into Solr soft commits.
A: As it's well explained here you should reduce the number of commits you make, or change the value of maxWarmingSearchers in solrconfig.xml (which is not a good practice)
A: As per the https://wiki.apache.org/solr/CommitWithin
There are multiple commit strategies in Solr. The most known is explicit commits from the client. Then you have AutoCommit, configured in solrconfig.xml, which lets Solr automatically commit adds after a certain time or number of documents, and finally there may be a behind-the-scenes commit when the input buffer gets full.
You can use 'CommitWithin' to handle this problem.
Solr3.5 and later, it can be server.add(mySolrInputDocument, 10000);
In earlier versions, you can use below code
UpdateRequest req = new UpdateRequest();
req.add(mySolrInputDocument);
req.setCommitWithin(10000);
req.process(server);
It can reduce the frequently you send the commits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Mysql query for selecting min/max values in a varchar field So I have a varchar column which is supposed to store product prices( don't ask me how I ended up with that, but now I have no option of changing this...sigh ), It can also be blank, or contain one of the texts(literally) "null","OUT" where both represents a price of 0. What is the best and most efficient way to find the MIN and MAX value of this column?
PS: I am open to php/mysql hybrid solutions, cause I need the most optimized and efficient way for this. This table is really huge...
A: Something like this should work and be reasonably efficient. It's not going to be fast in any case, though.
SELECT
MIN(CAST(price AS DECIMAL(8,2))) as price_min,
MAX(CAST(price AS DECIMAL(8,2))) as price_max
FROM products
WHERE price NOT IN('', 'null', 'OUT')
After testing this, I noticed that apparently the casting is done automatically, so you can just do:
SELECT
MIN(price) as price_min,
MAX(price) as price_max
FROM products
WHERE price NOT IN('', 'null', 'OUT')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I generate an absolute url in a Zend Framework (1.11) controller action? I have a facebook application.
Facebook says I need to redirect to a certain facebook url, in order for the user to give permissions to the application.
I currently have a view phtml file, with the following which works fine:
<script type="text/javascript">
top.location.href = 'https://www.facebook.com/dialog/oauth?client_id=<?php echo $this->fbAppId?>&redirect_uri=<?php echo $this->serverUrl() . $this->baseUrl() . $this->url(array('controller' => 'index', 'action' => 'post-authorize'))?>&scope=publish_stream,user_birthday,user_about_me,user_activities,user_location';
</script>
However - I want to try a different approach, that will save on resources and process time, by not rendering the view, and just redirecting via the Location header (using the redirector action helper, or any other action helper as such).
In the view script, I use the ServerUrl view helper, to generate an absolute path.
How can I generate an absolute path in the controller, without using a view helper ?
I don't see how using a view helper inside the controller is a good practice in the MVC pattern.
Notice: the redirect is made to facebook, where my own site url is appended as a get parameter. So the absolute url I need, is my own and not facebook. This means that using the setUseAbsoluteUri method will not help me, as it will work on the facebook url, and not mine.
A: Using view helpers in your controller action won't render a view.
$redirectUri = $this->view->serverUrl() . $this->view->baseUrl() . $this->view->url(array('controller' => 'index', 'action' => 'post-authorize'))
$fbUrl = 'https://www.facebook.com/dialog/oauth?client_id='.$this->fbAppId.'&redirect_uri='.$redirectUri.'&scope=publish_stream,user_birthday,user_about_me,user_activities,user_location';
$this->_redirect($fbUrl);
The View object (not script) is initialized anyway in your controller, before even your action is called.
A: Maybe you can have a look at the source code of the view helpers to get some "inspiration". For instance, Zend_View_Helper_BaseUrl uses the following:
Zend_Controller_Front::getInstance()->getBaseUrl();
And Zend_View_Helper_Url is using:
public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
{
$router = Zend_Controller_Front::getInstance()->getRouter();
return $router->assemble($urlOptions, $name, $reset, $encode);
}
Probably not as builtin as one would desire, but it's not a lot of code, so it could be helpful.
Hope that helps,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: mod_rewrite fails to redirect into the lib folder I've got a rewriterule that works for everything except the lib folder. The rule is
RewriteRule ^/uk(.*) $1
It's one of a much more complex set of rules but I've disabled all but this one.
The rule works fine for everything but the contents of the lib folder:
http://site.local/lib/cookies.js works but http://site.local/uk/lib/cookies.js doesn't.
Every other path on the site redirects fine eg:
http://site.local/uk/course/view.php?id=15 goes to http://site.local/course/view.php?id=15
*
*other folders with only three letters in their name work.
*uk/otherpath/lib works.
*there is no htaccess file in the lib folder
*there is no htaccess file in the site root (the rules are in the virtual host definition)
*the issue occurs on ubuntu and redhat (dev and production)
*the issue occurs on another moodle site on a colleagues workstation
*the permissions on the lib folder are identical to the rest of the directory tree
What am I missing?!?
HELP!!!!!!!!!
--- EDIT ---
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 9
Gives me
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e1b270/initial] (2) init rewrite engine with requested uri /uk/lib/cookies.js
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e1b270/initial] (3) applying pattern '^/uk(.*)' to uri '/uk/lib/cookies.js'
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e1b270/initial] (2) rewrite '/uk/lib/cookies.js' -> '/lib/cookies.js'
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e1b270/initial] (2) local path result: /lib/cookies.js
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e1b270/initial] (1) go-ahead with /lib/cookies.js [OK]
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e232b0/initial] (2) init rewrite engine with requested uri /favicon.ico
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e232b0/initial] (3) applying pattern '^/uk(.*)' to uri '/favicon.ico'
127.0.0.1 - - [22/Sep/2011:11:21:57 +0100] [site.local/sid#7f15a0b345d0][rid#7f15a0e232b0/initial] (1) pass through /favicon.ico
So it looks to me like that should work?
A: I'd suggest turning on RewriteLog and increasing the RewriteLogLevel to get further information about what Apache is doing.
A: After messing about with this on my local machine, it would appear that Apache is rewriting to /lib on your file system before checking for the document_root/lib directory.
You should change your Rewrite to:
RewriteRule ^/uk(.*) %{DOCUMENT_ROOT}$1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: is there any function like "strptime" in java suppose there is a time_string like: "wallclock(2011-09-22T01:52:00)"
in C language, I can use "strptime(time_string, "wallclock(%Y-%m-%dT%H:%M:%S)", &tm)"
to get date time and store it into the struct tm,
and then use mktime(&tm) to get the date in seconds
But in Java, I find no way about how to transfer string "wallclock(2011-09-22T01:52:00)",
is there any way to do this job? thank you :-)
A: You can either use SimpleDateFormat:
DateFormat format = new SimpleDateFormat("'wallclock('yyyy-MM-dd'T'HH:mm:ss')'");
Date parsed = format.parse(text);
(Note that you probably want to set the time zone of format appropriately.)
Or preferrably (IMO) use Joda Time to do the parsing:
String pattern = "'wallclock('yyyy-MM-dd'T'HH:mm:ss')'";
DateTimeFormatter formatter = DateTimeFormatter.forPattern(pattern);
LocalDateTime localDateTime = formatter.parseLocalDateTime(text);
This will parse to a LocalDateTime which doesn't have a time zone.
In Java 8, you'd use java.time.format.DateTimeFormatter instead.
A: SimpleDateFormat will get you pretty close.
A: use SimpleDateFormat class. It provides the functionality you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Working with code samples when they're images on a blog Quick question about something I've ran into alot recently:
So many times I'm looking for information from blogs, and find really interesting and helpful examples, only to discover the blog author has shown the code as an image..
With no cut-and-paste available, how does everyone handle this? Find the code elsewhere or type it all out?
A: use an OCR?
Here is a list of OCR software
A: Personally I don't really learn anything from just cutting and pasting so writing something out by hand is more beneficial. Also, code on blogs is rarely production quality anyway so you'll need often need to improve it with error handling, refactor names etc. so you're going to be changing it anyway - might as well write it out!
A: Maybe a quick ocr service can save the situation...
http://www.free-ocr.com/ (only for example)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: remove back color from multiple positions in richTextBox I have a rich text box and I've implemented a search option for it. When the user searches a string, all the matches gets highlighted with yellow background. I want that when the user presses the search button again, all of the previous highlights will be removed before the new search begins.
I found out two ways to do it:
1. select all text and then choose the back color to be the default one.
2. remove all text from the text box and then put it back again.
Both ways work, but it doesn't look natural when I use them.
So, is there another way that I can remove all highlights from the text?
I'm using .NET framework 4 and I write in C#.
A: Try this code:
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = System.Drawing.Color.White;
richTextBox1.DeselectAll();
here White will be the backcolor of Text before it gets highlighted with yellow color
A: The functionality that you're looking for is the multiple selection, something like:
richTextBox1.Select(4, 5);
richTextBox1.Select(29, 2);
richTextBox1.Select(95, 12);
but still have the previous selections selected.
Bad news because multiple selection is not build-in function in richTextBox, but I think you may do some tricks to achieve this:
Select one part make the selection highlighted (later make it normal when unselect) and record the part beginning & ending index and the same with second and third and more...
Hope it helps
A: There is a very simple solution to removing multiple instances of highlights that you have created without interfering with all other highlights, other formatting etc:
Use a unique highlight color no-one else is likely to be using eg
hColor as color = Color.FromArgb(255, 255, 1)
Then to remove all instances of highlights in that color from your richtext use:
Dim t As String = TextBox1.Rtf
t = t.Replace("\red255\green255\blue1;", "\red255\green255\blue255;")
TextBox1.Rtf = t
This replaces your special highlight color with the same color as the background, in this case Color.FromArgb(255, 255, 255), without having to search for any highlighted words or implement any other code.
Bye bye highlight...
A: Another solution is to take the RTF string from the RichTextBox's RTF property and use Regex to replace the Color Table and Highlight tags. You can then take the stripped string and use it in the RichTextBox. Hope this simple helper method helps someone...
public string StripRTFColor (string RTFString)
{
string result = "";
//
//STRIP COLOUR TABLES
//
string regexSearchString = @"\{\\colortb.*\}\r\n";
result = Regex.Replace(RTFString, regexSearchString, "");
//
//STRIP HIGHLIGHT TAG
//
regexSearchString = @"\\highlight[\d]* ";
result = Regex.Replace(result, regexSearchString, "");
return result;
}
A: here is the idea written in semi C# psedocode hope it helps
List<Match> matches = new List<Match> { };
void Highlight(string SearchString,Color highlightColor)
{
foreach (var match in matches)
{
UpdateMatchBgColor(richTextBox1,match.pos,match.length,match.color);
}
matches = SearchMatches(SearchString);
foreach (var match in matches)
{
UpdateMatchBgColor(richTextBox1,match.pos,match.length,highlightColor);
}
}
EDIT:
trying this:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=146
Edit2:
works awesome!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Multiple websites admin folder from central codebase I've written a small CMS system for my companies' customers.
It is supposed to run the 'admin' folder off the same codebase.
So if I have my codebase in the folder 'a.com/admin', then I could set up a new website on b.com, and when I go to 'b.com/admin', it should show the admin folder from 'a.com'.
Settings and configuration are handled by config files named after the HTTP_HOST.
I have tried Apache Alias, but couldn't get it working.
Then the solution would maybe be lndir to make shadow copies, but then we have to run that every time we create a new file.
Any suggestions?
A: I haven't used Apache for a while, but maybe this could work?
<VirtualHost>
...
<Directory /admin>
DocumentRoot "/path/to/a.com/public_html/admin"
</Directory>
</VirtualHost>
A: I got it working. Found out that I could set a custom per-domain httpd.conf:
Alias /admin "/home/xxxxx/domains/xxxx.com/public_html/admin"
DirectoryIndex index.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ExtJs3: how to make closable tab of tabpanel not closable and back? I want to be able to hide 'x' button near the tab title and to be able to show it back without a low level code manipulating DOM but using component level api functions if it is possible.
A: You should manually hide the close button in the DOM.
I tested this code over ExtJS 3 API page. It toggles close button on the second tab:
var tabPanel = Ext.getCmp('doc-body');
var tabHeader = tabPanel.items.get(1).tabEl;
Ext.get(tabHeader).down('a.x-tab-strip-close').toggleClass('x-hidden')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: regexr how to exclude a string match I want to match the following:
any string which contains any character, except / or . this is done using ([^/\.]+), how ever, I also want to add a string "faq" so to match any character, except if it's a string of "faq", some examples:
Currently, my Regex:
^([^/\.]+)/([^/\.]+)/$
However, it captures "faq" aswell.
faq/fsdfsd/ => No match
faqgff/fdsfs/ => Match
jhpo/ijkd/ => Match
f/iout/ => Match
a/iout/ => Match
q/iout/ => Match
I've tried running ([^/.]+)
Yes, it's for .htaccess redirects :)
A: This would be a negative lookhead
(?!.*faq)
it is true when it does not find the pattern "faq"
So include it in your regex like this
^(?!.*faq)([^/\.]+)/([^/\.]+)/$
Then it will match for your pattern, but fail if the string includes "faq". (Hope I understood you correctly)
See it here on Regexr
A: I can't say I fully understand your problem statement:
want to add a string "faq" so to match any character, except if it's a
string og "faq"
However, it sounds like negative lookbehind might be the tool for the job: https://serverfault.com/questions/78624/apache-2-negative-filesmatch-filesnotmatch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linq2SQL, EDMX, interfaces (Preparing for a TDD enabled project!) Is there an easy way to create a Linq to SQL class for my "DomainModel" off an EDMX (Entity Framework)?
I assume this IS what I want to do...
At the moment I am guessing that if I have my myModel.edmx which is generated from SQL DB which contains an entity/table Levels and I want to create an interface for it.
Currently I have a "levels.cs" inside an "Entities" folder inside the DomainModel project.
This should link to the Entity Framework and looks like this:
`
using System;
using System.Collections.Generic;
using DomainModel.Entities;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace DomainModel.Entities
{
[Table(Name="Levels")]
public class level
{
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public System.Guid Id { get; internal set; }
[Column] string UserId { get; set; }
[Column]public int ScenId { get; set; }
...other fields...
}
}
`
Is it looking correct so far? Is there an easier way to auto generate these files? I take it the next step is to create an interface?
The end goal is to develop this project using a test driven dev approach. The test part is fine, I've just never had to develop in this fashion before
A: You should have a look at T4 to generate files.
When you use Entity Framework you talk about Linq to Entities and not about linq to SQL
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Replace the url without refreshing the page in .net My default url home page is http://www.brindesbb.com/Pages/Default.aspx.
but I dont want to show Pages/Default.aspx in the address bar.
can anyone suggest me how to replace the url without reloading (refreshing ) the page.
Thanks in advance
A: What you want to do is URL Rewriting, read more here URL Rewriting in ASP.NET
Update: If you setup a new website(or edit the one you have) and point the /Pages directory as "root" and aspx is an default document the url will be as you want.
A: You can do so in two ways IIS URL Rewriting and ASP.NET Routing
http://learn.iis.net/page.aspx/496/iis-url-rewriting-and-aspnet-routing/
A: Technically that not possible with .net as .net is used on server side. and you need to change the URL which is on client side so... you will need to use JavaScript to manipulate the Browser URL history. Example [asp.net mvc] my url is http://localhost:123/Home/Product and I need to change it to http://localhost:123/Home/Product/301 this can be achieved by
<script>
window.history.pushState('', 'My Page', 'Home/Product/301');
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django: Form in your Site Base template I need to create a form, not search, but a kind of profile switcher that will be present in the site base.
Just wondering what's the best way of going about this? I'm not very familiar with middlewares but this sounds like the time to investigate it?
Alternatively, I was thinking I could load the form from a templatetag?
I'm just looking for different ways to implement this site wide form. Thanks.
A good example would be Github. The switch account context gives you different pages/accessibility based on your current account context.
A: Looks like you need context processor
A: You can write a template including a form, and include this template in your base.html. You have access to the user profile in the template via
{{ request.user.get_profile }}
It this what you need?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to calculate load time of Asp.net page using Jquery/Javascript? I am developing one web application in that I want to check load time of each and every page or controls load time..
How much time taken to load whole page contents?
I want to calculate asp.net page load Time in Micro second/Second,
How can I know using Javascript/Jquery ?
A: Following script help you;
<SCRIPT LANGUAGE="JavaScript">
//calculate the time before calling the function in window.onload
beforeload = (new Date()).getTime();
function pageloadingtime()
{
//calculate the current time in afterload
afterload = (new Date()).getTime();
// now use the beforeload and afterload to calculate the seconds
secondes = (afterload-beforeload)/1000;
// If necessary update in window.status
window.status='You Page Load took ' + secondes + ' seconde(s).';
// Place the seconds in the innerHTML to show the results
document.getElementById("loadingtime").innerHTML = "<font color='red'>(You Page Load took " + secondes + " seconde(s).)</font>";
}
window.onload = pageloadingtime;
</SCRIPT>
Ref from : http://www.dreamincode.net/code/snippet1908.htm
or
If you just want to check the time make use of Firebug of firefox which display excution time.
Something like this
A: Developed by the good people at stackoverflow - handy little profiling tool - may work for you:
http://code.google.com/p/mvc-mini-profiler/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Null values in matrix, why? I'm learning about dynamic programming via the 0-1 knapsack problem.
I'm getting some weird Nulls out from the function part1. Like 3Null, 5Null etc. Why is this?
The code is an implementation of:
http://www.youtube.com/watch?v=EH6h7WA7sDw
I use a matrix to store all the values and keeps, dont know how efficient this is since it is a list of lists(indexing O(1)?).
This is my code:
(* 0-1 Knapsack problem
item = {value, weight}
Constraint is maxweight. Objective is to max value.
Input on the form:
Matrix[{value,weight},
{value,weight},
...
]
*)
lookup[x_, y_, m_] := m[[x, y]];
part1[items_, maxweight_] := {
nbrofitems = Dimensions[items][[1]];
keep = values = Table[0, {j, 0, nbrofitems}, {i, 1, maxweight}];
For[j = 2, j <= nbrofitems + 1, j++,
itemweight = items[[j - 1, 2]];
itemvalue = items[[j - 1, 1]];
For[i = 1, i <= maxweight, i++,
{
x = lookup[j - 1, i, values];
diff = i - itemweight;
If[diff > 0, y = lookup[j - 1, diff, values], y = 0];
If[itemweight <= i ,
{If[x < itemvalue + y,
{values[[j, i]] = itemvalue + y; keep[[j, i]] = 1;},
{values[[j, i]] = x; keep[[j, i]] = 0;}]
},
y(*y eller x?*)]
}
]
]
{values, keep}
}
solvek[keep_, items_, maxweight_] :=
{
(*w=remaining weight in knapsack*)
(*i=current item*)
w = maxweight;
knapsack = {};
nbrofitems = Dimensions[items][[1]];
For[i = nbrofitems, i > 0, i--,
If[keep[[i, w]] == 1, {Append[knapsack, i]; w -= items[[i, 2]];
i -= 1;}, i - 1]];
knapsack
}
Clear[keep, v, a, b, c]
maxweight = 5;
nbrofitems = 3;
a = {5, 3};
b = {3, 2};
c = {4, 1};
items = {a, b, c};
MatrixForm[items]
Print["Results:"]
results = part1[items, 5];
keep = results[[1]];
Print["keep:"];
Print[keep];
Print["------"];
results2 = solvek[keep, items, 5];
MatrixForm[results2]
(*MatrixForm[results[[1]]]
MatrixForm[results[[2]]]*)
{{{0,0,0,0,0},{0,0,5 Null,5 Null,5 Null},{0,3 Null,5 Null,5 Null,8 Null},{4 Null,4 Null,7 Null,9 Null,9 Null}},{{0,0,0,0,0},{0,0,Null,Null,Null},{0,Null,0,0,Null},{Null,Null,Null,Null,Null}}}
A: While your code gives errors here, the Null problem occurs because For[] returns Null. So add a ; at the end of the outermost For statement in part1 (ie, just before {values,keep}.
As I said though, the code snippet gives errors when I run it.
In case my answer isn't clear, here is how the problem occurs:
(
Do[i, {i, 1, 10}]
3
)
(*3 Null*)
while
(
Do[i, {i, 1, 10}];
3
)
(*3*)
A: The Null error has been reported by acl. There are more errors though.
*
*Your keep matrix actually contains two matrices. You need to call solvek with the second one: solvek[keep[[2]], items, 5]
*Various errors in solvek:
*i -= 1 and i - 1 are more than superfluous (the latter one is a coding error anyway). The i-- in the beginning of the For is sufficient. As it is now you're decreasing i twice per iteration.
*Append must be AppendTo
*keep[[i, w]] == 1 must be keep[[i + 1, w]] == 1 as the keep matrix has one more row than there are items.
*Not wrong but superfluous: nbrofitems = Dimensions[items][[1]]; nbrofitems is already globally defined
The code of your second part could look like:
solvek[keep_, items_, maxweight_] :=
Module[{w = maxweight, knapsack = {}, nbrofitems = Dimensions[items][[1]]},
For[i = nbrofitems, i > 0, i--,
If[keep[[i + 1, w]] == 1, AppendTo[knapsack, i]; w -= items[[i, 2]]]
];
knapsack
]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: get a tooltip when hovering over a select list option using jquery I need a jQuery plugin that can show the option's text as a tooltip when we hover over a selectlist which has multiple select enabled. Else, can we do it manually.. if so can you give me some samples.
[edit] I am using IE 8 and need this to work across all browsers [IE, Chrome, FF, Safari].
A: There is some good tooltip. You can modify it to fit your needs.
This is how you can get current hovering option (jsfiddle):
HTML
<select height="2">
<option>hello</option>
<option>by</option>
</select>
JS
$('select option').hover( function(){
console.log( 'Hover on:' + $(this).html() )
}, function(){
console.log( 'Hover off from:' + $(this).html() )
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create route with Zend_Controller_Router_Route_Regex I have one route defined in application.ini like
router.routes.xx.route = "y/:var/:controller/:action/*"
router.routes.xx.defaults.controller = "page"
router.routes.xx.defaults.action = "index"
I try to create one more route, which must take contol under urls
*
*Which consist of only from one word ( www.bla.pl/myname )
*This word is not eqivalent word 'except' ( www.bla.pl/except -- dont process)
*transform www.bla.pl/myname into www.bla.pl/c?var=myname ( controller c with some action a and puts value 'myname' into parameter var )
I tried to write
router.routes.w.type = "Zend_Controller_Router_Route_Regex"
router.routes.w.route = "(\w)+[^?|/]"
router.routes.w.reverse = "c/var=%s"
router.routes.w.defaults.controller = "c"
router.routes.w.defaults.action = "index"
router.routes.w.map.var = 1
What do i do wrong ?
A: Why don't you just use a normal route ?
router.routes.w.route = "/:var"
router.routes.w.route.defaults.controller = "c"
router.routes.w.route.defaults.action = "index"
router.routes.w.reqs.var = "!(your|forbidden|words)"
This should work as expected
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IE - no longer possible to remove box outline? the usual way to remove the IE link outline no longer seems to work for me - I'm using IE9 which doesn't have the outline, but when I switch back to 7 or 8 (using IE9's dev tools) the outline is there. My CSS is below - anyone any ideas?
a:active, a:selected {
border: none;
outline: none;
}
A: Please download a proper virtual machine environment that contains old versions of Internet Explorer. It could be that the compatibility mode does not render your HTML the way it should. The best way to test IE is to actually use IE in a clean environment. You can download the App Compat VHDs here:
http://www.microsoft.com/download/en/details.aspx?id=11575
A: Please download a proper emulater for old versions of Internet explorer. It could be that the compatibility mode does not render your code the way it should. The best emulator is The IE Tester, you can download a copy from here..
http://www.my-debugbar.com/wiki/IETester/HomePage
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check JTextField text to String? I have a problem on checking the text and string.
public boolean Isequals(Object c){
boolean check = false;
if (c instanceof MyTextTwist){
MyTextTwist tt = (MyTextTwist)c;
if (txtGuessPad.getText().equals(answer))
check = true;}
return check;
}
this what i have so far.
A: Since your question is not very clear, i suggest these answers:
1st option - you want to get string from your JTextField:
String text = txtGuessPad.getText();
2nd option - you want to check if text contains only letter:
String text = txtGuessPad.getText();
if(text.matches("^[a-zA-Z]+$")){...
3rd option - you want to compare two strings (one of them is from JTextField):
String text = txtGuessPad.getText();
String text2 = "test";
if(text.equals(text2)){... //if you want to match whole word and case sensitive
if(text.equalsIgnoreCase(text2)){... //if you want to match whole word and NOT case sensitive
if(text.startsWith(text2)){... //if you want to check if you string starts with other string
4th option - let's put it in a function:
public boolean isEqualToString(JTextField textField, String compareTo) {
String text = textField.getText();
if(text.equals(compareTo)) {
return true;
}
return false;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery.fadeIn()/fadeOut(). Not working in IE7+8 I'm have a Ruby on Rails project which displays illustrations. There are category links at the top which fade out the illustrations, replaces it with new content and then fades back in.
I am using jQuery 1.6.2.
It works as expected in Safari 5, Firefox 6, Chrome 14 and IE9. In IE7+8 the html is replaced with the new content but no fade occurs.
To begin with I was using html5 elements so thought it could be that, but I've since replaced them all with divs and the problem still shows. I've tried adding/removing Modernizr and Selectivizr libraries to no effect. Any help is appreciated, code is as follows:
app/views/illustrations/index.html.erb
<div id="illustrations" class="illustration-list">
<%= render @illustrations %>
</div>
app/views/illustrations/_illustration.html.erb
<div class="illustration">
<div class="figure">
<%= link_to image_tag(illustration.image.url(:thumb), alt: illustration.title), illustration %>
<div class="figcaption">
<%= link_to illustration.title, illustration %>
</div>
</div>
</div>
app/views/shared/_category_links.html.erb - Which triggers the ajax
<ul>
<% category_links.each do |category| -%>
<li class="<%= category.name.downcase %>">
<%= link_to category.name, category, remote: true %>
</li>
<% end -%>
</ul>
and lastly /app/views/categories/show.js.erb
var data = "<%= escape_javascript(render(@illustrations)) %>";
var div = $('#illustrations');
div.fadeOut("slow", function() {
div.html(data);
div.fadeIn('slow');
});
EDIT Here is an example without the images, but you should be able to get the idea, http://jsbin.com/ifisuh/4/edit#preview.
A: IE7/8's opacity support is very flaky. As mentioned in the first comment, it requires ActiveX, so the first port of call is to ensure that:
*
*your Windows machine supports it (it doesn't like VMs or low-color desktops).
*you have the appropriate DLLs installed.
*your copy of IE has is configured to allow ActiveX in the appropriate zone.
Obviously this would need to be set up correctly for any IE7/8 client. On an intranet, this may mean you have to manually check each user's machine. On the other hand, if your site is going to be used on the internet at large, then you will never have any guarantee that any given IE user will be able to see your opacity effects. (although to be fair, most IE users should be okay)
But even if you can get it to work, IE's opacity has a number of known bugs, especially when working with images. Some of those bugs can be worked around by tweaking the graphic -- using a different image format; avoiding having any pure black or white in the image; don't try to fade images with alpha transparency; etc -- but some bugs simply can't be avoid. You should also avoid trying to fade grpahic and text elements at the same time, as this can make the bugs more noticable (as the text fades more smoothly than the graphic). [I can't find the site I want to reference at the moment which explains some of this in more detail; will edit this answer when (if) I find it]
The bottom line is that fading in IE7/8 is very hit-and-miss. If it goes right for you, great; but very often it simply can't be done in the way you'd want to. For some sites this means that the best solution is simply not to even try fading with IE7/8.
I'm sorry I'm not giving you very good news here. I hope some of the tips I've given will help, but please be prepared in case they don't.
A: Have you wrapped your code?
$(function() { // to fire when jquery is loaded
var data = "<%= escape_javascript(render(@illustrations)) %>";
var div = $('#illustrations');
div.fadeOut("slow", function() {
div.html(data);
div.fadeIn('slow');
});
});
Make sure this code isn't fired before jquery is loaded, else there might pop up an error which drives IE nuts.
Who knows? It could be a ridicilous problem such as you have an array which is ['example',]
IE 7's entire javascript stops working because there's a non defined array for, instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to use EF codefirst database initialisers in Migrator .NET migrations? I'm using Migrator.NET to manage schema changes on our production environment. Because I've been using EF code-first, all development to the database has been incremental to the code-first classes and no migrations have been applied to the project.
However, I'd like to be able to start using migrations once the project is in a production environment. As the baseline 'up' migration, I'd like to use code-first's database initializer to create the database and prime with default data. However, I'm having problems because the EF context classes and my wrapper classes for EF initializers are in .NET 4, whereas migrator .NET is using .NET 2.
When running the migrator console app, I'm getting 'This assembly is built by runtime newer than the currently loaded runtime...'
Am I expecting to much for this to work? I could use OSQL and create the SQL script on the server, but it would be nice if this worked just as it does in the development environment.
A: Hmm. Weird. Even if the migratordotnet binary is in .NET 2 you should be able to use it. I worked on a project where we did just this. We used EF Code First to automatically generate the schema if it didn't exist, otherwise we would run the migrations to the existing one (we started creating the migration steps while still in the dev phase).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is "(id) sender" What does (id)sender in -(IBAction)PushButton: (id)sender stand for ?
A: sender is an object that triggered an action, so in your case it is probably the button that was tapped.
A: It's the object that triggered the event. E.g. sender will be the button that was pressed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: 4 pixel offset of "Like" button I would like to line up all of the social media buttons on my site. The LinkedIn, GoogleOne and Twitter buttons all align vertically, but I can't seem to figure out why the FaceBook "Like" button jumps down 4 pixels.
I've tried adjusting the margin-top, the vertical-alignment css, etc. Nothing seems to move this button back up.
A: I had the same problem. Here's my fb-like button code:
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="mysite.com" data-send="false" data-layout="button_count" data-width="30" data-show-faces="false" data-font="arial"></div>
The only solution I could come up with is to manually offset the button a few pixels. I enclosed the above block in a div, and pushed it up a few pixels:
.shareable {
height: 20px;
display: inline-block;
}
.shareable .fb-like {
top:-3px;
}
A: I've used this and it seems to work consistently with no harm to other browsers presentation:
.fb-like { line-height: 0; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Check image url multithreading I am using PHP to check whether an image link is broken or not. Using PHP and cURL I can get the HTTP status code. However, it is taking a lot of time when checking millions of images.
Is there any better and faster ways of checking a large number of broken images?
A: how about using file_exists()?
A: Guessing the images are on a remote server...
Why not do it through a cronjob? Let it check every hour, and keep a database with files. If the file doesn't exist in the database, check it during the request.
A: you can't really multithread in php but you can emulate that using process control in php.
You'll need a main php script and a worker script. The main script will have a reference to the images pool (the links) and will distribute the load across a number of worker scripts.
The worker script is the one which will do the actual checking. After all the workers have done their job they will comunicate to main.php the result
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: UIActionSheet and UIView I want to create a UIActionSheet but I've also a UIView and this last one must be selectable.
How you can see I can't use the date picker. Ideas?
A: You can't. A UIActionSheet is modal by definition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery: If all children have same class How do I check if all children, or all selectors, have same class?
The class is unknown...
<script>
$(document).ready(function() {
var symbols = $("div:first-child").attr("class");
if ($("div").hasClass(symbols).length == 3) {
console.log("same");
};
});
</script>
<div class="john"></div>
<div class="john"></div>
<div class="john"></div>
This doesn't work... :-/
A: HTML:
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
jQuery:
if ($(".parent").children().length == $(".parent").children(".child").length) {
alert("wooo all the things have teh same class");
}
A: $("div").not('.john').length
If any of the divs are not class john this will find them, then you check the length and if it's not zero then some exist.
This is a problem:
$("div:first-child").attr("class")
It will return the entire class string, but the div could have more than one class, and all will be returned. But when you check with either my code or hasClass you can only send in one class, not a bunch together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Windows phone 7 Mango Development Links I am new to Windows Phone development. I am starting by learning C# and Silverlight. Does anybody have any links/resources for learning Windows Phone Mango?
A: Try out these:
*
*http://indyfromoz.wordpress.com/windows-phone-7-resources/
*http://www.reddit.com/r/wp7dev/
*http://msdn.microsoft.com/en-us/library/ff431744(v=vs.92).aspx
*http://www.kunal-chowdhury.com/2011/06/windows-phone-7-mango-tutorial-24-local.html
*http://www.windowsphonegeek.com/ArticleIndex
*http://www.silverlight.net/
*http://channel9.msdn.com/blogs/egibson/windows-phone-7-jump-start-session-1-of-12-introduction
*http://live.visitmix.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I scroll an overflowed div to a certain hashtag (anchor)? On my webpage I have an overflowed div (i.e. with the vertical scrollbar). Inside the div, I have anchors with ids. When I put one of these ids in the URL (mypage.html#id), I want the div, not the page, to scroll to that anchor.
How do I do that, preferably with plain JavaScript? If it's too complex, I'll go with jQuery, but I'm not using it in this project for anything else.
A: $('.overflow').scrollTop($('#anchor').offset().top);
There is no reason at all you can't convert this to standard javascript.
Note that the scroll will be off if there is a margin on the anchor element.
A: Have you tried to set focus() on the anchor?
Any DOM element with a tabindex is focusable, and any element which has focus will be scrolled into view by the browser.
A: This is a pure Javascript (ECMA 6) solution, similar to Ariel's answer.
const overflow = document.querySelector('.overflow');
const anchor = document.getElementById('anchor');
// Get the bounding client rectangles for both
// the overflow container and the target anchor
const rectOverflow = overflow.getBoundingClientRect();
const rectAnchor = anchor.getBoundingClientRect();
// Set the scroll position of the overflow container
overflow.scrollTop = rectAnchor.top - rectOverflow.top;
A: For those of you in nearly any major browser in 2021, use element.scrollIntoView().
https://developer.mozilla.org/docs/Web/API/Element/scrollIntoView
The Element interface's scrollIntoView() method scrolls the element's
parent container such that the element on which scrollIntoView() is
called is visible to the user - MDN Web Docs
Example:
var myEl = document.getElementById("child");
myEl.scrollIntoView()
or with Parameters -- Not supported in Safari or Internet Explorer:
myEl.scrollIntoView({
block: "center" // Start, center, end, or nearest. Defaults to start.
behavior: "smooth"
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Include remote JQuery-UI.css, problem in FF I include remote JQuery and JQuery-UI from Google. The page works for Chrome and Opera, but in FF it seems the JQuery UI styles are not loaded. In Firebug, when I open the page code and check the css file for the JQuery-UI, instead of the content I see:
Reload the page to get source for: http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css
My header file is:
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.15/jquery-ui.js">
<link type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">
<link type="text/css" href="css/index.css" rel="stylesheet">
</head>
EDIT:
I checked with the newest versions of the libraries, and still nothing
A: You need to close the script tags. It should work then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Starting alarm service in android In my application i want to use alarm service for specific period of time.I'm taking start time and end time values from user and saving it in database,Now i want to start a alarm service at start time and alarm should go off at end time specified by user.I'm new to this topic and not able to understand how to implement this...Any help will be appreciated.Thank u..
A: This is how you implement an alarm manager. But you will need to read about Calendar object in android also.
String alarm = Context.ALARM_SERVICE;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);//Just an example setting the alarm for the 8th hour of a day.
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
//This is the intent that is launched when the alarm goes off.
Intent intent = new Intent("WAKE_UP");
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
//If the user wants the alarm to repeat then use AlarmManager.setRepeating if they just want it one time use AlarmManager.set().
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
}
Also you will need to register a BroadCast Receiver to except the intent when the alarm sets it off.
You create the BroadCast reciever and register it in your manifest to receive the intent from the alarm.
http://www.vogella.de/articles/AndroidServices/article.html
Here is a great tutorial to help you understand better
A: The key is to use the AlarmManager with a pending intent.
mAlarmSender = PendingIntent.getService(AlarmService.this,
0, new Intent(AlarmService.this, AlarmService_Service.class), 0);
Then you create the AlarmManager from the current context:
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
And schedule the previously created pending intent.
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
firstTime, 30*1000, mAlarmSender);
On schedule the AlarmService_Service service will be called, or you can put another intent like open a specific activity.
Here is the complete example of how you can schedule an alarm: AlarmService.java
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to sort objects by date ascending order? If I have a list of object:
var objectList= LIST_OF_OBJECT;
each object in the list contains three attributes: "name", "date","gender"
How to sort the objects in the list by "date" attribute ascending order?
(the "date" attribute contain string value like "2002-08-29 21:15:31+0500")
A: yourArray.sort(function(a, b) {
a = new Date(a.date);
b = new Date(b.date);
return a >b ? -1 : a < b ? 1 : 0;
})
A: If your objects have the date information within a String field:
yourArray.sort(function(a, b) { return new Date(a.date) - new Date(b.date) })
or, if they have it within a Date field:
yourArray.sort(function(a, b) { return a.date - b.date })
A: The Array.sort method accepts a sort function, which accepts two elements as arguments, and should return:
*
*< 0 if the first is less than the second
*0 if the first is equal to the second
*> 0 if the first is greater than the second.
.
objectList.sort(function (a, b) {
var key1 = a.date;
var key2 = b.date;
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});
You're lucky that, in the date format you've provided, a date that is before another date is also < than the date when using string comparisons. If this wasn't the case, you'd have to convert the string to a date first:
objectList.sort(function (a, b) {
var key1 = new Date(a.date);
var key2 = new Date(b.date);
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});
A: You can try:
<script src="https://cyberknight.000webhostapp.com/arrange.js">
var a =[-1,0,5,4,3,2,6,1,1];
var b = totzarrange(a)
console.log(b);
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: access the variable in my javascript from controller In my CSHTML I have some JavaScript which contains a string variable. How do I access this variable from my controller?
A: When you invoke the controller you could pass it as parameter. For example if you are invoking the controller action using AJAX:
$.post('/someaction', { someValue: someVariable }, function() {
...
});
A: [HttpPost]
public ActionResult someAction(string id)
{
return Content("got it");
}
in script
$(function(){
var someid='12';
$.post('/Controller/someAction',{id:someid},function(data){
//this call back is executed upon successfull POST
console.log(data); // got it"
});
});
A: You can use a hidden input field in your form valorized with the value of your string variable. When you post the form you can read the value as usual.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to invoke local peripheral device from web script I am confused about invoking local app from web site.
Is there any way to start an ipad/iphone app from web scripts? I remember that there is ActiveX with IE which could start a local device such as a camera or printer. JavaScript could invoke ActiveX. But there is no activeX in iOS. Here is my problem: How could I start local device from a webpage? Does anyone have the same problem? I have one method but I don't know if it is feasible:
*
*UIWebView could execute JavaScript by stringByEvaluatingJavaScriptFromString.
*write a function in a page with JavaScript, which responds to an event on the page (button click, etc.), then change the state.
*start a thread to inquire the state. When the state changes , invoke local apps.
Is that possible or any better way ?
A: If you wish to open your app from Safari browser from you iPad then there is a method to do so. Add the following tags in your app's info.plist file:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.companyname.appname</string>
<key>CFBundleURLSchemes</key>
<array>
<string>openApp</string>
</array>
</dict>
</array>
Save the plist file and now on the web page put openApp:// in place of the link when user clicks the desired button. This won't be helpful if you try to implement it in your own app in a web view. But it will work from Safari browser from your iPad or from any other app.
I hope this is helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set a time limit to an oracle query I need to interrupt the execution of an oracle query if it is taking more than 10 seconds, and give user a message informing him about execution timeout.
I googled a lot but i didn't find anything useful.
Is there any way to set a time limit to oci_execute
A: A profile can be used but is a little harsh. A better solution is to use Oracle Resource Manager. Setup a resource manager plan, assign resource consumer groups, decide how a session gets assigned to a resource consumer group and off you go.
You can even make it refuse to start a query when the estimated runtime exceeds the allowed runtime.
Also check http://ronr.blogspot.com/2009/06/howto-configure-resource-manager-using.html
A: Maybe Oracle profiles are useful in your case:
http://www.adp-gmbh.ch/ora/concepts/profile.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Really Simple jQuery Sliding Photos So I'm looking for a basic jQuery photo-reel type thing to put on my site's homepage, and I found this page.
What I want is simply what looks like a plain <img> (no text, no arrows to switch), which slides a new photo across every 5 seconds... simple enough.
I found this sample code... which is exactly what I want, really simple, except it uses a crossfade instead of a horizontal slide.
I also found this jQuery plugin, which looks much more complex than I need, but has the kind of transition I want.
What's the easiest way of combining the two, so I have a really simple automated image slide (with no text or arrows), but it uses the nice transition in the 'easy slide' plugin?
A: jquery cycle is a very extensive plugin for jquery, you could use that one.
you can go as far as you want with it, but the basics support exactly what you need.
take a look at this example:
html:
<div class="pics">
<img src="images/beach1.jpg" width="200" height="200" />
<img src="images/beach2.jpg" width="200" height="200" />
<img src="images/beach3.jpg" width="200" height="200" />
</div>
css:
.pics {
height: 232px;
width: 232px;
padding: 0;
margin: 0;
}
.pics img {
padding: 15px;
border: 1px solid #ccc;
background-color: #eee;
width: 200px;
height: 200px;
top: 0;
left: 0
}
script:
$('.pics').cycle({
fx: 'scrollHorz',
timeout: 5000,
speed: 500
});
you can use a lot more options or effects, but these basics are what you ask for.
edit:
there is even a lite version of this jquery.cycle plugin, which also does everything you ask, and leaves out some of the more advanced stuff which you don't need for your example.
upside of this lite plugin, is that it's much smaller than the full plugin. better for the end user.
A: Nivo slider is great selection. Only 15kb packed, and you can configure it as you want.
Once you nivo slide you can't go back...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MS-Chart Zooming of x-axis with scroll bar in c# I have added the scroll bar to the x-axis of my mschart control using this link Adding a scroll bar to MS Chart control C# and it worked as expected. But now my requirement is, I need zooming for both the axis. But since I removed Zoom reset button for x-axis, I have used the following to reset it by forcing.
private void chart1_AxisScrollBarClicked(object sender, ScrollBarEventArgs e)
{
// Handle zoom reset button
if(e.ButtonType == ScrollBarButtonType.ZoomReset)
{
// Event is handled, no more processing required
e.IsHandled = true;
// Reset zoom on X and Y axis
chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset();
chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset();
}
}
But it is not working properly. Please help me in fixing this in c#..
A: Try using ZoomReset(0).
private void zeroZoom_Click(object sender, EventArgs e)
{
chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset(0);
chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset(0);
}
A: The first thing coming in mind, is that your problem is related to multiple zooming.
As you had noticed, by default the zoom-reset button (exactly like the ZoomReset method) doesn't reset the zoom completely, but restore the previous view-status, i.e. if you have zoomed more than one time, it returns just to the previous zoomed view.
To completely reset the zoom, you can use this code:
while (chart1.ChartAreas[0].AxisX.ScaleView.IsZoomed)
chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset();
while (chart1.ChartAreas[0].AxisY.ScaleView.IsZoomed)
chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset();
Conversely, if you like the default zoom-reset behaviour, you should have two buttons for the two axis because it's possible to have different number of view-statex for the different axis.
Another possibility, is that you are zooming a secondary axis, like AxisX2 or AxisY2 (not sure, but I think that is depending on the chart type), so you should reset those (or, to be safe, just reset all axis...).
A: I tried with the below code today and it seems like working fine. Here the for loop handles the X axis with scroll and the next if block handles the ordinary X-axis. Could you please have a glance at it and let me know your views about it?
private void chart1_AxisScrollBarClicked(object sender, ScrollBarEventArgs e)
{
Boolean blnIsXaxisReset = false;
try
{
// Handle zoom reset button
if(e.ButtonType == ScrollBarButtonType.ZoomReset)
{
// Event is handled, no more processing required
e.IsHandled = true;
// Reset zoom on Y axis
while (chart1.ChartAreas[0].AxisY.ScaleView.IsZoomed)
chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset();
//Handles Zoom reset on X axis with scroll bar
foreach (Series series in chart1.Series)
{
if (series.YAxisType == AxisType.Secondary)
{
chart1.ChartAreas[0].AxisX.ScaleView.Zoom(-10, 10);
blnIsXaxisReset = true;
break;
}
}
//Handles Zoom reset on ordinary X axis
if (blnIsXaxisReset == false)
{
while (chart1.ChartAreas[0].AxisX.ScaleView.IsZoomed)
chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset();
}
}
}
catch (Exception ex)
{
BuildException buildException = new BuildException();
buildException.SystemException = ex;
buildException.CustomMessage = "Error in zooming the Chart";
ExceptionHandler.HandleException(buildException);
}
}
Thanks for your effort!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How does YouTube 3D flash player instantly switch to anaglyph in 1080p? A 3D Youtube movie like this: http://www.youtube.com/watch?v=SmV4ieSpk4k can be watched in various 3D technics. I want to make a simular player but I can't understand how YouTube's 3D player can switch instantly from Side-By-Side to anaglyph and back to normal. And still running smooth!?!
This is what i tried:
two video instances from a Side-By-Side video(1280x720)
both are 200% width
first one x/y = 0/0, second one x/y, -720/0
than with the OPTMIZED ANAGLYPH FILTER ( http://davidshelton.de/blog/?p=163 ) filter it to anaglyph.
But the video's are not running simultanly, and in fullscreen mode not very smooth.
Can somebody give me some hands to start?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ASP.NET Chart Controls, is it possible to use a gradient on a pie chart? I'm prototyping a chart using ASP.NET Chart Controls. I have the following code to generate my chart. I'm trying to get as close to the client's brand guidelines as possible. The brand guidelines are using gradients in the pie chart segments. Is this possible when using custom colours?
/// <summary>
/// Create an image of a chart from the given data
/// </summary>
/// <param name="data">Dictionary of data, labels as key and value as value.</param>
/// <returns>The bytes of an image</returns>
private Byte[] CreatePieChart(Dictionary<string,string> data)
{
//Set up the chart
var chart = new Chart
{
Width = 550,
Height = 400,
RenderType = RenderType.BinaryStreaming,
AntiAliasing = AntiAliasingStyles.All,
TextAntiAliasingQuality = TextAntiAliasingQuality.High
};
//Add the title
chart.Titles.Add("Chart 1");
chart.Titles[0].Font = new Font("Arial", 16f);
//Set up labels etc
chart.ChartAreas.Add("");
chart.ChartAreas[0].AxisX.TitleFont = new Font("Arial", 12f);
chart.ChartAreas[0].AxisY.TitleFont = new Font("Arial", 12f);
chart.ChartAreas[0].AxisX.LabelStyle.Font = new Font("Arial", 10f);
chart.ChartAreas[0].AxisX.LabelStyle.Angle = -90;
chart.ChartAreas[0].BackColor = Color.White;
//Set up the series and specify Pie chart
chart.Series.Add("");
chart.Series[0].ChartType = SeriesChartType.Pie;
chart.Series[0].SetCustomProperty("PieLabelStyle", "outside");
chart.Series[0].IsValueShownAsLabel = true;
chart.Series[0].BackGradientStyle = GradientStyle.Center;
//MAke the chart 3D
chart.ChartAreas[0].Area3DStyle.Enable3D = true;
//chart.ChartAreas[0].Area3DStyle.Perspective = 75;
chart.ChartAreas[0].Area3DStyle.Inclination = 0;
//Loop over the data and add it to the series
foreach (var item in data)
{
chart.Series[0].Points.AddXY(item.Key, Convert.ToDouble(item.Value));
}
//Add a legend
chart.Legends.Add("");
chart.Legends[0].InsideChartArea = "";
Color[] myPalette = new Color[6]{
Color.FromArgb(255,101,187,226),
Color.FromArgb(255,253,214,91),
Color.FromArgb(255,38,190,151),
Color.FromArgb(255,253,183,101),
Color.FromArgb(255,218,143,183),
Color.FromArgb(255,242,242,242)};
chart.Palette = ChartColorPalette.None;
chart.PaletteCustomColors = myPalette;
byte[] chartBytes;
//Write the chart image to a stream and get the bytes
using (var chartimage = new MemoryStream())
{
chart.SaveImage(chartimage, ChartImageFormat.Png);
chartBytes = chartimage.GetBuffer();
}
return chartBytes;
}
A: It is possible to get a gradient on a pie chart with ASP.NET charting.
Here's the relevant lines:
Color[] myPalette = new Color[5]{
Color.FromArgb(255,101,187,226),
Color.FromArgb(255,253,214,91),
Color.FromArgb(255,38,190,151),
Color.FromArgb(255,253,183,101),
Color.FromArgb(255,218,143,183)};
chart.Palette = ChartColorPalette.None;
chart.PaletteCustomColors = myPalette;
//Loop over the data and add it to the series
int i = 0;
foreach (var item in data)
{
chart.Series[0].Points.AddXY(item.Key, Convert.ToDouble(item.Value));
chart.Series[0].Points[i].BackGradientStyle = GradientStyle.Center;
chart.Series[0].Points[i].Color = myPalette[i];
chart.Series[0].Points[i].BackSecondaryColor = LightenColor(myPalette[i]);
//chart.Series[0].Points[i].SetCustomProperty("Exploded","true");
i++;
}
Prototype code. Produces a passable gradient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++, non parameter types for templates: only const variables? I dont understand why a template parameter can be initialized only with a const variable.
As in, why doesn't the following code work:
#include <iostream>
template <class T,int dim>
class Vec
{
T _vec[dim];
int _dim;
public:
Vec () : _dim(dim) {};
~Vec () {};
// other operators and stuff
};
int main () {
int dim = 3;
Vec < int, dim> vecInt3;
}
If I add a const to the definition of dim in the main, everything is fine. Why is that?
A: Integer types parameters must be compile-time constants. You have to either use an integer literal or make your variable const. The reason is the template is instantiated before runtime and if there's a chance you can later change a variable name the program will behave inconsistent with the template.
A: I think, that's becouse you can't create a table with a variable as a length in T _vec[dim]. Why not think of a built-in vector type instead?
A: First, template are built at compile time, that is why you must use a const value: it can't be calculated at runtime. Infact when you compile your code the class will be compiled one time for each different use of it's parameters.
After this, the code should work if there aren't other syntax errors.
An important note before you go mad: you can't split templates in header/cpp file, you must write header and implementation on the same file!
A: Because the template parameter should be calculated at compile time. Compiler will make codes for different parameters.
In your case, you can see that if dim isn't a const, compiler would not know how much spaces should alloc for vecInt3. In factVec<int, 1> and Vec<int, 2> is different type.
If you want a vector with dynamic size, you could see std::vector to get some idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: toggle parent's element with parent I have this structure
<p>Integer ac porta felis. <a href="#" class="despLeerMas">...read more</a></p>
<div class="none masInfodespLeerMas"> onsectetur adipiscing elit. Sed condimentum dictum vestibulum. Praesent odio dolor, dapibus et consectetur quis, pulvinar eu orci. Integer ac porta felis.<a href="#" class="ocultarLeerMas"> ...read less</a></div>
<p>Integer ac porta felis. <a href="#" class="despLeerMas">...leer más</a></p>
<div class="none masInfodespLeerMas"> onsectetur adipiscing elit. Sed condimentum dictum vestibulum. Praesent odio dolor, dapibus et consectetur quis, pulvinar eu orci. Integer ac porta felis.<a href="#" class="ocultarLeerMas">..read less</a></div>
and i'm tring with this
$('.despLeerMas').click(function ()
{
$(this).parent().next('.masInfodespLeerMas').toggle();
$(this).parent().next('.ocultarLeerMas').toggle();
$(this).toggle();
return false;
});
$('.ocultarLeerMas').click(function ()
{
$(this).parent().toggle();
$(this).parent().parents('p').find('.despLeerMas').toggle(); ///cant' get it working
$(this).toggle();
return false;
});
online here: http://jsfiddle.net/xwQGN/1/
The hidden is shown when clicking .despLeerMas (and .despLeerMas is hidden)
when clicking .ocultarLeerMas the div is hidden again
the problem is that .despLeerMas is not shown again :S (I can't get with the selection code, i guess)
A: Try:
$(this).parent().prev().find('.despLeerMas').toggle();
Your updated fiddle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Validate input field in C# I have a input field that is supposed to take numbers only.
How can I validate the string?
Would this be ok:
string s = "12345";
double num;
bool isNum = double.TryParse(s, out num);
Or does .Net have a solution for this?
A: Single one line answer. Does the job.
string s = "1234";
if (s.ToCharArray().All(x => Char.IsDigit(x)))
{
console.writeline("its numeric");
}
else
{
console.writeline("NOT numeric");
}
A: What you've done looks correct.
You could also create an extension method to make it easier:
public static bool IsNumeric(this object _obj)
{
if (_obj == null)
return false;
bool isNum;
double retNum;
isNum = Double.TryParse(Convert.ToString(_obj), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
So then you could do:
s.IsNumeric()
A: your solution is ok but you could create a method that does this job for you. Bear in mind it may not work for other countries because of the culture. What about something like the below?
public bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
{
Double result;
return Double.TryParse(val,NumberStyle,
System.Globalization.CultureInfo.CurrentCulture,out result);
}
A: VB.NET has the IsNumeric function but what you have there is the way to do that in C#. To make it available app-wide just write an extension method on string
public static bool IsNumeric(this string input)
{
if (string.IsNullOrWhitespace(input))
return false;
double result;
return Double.TryParse(input, out result);
}
A: You can use Regular Expression Validators in ASP.NET to constrain the input.
A: Why don't you try to validate the input through the UI? I don't know if you're using asp.net, if so, the RegularExpressionValidator is normally a valid solution for this. (http://www.w3schools.com/aspnet/control_regularexpvalidator.asp). Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Weighted logistic regression in Python I'm looking for a good implementation for logistic regression (not regularized) in Python. I'm looking for a package that can also get weights for each vector. Can anyone suggest a good implementation / package?
Thanks!
A: The “balanced” mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as n_samples / (n_classes * np.bincount(y))
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(class_weight='balanced')
model = model.fit(X, y)
EDIT
Sample Weights can be added in the fit method. You just have to pass an array of n_samples. Check out documentation -
http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.fit
Hope this does it...
A: I think what you want is statsmodels. It has great support for GLM and other linear methods. If you're coming from R, you'll find the syntax very familiar.
statsmodels weighted regression
getting started w/ statsmodels
A: I notice that this question is quite old now but hopefully this can help someone. With sklearn, you can use the SGDClassifier class to create a logistic regression model by simply passing in 'log' as the loss:
sklearn.linear_model.SGDClassifier(loss='log', ...).
This class implements weighted samples in the fit() function:
classifier.fit(X, Y, sample_weight=weights)
where weights is a an array containing the sample weights that must be (obviously) the same length as the number of data points in X.
See http://scikit-learn.org/dev/modules/generated/sklearn.linear_model.SGDClassifier.html for full documentation.
A: Have a look at scikits.learn logistic regression implementation
A: Do you know Numpy? If no, take a look also to Scipy and matplotlib.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Is this the correct way to get file's size? I have retrieved all file names and store it to a string array. Following is the code:
Dim fi As System.IO.FileInfo
Dim file_size As Int32
'all file names are stored in Files string array
Dim Files() As String
Dim CurrentFile As String
For Each CurrentFile In Files
fi = New System.IO.FileInfo(CurrentFile)
file_size = fi.Length
Next
Is this the correct way of getting each file's size? Is there any better way to get file size? I have thousand of files and I'm looking for a better approach.
A: Yes the FileInfo classes Length Property gives you the size of the file in bytes.
FileInfo Description MSDN
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the cell value from another worksheet and assign it to the return value of UDF? Here is the little example of my two worksheets.
Original Sheet:
As you can see, this worksheet has two cells waiting to be recalculated at the later stage. (i.e. cells with red #Eval marker)
Result Sheet:
In the above Result sheet, we have got two results, Strawberry and Peach respectively. These two results are prepared for two #Eval cells and need to replace the #Eval marker.
Note that #Eval is actually returned by the UDF, indicating this cell needs to be recalculated. The recalculation will be initiated manually by clicking a button or something.
Also note that the position is mapped across two sheets -- if #Eval is located in Cell A3, then there will also be a result showing up in Cell A3 in the result sheet as well.
So, my primary goal here is to replace #Eval cell with its corresponding result. But I am having troubles with passing the results into my UDF -- I don't know how to programmatically get the reference / address of cell that is currently being recalculated.
Below is the code I have currently got, which I don't think it's been implemented correctly. Can anyone help? Or is there any other way to implement this?
Thanks in advance.
//assign value from result sheet back to result variable
private string getResultFromResultSheet(Excel.Worksheet originalSheet, Excel.Worksheet resultSheet)
{
string DataResult = null;
//Excel.Range resultSheetRange = resultSheet.UsedRange;
//string addresse = resultSheetRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
Excel.Range originalSheetRange = originalSheet.UsedRange; //<= I think it's incorrect here
string os_currentAddress = originalSheetRange.get_Address(Type.Missing, Type.Missing, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
Excel.Range currentRRange = null;
currentRRange = resultSheet.get_Range(os_currentAddress, Type.Missing);
if (currentRRange != null)
{
DataResult = currentRRange.Text;
}
return DataResult;
}
A: Personally I would go for a rethink and write your UDF the way Excel expects UDFS to be:
*
*pass ALL data from cells into your UDF as parameters (if you don't do this Excel does not know when to recalculate your UDF and you will have to make the UDF volatile, which is a BAD IDEA)
*the UDF should return its result(s) to the cell(s) it occupies
*as Govert says: if you need the range object for the cells the UDF occupies (usually to find out the dimensions of the calling range) you can use Application.Caller
*don't use .Text (that gives you the formatted result of the cell which is dependent on whatever the user does and may well contain ###) use .Value2 instead
Then your UDF in the original sheet =DataResult(ResultSheet!A1)
If this approach does not fit your overall task you probably need to create a C# macro that gets called by some event trigger or button instead of a UDF.
A: Calling Application.Caller from within your UDF will return a Range object for the calling cell. Your UDF could then read the data from the corresponding location in the other sheet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7513077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.